Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent-tui): jan agent ui console + command-scoped permission prompts
Akarshan Biswasc19f286a2677
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 4619d2e70..c36352ea8 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -11,6 +11,7 @@ dependencies = ["base64 0.22.1","chrono","clap",+ "comfy-table","console","dialoguer","dirs",@@ -40,6 +41,7 @@ dependencies = ["nix 0.30.1","once_cell","rand 0.8.7",+ "ratatui","regex","reqwest 0.12.28","rfd 0.15.4",@@ -75,6 +77,7 @@ dependencies = ["tokio-util","toml 0.8.2","toml_edit 0.23.10+spec-1.0.0",+ "tui-markdown","url","uuid","windows-sys 0.60.2",@@ -332,7 +335,7 @@ dependencies = ["futures-lite","parking","polling",- "rustix",+ "rustix 1.1.4","slab","windows-sys 0.61.2",]@@ -363,7 +366,7 @@ dependencies = ["cfg-if","event-listener","futures-lite",- "rustix",+ "rustix 1.1.4",][[package]]@@ -389,7 +392,7 @@ dependencies = ["cfg-if","futures-core","futures-io",- "rustix",+ "rustix 1.1.4","signal-hook-registry","slab","windows-sys 0.61.2",@@ -706,6 +709,21 @@ dependencies = ["toml 0.9.12+spec-1.1.0",]+[[package]]+name = "cassowary"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53"++[[package]]+name = "castaway"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"+dependencies = [+ "rustversion",+]+[[package]]name = "cbc"version = "0.1.2"@@ -883,6 +901,30 @@ dependencies = ["memchr",]+[[package]]+name = "comfy-table"+version = "7.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "958c5d6ecf1f214b4c2bbbbf6ab9523a864bd136dcf71a7e8904799acfe1ad47"+dependencies = [+ "unicode-segmentation",+ "unicode-width 0.2.0",+]++[[package]]+name = "compact_str"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7fd622ebbb56a5b2ccb651b32b911cdeb2a9b4b11776b2473bf26a26a286244e"+dependencies = [+ "castaway",+ "cfg-if",+ "itoa",+ "rustversion",+ "ryu",+ "static_assertions",+]+[[package]]name = "concurrent-queue"version = "2.5.0"@@ -901,7 +943,7 @@ dependencies = ["encode_unicode","libc","once_cell",- "unicode-width 0.2.2",+ "unicode-width 0.2.0","windows-sys 0.59.0",]@@ -1112,6 +1154,31 @@ version = "0.8.22"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"+[[package]]+name = "crossterm"+version = "0.28.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6"+dependencies = [+ "bitflags 2.13.0",+ "crossterm_winapi",+ "mio",+ "parking_lot",+ "rustix 0.38.44",+ "signal-hook",+ "signal-hook-mio",+ "winapi",+]++[[package]]+name = "crossterm_winapi"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"+dependencies = [+ "winapi",+]+[[package]]name = "crunchy"version = "0.2.4"@@ -1473,6 +1540,12 @@ dependencies = ["zeroize",]+[[package]]+name = "diff"+version = "0.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8"+[[package]]name = "digest"version = "0.10.7"@@ -2154,6 +2227,12 @@ version = "0.3.32"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"+[[package]]+name = "futures-timer"+version = "3.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968"+[[package]]name = "futures-util"version = "0.3.32"@@ -2286,10 +2365,19 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"dependencies = [- "rustix",+ "rustix 1.1.4","windows-link 0.2.1",]+[[package]]+name = "getopts"+version = "0.2.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"+dependencies = [+ "unicode-width 0.2.0",+]+[[package]]name = "getrandom"version = "0.2.17"@@ -3014,10 +3102,19 @@ dependencies = ["console","number_prefix","portable-atomic",- "unicode-width 0.2.2",+ "unicode-width 0.2.0","web-time",]+[[package]]+name = "indoc"+version = "2.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706"+dependencies = [+ "rustversion",+]+[[package]]name = "infer"version = "0.15.0"@@ -3046,6 +3143,19 @@ dependencies = ["generic-array",]+[[package]]+name = "instability"+version = "0.3.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5eb2d60ef19920a3a9193c3e371f726ec1dafc045dac788d0fb3704272458971"+dependencies = [+ "darling 0.23.0",+ "indoc",+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]+[[package]]name = "ipnet"version = "2.12.0"@@ -3077,6 +3187,24 @@ version = "1.70.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"+[[package]]+name = "itertools"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"+dependencies = [+ "either",+]++[[package]]+name = "itertools"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"+dependencies = [+ "either",+]+[[package]]name = "itoa"version = "1.0.18"@@ -3401,6 +3529,12 @@ dependencies = ["vcpkg",]+[[package]]+name = "linux-raw-sys"+version = "0.4.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"+[[package]]name = "linux-raw-sys"version = "0.12.1"@@ -3461,6 +3595,15 @@ dependencies = ["weezl",]+[[package]]+name = "lru"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38"+dependencies = [+ "hashbrown 0.15.5",+]+[[package]]name = "lru-slab"version = "0.1.2"@@ -3581,6 +3724,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"dependencies = ["libc",+ "log","wasi","windows-sys 0.61.2",]@@ -4542,7 +4686,7 @@ dependencies = ["concurrent-queue","hermit-abi","pin-project-lite",- "rustix",+ "rustix 1.1.4","windows-sys 0.61.2",]@@ -4621,6 +4765,16 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"+[[package]]+name = "pretty_assertions"+version = "1.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d"+dependencies = [+ "diff",+ "yansi",+]+[[package]]name = "proc-macro-crate"version = "1.3.1"@@ -4713,6 +4867,25 @@ dependencies = ["psl-types",]+[[package]]+name = "pulldown-cmark"+version = "0.13.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e"+dependencies = [+ "bitflags 2.13.0",+ "getopts",+ "memchr",+ "pulldown-cmark-escape",+ "unicase",+]++[[package]]+name = "pulldown-cmark-escape"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"+[[package]]name = "quick-xml"version = "0.31.0"@@ -4910,6 +5083,27 @@ version = "1.7.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "973443cf09a9c8656b574a866ab68dfa19f0867d0340648c7d2f6a71b8a8ea68"+[[package]]+name = "ratatui"+version = "0.29.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b"+dependencies = [+ "bitflags 2.13.0",+ "cassowary",+ "compact_str",+ "crossterm",+ "indoc",+ "instability",+ "itertools 0.13.0",+ "lru",+ "paste",+ "strum",+ "unicode-segmentation",+ "unicode-truncate",+ "unicode-width 0.2.0",+]+[[package]]name = "raw-window-handle"version = "0.5.2"@@ -5000,6 +5194,12 @@ version = "0.8.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"+[[package]]+name = "relative-path"+version = "1.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2"+[[package]]name = "reqwest"version = "0.12.28"@@ -5208,6 +5408,35 @@ dependencies = ["zeroize",]+[[package]]+name = "rstest"+version = "0.26.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f5a3193c063baaa2a95a33f03035c8a72b83d97a54916055ba22d35ed3839d49"+dependencies = [+ "futures-timer",+ "futures-util",+ "rstest_macros",+]++[[package]]+name = "rstest_macros"+version = "0.26.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c845311f0ff7951c5506121a9ad75aec44d083c31583b2ea5a30bcb0b0abba0"+dependencies = [+ "cfg-if",+ "glob",+ "proc-macro-crate 3.5.0",+ "proc-macro2",+ "quote",+ "regex",+ "relative-path",+ "rustc_version",+ "syn 2.0.118",+ "unicode-ident",+]+[[package]]name = "rusqlite"version = "0.32.1"@@ -5247,6 +5476,19 @@ dependencies = ["semver",]+[[package]]+name = "rustix"+version = "0.38.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"+dependencies = [+ "bitflags 2.13.0",+ "errno",+ "libc",+ "linux-raw-sys 0.4.15",+ "windows-sys 0.59.0",+]+[[package]]name = "rustix"version = "1.1.4"@@ -5256,7 +5498,7 @@ dependencies = ["bitflags 2.13.0","errno","libc",- "linux-raw-sys",+ "linux-raw-sys 0.12.1","windows-sys 0.61.2",]@@ -5794,6 +6036,17 @@ dependencies = ["signal-hook-registry",]+[[package]]+name = "signal-hook-mio"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"+dependencies = [+ "libc",+ "mio",+ "signal-hook",+]+[[package]]name = "signal-hook-registry"version = "1.4.8"@@ -6228,6 +6481,28 @@ version = "0.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"+[[package]]+name = "strum"+version = "0.26.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"+dependencies = [+ "strum_macros",+]++[[package]]+name = "strum_macros"+version = "0.26.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"+dependencies = [+ "heck 0.5.0",+ "proc-macro2",+ "quote",+ "rustversion",+ "syn 2.0.118",+]+[[package]]name = "subtle"version = "2.6.1"@@ -6994,7 +7269,7 @@ dependencies = ["fastrand","getrandom 0.4.3","once_cell",- "rustix",+ "rustix 1.1.4","windows-sys 0.61.2",]@@ -7450,6 +7725,20 @@ version = "0.25.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"+[[package]]+name = "tui-markdown"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bcc77f9d07ca84d2daa018ca91e6076ec9c36f36d4b0e964d5569c51f398b547"+dependencies = [+ "itertools 0.14.0",+ "pretty_assertions",+ "pulldown-cmark",+ "ratatui",+ "rstest",+ "tracing",+]+[[package]]name = "type1-encoding-parser"version = "0.1.1"@@ -7523,6 +7812,12 @@ dependencies = ["unic-common",]+[[package]]+name = "unicase"+version = "2.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"+[[package]]name = "unicode-bidi"version = "0.3.18"@@ -7556,6 +7851,17 @@ version = "1.13.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"+[[package]]+name = "unicode-truncate"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf"+dependencies = [+ "itertools 0.13.0",+ "unicode-segmentation",+ "unicode-width 0.1.14",+]+[[package]]name = "unicode-width"version = "0.1.14"@@ -7564,9 +7870,9 @@ checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"[[package]]name = "unicode-width"-version = "0.2.2"+version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"+checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd"[[package]]name = "universal-hash"@@ -7878,7 +8184,7 @@ checksum = "2857dd20b54e916ec7253b3d6b4d5c4d7d4ca2c33c2e11c6c76a99bd8744755d"dependencies = ["cc","downcast-rs",- "rustix",+ "rustix 1.1.4","scoped-tls","smallvec","wayland-sys",@@ -7891,7 +8197,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "645c7c96bb74690c3189b5c9cb4ca1627062bb23693a4fad9d8c3de958260144"dependencies = ["bitflags 2.13.0",- "rustix",+ "rustix 1.1.4","wayland-backend","wayland-scanner",]@@ -8784,7 +9090,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"dependencies = ["libc",- "rustix",+ "rustix 1.1.4",][[package]]@@ -8814,6 +9120,12 @@ dependencies = ["markup5ever 0.11.0",]+[[package]]+name = "yansi"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049"+[[package]]name = "yoke"version = "0.8.3"@@ -8891,7 +9203,7 @@ dependencies = ["hex","libc","ordered-stream",- "rustix",+ "rustix 1.1.4","serde","serde_repr","tokio",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 810db5626..28163ec8b 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -55,7 +55,7 @@ test-tauri = ["deep-link","hardware",]-cli = ["dep:env_logger", "dep:dialoguer", "dep:indicatif", "dep:console"]+cli = ["dep:env_logger", "dep:dialoguer", "dep:indicatif", "dep:console", "dep:ratatui", "dep:tui-markdown", "dep:comfy-table"][build-dependencies]tauri-build = { version = "2.0.2", features = [] }@@ -152,6 +152,11 @@ keyring = { version = "3", features = [] }aes-gcm = "0.10"machine-uid = "0.5"+ratatui = { version = "0.29.0", optional = true, features = ["unstable-rendered-line-info"] }+# Pinned exactly: 0.3.7+ target ratatui 0.30 (ratatui-core), which would fork an+# incompatible ratatui into the tree. 0.3.6 is the last release on ratatui 0.29.+tui-markdown = { version = "=0.3.6", optional = true, default-features = false }+comfy-table = { version = "7.2", default-features = false, optional = true }[dependencies.tauri]version = "2.8.5"diff --git a/src-tauri/src/bin/jan-cli.rs b/src-tauri/src/bin/jan-cli.rsindex 0cd4e50dc..2c1012a66 100644--- a/src-tauri/src/bin/jan-cli.rs+++ b/src-tauri/src/bin/jan-cli.rs@@ -14,7 +14,7 @@ use indicatif::{ProgressBar, ProgressStyle};// The lib target is named "app_lib" (see [lib] section in Cargo.toml).use app_lib::core::cli::providers::ProviderOverrides;use app_lib::core::cli::{- cli_agent_run, cli_agent_status, cli_agent_step, cli_delete_thread,+ cli_agent_run, cli_agent_status, cli_agent_step, cli_agent_ui, cli_delete_thread,cli_get_data_folder, cli_get_thread, cli_list_messages, cli_list_threads,discover_llamacpp_binary, download_hf_model, fetch_hf_gguf_files, init_llamacpp_state,list_models, looks_like_hf_repo, resolve_model_engine, HfFileInfo,@@ -134,8 +134,13 @@ struct ProviderArgs {impl ProviderArgs {fn into_overrides(self) -> ProviderOverrides {+ // Default the target provider to the desktop app's current selection so+ // env-key fallback (<PROVIDER>_API_KEY) works without an explicit flag.+ let provider = self+ .provider+ .or_else(|| app_lib::core::cli::providers::desktop_selection().provider);ProviderOverrides {- provider: self.provider,+ provider,api_key: self.api_key,}.with_env()@@ -160,6 +165,22 @@ enum AgentCommands {#[command(flatten)]providers: ProviderArgs,},+ /// Open the interactive chat console (optionally seeded with a first message)+ Ui {+ /// Project root containing .jan/agent/agent.toml+ #[arg(long, default_value = ".")]+ project: String,+ /// Optional first message; omit to start with an empty chat+ task: Option<String>,+ /// Model ID (overrides [agent].model in agent.toml)+ #[arg(long)]+ model: Option<String>,+ /// Max turns per message (overrides [agent].max_turns; clamped 1..=400)+ #[arg(long)]+ max_turns: Option<u32>,+ #[command(flatten)]+ providers: ProviderArgs,+ },/// Run a single turn (debugging)Step {/// Project root containing .jan/agent/agent.toml@@ -418,6 +439,13 @@ async fn handle_agent(cmd: AgentCommands) {).await}+ AgentCommands::Ui {+ project,+ task,+ model,+ max_turns,+ providers,+ } => cli_agent_ui(&project, task, model, max_turns, providers.into_overrides()).await,AgentCommands::Step {project,task,diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex baa443488..edec2efe9 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -38,6 +38,10 @@ pub enum StreamEvent {tool_name: String,capability: String,path: Option<String>,+ /// The shell command for exec prompts (drives the command-scoped+ /// "allow always" grant); `None` for non-exec tools.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ command: Option<String>,prompt_kind: String,offers_always: bool,},@@ -247,6 +251,7 @@ mod tests {tool_name: "write".into(),capability: "write".into(),path: Some("out.txt".into()),+ command: None,prompt_kind: "write".into(),offers_always: true,})diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 796052d46..555fbb7a6 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -167,7 +167,7 @@ impl ToolInvoker for CompositeToolInvoker {.and_then(|s| serde_json::from_str(s).ok()).unwrap_or(serde_json::Value::Object(Default::default()));let tool = lookup(name).expect("is_builtin implies lookup");- let snapshot = { *self.grants.lock().unwrap() };+ let snapshot = { self.grants.lock().unwrap().clone() };let decision = resolve_decision(tool,&args,@@ -203,11 +203,16 @@ impl ToolInvoker for CompositeToolInvoker {.and_then(|k| args.get(*k)).and_then(|v| v.as_str()).map(String::from);+ let command = matches!(tool.capability, Capability::Exec)+ .then(|| args.get("command").and_then(|v| v.as_str()))+ .flatten()+ .map(String::from);let _ = self.events.send(StreamEvent::PermissionRequest {request_id: request_id.clone(),tool_name: name.to_string(),capability: capability.to_string(),path,+ command,prompt_kind: prompt_kind.to_string(),offers_always: true,});@@ -221,17 +226,16 @@ impl ToolInvoker for CompositeToolInvoker {execute_builtin(tool, &args, &self.project_root).await}PermissionDecision::AllowAlways => {- self.grants.lock().unwrap().grant(kind);- // Persist for future runs (best-effort; the session- // grant above already covers the rest of this run).- let write_capable =- matches!(tool.capability, Capability::Write | Capability::Exec);- if let Err(e) = crate::core::agent::project::grant_tool_in_agent_toml(- &self.project_root,- name,- write_capable,- ) {- log::warn!("failed to persist always-allow for '{name}': {e}");+ // Thread-scoped only; never persisted to agent.toml.+ // Exec grants are scoped to the base command so that+ // "allow always" for `git status` covers `git ...`+ // but not arbitrary shell commands.+ if matches!(tool.capability, Capability::Exec) {+ let command =+ args.get("command").and_then(|v| v.as_str()).unwrap_or("");+ self.grants.lock().unwrap().grant_command(command);+ } else {+ self.grants.lock().unwrap().grant(kind);}execute_builtin(tool, &args, &self.project_root).await}diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rsindex e4766f1a1..277e359ab 100644--- a/src-tauri/src/core/agent/project.rs+++ b/src-tauri/src/core/agent/project.rs@@ -122,38 +122,19 @@ pub(crate) fn ensure_project(project_root: &Path) -> Result<PathBuf, String> {Ok(agent_dir)}-/// Persist an always-allow grant for `tool_name` into agent.toml, format-preserving-/// (comments kept). Write/exec tools go into `[tools].allow_write`, read tools into-/// `[tools].allow`. Idempotent (no duplicate entries). Errs if agent.toml is missing.-pub(crate) fn grant_tool_in_agent_toml(- project_root: &Path,- tool_name: &str,- write_capable: bool,-) -> Result<(), String> {- let path = agent_toml_path(project_root);- let raw = std::fs::read_to_string(&path)+/// Persist `[agent].model` into the agent.toml at `path`, format-preserving+/// (comments kept). Remembers a TUI `/model` selection across sessions.+pub(crate) fn set_model_in_agent_toml(path: &Path, model: &str) -> 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 tools = doc["tools"].or_insert(toml_edit::Item::Table(toml_edit::Table::new()));- let key = if write_capable {- "allow_write"- } else {- "allow"- };- let list = tools[key].or_insert(toml_edit::value(toml_edit::Array::new()));- let arr = list- .as_array_mut()- .ok_or_else(|| format!("[tools].{key} is not an array in {}", path.display()))?;-- if arr.iter().any(|v| v.as_str() == Some(tool_name)) {- return Ok(());- }- arr.push(tool_name);+ let agent = doc["agent"].or_insert(toml_edit::Item::Table(toml_edit::Table::new()));+ agent["model"] = toml_edit::value(model);- std::fs::write(&path, doc.to_string())+ std::fs::write(path, doc.to_string()).map_err(|e| format!("Failed to write {}: {e}", path.display()))}@@ -232,28 +213,21 @@ mod tests {}#[test]- fn grant_persists_by_capability_and_is_idempotent_and_keeps_comments() {- let root = unique_root("grant");+ fn set_model_persists_and_reloads_and_keeps_comments() {+ let root = unique_root("setmodel");ensure_project(&root).expect("scaffold");+ let path = agent_toml_path(&root);- grant_tool_in_agent_toml(&root, "write", true).expect("grant write");- grant_tool_in_agent_toml(&root, "read", false).expect("grant read");- // Idempotent: a second identical grant does not duplicate.- grant_tool_in_agent_toml(&root, "write", true).expect("grant write again");-+ set_model_in_agent_toml(&path, "claude-sonnet-5").expect("set");let cfg = load_agent_config(&root).expect("load");- assert_eq!(cfg.tools.allow_write, vec!["write".to_string()]);- assert_eq!(cfg.tools.allow, vec!["read".to_string()]);+ assert_eq!(cfg.agent.model.as_deref(), Some("claude-sonnet-5"));- // Format-preserving: the template's comment survives the edit.- let raw = std::fs::read_to_string(agent_toml_path(&root)).expect("read raw");+ // Overwrites on a second set; template comment survives.+ set_model_in_agent_toml(&path, "gpt-4o").expect("set again");+ let cfg = load_agent_config(&root).expect("load");+ assert_eq!(cfg.agent.model.as_deref(), Some("gpt-4o"));+ let raw = std::fs::read_to_string(&path).expect("read");assert!(raw.contains("Secure default"));let _ = std::fs::remove_dir_all(&root);}-- #[test]- fn grant_missing_agent_toml_errors() {- let root = unique_root("grant_missing");- assert!(grant_tool_in_agent_toml(&root, "write", true).is_err());- }}diff --git a/src-tauri/src/core/agent/tools/gate.rs b/src-tauri/src/core/agent/tools/gate.rsindex c468f9679..2948265ad 100644--- a/src-tauri/src/core/agent/tools/gate.rs+++ b/src-tauri/src/core/agent/tools/gate.rs@@ -23,11 +23,23 @@ pub enum PermissionDecision {Deny,}-#[derive(Debug, Clone, Copy, Default)]+/// In-memory, thread-scoped permission grants (never persisted). Exec grants are+/// per base command (e.g. granting `git` allows `git ...` but not `rm ...`),+/// matching the user's "allow all git commands" intent.+#[derive(Debug, Clone, Default)]pub struct SessionGrants {read_escape: bool,write: bool,- exec: bool,+ exec_commands: std::collections::BTreeSet<String>,+}++/// The base command a shell string runs: the first whitespace-delimited token,+/// with any directory prefix stripped (`/usr/bin/git` -> `git`). Returns `None`+/// for an empty command.+pub fn command_base(command: &str) -> Option<&str> {+ let first = command.split_whitespace().next()?;+ let base = first.rsplit(['/', '\\']).next().unwrap_or(first);+ (!base.is_empty()).then_some(base)}impl SessionGrants {@@ -35,15 +47,29 @@ impl SessionGrants {match kind {PromptKind::ReadEscape => self.read_escape,PromptKind::Write => self.write,- PromptKind::Exec => self.exec,+ // Exec coverage is command-specific; use `covers_command`.+ PromptKind::Exec => false,}}+ /// Whether a previously granted base command covers this shell command.+ pub fn covers_command(&self, command: &str) -> bool {+ command_base(command).is_some_and(|b| self.exec_commands.contains(b))+ }+pub fn grant(&mut self, kind: PromptKind) {match kind {PromptKind::ReadEscape => self.read_escape = true,PromptKind::Write => self.write = true,- PromptKind::Exec => self.exec = true,+ // No-op: exec is granted per command via `grant_command`.+ PromptKind::Exec => {}+ }+ }++ /// Grant the base command of `command` for the rest of this session.+ pub fn grant_command(&mut self, command: &str) {+ if let Some(base) = command_base(command) {+ self.exec_commands.insert(base.to_string());}}}@@ -110,7 +136,14 @@ pub fn resolve_decision(gated(PromptKind::Write, grants)}}- Capability::Exec => gated(PromptKind::Exec, grants),+ Capability::Exec => {+ let command = args.get("command").and_then(|v| v.as_str()).unwrap_or("");+ if grants.covers_command(command) {+ Decision::Allow+ } else {+ Decision::Prompt(PromptKind::Exec)+ }+ }}}@@ -209,6 +242,43 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ #[test]+ fn command_base_strips_path_and_args() {+ assert_eq!(command_base("git status"), Some("git"));+ assert_eq!(command_base("/usr/bin/git commit -m x"), Some("git"));+ assert_eq!(command_base(" "), None);+ assert_eq!(command_base(""), None);+ }++ #[test]+ fn exec_grant_is_scoped_to_base_command() {+ let root = unique_root();+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);+ let mut grants = SessionGrants::default();+ grants.grant_command("git status");++ // Same base command -> allowed without prompting.+ let d = resolve_decision(+ lookup("bash").unwrap(),+ &json!({"command": "git push"}),+ &root,+ &perms,+ &grants,+ );+ assert_eq!(d, Decision::Allow);++ // A different command still prompts.+ let d = resolve_decision(+ lookup("bash").unwrap(),+ &json!({"command": "rm -rf /"}),+ &root,+ &perms,+ &grants,+ );+ assert_eq!(d, Decision::Prompt(PromptKind::Exec));+ let _ = std::fs::remove_dir_all(&root);+ }+#[test]fn write_to_agent_workspace_is_auto_allowed() {let root = unique_root();diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 6f2f66ee9..efbf9d719 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -3,6 +3,7 @@//! This module is only compiled when the `cli` feature is enabled.pub mod providers;+mod tui;use std::path::PathBuf;use std::sync::Arc;@@ -12,8 +13,11 @@ use crate::core::server::proxy;use crate::core::state::AppState;use crate::core::threads::{constants::THREADS_FILE,- helpers::read_messages_from_file,- utils::{ensure_data_dirs, get_data_dir, get_thread_dir, get_thread_metadata_path},+ helpers::{read_messages_from_file, update_thread_metadata, write_messages_to_file},+ utils::{+ ensure_data_dirs, get_data_dir, get_messages_path, get_thread_dir,+ get_thread_metadata_path,+ },};use tauri_plugin_llamacpp::state::LlamacppState;#[cfg(target_os = "macos")]@@ -37,22 +41,18 @@ pub fn init_mlx_state() -> MlxState {// ── Thread operations ──────────────────────────────────────────────────────-/// List all threads from the Jan data folder.-pub async fn cli_list_threads() -> Result<Vec<serde_json::Value>, String> {+/// List thread metadata under `<base>/threads/`. `base` is the Jan data folder+/// (desktop store) or a project's `.jan/agent` dir (TUI store).+pub fn list_threads_in(base: &std::path::Path) -> Result<Vec<serde_json::Value>, String> {use std::fs;- let data_folder = resolve_jan_data_folder();- ensure_data_dirs(&data_folder)?;- let data_dir = get_data_dir(&data_folder);+ let data_dir = get_data_dir(base);let mut threads = Vec::new();-if !data_dir.exists() {return Ok(threads);}-for entry in fs::read_dir(&data_dir).map_err(|e| e.to_string())? {- let entry = entry.map_err(|e| e.to_string())?;- let path = entry.path();+ let path = entry.map_err(|e| e.to_string())?.path();if path.is_dir() {let metadata_path = path.join(THREADS_FILE);if metadata_path.exists() {@@ -63,10 +63,24 @@ pub async fn cli_list_threads() -> Result<Vec<serde_json::Value>, String> {}}}-Ok(threads)}+/// List all threads from the Jan data folder (desktop store).+pub async fn cli_list_threads() -> Result<Vec<serde_json::Value>, String> {+ let data_folder = resolve_jan_data_folder();+ ensure_data_dirs(&data_folder)?;+ list_threads_in(&data_folder)+}++/// Read a thread's messages from `<base>/threads/<id>/messages.jsonl`.+pub fn cli_list_messages_in(+ base: &std::path::Path,+ thread_id: &str,+) -> Result<Vec<serde_json::Value>, String> {+ read_messages_from_file(base, thread_id)+}+/// List messages for a thread.pub fn cli_list_messages(thread_id: &str) -> Result<Vec<serde_json::Value>, String> {let data_folder = resolve_jan_data_folder();@@ -96,6 +110,106 @@ pub fn cli_get_thread(thread_id: &str) -> Result<serde_json::Value, String> {serde_json::from_str(&data).map_err(|e| e.to_string())}+/// Persist a TUI conversation as a desktop-compatible thread so it appears in+/// `/resume` and the desktop app. `history` is OpenAI-shaped (`{role, content}`);+/// it is written as `thread.message` records plus `thread.json` metadata. Pass+/// an existing `thread_id` to update that thread, or `None` to create one+/// (returns the id). Title/created are preserved when updating.+pub fn cli_save_thread(+ base: &std::path::Path,+ thread_id: Option<&str>,+ model: &str,+ history: &[serde_json::Value],+) -> Result<String, String> {+ if history.is_empty() {+ return Err("empty conversation".to_string());+ }+ ensure_data_dirs(base)?;+ let id = thread_id+ .map(str::to_string)+ .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());+ std::fs::create_dir_all(get_thread_dir(base, &id)).map_err(|e| e.to_string())?;++ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default();+ let now_ms = now.as_millis() as i64;+ let now_secs = now.as_secs_f64();++ let messages: Vec<serde_json::Value> = history+ .iter()+ .filter_map(|m| {+ let role = m.get("role").and_then(|v| v.as_str())?;+ let content = m.get("content").and_then(|v| v.as_str()).unwrap_or("");+ Some(serde_json::json!({+ "id": uuid::Uuid::new_v4().to_string(),+ "object": "thread.message",+ "thread_id": id,+ "role": role,+ "type": "text",+ "status": "ready",+ "created_at": now_ms,+ "completed_at": now_ms,+ "content": [{ "type": "text", "text": { "value": content, "annotations": [] } }],+ }))+ })+ .collect();+ write_messages_to_file(&messages, &get_messages_path(base, &id))?;++ let existing: Option<serde_json::Value> =+ std::fs::read_to_string(get_thread_metadata_path(base, &id))+ .ok()+ .and_then(|s| serde_json::from_str(&s).ok());+ let created = existing+ .as_ref()+ .and_then(|e| e.get("created").and_then(serde_json::Value::as_f64))+ .unwrap_or(now_secs);+ let title = existing+ .as_ref()+ .and_then(|e| e.get("title").and_then(|v| v.as_str()))+ .filter(|s| !s.is_empty())+ .map(str::to_string)+ .unwrap_or_else(|| default_thread_title(history));++ let thread = serde_json::json!({+ "id": id,+ "object": "thread",+ "title": title,+ "created": created,+ "updated": now_secs,+ "model": { "id": model, "provider": "" },+ "metadata": {},+ });+ update_thread_metadata(base, &id, &thread)?;+ Ok(id)+}++/// Persist a TUI `/model` choice to the project's `agent.toml` `[agent].model`,+/// so it is remembered on the next session (agent.toml wins over the desktop+/// default in the model-resolution order). `agent_dir` is `<project>/.jan/agent`.+pub fn cli_set_project_model(agent_dir: &std::path::Path, model: &str) -> Result<(), String> {+ set_model_in_agent_toml(&agent_dir.join("agent.toml"), model)+}++/// Fallback thread title: the first user message, whitespace-collapsed and+/// truncated. Used only when no summarized title exists yet.+fn default_thread_title(history: &[serde_json::Value]) -> String {+ let first_user = history+ .iter()+ .find(|m| m.get("role").and_then(|v| v.as_str()) == Some("user"))+ .and_then(|m| m.get("content").and_then(|v| v.as_str()))+ .unwrap_or("");+ let collapsed = first_user.split_whitespace().collect::<Vec<_>>().join(" ");+ if collapsed.is_empty() {+ return "Agent chat".to_string();+ }+ if collapsed.chars().count() > 50 {+ format!("{}…", collapsed.chars().take(49).collect::<String>())+ } else {+ collapsed+ }+}+// ── Server operations ──────────────────────────────────────────────────────/// Stop the running proxy server.@@ -536,7 +650,9 @@ pub fn cli_get_config() -> Result<serde_json::Value, String> {// ── Agent operations ───────────────────────────────────────────────────────use crate::core::agent::events::StreamEvent;-use crate::core::agent::project::{ensure_project, load_agent_config, permissions_from};+use crate::core::agent::project::{+ ensure_project, load_agent_config, permissions_from, set_model_in_agent_toml,+};use crate::core::agent::r#loop::{run_orchestration_streamed, OrchestrationArgs, PermissionRegistry,};@@ -630,22 +746,58 @@ fn build_cli_orchestration_args(}}-async fn run_agent_loop(+/// Everything needed to drive one agent run: the engine handle, request body,+/// and the shared permission registry. Built once and consumed by either the+/// plain CLI printer or the TUI renderer.+pub(crate) struct PreparedRun {+ pub args: OrchestrationArgs,+ pub body: serde_json::Value,+ pub permission_requests: PermissionRegistry,+}++/// Resolved engine handle for a chat session: the args are built once and the+/// request body is assembled per turn (the TUI reuses this across many turns;+/// the plain CLI builds a single body). `model`/`max_turns` seed each body.+pub(crate) struct AgentSession {+ pub args: OrchestrationArgs,+ pub permission_requests: PermissionRegistry,+ pub model: String,+ pub max_turns: u32,+}++impl AgentSession {+ /// Build a streaming request body for the given conversation history.+ pub(crate) fn body(&self, messages: serde_json::Value) -> serde_json::Value {+ serde_json::json!({+ "model": self.model,+ "messages": messages,+ "max_turns": self.max_turns,+ "stream": true,+ })+ }+}++/// Resolve project config + credentials into a ready-to-run engine handle.+/// Shared by `run_agent_loop` (plain CLI) and `cli_agent_ui` (TUI).+fn prepare_agent_session(project: &str,- task: &str,model_override: Option<String>,max_turns_override: Option<u32>,overrides: ProviderOverrides,-) -> Result<(), String> {+) -> Result<AgentSession, String> {let project_root = PathBuf::from(project);ensure_project(&project_root)?;let cfg = load_agent_config(&project_root)?;let permissions = permissions_from(&cfg);+ // Resolution order: --model flag, then agent.toml [agent].model, then the+ // desktop app's currently-selected model (synced from settings.json).let model = model_override.or_else(|| cfg.agent.model.clone())+ .or_else(|| crate::core::cli::providers::desktop_selection().model).ok_or_else(|| {- "no model specified: pass --model or set [agent].model in agent.toml".to_string()+ "no model specified: pass --model, set [agent].model in agent.toml, or select a model in the desktop app"+ .to_string()})?;let max_turns = max_turns_override.or(cfg.agent.max_turns)@@ -661,12 +813,42 @@ async fn run_agent_loop(permission_requests.clone(),);- let body = serde_json::json!({- "model": model,- "messages": [{ "role": "user", "content": task }],- "max_turns": max_turns,- "stream": true,- });+ Ok(AgentSession {+ args,+ permission_requests,+ model,+ max_turns,+ })+}++fn prepare_agent_run(+ project: &str,+ task: &str,+ model_override: Option<String>,+ max_turns_override: Option<u32>,+ overrides: ProviderOverrides,+) -> Result<PreparedRun, String> {+ let session = prepare_agent_session(project, model_override, max_turns_override, overrides)?;+ let body = session.body(serde_json::json!([{ "role": "user", "content": task }]));+ Ok(PreparedRun {+ args: session.args,+ body,+ permission_requests: session.permission_requests,+ })+}++async fn run_agent_loop(+ project: &str,+ task: &str,+ model_override: Option<String>,+ max_turns_override: Option<u32>,+ overrides: ProviderOverrides,+) -> Result<(), String> {+ let PreparedRun {+ args,+ body,+ permission_requests,+ } = prepare_agent_run(project, task, model_override, max_turns_override, overrides)?;let (tx, mut rx) = mpsc::unbounded_channel::<StreamEvent>();let printer = tokio::spawn(async move {@@ -681,6 +863,23 @@ async fn run_agent_loop(result.map(|_| ())}+/// Launch the interactive chat console (`jan agent ui`). An optional `task`+/// seeds the first turn; otherwise the user types the first message. Shares the+/// engine with `run_agent_loop` via `AgentSession` — only presentation differs.+pub async fn cli_agent_ui(+ project: &str,+ task: Option<String>,+ model: Option<String>,+ max_turns: Option<u32>,+ overrides: ProviderOverrides,+) -> Result<(), String> {+ let session = prepare_agent_session(project, model, max_turns, overrides)?;+ // TUI threads persist under the project's .jan/agent dir, separate from the+ // desktop store, so continuing here never mutates desktop threads.+ let agent_dir = PathBuf::from(project).join(".jan").join("agent");+ tui::run(session, agent_dir, task).await+}+/// Render one `StreamEvent` for the terminal. Content tokens go to stdout so a/// run can be piped; progress/diagnostics go to stderr. `PermissionRequest` is/// resolved via the terminal (deny when non-interactive).@@ -717,9 +916,14 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {tool_name,capability,path,+ command,..} => {- let decision = prompt_permission(tool_name, capability, path).await;+ let detail = command+ .map(|c| format!(" ({c})"))+ .or_else(|| path.map(|p| format!(" on {p}")))+ .unwrap_or_default();+ let decision = prompt_permission(tool_name, capability, detail).await;if let Some(sender) = registry.lock().await.remove(&request_id) {let _ = sender.send(decision);}@@ -733,7 +937,7 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {async fn prompt_permission(tool_name: String,capability: String,- path: Option<String>,+ detail: String,) -> PermissionDecision {use std::io::IsTerminal;if !std::io::stdin().is_terminal() {@@ -741,8 +945,7 @@ async fn prompt_permission(return PermissionDecision::Deny;}tokio::task::spawn_blocking(move || {- let target = path.map(|p| format!(" on {p}")).unwrap_or_default();- eprint!("\x1b[33m[permission] allow {capability} via '{tool_name}'{target}? [y/N] \x1b[0m");+ eprint!("\x1b[33m[permission] allow {capability} via '{tool_name}'{detail}? [y/N] \x1b[0m");let _ = std::io::stderr().flush();let mut line = String::new();if std::io::stdin().read_line(&mut line).is_err() {@@ -761,6 +964,32 @@ async fn prompt_permission(mod tests {use super::*;+ // ── default_thread_title ───────────────────────────────────────────────++ #[test]+ fn default_thread_title_uses_first_user_message() {+ let history = serde_json::json!([+ { "role": "user", "content": "Explain the buffer\nlogic" },+ { "role": "assistant", "content": "sure" },+ ]);+ assert_eq!(+ default_thread_title(history.as_array().unwrap()),+ "Explain the buffer logic"+ );+ }++ #[test]+ fn default_thread_title_truncates_and_falls_back() {+ let long = "x".repeat(80);+ let history = serde_json::json!([{ "role": "user", "content": long }]);+ let title = default_thread_title(history.as_array().unwrap());+ assert_eq!(title.chars().count(), 50);+ assert!(title.ends_with('…'));++ let no_user = serde_json::json!([{ "role": "assistant", "content": "hi" }]);+ assert_eq!(default_thread_title(no_user.as_array().unwrap()), "Agent chat");+ }+// ── looks_like_hf_repo ─────────────────────────────────────────────────#[test]diff --git a/src-tauri/src/core/cli/providers.rs b/src-tauri/src/core/cli/providers.rsindex eabbe0856..abb17d0c7 100644--- a/src-tauri/src/core/cli/providers.rs+++ b/src-tauri/src/core/cli/providers.rs@@ -50,6 +50,68 @@ impl ProviderOverrides {}}+/// The desktop app's current selection (`state.selectedProvider` /+/// `state.selectedModel.id` in the `model-provider` store), used to default the+/// CLI `--provider`/`--model` when the user gives none.+#[derive(Debug, Default, Clone, PartialEq)]+pub struct DesktopSelection {+ pub provider: Option<String>,+ pub model: Option<String>,+}++/// Read the desktop's selected provider + model from `settings.json`. Missing or+/// malformed data yields an empty selection (no defaults applied).+pub fn desktop_selection() -> DesktopSelection {+ let path = resolve_jan_data_folder().join("settings.json");+ match std::fs::read_to_string(&path) {+ Ok(raw) => parse_selection(&raw),+ Err(_) => DesktopSelection::default(),+ }+}++/// Extract the selection from a `settings.json` body. Tolerant of shape drift.+fn parse_selection(raw: &str) -> DesktopSelection {+ let root: serde_json::Value = match serde_json::from_str(raw) {+ Ok(v) => v,+ Err(_) => return DesktopSelection::default(),+ };+ let blob = match root.get(MODEL_PROVIDER_KEY).and_then(|v| v.as_str()) {+ Some(s) => s,+ None => return DesktopSelection::default(),+ };+ let parsed: serde_json::Value = match serde_json::from_str(blob) {+ Ok(v) => v,+ Err(_) => return DesktopSelection::default(),+ };+ let state = parsed.get("state");+ let non_empty = |v: Option<&serde_json::Value>| {+ v.and_then(|x| x.as_str())+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(String::from)+ };+ DesktopSelection {+ provider: non_empty(state.and_then(|s| s.get("selectedProvider"))),+ model: non_empty(state.and_then(|s| s.get("selectedModel").and_then(|m| m.get("id")))),+ }+}++/// Enumerate `(provider, model_id)` pairs from the persisted desktop store,+/// sorted by provider then model. Used to populate the TUI `/model` selector.+pub fn list_provider_models() -> Vec<(String, String)> {+ let path = resolve_jan_data_folder().join("settings.json");+ let configs = match std::fs::read_to_string(&path) {+ Ok(raw) => parse_provider_store(&raw),+ Err(_) => return Vec::new(),+ };+ let mut out: Vec<(String, String)> = configs+ .values()+ .flat_map(|c| c.models.iter().map(|m| (c.provider.clone(), m.clone())))+ .collect();+ out.sort();+ out+}+/// Load cloud provider configs from the persisted desktop store, applying/// `overrides`. A missing/malformed store is not fatal: it yields an empty map/// so `--provider`/`--api-key`/env can still stand up a config on their own.@@ -320,6 +382,43 @@ mod tests {assert_eq!(configs.get("openai").unwrap().api_key, None);}+ #[test]+ fn provider_models_from_store_are_flattened_and_sorted() {+ let mut pairs: Vec<(String, String)> = parse_provider_store(STORE)+ .values()+ .flat_map(|c| c.models.iter().map(|m| (c.provider.clone(), m.clone())))+ .collect();+ pairs.sort();+ assert_eq!(+ pairs,+ vec![+ ("anthropic".to_string(), "claude-opus-4".to_string()),+ ("anthropic".to_string(), "claude-sonnet-4-5".to_string()),+ ("openai".to_string(), "gpt-4o".to_string()),+ ]+ );+ }++ #[test]+ fn parses_desktop_selection() {+ let store = r#"{"model-provider":"{\"state\":{\"selectedProvider\":\"anthropic\",\"selectedModel\":{\"id\":\"claude-sonnet-4-5\",\"provider\":\"anthropic\"},\"providers\":[]}}"}"#;+ let sel = parse_selection(store);+ assert_eq!(sel.provider.as_deref(), Some("anthropic"));+ assert_eq!(sel.model.as_deref(), Some("claude-sonnet-4-5"));+ }++ #[test]+ fn selection_absent_or_empty_is_none() {+ assert_eq!(parse_selection("not json"), DesktopSelection::default());+ assert_eq!(+ parse_selection(r#"{"model-provider":"{\"state\":{\"providers\":[]}}"}"#),+ DesktopSelection::default()+ );+ // Empty strings / null model are treated as unset.+ let blank = r#"{"model-provider":"{\"state\":{\"selectedProvider\":\"\",\"selectedModel\":null}}"}"#;+ assert_eq!(parse_selection(blank), DesktopSelection::default());+ }+#[test]fn no_override_is_noop() {let mut configs = parse_provider_store(STORE);diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsnew file mode 100644index 000000000..8ee164877--- /dev/null+++ b/src-tauri/src/core/cli/tui.rs@@ -0,0 +1,1595 @@+//! Interactive chat console over the agent loop (`jan agent ui`). A thin+//! renderer: the engine is shared with the plain CLI path, only the+//! presentation differs. Maintains a running conversation — the user types+//! messages into an input box, each submit spawns an agent run over the shared+//! `AgentSession`, and streamed `StreamEvent`s render as message history plus+//! inline workflow elements (turn steps, tool calls/results). Gated tool calls+//! are approved interactively via the shared `PermissionRegistry`.++use std::future::pending;+use std::io;+use std::sync::Arc;+use std::time::Duration;++use ratatui::crossterm::{+ event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},+ execute,+ terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},+};+use ratatui::prelude::*;+use ratatui::widgets::{Block, Borders, Paragraph, Wrap};+use tokio::sync::mpsc;+use tokio::task::JoinHandle;++use super::AgentSession;+use crate::core::agent::events::{describe_tool_call, StreamEvent, Usage};+use crate::core::agent::r#loop::{run_orchestration_streamed, OrchestrationArgs, PermissionRegistry};+use crate::core::agent::tools::gate::PermissionDecision;++#[derive(PartialEq)]+enum Status {+ Idle,+ Running,+}++/// Kind of the last transcript block, used to insert a blank line only when the+/// block kind changes (so consecutive tool lines group, but prose/tool/user+/// turns get breathing room).+#[derive(PartialEq, Clone, Copy)]+enum Kind {+ None,+ User,+ Prose,+ Tool,+ Meta,+}++struct Pending {+ request_id: String,+ tool_name: String,+ capability: String,+ path: Option<String>,+ /// Shell command for exec prompts; drives the command-scoped always-grant.+ command: Option<String>,+ offers_always: bool,+ /// Highlighted option in the docked prompt (index into `options()`).+ selected: usize,+}++impl Pending {+ /// One-line summary for the transcript decision record.+ fn summary(&self) -> String {+ let target = self+ .path+ .as_deref()+ .map(|p| format!(" on {p}"))+ .unwrap_or_default();+ format!("{} via '{}'{target}", self.capability, self.tool_name)+ }++ /// Base command of an exec prompt (`git status` -> `git`), if any.+ fn command_base(&self) -> Option<&str> {+ self.command+ .as_deref()+ .and_then(crate::core::agent::tools::gate::command_base)+ }++ /// Label for the "allow always" option: command-scoped for exec (thread+ /// only), capability-scoped otherwise. All grants are thread-scoped.+ fn always_label(&self) -> String {+ match self.command_base() {+ Some(base) => format!("Allow all '{base}' commands (this thread)"),+ None => "Allow always (this thread)".to_string(),+ }+ }++ /// Selectable decisions, in display order. `AllowAlways` only when offered.+ fn options(&self) -> Vec<(PermissionDecision, String)> {+ let mut opts = vec![(PermissionDecision::AllowOnce, "Allow once".to_string())];+ if self.offers_always {+ opts.push((PermissionDecision::AllowAlways, self.always_label()));+ }+ opts.push((PermissionDecision::Deny, "Deny".to_string()));+ opts+ }++ fn move_selection(&mut self, delta: isize) {+ let len = self.options().len() as isize;+ self.selected = (self.selected as isize + delta).rem_euclid(len) as usize;+ }+}++/// What a highlighted picker row does on Enter.+#[derive(PartialEq, Clone, Copy)]+enum PickerKind {+ ResumeThread,+ SelectModel,+}++/// Interactive list overlay (`/resume` threads, `/model` models): rows with a+/// highlighted cursor, acted on by `PickerKind` on Enter.+struct Picker {+ kind: PickerKind,+ items: Vec<PickerItem>,+ selected: usize,+}++impl Picker {+ fn title(&self) -> &'static str {+ match self.kind {+ PickerKind::ResumeThread => " resume thread ",+ PickerKind::SelectModel => " select model ",+ }+ }++ fn action_hint(&self) -> &'static str {+ match self.kind {+ PickerKind::ResumeThread => " ↑/↓ select Enter resume Esc cancel",+ PickerKind::SelectModel => " ↑/↓ select Enter choose Esc cancel",+ }+ }+}++struct PickerItem {+ /// The value acted on (thread id or model id).+ value: String,+ /// Primary display text.+ label: String,+ /// Optional dim prefix (e.g. a thread's short id).+ hint: Option<String>,+}++/// A spawned agent run: the event stream and its abort handle.+struct CurrentRun {+ rx: mpsc::UnboundedReceiver<StreamEvent>,+ handle: JoinHandle<()>,+}++struct App {+ model: String,+ max_turns: u32,+ /// Project `.jan/agent` dir where this TUI's threads are saved/listed.+ agent_dir: std::path::PathBuf,+ /// OpenAI-shaped conversation history sent with each run.+ history: Vec<serde_json::Value>,+ /// Thread this conversation persists to (set on first save or on resume).+ thread_id: Option<String>,+ /// Styled display transcript (user turns, assistant text, workflow lines).+ transcript: Vec<Line<'static>>,+ /// In-progress assistant text for the current turn, flushed on the next+ /// step/tool/terminal event.+ assistant_buf: String,+ input: String,+ status: Status,+ turn: (u32, u32),+ tokens: u64,+ detail: String,+ pending: Option<Pending>,+ picker: Option<Picker>,+ /// Lines scrolled back from the tail; 0 pins the view to the bottom so new+ /// content follows. Non-zero survives streaming so scroll-back stays usable.+ scrollback: u16,+ /// Set when the user submits a message; the loop spawns a run next tick.+ want_start: bool,+ /// Transcript viewport width in cells, refreshed each `draw`; tables wrap to+ /// it. 0 until the first draw (callers fall back to a default).+ view_width: u16,+ last_kind: Kind,+ should_quit: bool,+}++impl App {+ fn new(model: String, max_turns: u32, agent_dir: std::path::PathBuf) -> Self {+ Self {+ model,+ max_turns,+ agent_dir,+ history: Vec::new(),+ thread_id: None,+ transcript: Vec::new(),+ assistant_buf: String::new(),+ input: String::new(),+ status: Status::Idle,+ turn: (0, 0),+ tokens: 0,+ detail: String::new(),+ pending: None,+ picker: None,+ scrollback: 0,+ want_start: false,+ view_width: 0,+ last_kind: Kind::None,+ should_quit: false,+ }+ }++ /// Effective width for table wrapping (fallback before the first draw).+ fn render_width(&self) -> u16 {+ if self.view_width == 0 {+ 80+ } else {+ self.view_width+ }+ }++ fn push(&mut self, line: Line<'static>) {+ self.transcript.push(line);+ }++ /// Insert a blank separator when the block kind changes, then record it.+ /// Keeps consecutive same-kind lines tight while spacing turn boundaries.+ fn gap(&mut self, next: Kind) {+ let last_blank = self+ .transcript+ .last()+ .map(|l| l.spans.iter().all(|s| s.content.trim().is_empty()))+ .unwrap_or(true);+ if !self.transcript.is_empty() && self.last_kind != next && !last_blank {+ self.transcript.push(Line::raw(""));+ }+ self.last_kind = next;+ }++ /// Append a dim single-line status note (command output, cancel, errors).+ fn note(&mut self, text: &str) {+ self.scrollback = 0;+ self.gap(Kind::Meta);+ self.push(Line::styled(text.to_string(), Style::new().dim()));+ }++ fn flush_assistant(&mut self) {+ let text = self.assistant_buf.trim_end().to_string();+ self.assistant_buf.clear();+ if text.is_empty() {+ return;+ }+ let lines = format_assistant_lines(&text, self.render_width());+ if lines.is_empty() {+ return;+ }+ self.gap(Kind::Prose);+ self.transcript.extend(lines);+ }++ /// Queue a user message: record it in history and the transcript, and ask+ /// the loop to start a run. Flips to `Running` synchronously so further keys+ /// in the same input batch can't slip through as a second submit.+ fn submit_user(&mut self, text: String) {+ self.history+ .push(serde_json::json!({ "role": "user", "content": text }));+ self.gap(Kind::User);+ self.push(Line::from(vec![+ Span::styled("› ", Style::new().light_magenta().bold()),+ Span::styled(text, Style::new().bold()),+ ]));+ self.status = Status::Running;+ self.turn = (0, 0);+ self.scrollback = 0;+ self.want_start = true;+ self.persist();+ }++ fn body(&self) -> serde_json::Value {+ serde_json::json!({+ "model": self.model,+ "messages": self.history,+ "max_turns": self.max_turns,+ "stream": true,+ })+ }++ /// Save the conversation to a thread on disk so it survives and appears in+ /// `/resume`. Fire-and-forget: failures surface in the status detail only.+ fn persist(&mut self) {+ if self.history.is_empty() {+ return;+ }+ match super::cli_save_thread(+ &self.agent_dir,+ self.thread_id.as_deref(),+ &self.model,+ &self.history,+ ) {+ Ok(id) => self.thread_id = Some(id),+ Err(e) => self.detail = format!("save failed: {e}"),+ }+ }++ /// Switch the active model and remember it in the project's agent.toml so it+ /// persists across sessions.+ fn set_model(&mut self, model: String) {+ self.model = model;+ match super::cli_set_project_model(&self.agent_dir, &self.model) {+ Ok(()) => self.note(&format!("model set to {}", self.model)),+ Err(e) => self.note(&format!("model set to {} (not saved: {e})", self.model)),+ }+ }++ /// Non-terminal stream events. `Done`/`Error` are handled by the loop since+ /// they mutate history and the run handle.+ fn apply(&mut self, ev: StreamEvent) {+ match ev {+ StreamEvent::Token { text } => self.assistant_buf.push_str(&text),+ StreamEvent::Step { index, max } => {+ // Turn progress lives in the header statusline, not the transcript.+ self.flush_assistant();+ self.turn = (index, max);+ }+ StreamEvent::ToolCall { name, args, .. } => {+ self.flush_assistant();+ self.gap(Kind::Tool);+ let max = self.render_width().saturating_sub(6) as usize;+ let label = truncate(&format_tool_call(&name, &args), max);+ self.push(Line::from(vec![+ Span::styled("│ ", Style::new().dark_gray()),+ Span::styled("▸ ", Style::new().cyan()),+ Span::styled(label, Style::new().cyan().dim()),+ ]));+ }+ StreamEvent::ToolResult {+ content, is_error, ..+ } => {+ self.flush_assistant();+ self.gap(Kind::Tool);+ let (tag, tag_style) = if is_error {+ ("✗", Style::new().red())+ } else {+ ("✓", Style::new().green())+ };+ let max = self.render_width().saturating_sub(8) as usize;+ self.push(Line::from(vec![+ Span::styled("│ ", Style::new().dark_gray()),+ Span::styled(format!("{tag} "), tag_style),+ Span::styled(summarize_result(&content, max), Style::new().dim()),+ ]));+ }+ StreamEvent::PermissionRequest {+ request_id,+ tool_name,+ capability,+ path,+ command,+ offers_always,+ ..+ } => {+ self.pending = Some(Pending {+ request_id,+ tool_name,+ capability,+ path,+ command,+ offers_always,+ selected: 0,+ });+ }+ StreamEvent::Done { .. } | StreamEvent::Error { .. } => {}+ }+ }++ /// Flush the current turn and return its text as the final assistant answer.+ fn take_answer(&mut self) -> String {+ let answer = self.assistant_buf.trim().to_string();+ self.flush_assistant();+ answer+ }++ fn on_done(&mut self, stop_reason: String, usage: Option<Usage>) {+ let answer = self.take_answer();+ if !answer.is_empty() {+ self.history+ .push(serde_json::json!({ "role": "assistant", "content": answer }));+ }+ self.tokens = usage.and_then(|u| u.total_tokens).unwrap_or(self.tokens);+ self.status = Status::Idle;+ self.detail = format!("stop_reason={stop_reason}");+ self.scrollback = 0;+ self.persist();+ }++ fn on_error(&mut self, code: String, message: String) {+ self.flush_assistant();+ self.status = Status::Idle;+ self.detail = if message.contains("budget") {+ format!("budget exhausted: {message}")+ } else {+ format!("{code}: {message}")+ };+ self.gap(Kind::Meta);+ self.push(Line::styled(+ format!("error: {message}"),+ Style::new().red().bold(),+ ));+ self.scrollback = 0;+ }++ /// Cancel the in-flight run, keeping the conversation intact.+ fn cancel_run(&mut self) {+ self.assistant_buf.clear();+ self.status = Status::Idle;+ self.detail = "cancelled".to_string();+ self.scrollback = 0;+ self.gap(Kind::Meta);+ self.push(Line::styled("cancelled", Style::new().yellow()));+ }+}++/// Truncate to `max` chars with a trailing ellipsis (char-safe).+fn truncate(s: &str, max: usize) -> String {+ if s.chars().count() <= max.max(1) {+ return s.to_string();+ }+ let head: String = s.chars().take(max.saturating_sub(1).max(1)).collect();+ format!("{head}…")+}++/// Summarize tool output to one transcript line: first non-empty line with its+/// internal whitespace collapsed, truncated to `max`, plus a `(+N lines)`+/// suffix when more follow.+fn summarize_result(s: &str, max: usize) -> String {+ let mut lines = s.lines().filter(|l| !l.trim().is_empty());+ let first = lines.next().unwrap_or("");+ let collapsed = first.split_whitespace().collect::<Vec<_>>().join(" ");+ let extra = lines.count();+ let head = truncate(&collapsed, max);+ if extra > 0 {+ format!("{head} (+{extra} lines)")+ } else {+ head+ }+}++/// Human-facing label for a tool call: known tools get a clean verb+target,+/// everything else falls back to the shared `describe_tool_call`.+fn format_tool_call(name: &str, args: &serde_json::Value) -> String {+ let s = |k: &str| args.get(k).and_then(|v| v.as_str()).unwrap_or("");+ match name {+ "bash" | "shell" | "exec" => {+ let cmd = s("command");+ if cmd.is_empty() {+ describe_tool_call(name, args)+ } else {+ format!("$ {}", cmd.replace('\n', " "))+ }+ }+ "read" => format!("read {}", s("path")),+ "write" => format!("write {}", s("path")),+ "edit" => format!("edit {}", s("path")),+ "list" | "ls" => format!("ls {}", s("path")),+ "grep" | "search" => {+ let pat = s("pattern");+ let path = s("path");+ if path.is_empty() {+ format!("grep \"{pat}\"")+ } else {+ format!("grep \"{pat}\" in {path}")+ }+ }+ _ => describe_tool_call(name, args),+ }+}++fn think_re() -> &'static regex::Regex {+ static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();+ RE.get_or_init(|| regex::Regex::new(r"</?[a-zA-Z:]*think>").unwrap())+}++/// Split assistant text into `(is_reasoning, segment)` runs by `<think>` /+/// `<mm:think>` tags (tags themselves dropped). An unterminated open tag makes+/// the trailing text reasoning, which keeps live streaming clean.+fn split_reasoning(text: &str) -> Vec<(bool, String)> {+ let mut out = Vec::new();+ let mut in_think = false;+ let mut last = 0;+ for m in think_re().find_iter(text) {+ let seg = &text[last..m.start()];+ if !seg.is_empty() {+ out.push((in_think, seg.to_string()));+ }+ in_think = !m.as_str().starts_with("</");+ last = m.end();+ }+ let seg = &text[last..];+ if !seg.is_empty() {+ out.push((in_think, seg.to_string()));+ }+ out+}++/// Render assistant text to styled lines: reasoning dimmed, answer prose passed+/// through markdown formatting. `width` bounds table wrapping.+fn format_assistant_lines(text: &str, width: u16) -> Vec<Line<'static>> {+ let mut lines = Vec::new();+ for (reasoning, seg) in split_reasoning(text) {+ if reasoning {+ for l in seg.lines() {+ if !l.trim().is_empty() {+ lines.push(Line::styled(l.to_string(), Style::new().dim().italic()));+ }+ }+ } else {+ lines.extend(format_markdown_lines(&seg, width));+ }+ }+ lines+}++fn table_cells(line: &str) -> Vec<String> {+ line.trim()+ .trim_matches('|')+ .split('|')+ .map(|c| c.trim().to_string())+ .collect()+}++/// A `|---|:--:|` markdown table separator row.+fn is_table_separator(line: &str) -> bool {+ let body = line.trim().trim_matches('|');+ !body.is_empty()+ && body.split('|').all(|c| {+ let c = c.trim();+ !c.is_empty() && c.contains('-') && c.chars().all(|ch| matches!(ch, '-' | ':' | ' '))+ })+}++/// Render answer prose: GitHub pipe tables are aligned into padded columns by+/// `render_table` (tui-markdown does not support tables); every other block is+/// rendered by `tui-markdown` (headings, bold/italic, lists, code, quotes).+fn format_markdown_lines(text: &str, width: u16) -> Vec<Line<'static>> {+ let src: Vec<&str> = text.lines().collect();+ let mut out = Vec::new();+ let mut prose: Vec<&str> = Vec::new();+ let mut i = 0;+ while i < src.len() {+ let is_table_head =+ src[i].contains('|') && i + 1 < src.len() && is_table_separator(src[i + 1]);+ if is_table_head {+ flush_prose(&mut prose, &mut out);+ let header = table_cells(src[i]);+ let mut rows = Vec::new();+ i += 2;+ while i < src.len() && src[i].contains('|') && !src[i].trim().is_empty() {+ rows.push(table_cells(src[i]));+ i += 1;+ }+ out.extend(render_table(&header, &rows, width));+ } else {+ prose.push(src[i]);+ i += 1;+ }+ }+ flush_prose(&mut prose, &mut out);+ out+}++fn flush_prose(prose: &mut Vec<&str>, out: &mut Vec<Line<'static>>) {+ if prose.is_empty() {+ return;+ }+ out.extend(markdown_to_lines(&prose.join("\n")));+ prose.clear();+}++/// Render a markdown block to owned ratatui lines via `tui-markdown`.+fn markdown_to_lines(text: &str) -> Vec<Line<'static>> {+ tui_markdown::from_str(text)+ .lines+ .into_iter()+ .map(own_line)+ .collect()+}++/// Deep-clone a borrowed `Line` into a `'static` one (own each span's text).+fn own_line(line: Line<'_>) -> Line<'static> {+ let spans: Vec<Span<'static>> = line+ .spans+ .into_iter()+ .map(|s| Span::styled(s.content.into_owned(), s.style))+ .collect();+ let mut owned = Line::from(spans);+ owned.style = line.style;+ owned.alignment = line.alignment;+ owned+}++/// Strip the inline markdown markers that would otherwise show as literal text+/// inside table cells (comfy-table renders plain text).+fn strip_inline_md(s: &str) -> String {+ s.replace("**", "").replace("__", "").replace('`', "")+}++/// Render a markdown table via comfy-table: `Dynamic` arrangement wraps long+/// cells within their column and keeps the whole table within `width`, fixing+/// the overflow/separator-wrap failure of naive padding. Border rows are dimmed.+fn render_table(header: &[String], rows: &[Vec<String>], width: u16) -> Vec<Line<'static>> {+ use comfy_table::{ContentArrangement, Table};++ let mut table = Table::new();+ table+ .load_preset(comfy_table::presets::UTF8_FULL)+ .set_content_arrangement(ContentArrangement::Dynamic)+ .set_width(width.max(20))+ .set_header(header.iter().map(|c| strip_inline_md(c)));+ for r in rows {+ table.add_row(r.iter().map(|c| strip_inline_md(c)));+ }++ table+ .to_string()+ .lines()+ .map(|l| {+ let is_border = !l.chars().any(|c| c.is_alphanumeric());+ if is_border {+ Line::styled(l.to_string(), Style::new().dim())+ } else {+ Line::raw(l.to_string())+ }+ })+ .collect()+}++fn spawn_run(args: &Arc<OrchestrationArgs>, body: serde_json::Value) -> CurrentRun {+ let (tx, rx) = mpsc::unbounded_channel::<StreamEvent>();+ let args = Arc::clone(args);+ let handle = tokio::spawn(async move {+ let _ = run_orchestration_streamed(&tx, &body, &args).await;+ });+ CurrentRun { rx, handle }+}++/// Await the next event of the active run, or park forever when idle.+async fn next_event(current: &mut Option<CurrentRun>) -> Option<StreamEvent> {+ match current {+ Some(c) => c.rx.recv().await,+ None => pending().await,+ }+}++pub async fn run(+ session: AgentSession,+ agent_dir: std::path::PathBuf,+ initial_task: Option<String>,+) -> Result<(), String> {+ let AgentSession {+ args,+ permission_requests,+ model,+ max_turns,+ } = session;+ let args = Arc::new(args);++ enable_raw_mode().map_err(|e| e.to_string())?;+ let mut stdout = io::stdout();+ execute!(stdout, EnterAlternateScreen).map_err(|e| e.to_string())?;+ let backend = CrosstermBackend::new(stdout);+ let mut terminal = Terminal::new(backend).map_err(|e| e.to_string())?;++ let mut app = App::new(model, max_turns, agent_dir);+ let res = chat_loop(&mut terminal, &args, &permission_requests, &mut app, initial_task).await;++ let _ = disable_raw_mode();+ let _ = execute!(terminal.backend_mut(), LeaveAlternateScreen);+ let _ = terminal.show_cursor();+ res+}++async fn chat_loop<B: Backend>(+ terminal: &mut Terminal<B>,+ args: &Arc<OrchestrationArgs>,+ registry: &PermissionRegistry,+ app: &mut App,+ initial_task: Option<String>,+) -> Result<(), String> {+ let mut current: Option<CurrentRun> = None;+ let mut ticker = tokio::time::interval(Duration::from_millis(50));++ match initial_task {+ Some(task) if !task.trim().is_empty() => app.submit_user(task.trim().to_string()),+ _ => app.note("type a message to start, or /help for commands"),+ }++ while !app.should_quit {+ // Kick off a queued run once the previous one has cleared. `submit_user`+ // already flipped status to Running and reset the turn counter.+ if app.want_start && current.is_none() {+ app.want_start = false;+ current = Some(spawn_run(args, app.body()));+ }++ terminal+ .draw(|f| draw(f, app))+ .map_err(|e| e.to_string())?;++ tokio::select! {+ _ = ticker.tick() => {+ while event::poll(Duration::ZERO).unwrap_or(false) {+ if let Ok(Event::Key(key)) = event::read() {+ handle_key(app, key, registry, &mut current).await;+ }+ }+ }+ ev = next_event(&mut current) => match ev {+ Some(StreamEvent::Done { stop_reason, usage }) => {+ app.on_done(stop_reason, usage);+ current = None;+ }+ Some(StreamEvent::Error { code, message }) => {+ app.on_error(code, message);+ current = None;+ }+ Some(other) => app.apply(other),+ None => {+ // Stream closed without a terminal event (aborted task).+ app.pending = None;+ if app.status == Status::Running {+ app.status = Status::Idle;+ app.assistant_buf.clear();+ }+ current = None;+ }+ },+ }+ }++ if let Some(c) = current {+ c.handle.abort();+ }+ Ok(())+}++async fn handle_key(+ app: &mut App,+ key: KeyEvent,+ registry: &PermissionRegistry,+ current: &mut Option<CurrentRun>,+) {+ if key.kind != KeyEventKind::Press {+ return;+ }++ let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);+ let ctrl_c = ctrl && key.code == KeyCode::Char('c');+ let ctrl_d = ctrl && key.code == KeyCode::Char('d');++ // A pending permission prompt captures y/a/n; Ctrl-C cancels the run and+ // Ctrl-D quits, so it can't be wedged waiting on an unanswered prompt.+ if let Some(mut pending) = app.pending.take() {+ if ctrl_c || ctrl_d {+ deny(registry, &pending.request_id).await;+ abort_run(current);+ if ctrl_d {+ app.should_quit = true;+ } else {+ app.cancel_run();+ }+ return;+ }+ let decision = match key.code {+ KeyCode::Up => {+ pending.move_selection(-1);+ None+ }+ KeyCode::Down => {+ pending.move_selection(1);+ None+ }+ KeyCode::Enter => Some(pending.options()[pending.selected].0),+ KeyCode::Char('y') | KeyCode::Char('Y') => Some(PermissionDecision::AllowOnce),+ KeyCode::Char('a') | KeyCode::Char('A') if pending.offers_always => {+ Some(PermissionDecision::AllowAlways)+ }+ KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {+ Some(PermissionDecision::Deny)+ }+ _ => None,+ };+ match decision {+ Some(d) => {+ let verb = match d {+ PermissionDecision::AllowOnce => "allowed once",+ PermissionDecision::AllowAlways => "allowed always",+ PermissionDecision::Deny => "denied",+ };+ app.push(Line::styled(+ format!("• {verb}: {}", pending.summary()),+ Style::new().yellow(),+ ));+ if let Some(sender) = registry.lock().await.remove(&pending.request_id) {+ let _ = sender.send(d);+ }+ }+ None => app.pending = Some(pending),+ }+ return;+ }++ // Ctrl-D quits from anywhere; Ctrl-C cancels a run or quits when idle.+ if ctrl_d {+ abort_run(current);+ app.should_quit = true;+ return;+ }++ // The `/resume` picker owns navigation/Enter/Esc while it is open.+ if let Some(picker) = app.picker.as_mut() {+ match key.code {+ KeyCode::Up | KeyCode::Char('k') => {+ picker.selected = picker.selected.saturating_sub(1);+ }+ KeyCode::Down | KeyCode::Char('j') => {+ picker.selected = (picker.selected + 1).min(picker.items.len() - 1);+ }+ KeyCode::Enter => {+ let kind = picker.kind;+ let value = picker.items[picker.selected].value.clone();+ app.picker = None;+ match kind {+ PickerKind::ResumeThread => resume_thread(app, &value),+ PickerKind::SelectModel => app.set_model(value),+ }+ }+ KeyCode::Esc | KeyCode::Char('q') if !ctrl => {+ app.picker = None;+ app.note("resume cancelled");+ }+ _ if ctrl_c => {+ app.picker = None;+ app.note("resume cancelled");+ }+ _ => {}+ }+ return;+ }+ if ctrl_c {+ if app.status == Status::Running {+ abort_run(current);+ app.cancel_run();+ } else {+ app.should_quit = true;+ }+ return;+ }++ match key.code {+ KeyCode::Esc => {+ if app.status == Status::Running {+ abort_run(current);+ app.cancel_run();+ } else if !app.input.is_empty() {+ app.input.clear();+ } else {+ app.should_quit = true;+ }+ }+ KeyCode::Enter => {+ if app.status == Status::Idle {+ let text = app.input.trim().to_string();+ app.input.clear();+ if let Some(cmd) = text.strip_prefix('/') {+ run_command(app, cmd).await;+ } else if !text.is_empty() {+ app.submit_user(text);+ }+ }+ }+ KeyCode::Backspace if app.status == Status::Idle => {+ app.input.pop();+ }+ KeyCode::Char(c) if app.status == Status::Idle && !ctrl => {+ app.input.push(c);+ }+ KeyCode::Up | KeyCode::PageUp => {+ let step = if key.code == KeyCode::PageUp { 10 } else { 1 };+ app.scrollback = app.scrollback.saturating_add(step);+ }+ KeyCode::Down | KeyCode::PageDown => {+ let step = if key.code == KeyCode::PageDown { 10 } else { 1 };+ app.scrollback = app.scrollback.saturating_sub(step);+ }+ _ => {}+ }+}++async fn deny(registry: &PermissionRegistry, request_id: &str) {+ if let Some(sender) = registry.lock().await.remove(request_id) {+ let _ = sender.send(PermissionDecision::Deny);+ }+}++fn abort_run(current: &mut Option<CurrentRun>) {+ if let Some(c) = current.take() {+ c.handle.abort();+ }+}++/// Split a command line into `(name, arg)`, UTF-8 safe (no byte slicing).+fn parse_command(line: &str) -> (&str, &str) {+ match line.trim().split_once(char::is_whitespace) {+ Some((n, rest)) => (n, rest.trim()),+ None => (line.trim(), ""),+ }+}++/// Execute a `/command` typed into the input box. Runs only while idle.+async fn run_command(app: &mut App, line: &str) {+ let (name, arg) = parse_command(line);+ match name {+ "" | "help" | "?" => {+ app.gap(Kind::Meta);+ for l in [+ "commands:",+ " /help show this help",+ " /clear clear the conversation",+ " /threads list saved threads",+ " /resume [id] pick a saved thread to load (or pass an id)",+ " /model [id] pick a provider/model (or pass an id)",+ " /quit exit",+ ] {+ app.push(Line::styled(l.to_string(), Style::new().dim()));+ }+ }+ "clear" => {+ app.history.clear();+ app.thread_id = None;+ app.transcript.clear();+ app.assistant_buf.clear();+ app.pending = None;+ app.tokens = 0;+ app.turn = (0, 0);+ app.detail.clear();+ app.scrollback = 0;+ app.last_kind = Kind::None;+ app.note("conversation cleared");+ }+ "threads" | "list" => match super::list_threads_in(&app.agent_dir) {+ Ok(threads) if threads.is_empty() => {+ app.note("no saved threads found");+ }+ Ok(mut threads) => {+ sort_threads_recent(&mut threads);+ let base = app.agent_dir.clone();+ app.gap(Kind::Meta);+ app.push(Line::styled(+ format!("{} saved thread(s):", threads.len()),+ Style::new().dim(),+ ));+ for t in &threads {+ let id = t.get("id").and_then(|v| v.as_str()).unwrap_or("?");+ let title =+ thread_display_name(&base, id, t.get("title").and_then(|v| v.as_str()));+ let short: String = id.chars().take(8).collect();+ app.push(Line::from(vec![+ Span::styled(format!(" {short} "), Style::new().cyan()),+ Span::raw(title),+ ]));+ }+ app.push(Line::styled(+ "resume with /resume".to_string(),+ Style::new().dim(),+ ));+ }+ Err(e) => app.note(&format!("failed to list threads: {e}")),+ },+ "resume" => {+ if arg.is_empty() {+ open_thread_picker(app);+ } else {+ resume_thread(app, arg);+ }+ }+ "model" => {+ if arg.is_empty() {+ open_model_picker(app);+ } else {+ app.set_model(arg.to_string());+ }+ }+ "quit" | "exit" => app.should_quit = true,+ other => app.note(&format!("unknown command '/{other}' (try /help)")),+ }+}++/// Display name for a saved thread: its summarized `title` when present, else a+/// snippet of the last user message (so untitled threads still show content),+/// else `(untitled)`.+fn thread_display_name(base: &std::path::Path, id: &str, title: Option<&str>) -> String {+ if let Some(t) = title.map(str::trim).filter(|s| !s.is_empty()) {+ return t.to_string();+ }+ if let Ok(messages) = super::cli_list_messages_in(base, id) {+ if let Some(last_user) = messages+ .iter()+ .rev()+ .find(|m| m.get("role").and_then(|v| v.as_str()) == Some("user"))+ {+ let collapsed = message_text(last_user)+ .split_whitespace()+ .collect::<Vec<_>>()+ .join(" ");+ if !collapsed.is_empty() {+ return truncate(&collapsed, 60);+ }+ }+ }+ "(untitled)".to_string()+}++/// Recency sort key for a saved thread (`updated`, falling back to `created`).+fn thread_recency(t: &serde_json::Value) -> f64 {+ t.get("updated")+ .or_else(|| t.get("created"))+ .and_then(|v| v.as_f64())+ .unwrap_or(0.0)+}++/// Sort threads most-recent-first (by `updated`/`created`).+fn sort_threads_recent(threads: &mut [serde_json::Value]) {+ threads.sort_by(|a, b| {+ thread_recency(b)+ .partial_cmp(&thread_recency(a))+ .unwrap_or(std::cmp::Ordering::Equal)+ });+}++/// Load saved threads and open the interactive picker (Enter selects). Falls+/// back to a note when there is nothing to resume.+fn open_thread_picker(app: &mut App) {+ match super::list_threads_in(&app.agent_dir) {+ Ok(threads) if threads.is_empty() => app.note("no saved threads found"),+ Ok(mut threads) => {+ sort_threads_recent(&mut threads);+ let base = app.agent_dir.clone();+ let items = threads+ .iter()+ .filter_map(|t| {+ let id = t.get("id").and_then(|v| v.as_str())?.to_string();+ let label =+ thread_display_name(&base, &id, t.get("title").and_then(|v| v.as_str()));+ let hint = Some(id.chars().take(8).collect());+ Some(PickerItem { value: id, label, hint })+ })+ .collect::<Vec<_>>();+ if items.is_empty() {+ app.note("no saved threads found");+ } else {+ app.picker = Some(Picker {+ kind: PickerKind::ResumeThread,+ items,+ selected: 0,+ });+ }+ }+ Err(e) => app.note(&format!("failed to list threads: {e}")),+ }+}++/// Open the `/model` selector listing `provider / model` pairs from the desktop+/// store, with the current model pre-highlighted.+fn open_model_picker(app: &mut App) {+ let pairs = super::providers::list_provider_models();+ if pairs.is_empty() {+ return app.note("no models available (configure a provider in the desktop app)");+ }+ let selected = pairs.iter().position(|(_, m)| *m == app.model).unwrap_or(0);+ let items = pairs+ .into_iter()+ .map(|(provider, model)| PickerItem {+ label: format!("{provider} / {model}"),+ value: model,+ hint: None,+ })+ .collect();+ app.picker = Some(Picker {+ kind: PickerKind::SelectModel,+ items,+ selected,+ });+}++/// Resolve a thread by id (exact or unique prefix), load its messages into the+/// conversation history, and render them into the transcript.+fn resume_thread(app: &mut App, id_arg: &str) {+ let threads = match super::list_threads_in(&app.agent_dir) {+ Ok(t) => t,+ Err(e) => return app.note(&format!("failed to list threads: {e}")),+ };+ let matches: Vec<&serde_json::Value> = threads+ .iter()+ .filter(|t| {+ t.get("id")+ .and_then(|v| v.as_str())+ .is_some_and(|full| full == id_arg || full.starts_with(id_arg))+ })+ .collect();+ let thread = match matches.as_slice() {+ [] => return app.note(&format!("no thread matches '{id_arg}'")),+ [t] => *t,+ _ => return app.note(&format!("'{id_arg}' is ambiguous ({} matches)", matches.len())),+ };+ let full_id = thread.get("id").and_then(|v| v.as_str()).unwrap_or_default();++ let messages = match super::cli_list_messages_in(&app.agent_dir, full_id) {+ Ok(m) => m,+ Err(e) => return app.note(&format!("failed to load messages: {e}")),+ };++ app.history.clear();+ app.thread_id = Some(full_id.to_string());+ app.transcript.clear();+ app.assistant_buf.clear();+ app.turn = (0, 0);+ app.tokens = 0;+ app.scrollback = 0;++ // Adopt the thread's model so continuation stays coherent.+ if let Some(model) = thread+ .get("model")+ .and_then(|m| m.get("id"))+ .and_then(|v| v.as_str())+ {+ app.model = model.to_string();+ }++ let width = app.render_width();+ let mut count = 0;+ for msg in &messages {+ let role = msg.get("role").and_then(|v| v.as_str()).unwrap_or("");+ let text = message_text(msg);+ if text.is_empty() || !matches!(role, "user" | "assistant") {+ continue;+ }+ app.history+ .push(serde_json::json!({ "role": role, "content": text }));+ if role == "user" {+ app.gap(Kind::User);+ app.push(Line::from(vec![+ Span::styled("› ", Style::new().light_magenta().bold()),+ Span::styled(text, Style::new().bold()),+ ]));+ } else {+ let lines = format_assistant_lines(&text, width);+ if lines.is_empty() {+ continue;+ }+ app.gap(Kind::Prose);+ app.transcript.extend(lines);+ }+ count += 1;+ }++ let title = thread+ .get("title")+ .and_then(|v| v.as_str())+ .filter(|s| !s.is_empty())+ .unwrap_or("(untitled)");+ app.note(&format!("resumed \"{title}\" ({count} messages)"));+}++/// Extract plain text from a stored thread message (`content` is an array of+/// `{type,text:{value}}` parts, or occasionally a bare string).+fn message_text(msg: &serde_json::Value) -> String {+ match msg.get("content") {+ Some(serde_json::Value::String(s)) => s.clone(),+ Some(serde_json::Value::Array(parts)) => parts+ .iter()+ .filter_map(|p| {+ p.get("text")+ .and_then(|t| t.get("value"))+ .and_then(|v| v.as_str())+ .or_else(|| p.get("text").and_then(|t| t.as_str()))+ .or_else(|| p.as_str())+ })+ .collect::<Vec<_>>()+ .join(""),+ _ => String::new(),+ }+}++fn draw(f: &mut Frame, app: &mut App) {+ let chunks = Layout::vertical([+ Constraint::Length(1),+ Constraint::Min(1),+ Constraint::Length(3),+ Constraint::Length(1),+ ])+ .split(f.area());++ f.render_widget(header(app), chunks[0]);++ // Top/bottom borders only, so wrapping uses the full width; the two border+ // rows reduce the vertical viewport. Cache the width so flushed tables wrap.+ let width = chunks[1].width.max(1);+ app.view_width = width;++ if let Some(picker) = &app.picker {+ draw_picker(f, chunks[1], picker);+ f.render_widget(input_box(app), chunks[2]);+ f.render_widget(footer(app), chunks[3]);+ return;+ }++ let mut lines = app.transcript.clone();+ if !app.assistant_buf.is_empty() {+ // Live tail: strip reasoning tags so partial streaming stays clean.+ lines.extend(format_assistant_lines(&app.assistant_buf, width));+ }+ let body = Paragraph::new(lines)+ .wrap(Wrap { trim: false })+ .block(Block::default().borders(Borders::TOP | Borders::BOTTOM));+ let inner_h = chunks[1].height.saturating_sub(2);+ let total = body.line_count(width).min(u16::MAX as usize) as u16;+ let max_back = total.saturating_sub(inner_h);+ app.scrollback = app.scrollback.min(max_back);+ let scroll = max_back - app.scrollback;+ f.render_widget(body.scroll((scroll, 0)), chunks[1]);++ f.render_widget(input_box(app), chunks[2]);+ f.render_widget(footer(app), chunks[3]);++ // Dock the permission prompt directly above the input box, growing upward+ // and clamped to the body area so it never overruns the transcript.+ if let Some(pending) = &app.pending {+ let detail_rows = 1 + u16::from(pending.path.is_some() || pending.command.is_some());+ let height = (pending.options().len() as u16 + detail_rows + 2).min(chunks[1].height);+ let y = chunks[2].y.saturating_sub(height).max(chunks[1].y);+ let rect = ratatui::layout::Rect {+ x: chunks[2].x,+ y,+ width: chunks[2].width,+ height,+ };+ draw_permission(f, rect, pending);+ }+}++/// Permission prompt docked above the input: names the tool, capability, and+/// target path, then an arrow-navigable option list (Enter confirms the+/// highlighted choice; `y`/`a`/`n` still work as shortcuts).+fn draw_permission(f: &mut Frame, area: ratatui::layout::Rect, pending: &Pending) {+ use ratatui::widgets::{Clear, List, ListItem, ListState};++ let dim = Style::new().dark_gray();+ let mut detail = vec![Line::from(vec![+ Span::styled(pending.tool_name.clone(), Style::new().cyan().bold()),+ Span::styled(" wants ", dim),+ Span::styled(pending.capability.clone(), Style::new().yellow().bold()),+ ])];+ if let Some(command) = &pending.command {+ detail.push(Line::from(vec![+ Span::styled("$ ", dim),+ Span::styled(command.clone(), Style::new().white()),+ ]));+ } else if let Some(path) = &pending.path {+ detail.push(Line::from(vec![+ Span::styled("on ", dim),+ Span::styled(path.clone(), Style::new().white()),+ ]));+ }++ let block = Block::default()+ .borders(Borders::ALL)+ .border_style(Style::new().yellow())+ .title(Span::styled(+ " permission required ",+ Style::new().on_yellow().black().bold(),+ ));+ let inner = block.inner(area);+ f.render_widget(Clear, area);+ f.render_widget(block, area);++ let rows = Layout::vertical([+ Constraint::Length(detail.len() as u16),+ Constraint::Min(1),+ ])+ .split(inner);+ f.render_widget(Paragraph::new(detail).wrap(Wrap { trim: false }), rows[0]);++ let items: Vec<ListItem> = pending+ .options()+ .into_iter()+ .map(|(_, label)| ListItem::new(Line::raw(label)))+ .collect();+ let list = List::new(items)+ .highlight_style(Style::new().reversed().bold())+ .highlight_symbol("▶ ");+ let mut state = ListState::default();+ state.select(Some(pending.selected));+ f.render_stateful_widget(list, rows[1], &mut state);+}++fn draw_picker(f: &mut Frame, area: ratatui::layout::Rect, picker: &Picker) {+ use ratatui::widgets::{List, ListItem, ListState};++ let items: Vec<ListItem> = picker+ .items+ .iter()+ .map(|it| {+ let mut spans = Vec::new();+ if let Some(hint) = &it.hint {+ spans.push(Span::styled(format!("{hint} "), Style::new().dark_gray()));+ }+ spans.push(Span::raw(it.label.clone()));+ ListItem::new(Line::from(spans))+ })+ .collect();+ let list = List::new(items)+ .block(Block::default().borders(Borders::ALL).title(picker.title()))+ .highlight_style(Style::new().reversed())+ .highlight_symbol("▶ ");+ let mut state = ListState::default();+ state.select(Some(picker.selected));+ f.render_stateful_widget(list, area, &mut state);+}++fn header(app: &App) -> Paragraph<'static> {+ let (status, style) = match app.status {+ Status::Idle => ("ready", Style::new().green()),+ Status::Running => ("working", Style::new().yellow().bold()),+ };+ let turn = if app.turn.1 > 0 {+ format!("turn {}/{} ", app.turn.0, app.turn.1)+ } else {+ String::new()+ };+ Paragraph::new(Line::from(vec![+ Span::styled(" jan agent ", Style::new().on_blue().white().bold()),+ Span::raw(format!(" {} {turn}tokens {} ", app.model, app.tokens)),+ Span::styled(format!("[{status}]"), style),+ ]))+}++fn input_box(app: &App) -> Paragraph<'static> {+ let block = Block::default().borders(Borders::ALL).title(" message ");+ if app.picker.is_some() {+ Paragraph::new(Line::styled("selecting…", Style::new().dim().italic())).block(block)+ } else if app.status == Status::Running {+ Paragraph::new(Line::styled(+ "working… (Esc to cancel)",+ Style::new().dim().italic(),+ ))+ .block(block)+ } else {+ Paragraph::new(Line::from(vec![+ Span::styled("› ", Style::new().cyan().bold()),+ Span::raw(format!("{}▏", app.input)),+ ]))+ .block(block)+ }+}++fn footer(app: &App) -> Paragraph<'static> {+ if app.pending.is_some() {+ return Paragraph::new(Line::styled(+ " ↑/↓ select Enter confirm Esc deny Ctrl-C cancel",+ Style::new().yellow().dim(),+ ));+ }+ if let Some(picker) = &app.picker {+ return Paragraph::new(Line::styled(picker.action_hint(), Style::new().dim()));+ }+ let hint = match app.status {+ Status::Running => "Esc/Ctrl-C cancel ↑/↓ scroll",+ Status::Idle => "Enter send /help commands ↑/↓ scroll Ctrl-D quit",+ };+ let detail = if app.detail.is_empty() {+ String::new()+ } else {+ format!(" {}", app.detail)+ };+ Paragraph::new(Line::styled(format!(" {hint}{detail}"), Style::new().dim()))+}++#[cfg(test)]+mod tests {+ use super::{+ format_tool_call, is_table_separator, message_text, parse_command, render_table,+ split_reasoning, summarize_result, Pending,+ };+ use crate::core::agent::tools::gate::PermissionDecision;+ use serde_json::json;++ fn pending(offers_always: bool) -> Pending {+ Pending {+ request_id: "r".into(),+ tool_name: "bash".into(),+ capability: "execute".into(),+ path: None,+ command: Some("git status".into()),+ offers_always,+ selected: 0,+ }+ }++ #[test]+ fn always_label_is_command_scoped_for_exec() {+ assert_eq!(+ pending(true).always_label(),+ "Allow all 'git' commands (this thread)"+ );+ let mut p = pending(true);+ p.command = None;+ assert_eq!(p.always_label(), "Allow always (this thread)");+ }++ #[test]+ fn pending_options_include_always_only_when_offered() {+ assert_eq!(pending(false).options().len(), 2);+ let opts = pending(true).options();+ assert_eq!(opts.len(), 3);+ assert_eq!(opts[1].0, PermissionDecision::AllowAlways);+ }++ #[test]+ fn pending_selection_wraps_both_directions() {+ let mut p = pending(true); // 3 options+ p.move_selection(-1);+ assert_eq!(p.selected, 2);+ p.move_selection(1);+ assert_eq!(p.selected, 0);+ p.move_selection(1);+ assert_eq!(p.selected, 1);+ }++ #[test]+ fn split_reasoning_separates_think_blocks() {+ let segs = split_reasoning("before<think>hidden</think>after");+ assert_eq!(+ segs,+ vec![+ (false, "before".to_string()),+ (true, "hidden".to_string()),+ (false, "after".to_string()),+ ]+ );+ }++ #[test]+ fn split_reasoning_handles_namespaced_and_unterminated_tags() {+ let segs = split_reasoning("<mm:think>reasoning tail");+ assert_eq!(segs, vec![(true, "reasoning tail".to_string())]);+ }++ #[test]+ fn format_tool_call_bash_and_read() {+ assert_eq!(+ format_tool_call("bash", &json!({ "command": "ls src/ | head" })),+ "$ ls src/ | head"+ );+ assert_eq!(+ format_tool_call("read", &json!({ "path": "src/main.rs" })),+ "read src/main.rs"+ );+ assert_eq!(+ format_tool_call("grep", &json!({ "pattern": "foo", "path": "src/" })),+ "grep \"foo\" in src/"+ );+ }++ #[test]+ fn summarize_result_first_line_plus_count() {+ assert_eq!(summarize_result("only line", 80), "only line");+ assert_eq!(summarize_result("a\nb\nc", 80), "a (+2 lines)");+ assert_eq!(summarize_result(" \nreal\nx", 80), "real (+1 lines)");+ // Collapses internal whitespace runs (e.g. columnar grep output).+ assert_eq!(summarize_result("a b\tc", 80), "a b c");+ // Truncates the head to max.+ assert_eq!(summarize_result("abcdefgh", 4), "abc…");+ }++ #[test]+ fn sort_threads_recent_orders_newest_first() {+ let mut threads = vec![+ json!({ "id": "a", "updated": 100.0 }),+ json!({ "id": "b", "updated": 300.0 }),+ json!({ "id": "c", "created": 200.0 }),+ json!({ "id": "d" }),+ ];+ super::sort_threads_recent(&mut threads);+ let ids: Vec<&str> = threads.iter().map(|t| t["id"].as_str().unwrap()).collect();+ assert_eq!(ids, ["b", "c", "a", "d"]);+ }++ #[test]+ fn thread_display_name_prefers_title() {+ let base = std::path::Path::new("/nonexistent");+ assert_eq!(super::thread_display_name(base, "id", Some("My Title")), "My Title");+ assert_eq!(super::thread_display_name(base, "id", Some(" padded ")), "padded");+ }++ #[test]+ fn truncate_is_char_safe() {+ assert_eq!(super::truncate("héllo wörld", 5), "héll…");+ assert_eq!(super::truncate("short", 20), "short");+ }++ #[test]+ fn table_separator_detection() {+ assert!(is_table_separator("|---|:--:|"));+ assert!(is_table_separator(" --- | --- "));+ assert!(!is_table_separator("| a | b |"));+ assert!(!is_table_separator("plain text"));+ }++ #[test]+ fn markdown_renders_bold_and_keeps_text() {+ // tui-markdown should strip the ** markers and keep the word.+ let lines = super::markdown_to_lines("hello **world**");+ let text: String = lines+ .iter()+ .flat_map(|l| l.spans.iter())+ .map(|s| s.content.as_ref())+ .collect();+ assert!(text.contains("hello"), "got {text:?}");+ assert!(text.contains("world"), "got {text:?}");+ assert!(!text.contains("**"), "markers not stripped: {text:?}");+ }++ fn joined(lines: &[ratatui::text::Line]) -> String {+ lines+ .iter()+ .flat_map(|l| l.spans.iter())+ .map(|s| s.content.as_ref())+ .collect()+ }++ #[test]+ fn format_markdown_routes_table_through_comfy_table() {+ let md = "| a | b |\n|---|---|\n| 1 | 2 |";+ let lines = super::format_markdown_lines(md, 40);+ let text = joined(&lines);+ // No raw markdown pipes; cell content preserved; wrapped within width.+ assert!(text.contains('a') && text.contains('b') && text.contains('1'));+ assert!(lines.iter().all(|l| joined(std::slice::from_ref(l)).chars().count() <= 40));+ }++ #[test]+ fn render_table_wraps_and_strips_inline_md() {+ let header = vec!["name".to_string(), "note".to_string()];+ let rows = vec![vec![+ "**apple**".to_string(),+ "a `very` long note that must wrap across several lines".to_string(),+ ]];+ let lines = render_table(&header, &rows, 30);+ let text = joined(&lines);+ assert!(text.contains("apple") && !text.contains('*'), "md not stripped: {text:?}");+ assert!(!text.contains('`'), "backticks not stripped: {text:?}");+ // Dynamic wrapping keeps every rendered row within the target width.+ assert!(lines.iter().all(|l| joined(std::slice::from_ref(l)).chars().count() <= 30));+ }++ #[test]+ fn parse_command_splits_name_and_arg() {+ assert_eq!(parse_command("resume abc123"), ("resume", "abc123"));+ assert_eq!(parse_command("help"), ("help", ""));+ assert_eq!(parse_command(" resume abc "), ("resume", "abc"));+ assert_eq!(parse_command(""), ("", ""));+ }++ #[test]+ fn parse_command_handles_multibyte_without_panic() {+ // Leading space + multibyte would panic under byte slicing.+ assert_eq!(parse_command(" résumé foo"), ("résumé", "foo"));+ assert_eq!(parse_command("café"), ("café", ""));+ }++ #[test]+ fn message_text_extracts_content_parts() {+ let msg = json!({+ "role": "user",+ "content": [{ "type": "text", "text": { "value": "hello", "annotations": [] } }]+ });+ assert_eq!(message_text(&msg), "hello");+ }++ #[test]+ fn message_text_joins_multiple_parts_and_handles_string() {+ let multi = json!({ "content": [+ { "text": { "value": "a" } },+ { "text": { "value": "b" } },+ ] });+ assert_eq!(message_text(&multi), "ab");+ let bare = json!({ "content": "plain" });+ assert_eq!(message_text(&bare), "plain");+ let empty = json!({ "role": "user" });+ assert_eq!(message_text(&empty), "");+ }+}