Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): let the agent read images, and polish the TUI brand (#8729)
Akarshan Biswasa338c0325c80
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 595497a61..9e847a9ad 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -7245,6 +7245,7 @@ dependencies = [name = "tauri-plugin-agent-tools"version = "0.8.3"dependencies = [+ "base64 0.22.1","glob","ignore","nix 0.30.1",diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.tomlindex 9134c3162..77bafcc46 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml+++ b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml@@ -18,6 +18,7 @@ default = ["tauri"]tauri = ["dep:tauri", "dep:tauri-plugin"][dependencies]+base64 = "0.22"glob = "0.3"ignore = "0.4"regex = "1"diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex 869f82c9a..c1f54f3fe 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -352,7 +352,7 @@ pub async fn execute_tool(.with_confined_writes(true).with_mask_root(Path::new(&data_folder)).with_scratch_root(&scratch);- let (content, diff) = handlers::execute_builtin_with_diff(tool, &args, &ctx).await;+ let (content, diff, _images) = handlers::execute_builtin_with_diff(tool, &args, &ctx).await;let is_error =content.starts_with("ERROR") || (name == "bash" && handlers::bash_result_failed(&content));Ok(ToolResult {diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rsindex e7c8c5e0b..9d934190b 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs@@ -19,10 +19,15 @@ use crate::tools::sandbox::{escapes_project, in_scratch, is_hidden_jan_path, lexical_normalize, resolve_path,scratch_display_path, symlink_escapes_root,};-use crate::tools::{BuiltinTool, ToolContext};+use crate::tools::{BuiltinTool, ImageContentPart, ToolContext};const MAX_BYTES: usize = 64 * 1024;const MAX_LINES: usize = 2000;+/// Cap on a `read` image payload returned as an `image_url` content part.+/// Mirrors the TUI's `MAX_IMAGE_BYTES` so an oversized raster (or a large+/// text file whose name ends in an image extension) cannot flood the model+/// context as a base64 blob.+const MAX_IMAGE_BYTES: usize = 20 * 1024 * 1024;/// bash output caps: generous enough that typical command output reaches the/// model intact on a large-context run, spilling to a temp file only past this.const BASH_MAX_BYTES: usize = 256 * 1024;@@ -119,17 +124,31 @@ fn collapse_carriage_returns(s: &str) -> String {out}-/// Execute a built-in tool. Returns the tool-result text. Errors are returned-/// as a String STARTING WITH "ERROR" rather than as Err.+/// Execute a built-in tool. Returns the tool-result text plus, for a `read` of+/// an image file, the base64 `image_url` content parts the model needs to see+/// the image. Errors are returned as a String STARTING WITH "ERROR" rather than+/// as Err.pub async fn execute_builtin(tool: &BuiltinTool,args: &serde_json::Value,ctx: &ToolContext<'_>,-) -> String {+) -> (String, Option<Vec<ImageContentPart>>) {let project_root = ctx.project_root;let scratch = ctx.scratch_root;- match tool.name {+ let (content, images) = match tool.name {"read" => read(args, project_root, scratch).await,+ _ => (execute_text(tool, args, ctx).await, None),+ };+ (content, images)+}++/// The text result for every tool except `read`. Split out so `read` can also+/// return image parts without duplicating the remaining tool dispatch.+async fn execute_text(tool: &BuiltinTool, args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {+ let project_root = ctx.project_root;+ let scratch = ctx.scratch_root;+ match tool.name {+ "read" => read(args, project_root, scratch).await.0,"ls" => ls(args, project_root, scratch, ctx.sandbox).await,"write" => write(args, project_root, scratch, ctx.confine_writes).await,"edit" => edit(args, project_root, scratch, ctx.confine_writes).await,@@ -211,17 +230,21 @@ pub async fn execute_builtin_with_diff(tool: &BuiltinTool,args: &serde_json::Value,ctx: &ToolContext<'_>,-) -> (String, Option<String>) {+) -> (String, Option<String>, Option<Vec<ImageContentPart>>) {match tool.name {"write" | "edit" => {let diff = preview_diff(tool, args, ctx).await;- let content = execute_builtin(tool, args, ctx).await;+ let (content, images) = execute_builtin(tool, args, ctx).await;if content.starts_with("ERROR") {- return (content, None);+ return (content, None, None);}- (content, diff)+ (content, diff, images)}- _ => (execute_builtin(tool, args, ctx).await, None),+ "read" => {+ let (content, images) = execute_builtin(tool, args, ctx).await;+ (content, None, images)+ }+ _ => (execute_builtin(tool, args, ctx).await.0, None, None),}}@@ -453,9 +476,13 @@ async fn memory_write(args: &serde_json::Value, store: &Path) -> String {}}-async fn read(args: &serde_json::Value, root: &Path, scratch: Option<&Path>) -> String {+async fn read(+ args: &serde_json::Value,+ root: &Path,+ scratch: Option<&Path>,+) -> (String, Option<Vec<ImageContentPart>>) {let Some(path) = arg_str(args, "path") else {- return "ERROR: missing required argument 'path'".to_string();+ return ("ERROR: missing required argument 'path'".to_string(), None);};let offset = arg_u64(args, "offset").map(|v| v as usize);let limit = arg_u64(args, "limit").map(|v| v as usize);@@ -463,26 +490,55 @@ async fn read(args: &serde_json::Value, root: &Path, scratch: Option<&Path>) ->// Fail closed: a component swapped to a symlink after the gate validated// the path must not redirect the open out of the workspace.if symlink_escapes_root(root, scratch, &target) {- return format!("ERROR: refused to read through a symlink out of the workspace: {path}");+ return (+ format!("ERROR: refused to read through a symlink out of the workspace: {path}"),+ None,+ );}let bytes = match tokio::fs::read(&target).await {Ok(b) => b,- Err(e) => return format!("ERROR: {e}"),+ Err(e) => return (format!("ERROR: {e}"), None),};++ // An image file is returned as an OpenAI `image_url` content part rather+ // than text: the model cannot see a raster through a base64 string. Only a+ // plain read (no offset/limit) does this, since slicing an image makes no+ // sense and offset/limit still refers to text lines.+ if offset.is_none() && limit.is_none() && bytes.len() <= MAX_IMAGE_BYTES {+ if let Some(mime) = crate::tools::image::detect(&target) {+ use base64::Engine;+ let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);+ let name = target+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("image")+ .to_string();+ let note = format!("Read image {name} ({mime}, {} bytes)", bytes.len());+ let image = ImageContentPart {+ data_url: format!("data:{mime};base64,{b64}"),+ name,+ };+ return (note, Some(vec![image]));+ }+ }+let content = match String::from_utf8(bytes) {Ok(c) => c,- Err(_) => return "ERROR: not a UTF-8 text file".to_string(),+ Err(_) => return ("ERROR: not a UTF-8 text file".to_string(), None),};let selected = if offset.is_some() || limit.is_some() {let lines: Vec<&str> = content.split('\n').collect();let start = offset.map(|o| o.saturating_sub(1)).unwrap_or(0);if start >= lines.len() {- return format!(- "ERROR: offset {} is beyond end of file ({} lines total)",- offset.unwrap_or(1),- lines.len()+ return (+ format!(+ "ERROR: offset {} is beyond end of file ({} lines total)",+ offset.unwrap_or(1),+ lines.len()+ ),+ None,);}let end = match limit {@@ -494,11 +550,14 @@ async fn read(args: &serde_json::Value, root: &Path, scratch: Option<&Path>) ->content};- cap_output(- &selected,- MAX_LINES,- MAX_BYTES,- "\n[truncated: use offset/limit to read more]",+ (+ cap_output(+ &selected,+ MAX_LINES,+ MAX_BYTES,+ "\n[truncated: use offset/limit to read more]",+ ),+ None,)}@@ -1285,7 +1344,9 @@ mod tests {// `workspace` and `commands`.async fn execute_builtin(tool: &BuiltinTool, args: &serde_json::Value, root: &Path) -> String {let store = crate::workspace::project_store(root);- super::execute_builtin(tool, args, &ToolContext::new(root, &store, &[])).await+ super::execute_builtin(tool, args, &ToolContext::new(root, &store, &[]))+ .await+ .0}async fn execute_builtin_with_diff(@@ -1294,7 +1355,9 @@ mod tests {root: &Path,) -> (String, Option<String>) {let store = crate::workspace::project_store(root);- super::execute_builtin_with_diff(tool, args, &ToolContext::new(root, &store, &[])).await+ let (content, diff, _images) =+ super::execute_builtin_with_diff(tool, args, &ToolContext::new(root, &store, &[])).await;+ (content, diff)}async fn preview_diff(@@ -1348,6 +1411,81 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ #[tokio::test]+ async fn read_returns_image_payload_for_a_png() {+ let root = unique_root();+ // Minimal valid PNG signature suffices for detection; the payload is+ // what the tool validates, not a decodable image.+ let bytes: Vec<u8> = vec![+ 0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48,+ 0x44, 0x52,+ ];+ std::fs::write(root.join("pic.png"), &bytes).unwrap();+ let (content, images) = super::execute_builtin(+ lookup("read").unwrap(),+ &json!({"path": "pic.png"}),+ &ToolContext::new(&root, &crate::workspace::project_store(&root), &[]),+ )+ .await;+ assert!(content.contains("image/png"), "note: {content}");+ let img = images.expect("an image read must return image parts");+ assert_eq!(img.len(), 1);+ assert_eq!(img[0].name, "pic.png");+ assert!(img[0].data_url.starts_with("data:image/png;base64,"));+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn read_extension_fallback_catches_a_misnamed_image() {+ let root = unique_root();+ // No valid signature header, but the extension says PNG: the extension+ // fallback still returns an image payload.+ std::fs::write(root.join("scanned.png"), b"not a real png").unwrap();+ let (content, images) = super::execute_builtin(+ lookup("read").unwrap(),+ &json!({"path": "scanned.png"}),+ &ToolContext::new(&root, &crate::workspace::project_store(&root), &[]),+ )+ .await;+ assert!(!content.starts_with("ERROR"), "got: {content}");+ assert!(images.is_some(), "extension-matching png must yield an image");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn read_image_with_offset_falls_back_to_text_error() {+ let root = unique_root();+ let bytes: Vec<u8> = vec![0x89, b'P', b'N', b'G'];+ std::fs::write(root.join("pic.png"), &bytes).unwrap();+ let out = execute_builtin(+ lookup("read").unwrap(),+ &json!({"path": "pic.png", "offset": 1, "limit": 1}),+ &root,+ )+ .await;+ assert!(out.starts_with("ERROR"), "slicing an image must not render: {out}");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn read_image_over_cap_falls_back_to_text_error() {+ let root = unique_root();+ // Valid PNG signature but far larger than MAX_IMAGE_BYTES: the size+ // gate must refuse to base64-dump it into model context.+ let mut bytes: Vec<u8> = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];+ bytes.resize(MAX_IMAGE_BYTES + 1, 0u8);+ std::fs::write(root.join("huge.png"), &bytes).unwrap();+ let (content, images) = super::execute_builtin(+ lookup("read").unwrap(),+ &json!({"path": "huge.png"}),+ &ToolContext::new(&root, &crate::workspace::project_store(&root), &[]),+ )+ .await;+ assert!(images.is_none(), "an over-cap image must not yield image parts");+ assert!(content.starts_with("ERROR"), "got: {content}");+ let _ = std::fs::remove_dir_all(&root);+ }+#[tokio::test]async fn write_then_read_roundtrips() {let root = unique_root();@@ -1766,7 +1904,7 @@ mod tests {&json!({"path": "../escape.txt", "content": "x"}),&ctx,)- .await;+ .await.0;assert!(out.starts_with("ERROR: refused to write outside"), "got: {out}");assert!(!root.parent().unwrap().join("escape.txt").exists());@@ -1775,7 +1913,7 @@ mod tests {&json!({"path": "../escape.txt", "edits": [{"old_string": "a", "new_string": "b"}]}),&ctx,)- .await;+ .await.0;assert!(out.starts_with("ERROR: refused to edit outside"), "got: {out}");let _ = std::fs::remove_dir_all(&root);}@@ -1822,7 +1960,7 @@ mod tests {&json!({"pattern": "*.txt", "path": "/tmp"}),&ctx,)- .await;+ .await.0;assert!(!out.contains("secret.txt"),"walked out of the scratch through a symlink: {out}"@@ -1944,7 +2082,7 @@ mod tests {&json!({"path": "/tmp/esc/pwned.txt", "content": "x"}),&ctx,)- .await;+ .await.0;assert!(out.starts_with("ERROR"), "must be refused, got: {out}");assert!(!outside.join("pwned.txt").exists(),@@ -2027,7 +2165,7 @@ mod tests {&json!({"path": "/tmp/scratch.txt", "content": "persist"}),&ctx,)- .await;+ .await.0;assert!(out.starts_with("Created /tmp/scratch.txt"), "got: {out}");assert!(scratch.join("scratch.txt").exists(), "wrote into scratch");@@ -2036,7 +2174,7 @@ mod tests {&json!({"path": "/tmp/scratch.txt"}),&ctx,)- .await;+ .await.0;assert_eq!(out, "persist");// No stray file on the real host /tmp.@@ -2194,7 +2332,7 @@ mod tests {std::fs::write(root.join("src.rs"), b"x").unwrap();let store = crate::workspace::project_store(&root);let ctx = ToolContext::new(&root, &store, &[]).with_sandbox(false);- let out = super::execute_builtin(lookup("ls").unwrap(), &json!({}), &ctx).await;+ let out = super::execute_builtin(lookup("ls").unwrap(), &json!({}), &ctx).await.0;assert!(out.contains("src.rs"), "unexpected: {out}");assert!(out.contains(".jan/"), "must list .jan when unconfined: {out}");let _ = std::fs::remove_dir_all(&root);@@ -2575,7 +2713,7 @@ mod tests {&json!({"command": "for i in $(seq 1 16000); do printf '%064d\\n' \"$i\"; done"}),&ctx,)- .await;+ .await.0;let path = out.rsplit("full output written to ").next()@@ -2592,7 +2730,7 @@ mod tests {&json!({"path": path, "offset": 15999, "limit": 1}),&ctx,)- .await;+ .await.0;assert!(full.contains("015999") || full.contains("016000"),"spill at {path} must be readable back: {full}"@@ -2615,7 +2753,7 @@ mod tests {&json!({"command": "echo unconfined"}),&ctx,)- .await;+ .await.0;assert!(out.contains("unconfined"), "unsandboxed bash did not run: {out}");assert!(!out.contains("no OS sandbox could be established"),@@ -2829,20 +2967,20 @@ mod tests {let store = crate::workspace::project_store(&root);let ctx = ToolContext::new(&root, &store, &enabled);- let list = super::execute_builtin(lookup("skill_list").unwrap(), &json!({}), &ctx).await;+ let list = super::execute_builtin(lookup("skill_list").unwrap(), &json!({}), &ctx).await.0;assert!(list.contains("on"), "list: {list}");assert!(!list.contains("off body"), "disabled skill leaked: {list}");// Disabled skill is unreadable.let read_off =super::execute_builtin(lookup("skill_read").unwrap(), &json!({"name": "off"}), &ctx)- .await;+ .await.0;assert!(read_off.starts_with("ERROR"), "disabled read: {read_off}");// Enabled skill still readable.let read_on =super::execute_builtin(lookup("skill_read").unwrap(), &json!({"name": "on"}), &ctx)- .await;+ .await.0;assert_eq!(read_on, "on body");// A disabled skill is read-only for the model: writing to it is refused@@ -2852,14 +2990,14 @@ mod tests {&json!({"name": "off", "content": "evil body"}),&ctx,)- .await;+ .await.0;assert!(write_off.starts_with("ERROR"),"disabled write: {write_off}");let r =super::execute_builtin(lookup("skill_read").unwrap(), &json!({"name": "off"}), &ctx)- .await;+ .await.0;assert!(r.starts_with("ERROR"), "still disabled after write");let _ = std::fs::remove_dir_all(&root);}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/image.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/image.rsnew file mode 100644index 000000000..1ac88e1ef--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/image.rs@@ -0,0 +1,78 @@+//! Image detection for the `read` tool: a file whose bytes are a recognized+//! raster image (or, failing that, whose extension names one) is returned as an+//! OpenAI `image_url` content part instead of a text read. Detection prefers the+//! file signature so a misnamed image still renders, falling back to the+//! extension so an unusual-but-valid file is still picked up.++/// The MIME type inferred for a byte prefix, or `None` when the bytes do not+/// match a supported image signature. Mirrors the TUI's accepted set+/// (`image_mime_of`): png, jpeg, gif, webp.+pub fn mime_from_signature(bytes: &[u8]) -> Option<&'static str> {+ if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {+ return Some("image/png");+ }+ if bytes.starts_with(b"\xff\xd8\xff") {+ return Some("image/jpeg");+ }+ if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {+ return Some("image/gif");+ }+ // WebP: "RIFF" + 4 bytes size + "WEBP".+ if bytes.starts_with(b"RIFF") && bytes.len() >= 12 && &bytes[8..12] == b"WEBP" {+ return Some("image/webp");+ }+ None+}++/// The MIME type for a known image file extension, or `None`.+pub fn mime_from_extension(path: &std::path::Path) -> Option<&'static str> {+ let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();+ match ext.as_str() {+ "png" => Some("image/png"),+ "jpg" | "jpeg" => Some("image/jpeg"),+ "gif" => Some("image/gif"),+ "webp" => Some("image/webp"),+ _ => None,+ }+}++/// The MIME type of the image at `path`, decided by file signature first and+/// extension second. `None` when neither identifies a supported image.+pub fn detect(path: &std::path::Path) -> Option<&'static str> {+ let bytes = std::fs::read(path).ok()?;+ mime_from_signature(&bytes).or_else(|| mime_from_extension(path))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn signature_recognizes_each_supported_format() {+ assert_eq!(mime_from_signature(b"\x89PNG\r\n\x1a\nrest"), Some("image/png"));+ assert_eq!(mime_from_signature(b"\xff\xd8\xffrest"), Some("image/jpeg"));+ assert_eq!(mime_from_signature(b"GIF89a rest"), Some("image/gif"));+ assert_eq!(mime_from_signature(b"GIF87a rest"), Some("image/gif"));+ assert_eq!(+ mime_from_signature(b"RIFF\x00\x00\x00\x00WEBPrest"),+ Some("image/webp")+ );+ assert_eq!(mime_from_signature(b"plain text"), None);+ }++ #[test]+ fn webp_requires_the_webp_fourcc() {+ assert_eq!(mime_from_signature(b"RIFF\x00\x00\x00\x00WAVErest"), None);+ assert_eq!(mime_from_signature(b"RIFF"), None);+ }++ #[test]+ fn extension_is_case_insensitive_and_unknown_is_none() {+ assert_eq!(mime_from_extension(std::path::Path::new("a.PNG")), Some("image/png"));+ assert_eq!(mime_from_extension(std::path::Path::new("a.jpeg")), Some("image/jpeg"));+ assert_eq!(mime_from_extension(std::path::Path::new("a.jpg")), Some("image/jpeg"));+ assert_eq!(mime_from_extension(std::path::Path::new("a.webp")), Some("image/webp"));+ assert_eq!(mime_from_extension(std::path::Path::new("a.pdf")), None);+ assert_eq!(mime_from_extension(std::path::Path::new("noext")), None);+ }+}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rsindex 62e19cee4..50f3842c5 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs@@ -9,6 +9,7 @@ pub mod appcontainer;pub mod cmdscan;pub mod gate;pub mod handlers;+pub mod image;pub mod jail;pub mod proc;/// Path containment for the filesystem tools. Distinct from [`jail`], which is@@ -17,6 +18,18 @@ pub mod sandbox;pub mod schema;pub mod web;+/// A single OpenAI `image_url` content part: the `data:<mime>;base64,<bytes>`+/// URL plus a display name. This is what the `read` tool returns for an image+/// file, and the agent loop threads into the tool-result message so a vision+/// model sees the image.+#[derive(Debug, Clone, serde::Serialize)]+pub struct ImageContentPart {+ /// `data:image/png;base64,...` URL, ready to embed in an `image_url` part.+ pub data_url: String,+ /// Basename shown to the model and in the transcript.+ pub name: String,+}+/// Ambient context a tool call executes against.////// The two roots are separate because they have different lifetimes.diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rsindex 246d1fc45..7df6ed50f 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs@@ -11,7 +11,7 @@ pub fn builtin_tool_schemas() -> Vec<Value> {"type": "function","function": {"name": "read",- "description": "Read the contents of a UTF-8 text file. Output is truncated to 2000 lines or 64KB (whichever is hit first). Use offset/limit for large files.",+ "description": "Read the contents of a UTF-8 text file. Output is truncated to 2000 lines or 64KB (whichever is hit first). Use offset/limit for large files. Image files (png/jpeg/gif/webp, detected by signature or extension) are returned as a vision image instead of text.","parameters": {"type": "object","properties": {diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 75b69c601..a650ffb2d 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -117,11 +117,15 @@ pub(crate) trait ModelInvoker: Send + Sync {}/// One tool call's outcome: `content` is the model-facing result string,-/// `diff` is display-only focused-change text (`write`/`edit` only).+/// `diff` is display-only focused-change text (`write`/`edit` only). `images`+/// carries OpenAI `image_url` content parts for a `read` of an image file; when+/// present, the result is emitted as a multimodal `tool` message with these+/// parts (plus `content` as a text part) instead of plain text.pub(crate) struct ToolOutcome {pub id: String,pub content: String,pub diff: Option<String>,+ pub images: Vec<tauri_plugin_agent_tools::tools::ImageContentPart>,}impl ToolOutcome {@@ -130,6 +134,7 @@ impl ToolOutcome {id,content,diff: None,+ images: Vec::new(),}}}@@ -839,19 +844,23 @@ impl ToolInvoker for CompositeToolInvoker {.with_home_readonly(allow_home_read).with_sandbox(sandbox).with_scratch_root(&scratch);- let (text, diff) = execute_builtin_with_diff(tool, &args, &ctx).await;+ let (text, diff, images) =+ execute_builtin_with_diff(tool, &args, &ctx).await;ToolOutcome {id,content: text,diff,+ images: images.unwrap_or_default(),}});continue;}- let (text, diff) = match decision {- Decision::Allow => execute_builtin_with_diff(tool, &args, &self.tool_context()).await,+ let (text, diff, images) = match decision {+ Decision::Allow => {+ execute_builtin_with_diff(tool, &args, &self.tool_context()).await+ }Decision::HardDeny(reason) => {- (hard_deny_msg(name, reason, &self.project_root), None)+ (hard_deny_msg(name, reason, &self.project_root), None, None)}Decision::Prompt(kind) => {let request_id = next_permission_id();@@ -919,7 +928,7 @@ impl ToolInvoker for CompositeToolInvoker {execute_builtin_with_diff(tool, &args, &self.tool_context()).await}PermissionDecision::Deny => {- (format!("ERROR: tool '{name}' denied by user"), None)+ (format!("ERROR: tool '{name}' denied by user"), None, None)}}}@@ -928,6 +937,7 @@ impl ToolInvoker for CompositeToolInvoker {id,content: text,diff,+ images: images.unwrap_or_default(),});}if !read_futures.is_empty() {@@ -1931,14 +1941,14 @@ async fn run_turn_cycle("role": "assistant","content": final_text,}));- conversation_messages.push(serde_json::json!({- "role": "user",- "content": format!(+ crate::core::agent::reminder::attach(+ &mut conversation_messages,+ &format!("Before you stop: these todos are still open:\n{summary}\n\nFor each \one you actually completed, call `todo` with `done` now (or `drop` if \you skipped it). If work genuinely remains, continue it instead."),- }));+ );turn += 1;continue;}@@ -2092,7 +2102,12 @@ async fn run_turn_cycle(// what else ran alongside it.let mut todo_touched_this_batch = false;for outcome in tool_results {- let ToolOutcome { id, content, diff } = outcome;+ let ToolOutcome {+ id,+ content,+ diff,+ images,+ } = outcome;// A `bash` call that exits non-zero isn't prefixed "ERROR" (that// convention is reserved for hard tool failures the model must// treat as errors), but its failed exit marker still flags the@@ -2110,12 +2125,31 @@ async fn run_turn_cycle(id: id.clone(),content: content.clone(),is_error,- diff,+ diff: diff.clone(),});+ // A `read` of an image carries OpenAI `image_url` content parts; the+ // tool message is then a content-part array (text note first, the+ // image parts after) so a vision model sees the image. Other results+ // stay plain text, preserving the standard tool protocol.+ let wire_content = if images.is_empty() {+ serde_json::Value::String(content.clone())+ } else {+ let mut parts = vec![serde_json::json!({+ "type": "text",+ "text": content.clone(),+ })];+ for img in &images {+ parts.push(serde_json::json!({+ "type": "image_url",+ "image_url": { "url": img.data_url, "detail": "auto" },+ }));+ }+ serde_json::Value::Array(parts)+ };conversation_messages.push(serde_json::json!({"role": "tool","tool_call_id": id,- "content": content+ "content": wire_content}));}if todo_touched_this_batch {@@ -2145,14 +2179,14 @@ async fn run_turn_cycle(mutations_since_todo_touch = 0;mid_run_nudge_count += 1;let plural = if open_count == 1 { "" } else { "s" };- conversation_messages.push(serde_json::json!({- "role": "user",- "content": format!(+ crate::core::agent::reminder::attach(+ &mut conversation_messages,+ &format!("Reminder: {open_count} todo item{plural} still open. If you finished a \task since the last todo update, mark it done now so progress stays \visible; otherwise just keep working."- )- }));+ ),+ );}}turn += 1;@@ -2393,6 +2427,82 @@ mod tests {assert!(saw_tool_call && saw_tool_result);}+ /// Reads the tool message the loop wrote into the next request's+ /// conversation. The image case must land there as an OpenAI content-part+ /// array (text note + `image_url`) rather than a plain string, or the+ /// vision model never sees the image.+ #[tokio::test]+ async fn image_tool_result_is_emitted_as_a_multimodal_tool_message() {+ let (tx, _rx) = mpsc::unbounded_channel();+ let model = MockModel::new(vec![+ tool_call_completion(),+ json!({ "choices": [{ "message": { "content": "final answer" }, "finish_reason": "stop" }] }),+ ]);+ struct ImageTool;+ #[async_trait]+ impl ToolInvoker for ImageTool {+ async fn invoke(+ &self,+ tool_calls: &[serde_json::Value],+ ) -> Result<Vec<ToolOutcome>, String> {+ Ok(tool_calls+ .iter()+ .map(|tc| {+ let id = tc+ .get("id")+ .and_then(|v| v.as_str())+ .unwrap_or("")+ .to_string();+ ToolOutcome {+ id,+ content: "Read image pic.png (image/png, 10 bytes)".to_string(),+ diff: None,+ images: vec![tauri_plugin_agent_tools::tools::ImageContentPart {+ data_url: "data:image/png;base64,QUJD".to_string(),+ name: "pic.png".to_string(),+ }],+ }+ })+ .collect())+ }+ }+ let tool = ImageTool;+ let mut budget = SessionBudget::new(None);+ let convo = vec![json!({ "role": "user", "content": "hi" })];++ run_turn_cycle(+ &tx,+ &json!({}),+ "m",+ &[],+ convo,+ 8,+ &mut budget,+ &model,+ &tool,+ crate::core::agent::plan::RunMode::Normal,+ None,+ None,+ )+ .await+ .unwrap();++ let requests = model.requests.lock().unwrap();+ assert_eq!(requests.len(), 2, "tool call then final answer");+ let messages = requests[1]["messages"].as_array().unwrap();+ let tool_msg = messages+ .iter()+ .find(|m| m.get("role").and_then(|v| v.as_str()) == Some("tool"))+ .unwrap_or_else(|| panic!("no tool message: {messages:#?}"));+ assert_eq!(tool_msg["tool_call_id"], "call_1");+ let content = tool_msg["content"].as_array().unwrap();+ assert_eq!(content.len(), 2);+ assert_eq!(content[0]["type"], "text");+ assert_eq!(content[1]["type"], "image_url");+ assert_eq!(content[1]["image_url"]["url"], "data:image/png;base64,QUJD");+ assert_eq!(content[1]["image_url"]["detail"], "auto");+ }+#[tokio::test]async fn force_first_tool_only_applies_to_the_first_turn() {let (tx, _rx) = mpsc::unbounded_channel();diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rsindex 2470c21a7..888bf25e3 100644--- a/src-tauri/src/core/agent/mod.rs+++ b/src-tauri/src/core/agent/mod.rs@@ -24,6 +24,7 @@ pub mod plan;pub mod plugin_commands;pub mod plugins;pub mod project;+pub mod reminder;pub mod session;pub mod skill_hub;pub mod skills;diff --git a/src-tauri/src/core/agent/reminder.rs b/src-tauri/src/core/agent/reminder.rsnew file mode 100644index 000000000..6aecbeadb--- /dev/null+++ b/src-tauri/src/core/agent/reminder.rs@@ -0,0 +1,174 @@+//! Hidden guidance folded into an agent conversation (todo nudges and the+//! like). Two problems this module owns.+//!+//! It is marked with `<SYSTEM>` so the model can tell it from user-authored+//! text, and so the surfaces that enumerate user *turns* -- the rewind picker,+//! input recall, workspace checkpoints -- can skip a message that only exists+//! to carry a reminder. Those indices are shared with the display journal,+//! which never held the reminder, so an unmarked one drifted them out of step.+//!+//! And it is folded into the trailing message rather than pushed as its own+//! whenever that message is the user's own, unanswered. It is never folded into+//! a `tool` message: tool output is untrusted, so guidance appended there would+//! sit inside attacker-reachable text, and output that carried its own+//! `<SYSTEM>` block would be indistinguishable from a real reminder. A `system`+//! message is not an option either -- many models accept only one.++use serde_json::Value;++pub const OPEN_TAG: &str = "<SYSTEM>";+pub const CLOSE_TAG: &str = "</SYSTEM>";++pub fn wrap(text: &str) -> String {+ format!("{OPEN_TAG}\n{text}\n{CLOSE_TAG}")+}++/// Fold a reminder into `messages` so it reaches the model as late as possible+/// without inventing a turn. A trailing `user` message has not been answered+/// yet, so the marked text is appended to it in flight. Anything else trailing+/// -- an assistant turn, or a tool result the reminder must not be mixed into+/// -- means prompting another turn requires a `user` message of its own, so one+/// is pushed carrying the marked text alone, which `is_reminder_only` then+/// recognizes.+pub fn attach(messages: &mut Vec<Value>, text: &str) {+ let marked = wrap(text);+ let open = messages+ .last()+ .and_then(|m| m.get("role"))+ .and_then(|v| v.as_str())+ == Some("user");+ if open {+ let content = messages+ .last_mut()+ .expect("last() matched above")+ .get_mut("content");+ match content {+ Some(Value::String(s)) => {+ s.push_str("\n\n");+ s.push_str(&marked);+ return;+ }+ Some(Value::Array(parts)) => {+ parts.push(serde_json::json!({ "type": "text", "text": marked }));+ return;+ }+ _ => {}+ }+ }+ messages.push(serde_json::json!({ "role": "user", "content": marked }));+}++/// True when `text` is a reminder and nothing else, i.e. it was never typed by+/// the user. Text that merely had one appended is not one.+pub fn is_reminder_text(text: &str) -> bool {+ let text = text.trim();+ text.starts_with(OPEN_TAG) && text.ends_with(CLOSE_TAG)+}++/// Drop every reminder block from `text`, leaving what the user actually typed.+/// The display surfaces (input recall, rewind fill, transcript rebuild) go+/// through this, so an in-flight reminder never comes back as text to re-send.+pub fn strip(text: &str) -> String {+ let mut out = String::with_capacity(text.len());+ let mut rest = text;+ while let Some(start) = rest.find(OPEN_TAG) {+ out.push_str(&rest[..start]);+ rest = match rest[start..].find(CLOSE_TAG) {+ Some(end) => &rest[start + end + CLOSE_TAG.len()..],+ // Unterminated: nothing after the marker is user text either.+ None => "",+ };+ }+ out.push_str(rest);+ out.trim().to_string()+}++/// `is_reminder_text` over a wire `content` field. A content-part array is never+/// reminder-only: `attach` only ever adds a part to a message that had one.+pub fn is_reminder_only(content: &Value) -> bool {+ content.as_str().is_some_and(is_reminder_text)+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ /// Tool output is untrusted and may itself contain a `<SYSTEM>` block, so a+ /// reminder is never mixed into it -- it takes its own turn instead.+ #[test]+ fn a_trailing_tool_result_is_never_appended_to() {+ let mut messages = vec![+ json!({ "role": "user", "content": "do it" }),+ json!({ "role": "tool", "tool_call_id": "a", "content": "ok" }),+ ];+ attach(&mut messages, "keep going");+ assert_eq!(messages.len(), 3);+ assert_eq!(messages[1]["content"], json!("ok"));+ assert_eq!(messages[2]["role"], json!("user"));+ assert!(is_reminder_only(&messages[2]["content"]));+ }++ #[test]+ fn a_trailing_user_message_absorbs_the_reminder_in_flight() {+ let mut messages = vec![json!({ "role": "user", "content": "do it" })];+ attach(&mut messages, "keep going");+ assert_eq!(messages.len(), 1);+ assert!(messages[0]["content"]+ .as_str()+ .unwrap()+ .starts_with("do it\n\n"));+ assert!(!is_reminder_only(&messages[0]["content"]));+ }++ #[test]+ fn a_content_part_array_gains_a_text_part() {+ let mut messages = vec![json!({+ "role": "user",+ "content": [{ "type": "text", "text": "look" }],+ })];+ attach(&mut messages, "keep going");+ assert_eq!(messages.len(), 1);+ let parts = messages[0]["content"].as_array().unwrap();+ assert_eq!(parts.len(), 2);+ assert_eq!(parts[1]["text"], json!(wrap("keep going")));+ }++ #[test]+ fn a_trailing_assistant_message_gets_a_reminder_only_turn() {+ let mut messages = vec![+ json!({ "role": "user", "content": "do it" }),+ json!({ "role": "assistant", "content": "done" }),+ ];+ attach(&mut messages, "keep going");+ assert_eq!(messages.len(), 3);+ assert_eq!(messages[2]["role"], json!("user"));+ assert!(is_reminder_only(&messages[2]["content"]));+ }++ #[test]+ fn an_empty_conversation_gets_a_reminder_only_turn() {+ let mut messages = Vec::new();+ attach(&mut messages, "keep going");+ assert_eq!(messages.len(), 1);+ assert!(is_reminder_only(&messages[0]["content"]));+ }++ #[test]+ fn strip_leaves_only_what_the_user_typed() {+ assert_eq!(strip(&format!("first\n\n{}", wrap("nudge"))), "first");+ assert_eq!(strip(&wrap("nudge")), "");+ assert_eq!(strip("plain"), "plain");+ assert_eq!(strip("head <SYSTEM>a</SYSTEM> tail"), "head tail");+ assert_eq!(strip("head <SYSTEM>unterminated"), "head");+ }++ #[test]+ fn ordinary_text_is_not_a_reminder() {+ assert!(!is_reminder_only(&json!("hello")));+ assert!(!is_reminder_only(+ &json!([{ "type": "text", "text": "hi" }])+ ));+ assert!(!is_reminder_only(&Value::Null));+ }+}diff --git a/src-tauri/src/core/cli/brand.rs b/src-tauri/src/core/cli/brand.rsindex 9e28b7778..0d0f6cb55 100644--- a/src-tauri/src/core/cli/brand.rs+++ b/src-tauri/src/core/cli/brand.rs@@ -14,6 +14,61 @@ pub const LOGO: [&str; 6] = [pub const LOGO_WIDTH: u16 = 25;+/// The Jan hand-wave mark: the brand logo rendered above the wordmark in the+/// TUI splash, and repeatedly whenever a slash command starts a fresh view+/// (`/clear`, `/new`, `/resume`). Each glyph cell is one terminal column, so+/// `HAND_WIDTH` is the rendered width.+pub const HAND: [&str; 15] = [+ r" ██ ███ ",+ r" ███████████ ████ ",+ r" ███ ██ ██ ███ ██ ",+ r" ██ ███ ███ ███ ██ █ ",+ r" ██ ███ ██ ██ ███ ",+ r" ██ ███ ███ ███ ██ ██",+ r" █████ ███ ██ ████ ██",+ r" ██ ██ ██ ██ ██",+ r" ███ ███ █ ██",+ r" █ █ ██ ██ ██",+ r" ██ ██ ███ █ ",+ r" ██ ██ ██ ██ ",+ r" ████ ███ ███ ",+ r" ████ █████ ",+ r" ████████ ",+];++pub const HAND_WIDTH: u16 = 32;++/// The hand-wave mark as a single glyph, for the header's leading column where+/// the block art has no room. No VS16: the emoji is already presentation-default+/// and the extra selector makes some terminals advance a column ratatui has not+/// reserved, which shifts the rest of the row.+pub const WAVE: &str = "\u{1F44B}";++/// Columns between the hand mark and the wordmark in the lockup.+const LOCKUP_GAP: u16 = 2;++/// Rendered width of `lockup()`.+pub const LOCKUP_WIDTH: u16 = HAND_WIDTH + LOCKUP_GAP + LOGO_WIDTH;++/// The full brand lockup: the hand mark with the wordmark set beside it,+/// vertically centred against the hand. Lines are padded to `LOCKUP_WIDTH`.+pub fn lockup() -> Vec<String> {+ let gap = " ".repeat(LOCKUP_GAP as usize);+ let top = (HAND.len() - LOGO.len()) / 2;+ HAND.iter()+ .enumerate()+ .map(|(i, hand)| {+ let word = i+ .checked_sub(top)+ .and_then(|row| LOGO.get(row))+ .copied()+ .unwrap_or("");+ let pad = LOGO_WIDTH as usize - word.chars().count();+ format!("{hand}{gap}{word}{}", " ".repeat(pad))+ })+ .collect()+}+#[cfg(test)]mod tests {use super::*;@@ -28,4 +83,52 @@ mod tests {);}}++ #[test]+ fn every_hand_line_is_the_advertised_width() {+ for line in HAND {+ assert_eq!(+ line.chars().count(),+ HAND_WIDTH as usize,+ "ragged hand line: {line}"+ );+ }+ }++ #[test]+ fn every_lockup_line_is_the_advertised_width() {+ let lockup = lockup();+ assert_eq!(lockup.len(), HAND.len(), "the lockup is as tall as the hand");+ for line in &lockup {+ assert_eq!(+ line.chars().count(),+ LOCKUP_WIDTH as usize,+ "ragged lockup line: {line}"+ );+ }+ }++ /// Side by side, not stacked: the wordmark shares its rows with the hand,+ /// centred against it.+ #[test]+ fn the_wordmark_sits_beside_the_hand() {+ let lockup = lockup();+ let rows: Vec<usize> = lockup+ .iter()+ .enumerate()+ .filter(|(_, l)| l[..].contains(LOGO[0].trim()) || l.contains(LOGO[3].trim()))+ .map(|(i, _)| i)+ .collect();+ assert!(!rows.is_empty(), "wordmark missing from the lockup");+ for row in rows {+ let line = &lockup[row];+ let hand = HAND[row].trim();+ assert!(+ !hand.is_empty() && line.contains(hand),+ "row {row} must carry the hand too: {line}"+ );+ }+ let blank_above = lockup[0].chars().skip(HAND_WIDTH as usize).all(|c| c == ' ');+ assert!(blank_above, "the wordmark should be centred, not flush top");+ }}diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 01cba0983..bb83e2427 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -662,10 +662,11 @@ fn banner_lines(banner: &Banner, width: u16) -> Vec<Line<'static>> {let indent = " ".repeat(BANNER_INDENT as usize);let mut out: Vec<Line<'static>> = Vec::new();- // A clipped wordmark reads as breakage, so a narrow terminal gets the name- // as text instead.- if width >= brand::LOGO_WIDTH + BANNER_INDENT * 2 {- for art in brand::LOGO {+ // A clipped logo reads as breakage, so a narrow terminal gets the name+ // as text instead. The lockup (hand beside the wordmark) is the widest+ // splash element, so it sets the threshold that gates the whole block.+ if width >= brand::LOCKUP_WIDTH + BANNER_INDENT * 2 {+ for art in brand::lockup() {out.push(Line::styled(format!("{indent}{art}"), accent));}out.push(Line::raw(""));@@ -1217,6 +1218,10 @@ struct App {/// Orchestration handle for out-of-run model calls (the `/compact` command)./// `None` in unit tests, set by `run` for the live session.args: Option<Arc<OrchestrationArgs>>,+ /// The approval-mode phrasing used by the splash (e.g. "--safe: writes, ...").+ /// Captured once at startup so `/clear`, `/new` and `/resume` re-print the+ /// same branding without re-deriving it.+ approval_phrasing: String,/// Context window limit for the current model (default 128K).context_window: u64,/// Tokens to reserve for the model's response (compaction triggers at limit - reserve).@@ -1555,46 +1560,6 @@ const SPINNER: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "/// Milliseconds per spinner frame, decoupled from the 50ms render tick.const SPINNER_ADVANCE_MS: u64 = 80;-const HAND: &str = "👋\u{FE0F}";--fn hand_sweep_position(char_count: usize, frame: usize) -> usize {- let cycle = char_count.saturating_mul(2).max(1);- let step = frame % cycle;- if step <= char_count {- step- } else {- cycle - step- }-}--fn hand_sweep_line(word: &'static str, frame: usize, text_style: Style) -> Line<'static> {- let message = format!("{word}...");- let char_count = message.chars().count();- let position = hand_sweep_position(char_count, frame);- let start = message- .char_indices()- .nth(position)- .map_or(message.len(), |(byte, _)| byte);- let end = if position == char_count {- start- } else {- message- .char_indices()- .nth(position + 1)- .map_or(message.len(), |(byte, _)| byte)- };-- let mut spans = Vec::with_capacity(3);- if start > 0 {- spans.push(Span::styled(message[..start].to_string(), text_style));- }- spans.push(Span::styled(HAND, Style::new().cyan()));- if end < message.len() {- spans.push(Span::styled(message[end..].to_string(), text_style));- }- Line::from(spans)-}-/// Rotating action words for the running input placeholder, replacing a static/// "working…" so a long turn does not read as a hung UI.const WORKING_WORDS: [&str; 12] = [@@ -1750,6 +1715,7 @@ impl App {goal_eval_pending: false,run_mode: crate::core::agent::plan::RunMode::Normal,args: None,+ approval_phrasing: String::new(),context_window: limits.context_window,reserve_tokens: limits.reserve_tokens,max_tokens: limits.max_tokens,@@ -1960,8 +1926,8 @@ impl App {.map(|(_, lines)| lines)}- /// Open the session with the splash: the wordmark, this session's project- /// and approval mode, and where to go next.+ /// Open the session with the splash: the hand-wave logo and wordmark, this+ /// session's project and approval mode, and where to go next.fn push_banner(&mut self, tools: &str, awaiting_first_message: bool) {let banner = Banner {version: super::updater::build_version(),@@ -1977,8 +1943,17 @@ impl App {self.last_kind = Kind::None;}+ /// Push the splash using the startup approval phrasing, to re-brand the+ /// screen after a slash command opens a fresh view (`/clear`, `/new`,+ /// `/resume`). `awaiting_first_message` starts false once a thread is+ /// loaded or a task is seeded.+ fn push_session_banner(&mut self, awaiting_first_message: bool) {+ let phrasing = self.approval_phrasing.clone();+ self.push_banner(&phrasing, awaiting_first_message);+ }+/// Append a line the *app* is saying, in its own gutter column. Every other- /// transcript class owns one (`› ` user, `│ ` tool, `┊ ` reasoning), so+ /// transcript class owns one (`> ` user, `│ ` tool, `┊ ` reasoning), so/// without it a note is indistinguishable from model prose. `glyph` names the/// category and `level` carries severity.fn system_marked(&mut self, glyph: &'static str, level: Level, text: &str) {@@ -3140,10 +3115,11 @@ impl App {/// Inject a hidden todo reminder and continue with one more model turn. The/// reminder text enters the conversation (so the model sees it) but renders- /// as a dim system note, never a user-authored transcript row.+ /// as a dim system note, never a user-authored transcript row -- and is+ /// marked, so `is_user_turn` keeps it out of the rewind picker, recall and+ /// checkpoint keys.fn submit_reminder(&mut self, text: String) {- self.history- .push(serde_json::json!({ "role": "user", "content": text }));+ crate::core::agent::reminder::attach(&mut self.history, &text);self.note("todo reminder — unfinished work, continuing");self.begin_turn();self.want_start = true;@@ -3239,7 +3215,7 @@ impl App {// carries its own newlines, and a single `Line` renders those as blank// cells in one run-on row.self.push_row(RowKind::System {- glyph: "›",+ glyph: ">",cont: " ",gutter: Style::new().light_magenta().bold(),body: vec![Span::styled(text.to_string(), Style::new().bold())],@@ -3262,14 +3238,14 @@ impl App {fn push_invocation_label(&mut self, label: String) {self.gap(Kind::User);self.push_row(RowKind::System {- glyph: "›",+ glyph: ">",cont: " ",gutter: Style::new().light_magenta().bold(),body: vec![Span::styled(label, Style::new().cyan().bold())],});}- /// The `› [skill:foo] <args>` row a slash invocation commits. A `System`+ /// The `> [skill:foo] <args>` row a slash invocation commits. A `System`/// row for the same reason as `push_user_line`: `args` is user text and can/// arrive pasted and multi-line, which a single `Line` renders as blank/// cells in one run-on row.@@ -3282,7 +3258,7 @@ impl App {}self.gap(Kind::User);self.push_row(RowKind::System {- glyph: "›",+ glyph: ">",cont: " ",gutter: Style::new().light_magenta().bold(),body,@@ -3409,16 +3385,15 @@ impl App {let user_index = self.history.iter()- .filter(|m| m.get("role").and_then(|v| v.as_str()) == Some("user"))+ .filter(|m| is_user_turn(m)).count().saturating_sub(1);let preview = self.history.iter().rev()- .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()))- .map(truncate_preview)+ .find(|m| is_user_turn(m))+ .map(|m| truncate_preview(&user_content_parts(&m["content"]).0)).unwrap_or_default();self.snap_queue.push_back(SnapshotJob::Checkpoint {user_index,@@ -5969,15 +5944,13 @@ pub async fn run(let sandboxed = args.sandbox.unwrap_or_else(|| crate::core::agent::r#loop::effective_sandbox(&app.project_root));- app.push_banner(- match (args.auto_approve, sandboxed) {- (true, true) => "auto-approved inside the OS sandbox (start with --safe to be asked first)",- (true, false) => "auto-approved and unsandboxed: commands run with your own access (--safe to be asked first, --sandbox to confine)",- (false, true) => "--safe: writes, shell commands and MCP tool calls need approval",- (false, false) => "--safe: approval needed, but unsandboxed - what you approve runs with your own access (--sandbox to confine)",- },- !seeded,- );+ app.approval_phrasing = match (args.auto_approve, sandboxed) {+ (true, true) => "auto-approved inside the OS sandbox (start with --safe to be asked first)".to_string(),+ (true, false) => "auto-approved and unsandboxed: commands run with your own access (--safe to be asked first, --sandbox to confine)".to_string(),+ (false, true) => "--safe: writes, shell commands and MCP tool calls need approval".to_string(),+ (false, false) => "--safe: approval needed, but unsandboxed - what you approve runs with your own access (--sandbox to confine)".to_string(),+ };+ app.push_session_banner(!seeded);if app.model.is_empty() {app.note("not signed in — run /login to sign in to Tokamak, or `jan config set` to configure a provider manually");}@@ -7862,11 +7835,13 @@ async fn run_command(app: &mut App, line: &str) {"clear" => {app.reset_session();clear_todos(app).await;+ app.push_session_banner(true);app.note("conversation cleared");}"new" => {app.reset_session();clear_todos(app).await;+ app.push_session_banner(true);app.note("started a new session");}"compact" => compact_command(app),@@ -9546,11 +9521,10 @@ fn thread_display_name(base: &std::path::Path, id: &str, title: Option<&str>) ->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"))- {+ if let Some(last_user) = messages.iter().rev().find(|m| {+ m.get("role").and_then(|v| v.as_str()) == Some("user")+ && !crate::core::agent::reminder::is_reminder_text(&message_text(m))+ }) {let collapsed = message_text(last_user).split_whitespace().collect::<Vec<_>>()@@ -9950,11 +9924,11 @@ fn open_rewind_picker(app: &mut App) {let mut items = Vec::new();let mut ui = 0usize;for m in &app.history {- if m.get("role").and_then(|v| v.as_str()) == Some("user") {- let text = m.get("content").and_then(|v| v.as_str()).unwrap_or("");+ if is_user_turn(m) {+ let text = user_content_parts(&m["content"]).0;items.push(PickerItem {value: ui.to_string(),- label: truncate_preview(text),+ label: truncate_preview(&text),hint: Some(format!("#{}", ui + 1)),checkbox: None,});@@ -10006,7 +9980,7 @@ fn rewind_to(app: &mut App, target: usize, restore_workspace: bool) {let mut ui = 0usize;let mut cut = None;for (i, m) in app.history.iter().enumerate() {- if m.get("role").and_then(|v| v.as_str()) == Some("user") {+ if is_user_turn(m) {if ui == target {cut = Some(i);break;@@ -10078,7 +10052,7 @@ fn rebuild_recall(app: &mut App) {let texts: Vec<String> = app.history.iter()- .filter(|m| m.get("role").and_then(|v| v.as_str()) == Some("user"))+ .filter(|m| is_user_turn(m)).filter_map(|m| m.get("content")).map(|c| user_content_parts(c).0).filter(|t| !t.is_empty())@@ -10190,6 +10164,8 @@ fn rebuild_transcript(app: &mut App) {}async fn resume_thread(app: &mut App, id_arg: &str) {+ // Re-brand the fresh view before the saved conversation is replayed.+ app.push_session_banner(false);apply_resume(app, &ResumeTarget::Id(id_arg.to_string())).await;}@@ -10447,9 +10423,21 @@ fn build_user_message(text: &str, images: &[PendingImage]) -> serde_json::Value/// Split a user message's `content` into display text and one label per attached/// image. Handles plain-string content and the `image_url` content-part array;/// data-URL parts carry no filename, so their label is empty.+/// True for a `user` message the user actually authored. Hidden reminders ride+/// in on the `user` role but are not turns: a rewind target, a recall entry or a+/// checkpoint key built from one would be a row the user never typed, and would+/// shift every later index out of step with the display journal, which holds no+/// reminder at all.+fn is_user_turn(m: &serde_json::Value) -> bool {+ m.get("role").and_then(|v| v.as_str()) == Some("user")+ && !crate::core::agent::reminder::is_reminder_only(+ m.get("content").unwrap_or(&serde_json::Value::Null),+ )+}+fn user_content_parts(content: &serde_json::Value) -> (String, Vec<String>) {match content {- serde_json::Value::String(s) => (s.clone(), Vec::new()),+ serde_json::Value::String(s) => (crate::core::agent::reminder::strip(s), Vec::new()),serde_json::Value::Array(parts) => {let mut text = String::new();let mut images = Vec::new();@@ -10457,7 +10445,7 @@ fn user_content_parts(content: &serde_json::Value) -> (String, Vec<String>) {match p.get("type").and_then(|v| v.as_str()) {Some("text") => {if let Some(t) = p.get("text").and_then(|v| v.as_str()) {- text.push_str(t);+ text.push_str(&crate::core::agent::reminder::strip(t));}}Some("image_url") => images.push(String::new()),@@ -10603,7 +10591,7 @@ fn draw(f: &mut Frame, app: &mut App) {app.row_index.clear();let toml_path = app.agent_dir.join("agent.toml");draw_picker(f, chunks[1], picker, &toml_path);- f.render_widget(input_box(app, chunks[2].width), chunks[2]);+ f.render_widget(input_box(app), chunks[2]);f.render_widget(dock_line(app, chunks[3].width), chunks[3]);return;}@@ -10832,10 +10820,7 @@ fn draw(f: &mut Frame, app: &mut App) {if let Some(lines) = panel_lines {f.render_widget(Paragraph::new(lines), panel_area);}- f.render_widget(- input_box(app, chunks[2].width).scroll((input_scroll, 0)),- chunks[2],- );+ f.render_widget(input_box(app).scroll((input_scroll, 0)), chunks[2]);f.render_widget(dock_line(app, chunks[3].width), chunks[3]);// `/login` is modal and user-initiated (only reachable while idle), so it@@ -11876,14 +11861,18 @@ fn header_spans(app: &App) -> Vec<Span<'static>> {.map(|t| format!(" {}", format_elapsed(t.elapsed().as_secs()))).unwrap_or_default();// No name chip: the splash names the app (see `Banner`), and the header's- // columns are better spent on state that changes. The model leads instead,- // bold so the row still has an anchor on the left; an unset model says so- // rather than opening the row with blanks.- let mut spans = vec![if app.model.is_empty() {- Span::styled(" no model ", Style::new().red().bold())- } else {- Span::styled(format!(" {} ", app.model), Style::new().bold())- }];+ // columns are better spent on state that changes. The wave mark stands in+ // for the name in one glyph, then the model, bold so the row still has an+ // anchor on the left; an unset model says so rather than opening the row+ // with blanks.+ let mut spans = vec![+ Span::styled(format!(" {}", brand::WAVE), Style::new().yellow()),+ if app.model.is_empty() {+ Span::styled(" no model", Style::new().red().bold())+ } else {+ Span::styled(format!(" {}", app.model), Style::new().bold())+ },+ ];// Reasoning-effort badge: `effort high` after the model, so the configured// reasoning depth is visible at a glance. Reported low/medium/high exactly// as set, so the display always matches what is sent upstream.@@ -12198,13 +12187,13 @@ fn input_box_height(app: &App, width: u16) -> u16 {content + 1}-/// Visible input as styled lines: `› ` on the first line, 2-space hang on+/// Visible input as styled lines: `> ` on the first line, 2-space hang on/// continuations, and a solid block cursor at the byte offset `cursor` (the/// character under the cursor is drawn in reverse video; at end of line a/// reversed space forms the block). Wrapping is left to the Paragraph so long/// single lines fold within the box width.fn input_content_lines(input: &str, cursor: usize) -> Vec<Line<'static>> {- let arrow = Span::styled("› ", Style::new().cyan().bold());+ let arrow = Span::styled("> ", Style::new().cyan().bold());let segments: Vec<&str> = input.split('\n').collect();let last = segments.len() - 1;// Locate the segment + in-segment byte offset holding the caret.@@ -12254,7 +12243,7 @@ fn input_content_lines(input: &str, cursor: usize) -> Vec<Line<'static>> {.collect()}-fn input_box(app: &App, width: u16) -> Paragraph<'static> {+fn input_box(app: &App) -> Paragraph<'static> {let block = Block::default();if let Some(kind) = app.compacting.filter(|_| app.input.is_empty()) {// Compaction puts nothing in the transcript while it runs, so the input@@ -12274,43 +12263,33 @@ fn input_box(app: &App, width: u16) -> Paragraph<'static> {} else if app.picker.is_some() {Paragraph::new(Line::styled("selecting…", Style::new().dim().italic())).block(block)} else if app.status == Status::Running && app.input.is_empty() {- // Show queue status when running with empty input.+ // Show queue status when running with empty inputif app.message_queue.is_empty() {+ // The spinner carries the fast motion; the action word turns over+ // on a slower cadence, cycling "working" synonyms -- or "thinking"+ // synonyms in orange while a reasoning block streams -- so the row+ // reads alive without shifting under the eye.let step = app.spinner_frame / WORD_ROTATE_FRAMES;- let suffix = || {- Span::styled(- " (Esc to cancel, type to queue next message)",+ let (word, style) = if app.reasoning_open() {+ (+ THINKING_WORDS[step % THINKING_WORDS.len()],+ Style::new().fg(THINKING_ORANGE).italic(),+ )+ } else {+ (+ WORKING_WORDS[step % WORKING_WORDS.len()],Style::new().dim().italic(),)};- if app.reasoning_open() {- let word = THINKING_WORDS[step % THINKING_WORDS.len()];- let style = Style::new().fg(THINKING_ORANGE).italic();- Paragraph::new(Line::from(vec![- Span::styled(format!("{} ", app.spinner()), Style::new().cyan()),- Span::styled(format!("{word}…"), style),- suffix(),- ]))- .block(block)- } else {- let word = WORKING_WORDS[step % WORKING_WORDS.len()];- let text_style = Style::new().dim().italic();- let mut spans = vec![Span::styled("› ", Style::new().cyan().bold())];- spans.extend(hand_sweep_line(word, app.spinner_frame, text_style).spans);- spans.push(suffix());- let animated = Line::from(spans);- let line = if spans_width(&animated.spans) <= width as usize {- animated- } else {- Line::from(vec![- Span::styled("› ", Style::new().cyan().bold()),- Span::styled(format!("{} ", app.spinner()), Style::new().cyan()),- Span::styled(format!("{word}…"), text_style),- suffix(),- ])- };- Paragraph::new(line).block(block)- }+ Paragraph::new(Line::from(vec![+ Span::styled(format!("{} ", app.spinner()), Style::new().cyan()),+ Span::styled(format!("{word}…"), style),+ Span::styled(+ " (Esc to cancel, type to queue next message)",+ Style::new().dim().italic(),+ ),+ ]))+ .block(block)} else {let n = app.message_queue.len();Paragraph::new(Line::from(vec![@@ -12323,7 +12302,7 @@ fn input_box(app: &App, width: u16) -> Paragraph<'static> {.block(block)}} else if app.input.is_empty() {- // Same `› ` arrow as the typing view, then a fixed (non-blinking)+ // Same `> ` prompt as the typing view, then a fixed (non-blinking)// block cursor in front of the placeholder.let placeholder = if app.status == Status::Running {"Type to queue next message"@@ -12331,7 +12310,7 @@ fn input_box(app: &App, width: u16) -> Paragraph<'static> {"Type here to chat with agent"};let cursor_spans: Vec<Span<'static>> = vec![- Span::styled("› ", Style::new().cyan().bold()),+ Span::styled("> ", Style::new().cyan().bold()),Span::styled(" ", Style::new().add_modifier(Modifier::REVERSED)),Span::raw(" "),Span::styled(placeholder, Style::new().dim().italic()),@@ -12514,11 +12493,10 @@ mod tests {unescape_partial_json_string,running_group_rows, split_reasoning, strip_system_xml_tags, subagent_activity,answer_without_reasoning, assistant_runs, replay_display_log, thinking_open,- hand_sweep_line, hand_sweep_position, HAND,without_think_tags, ReasoningSeg,subagent_name_from_run_id, summarize_result, tilde_path, tokens_per_second,tool_activity, tool_finished,- transcript_top_padding, rewind_to,+ transcript_top_padding, rewind_to, open_rewind_picker, rebuild_recall,row_width, user_content_parts, App, CurrentRun, Pending, PendingImage, PickerKind,ResumeTarget, RowKind, finish_plugin_install,SnapshotJob, Status, AGENT_SETTINGS, ALT_SCROLL_RESTORE, ALT_SCROLL_SAVE_OFF,@@ -12849,32 +12827,6 @@ mod tests {assert_eq!(app.spinner_frame, 6);}- #[test]- fn hand_sweep_moves_forward_and_back_across_the_message() {- let text = |frame| line_text(&hand_sweep_line("build", frame, Style::default()));-- assert_eq!(text(0), format!("{HAND}uild..."));- assert_eq!(text(3), format!("bui{HAND}d..."));- assert_eq!(text(8), format!("build...{HAND}"));- assert_eq!(text(9), format!("build..{HAND}"));- assert_eq!(text(16), format!("{HAND}uild..."));- }-- #[test]- fn hand_uses_explicit_emoji_presentation() {- assert_eq!(HAND.chars().last(), Some('\u{FE0F}'));- }-- #[test]- fn hand_sweep_uses_character_boundaries() {- let message = "éx...";- assert_eq!(hand_sweep_position(message.chars().count(), 1), 1);- assert_eq!(- line_text(&hand_sweep_line("éx", 1, Style::default())),- format!("é{HAND}...")- );- }-#[test]fn transcript_bottom_anchors_short_content() {// Short transcript: pad to push the last line to the viewport bottom.@@ -13113,7 +13065,7 @@ mod tests {let rows = render_rows(&mut app, 60, 12);assert!(rows.iter()- .any(|r| r.trim_end().ends_with("\u{203a} first line")),+ .any(|r| r.trim_end().ends_with("> first line")),"first line not on its own row: {rows:?}");assert!(@@ -13245,7 +13197,7 @@ mod tests {let rows = render_rows(&mut app, 60, 12);assert!(rows.iter()- .any(|r| r.trim_end().ends_with("\u{203a} [skill:deploy] first line")),+ .any(|r| r.trim_end().ends_with("> [skill:deploy] first line")),"first line not on its own row: {rows:?}");assert!(@@ -14697,6 +14649,68 @@ mod tests {}}+ /// A hidden reminder rides in on the `user` role, so every surface that+ /// counts user turns has to skip it: otherwise it becomes a rewind target+ /// and a recall entry the user never typed, and shifts the indices those+ /// share with the display journal (which holds no reminder at all).+ #[test]+ fn a_hidden_reminder_is_not_a_user_turn() {+ let mut app = test_app();+ app.thread_id = Some("t1".into());+ app.repo_root = Some(std::path::PathBuf::from("/tmp/repo"));+ app.base_requested = true;+ app.submit_user("first".into());+ app.history+ .push(json!({ "role": "assistant", "content": "reply" }));+ app.submit_reminder("unfinished todos remain".into());+ assert_eq!(+ app.history.len(),+ 3,+ "the reminder needed its own turn here"+ );+ assert!(crate::core::agent::reminder::is_reminder_only(+ &app.history[2]["content"]+ ));++ open_rewind_picker(&mut app);+ let picker = app.picker.as_ref().expect("picker");+ assert_eq!(picker.items.len(), 1);+ assert_eq!(picker.items[0].label, "first");++ rebuild_recall(&mut app);+ assert_eq!(app.input_history, vec!["first"]);++ app.checkpoint_turn();+ match app.snap_queue.back() {+ Some(SnapshotJob::Checkpoint {+ user_index,+ preview,+ ..+ }) => {+ assert_eq!(*user_index, 0, "the reminder must not shift the key");+ assert_eq!(preview, "first");+ }+ other => panic!("expected a checkpoint job, got {:?}", other.is_some()),+ }+ }++ /// The reminder is folded into a message the model has not answered yet+ /// where one exists, so no extra turn is invented at all.+ #[test]+ fn a_reminder_lands_in_flight_on_an_unanswered_turn() {+ let mut app = test_app();+ app.thread_id = Some("t1".into());+ app.submit_user("first".into());+ app.submit_reminder("unfinished todos remain".into());+ assert_eq!(app.history.len(), 1);+ let content = app.history[0]["content"].as_str().expect("text");+ assert!(content.starts_with("first\n\n"), "{content}");+ assert!(content.contains("unfinished todos remain"));+ // Recall and rewind offer the typed text back, never the reminder.+ rebuild_recall(&mut app);+ assert_eq!(app.input_history, vec!["first"]);+ }+#[test]fn rewind_to_fills_input_with_target_user_message() {let mut app = test_app();@@ -17064,14 +17078,14 @@ mod tests {fn input_lines_single_line_has_arrow_and_cursor() {let lines = input_content_lines("hello", 5);assert_eq!(lines.len(), 1);- assert_eq!(caret_text(&lines[0]), "› hello▏");+ assert_eq!(caret_text(&lines[0]), "> hello▏");}#[test]fn input_lines_multiline_hangs_and_cursor_on_last() {let lines = input_content_lines("one\ntwo\nthree", "one\ntwo\nthree".len());assert_eq!(lines.len(), 3);- assert_eq!(line_text(&lines[0]), "› one");+ assert_eq!(line_text(&lines[0]), "> one");assert_eq!(line_text(&lines[1]), " two");assert_eq!(caret_text(&lines[2]), " three▏");}@@ -17080,7 +17094,7 @@ mod tests {fn input_lines_trailing_newline_gives_empty_cursor_row() {let lines = input_content_lines("hi\n", 3);assert_eq!(lines.len(), 2);- assert_eq!(line_text(&lines[0]), "› hi");+ assert_eq!(line_text(&lines[0]), "> hi");assert_eq!(caret_text(&lines[1]), " ▏");}@@ -17089,14 +17103,14 @@ mod tests {// Caret sits between "he" and "llo" on a single line.let lines = input_content_lines("hello", 2);assert_eq!(lines.len(), 1);- assert_eq!(caret_text(&lines[0]), "› he▏llo");+ assert_eq!(caret_text(&lines[0]), "> he▏llo");}#[test]fn input_lines_caret_on_earlier_line_only() {// Cursor inside the first segment: caret there, none on later lines.let lines = input_content_lines("one\ntwo", 1);- assert_eq!(caret_text(&lines[0]), "› o▏ne");+ assert_eq!(caret_text(&lines[0]), "> o▏ne");assert_eq!(line_text(&lines[1]), " two");}@@ -19758,28 +19772,19 @@ mod tests {app.spinner_frame = 0;let first = frame_of(&mut app);- assert!(first.contains(HAND), "expected hand frame: {first:?}");- assert!(- !first.contains(SPINNER[0]),- "working row still has Braille spinner: {first:?}"- );+ assert!(first.contains(SPINNER[0]), "expected frame 0 glyph: {first:?}");- // The hand covers the first character at frame 0, leaving the rest of- // the selected working word visible.- assert!(first.starts_with("› "), "working row lost the prompt: {first:?}");+ // While a plain turn is running (no reasoning), the row shows a+ // rotating synonym of "working".assert!(- first.contains("orking..."),- "expected the working word behind the hand: {first:?}"+ WORKING_WORDS.iter().any(|w| first.contains(w)),+ "expected a working synonym in: {first:?}");app.spinner_frame = 3;let later = frame_of(&mut app);- assert!(later.contains(HAND), "expected later hand frame: {later:?}");- assert!(- !later.contains(SPINNER[3]),- "working row still has Braille spinner: {later:?}"- );- assert_ne!(first, later, "row must change as the hand advances");+ assert!(later.contains(SPINNER[3]), "expected frame 3 glyph: {later:?}");+ assert_ne!(first, later, "row must change as the frame advances");assert!(later.contains("(Esc to cancel, type to queue next message)"), "{later:?}");}@@ -19838,24 +19843,21 @@ mod tests {fn working_synonym_rotates_across_frames() {let mut app = test_app();app.submit_user("go".into());- let mut row_at = |frame: usize| {+ let mut word_at = |frame: usize| {app.spinner_frame = frame;- render_rows(&mut app, 80, 12)+ let row = render_rows(&mut app, 80, 12).into_iter().find(|r| r.contains("(Esc to cancel, type to queue next message)"))- .expect("running placeholder present")+ .expect("running placeholder present");+ WORKING_WORDS+ .iter()+ .find(|w| row.contains(*w))+ .map(|w| w.to_string())+ .expect("working synonym present")};- let first = row_at(0);- let later = row_at(super::WORD_ROTATE_FRAMES);- assert!(- first.contains("orking..."),- "first working word is covered by the hand: {first}"- );- assert!(- later.contains("omputing..."),- "later working word is covered by the hand: {later}"- );- assert_ne!(first, later, "working word must rotate as frames advance");+ let a = word_at(0);+ let b = word_at(super::WORD_ROTATE_FRAMES);+ assert_ne!(a, b, "working word must rotate as frames advance: {a}");}/// A queued-message row is still a running row, so it animates too.@@ -19872,58 +19874,6 @@ mod tests {assert!(row.contains(SPINNER[5]), "expected frame 5 glyph: {row:?}");}- #[test]- fn hand_spinner_stays_out_of_reasoning_queued_and_editable_rows() {- let mut reasoning = test_app();- reasoning.submit_user("go".into());- reasoning.apply(StreamEvent::Token {- text: "<think>ponder".into(),- });- let thinking = render_rows(&mut reasoning, 80, 12).join("\n");- assert!(!thinking.contains(HAND), "reasoning row must retain Braille spinner");- assert!(- thinking.contains(SPINNER[0]),- "reasoning spinner changed: {thinking}"- );-- let mut queued = test_app();- queued.submit_user("go".into());- queued.message_queue.push_back("next".into());- let queued_text = render_rows(&mut queued, 80, 12).join("\n");- assert!(!queued_text.contains(HAND), "queued row must retain queue indicator");- assert!(- queued_text.contains(SPINNER[0]),- "queued spinner changed: {queued_text}"- );-- let mut editable = test_app();- editable.submit_user("go".into());- editable.input = "draft".into();- let editable_text = render_rows(&mut editable, 80, 12).join("\n");- assert!(- !editable_text.contains(HAND),- "hand must not enter editable input"- );- }-- #[test]- fn narrow_working_row_falls_back_to_braille_spinner() {- let mut app = test_app();- app.submit_user("go".into());- app.spinner_frame = 0;-- let rendered = render_rows(&mut app, 20, 12).join("\n");- assert!(- !rendered.contains(HAND),- "hand row must fall back when it cannot fit"- );- assert!(- rendered.contains(SPINNER[0]),- "Braille fallback missing: {rendered}"- );- assert!(app.input.is_empty(), "status rendering changed the input buffer");- }-/// Native reasoning events (a dedicated `reasoning_content` field) drive the/// same orange thinking placeholder as inline `<`> tags, are folded into the/// transcript like a wrapped block on flush, and never enter the wire answer.@@ -21076,9 +21026,9 @@ mod tests {let injected = last_history_content(&app);assert!(injected.contains("unfinished todos"), "got: {injected}");assert!(injected.contains("t1") && injected.contains("t2"));- // The reminder is hidden: no user-authored `› ` row in the transcript.+ // The reminder is hidden: no user-authored `> ` row in the transcript.let rows: String = app.transcript.iter().map(row_text).collect();- assert!(!rows.contains("› "), "reminder must not render as a user row");+ assert!(!rows.contains("> "), "reminder must not render as a user row");}#[test]@@ -21887,6 +21837,30 @@ mod tests {assert!(text.contains("started a new session"), "missing note: {text}");}+ #[tokio::test]+ async fn clear_re_prints_the_branded_splash() {+ let mut app = test_app();+ app.approval_phrasing = "--safe: approval needed".to_string();+ app.push(Line::raw("old content"));++ run_command(&mut app, "clear").await;++ let text: String = app.transcript.iter().map(row_text).collect();+ assert!(+ !text.contains("old content"),+ "transcript not reset: {text}"+ );+ assert!(+ text.contains(brand::HAND[0].trim()),+ "hand logo missing after /clear: {text}"+ );+ assert!(+ text.contains("--safe: approval needed"),+ "approval phrasing missing after /clear: {text}"+ );+ assert!(text.contains("type a message to start"), "{text}");+ }+#[test]fn parse_command_handles_multibyte_without_panic() {// Leading space + multibyte would panic under byte slicing.@@ -23194,6 +23168,40 @@ mod tests {);}+ /// The mark and the name are one lockup, so they share rows instead of+ /// stacking: the wordmark's first row also carries part of the hand.+ #[test]+ fn banner_opens_with_the_hand_logo_beside_the_wordmark() {+ let mut app = test_app();+ app.push_banner("--safe", true);++ let text = banner_text(&app, 90);+ let joined = text.join("\n");+ let row = text+ .iter()+ .find(|l| l.contains(brand::LOGO[0].trim()))+ .unwrap_or_else(|| panic!("wordmark missing:\n{joined}"));+ let hand_row = brand::HAND+ .iter()+ .find(|h| row.contains(h.trim()))+ .unwrap_or_else(|| panic!("the wordmark's row carries no hand: {row}"));+ assert!(+ row.find(hand_row.trim()).unwrap() < row.find(brand::LOGO[0].trim()).unwrap(),+ "the hand should sit left of the wordmark: {row}"+ );+ assert!(joined.contains('█'), "{joined}");+ }++ #[test]+ fn a_24_column_terminal_drops_the_hand_logo_too() {+ let mut app = test_app();+ app.push_banner("--safe", true);+ let narrow = banner_text(&app, 24);+ let joined = narrow.join("\n");+ assert!(!joined.contains('█'), "{joined}");+ assert!(joined.contains("jan"), "{joined}");+ }+/// `/init` is the first thing a new project wants and is invisible unless/// promoted, so the splash lists it beside `/help`.#[test]@@ -23251,21 +23259,30 @@ mod tests {}}+ /// The wave mark is the only branding the header carries: one glyph, then+ /// the model. A name chip would spend the columns the status needs.#[test]- fn header_leads_with_the_model_not_a_name_chip() {+ fn header_leads_with_the_wave_then_the_model() {let mut app = test_app();app.model = "tokamak-1-preview".into();let top = render_rows(&mut app, 60, 12).remove(0);+ let head = top.trim_start();+ assert!(+ head.starts_with(brand::WAVE),+ "the wave should open the row: {top:?}"+ );assert!(- top.starts_with(" tokamak-1-preview"),- "the name chip is back: {top:?}"+ head[brand::WAVE.len()..]+ .trim_start()+ .starts_with("tokamak-1-preview"),+ "the model should follow the wave, with no name chip between: {top:?}");// The freed columns are what let the status survive a 60-column frame.assert!(top.contains("[ready]"), "{top:?}");app.model.clear();let top = render_rows(&mut app, 60, 12).remove(0);- assert!(top.starts_with(" no model"), "{top:?}");+ assert!(top.contains("no model"), "{top:?}");}#[test]@@ -23307,7 +23324,7 @@ mod tests {assert_eq!(last_row(&app)[0].0, "\u{2022} ", "system note");app.push_user_line("do it", &[]);- assert_eq!(last_row(&app)[0].0, "\u{203a} ", "user message");+ assert_eq!(last_row(&app)[0].0, "> ", "user message");app.apply(StreamEvent::ToolCall {id: "t1".into(),@@ -23329,7 +23346,7 @@ mod tests {app.flush_assistant();let prose = last_row(&app);assert!(- !prose[0].0.starts_with('\u{2022}') && !prose[0].0.starts_with('\u{203a}'),+ !prose[0].0.starts_with('\u{2022}') && !prose[0].0.starts_with('>'),"prose took a gutter: {prose:?}");}