Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent-tui): focused write/edit diffs + multiline input box
Akarshan Biswas2e74a2409ca5
diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex edec2efe9..3768415c4 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -19,10 +19,14 @@ pub enum StreamEvent {args: serde_json::Value,},/// A tool finished. `is_error` reflects the upstream "ERROR" encoding.+ /// `diff` is display-only focused-change text (line-prefixed `-`/`+`) for+ /// `write`/`edit`; `None` for other tools.ToolResult {id: String,content: String,is_error: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ diff: Option<String>,},/// Terminal success: the model returned a final (tool-free) completion.Done {@@ -213,6 +217,7 @@ mod tests {id: "c1".into(),content: "ok".into(),is_error: false,+ diff: None,}).unwrap();assert_eq!(diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 555fbb7a6..4689d840e 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -67,12 +67,28 @@ pub(crate) trait ModelInvoker: Send + Sync {) -> Result<serde_json::Value, String>;}+/// One tool call's outcome: `content` is the model-facing result string,+/// `diff` is display-only focused-change text (`write`/`edit` only).+pub(crate) struct ToolOutcome {+ pub id: String,+ pub content: String,+ pub diff: Option<String>,+}++impl ToolOutcome {+ fn plain(id: String, content: String) -> Self {+ Self {+ id,+ content,+ diff: None,+ }+ }+}+#[async_trait]pub(crate) trait ToolInvoker: Send + Sync {- async fn invoke(- &self,- tool_calls: &[serde_json::Value],- ) -> Result<Vec<(String, String)>, String>;+ async fn invoke(&self, tool_calls: &[serde_json::Value])+ -> Result<Vec<ToolOutcome>, String>;}struct HttpModelInvoker {@@ -110,14 +126,18 @@ impl ToolInvoker for McpToolInvoker {async fn invoke(&self,tool_calls: &[serde_json::Value],- ) -> Result<Vec<(String, String)>, String> {- execute_mcp_tool_calls(+ ) -> Result<Vec<ToolOutcome>, String> {+ let results = execute_mcp_tool_calls(tool_calls,&self.tool_to_server,&self.mcp_servers,&self.mcp_settings,)- .await+ .await?;+ Ok(results+ .into_iter()+ .map(|(id, content)| ToolOutcome::plain(id, content))+ .collect())}}@@ -137,13 +157,13 @@ impl ToolInvoker for CompositeToolInvoker {async fn invoke(&self,tool_calls: &[serde_json::Value],- ) -> Result<Vec<(String, String)>, String> {+ ) -> Result<Vec<ToolOutcome>, String> {use crate::core::agent::tools::{gate::{resolve_decision, Decision, PromptKind},- handlers::execute_builtin,+ handlers::execute_builtin_with_diff,is_builtin, lookup, Capability,};- let mut out: Vec<(String, String)> = Vec::with_capacity(tool_calls.len());+ let mut out: Vec<ToolOutcome> = Vec::with_capacity(tool_calls.len());let mut mcp_calls: Vec<serde_json::Value> = Vec::new();for tc in tool_calls {let name = tc@@ -175,10 +195,10 @@ impl ToolInvoker for CompositeToolInvoker {&self.permissions,&snapshot,);- let text = match decision {- Decision::Allow => execute_builtin(tool, &args, &self.project_root).await,+ let (text, diff) = match decision {+ Decision::Allow => execute_builtin_with_diff(tool, &args, &self.project_root).await,Decision::HardDeny => {- format!("ERROR: tool '{name}' denied by project policy")+ (format!("ERROR: tool '{name}' denied by project policy"), None)}Decision::Prompt(kind) => {let request_id = next_permission_id();@@ -223,7 +243,7 @@ impl ToolInvoker for CompositeToolInvoker {self.permission_requests.lock().await.remove(&request_id);match decision {PermissionDecision::AllowOnce => {- execute_builtin(tool, &args, &self.project_root).await+ execute_builtin_with_diff(tool, &args, &self.project_root).await}PermissionDecision::AllowAlways => {// Thread-scoped only; never persisted to agent.toml.@@ -237,15 +257,19 @@ impl ToolInvoker for CompositeToolInvoker {} else {self.grants.lock().unwrap().grant(kind);}- execute_builtin(tool, &args, &self.project_root).await+ execute_builtin_with_diff(tool, &args, &self.project_root).await}PermissionDecision::Deny => {- format!("ERROR: tool '{name}' denied by user")+ (format!("ERROR: tool '{name}' denied by user"), None)}}}};- out.push((id, text));+ out.push(ToolOutcome {+ id,+ content: text,+ diff,+ });}if !mcp_calls.is_empty() {out.extend(self.mcp.invoke(&mcp_calls).await?);@@ -255,7 +279,7 @@ impl ToolInvoker for CompositeToolInvoker {.enumerate().filter_map(|(i, tc)| tc.get("id").and_then(|v| v.as_str()).map(|id| (id, i))).collect();- out.sort_by_key(|(id, _)| *order.get(id.as_str()).unwrap_or(&usize::MAX));+ out.sort_by_key(|o| *order.get(o.id.as_str()).unwrap_or(&usize::MAX));Ok(out)}}@@ -670,16 +694,18 @@ async fn run_turn_cycle(let tool_results = tools.invoke(&tool_calls).await?;- for (tool_call_id, result_text) in tool_results {+ for outcome in tool_results {+ let ToolOutcome { id, content, diff } = outcome;let _ = events.send(StreamEvent::ToolResult {- id: tool_call_id.clone(),- content: result_text.clone(),- is_error: result_text.starts_with("ERROR"),+ id: id.clone(),+ content: content.clone(),+ is_error: content.starts_with("ERROR"),+ diff,});conversation_messages.push(serde_json::json!({"role": "tool",- "tool_call_id": tool_call_id,- "content": result_text+ "tool_call_id": id,+ "content": content}));}}@@ -732,7 +758,7 @@ mod tests {async fn invoke(&self,tool_calls: &[serde_json::Value],- ) -> Result<Vec<(String, String)>, String> {+ ) -> Result<Vec<ToolOutcome>, String> {self.calls.lock().unwrap().push(tool_calls.to_vec());Ok(tool_calls.iter()@@ -742,7 +768,7 @@ mod tests {.and_then(|v| v.as_str()).unwrap_or("").to_string();- (id, "MOCK_RESULT".to_string())+ ToolOutcome::plain(id, "MOCK_RESULT".to_string())}).collect())}@@ -959,7 +985,7 @@ mod tests {responder.await.unwrap();assert_eq!(out.len(), 1);- assert!(!out[0].1.starts_with("ERROR"), "unexpected: {}", out[0].1);+ assert!(!out[0].content.starts_with("ERROR"), "unexpected: {}", out[0].content);assert_eq!(std::fs::read_to_string(root.join("out.txt")).unwrap(), "hi");let _ = std::fs::remove_dir_all(&root);}@@ -983,7 +1009,7 @@ mod tests {responder.await.unwrap();assert_eq!(out.len(), 1);- assert!(out[0].1.contains("denied by user"), "got: {}", out[0].1);+ assert!(out[0].content.contains("denied by user"), "got: {}", out[0].content);assert!(!root.join("out.txt").exists());let _ = std::fs::remove_dir_all(&root);}@@ -1012,7 +1038,7 @@ mod tests {};let out1 = invoker.invoke(&[write_call()]).await.unwrap();- assert!(!out1[0].1.starts_with("ERROR"), "first: {}", out1[0].1);+ assert!(!out1[0].content.starts_with("ERROR"), "first: {}", out1[0].content);let second = json!({"id": "c2",@@ -1023,7 +1049,7 @@ mod tests {}});let out2 = invoker.invoke(&[second]).await.unwrap();- assert!(!out2[0].1.starts_with("ERROR"), "second: {}", out2[0].1);+ assert!(!out2[0].content.starts_with("ERROR"), "second: {}", out2[0].content);drop(invoker); // close events channel so responder loop endsresponder.await.unwrap();diff --git a/src-tauri/src/core/agent/tools/handlers.rs b/src-tauri/src/core/agent/tools/handlers.rsindex c6c6a7466..a6de77fc5 100644--- a/src-tauri/src/core/agent/tools/handlers.rs+++ b/src-tauri/src/core/agent/tools/handlers.rs@@ -89,6 +89,88 @@ pub async fn execute_builtin(}}+/// Run a built-in tool and, for `write`/`edit`, also produce a focused diff.+/// Returns `(content, diff)` where `diff` is line-prefixed (`-`/`+`) hunk text+/// for display; `None` for non-mutating tools or on error. For `edit` the diff+/// is also appended to `content` (the model sees exactly what changed); for+/// `write` the diff is display-only and `content` stays the concise summary.+pub(crate) async fn execute_builtin_with_diff(+ tool: &BuiltinTool,+ args: &serde_json::Value,+ project_root: &Path,+) -> (String, Option<String>) {+ match tool.name {+ "edit" => {+ let content = execute_builtin(tool, args, project_root).await;+ if content.starts_with("ERROR") {+ return (content, None);+ }+ let diff = args+ .get("edits")+ .and_then(|v| v.as_array())+ .map(|e| render_edit_diff(e))+ .filter(|d| !d.is_empty());+ match diff {+ Some(d) => (format!("{content}\n\n{d}"), Some(d)),+ None => (content, None),+ }+ }+ "write" => {+ let prior = match arg_str(args, "path") {+ Some(p) => tokio::fs::read_to_string(resolve(project_root, p)).await.ok(),+ None => None,+ };+ let content = execute_builtin(tool, args, project_root).await;+ if content.starts_with("ERROR") {+ return (content, None);+ }+ let new = arg_str(args, "content").unwrap_or("");+ (content, Some(render_write_diff(prior.as_deref(), new)))+ }+ _ => (execute_builtin(tool, args, project_root).await, None),+ }+}++/// Per-edit `-old`/`+new` hunks. Multiple edits are separated by `@@ edit i/n @@`.+fn render_edit_diff(edits: &[serde_json::Value]) -> String {+ let n = edits.len();+ let mut out = String::new();+ for (i, e) in edits.iter().enumerate() {+ let old = e.get("old_string").and_then(|v| v.as_str()).unwrap_or("");+ let new = e.get("new_string").and_then(|v| v.as_str()).unwrap_or("");+ if n > 1 {+ out.push_str(&format!("@@ edit {}/{} @@\n", i + 1, n));+ }+ for line in old.lines() {+ out.push_str("- ");+ out.push_str(line);+ out.push('\n');+ }+ for line in new.lines() {+ out.push_str("+ ");+ out.push_str(line);+ out.push('\n');+ }+ }+ out.trim_end().to_string()+}++/// Whole-file `+` preview for a write, headed by created/overwrote. Display-only;+/// the TUI collapses long output.+fn render_write_diff(prior: Option<&str>, content: &str) -> String {+ let mut out = String::from(if prior.is_some() {+ "@@ overwrote file @@\n"+ } else {+ "@@ created file @@\n"+ });+ for line in content.lines() {+ out.push_str("+ ");+ out.push_str(line);+ out.push('\n');+ }+ out.trim_end().to_string()+}+/// `.jan/agent/<kind>` directory for the agent's own workspace.fn workspace_dir(root: &Path, kind: &str) -> PathBuf {root.join(".jan").join("agent").join(kind)@@ -666,6 +748,75 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ #[test]+ fn edit_diff_single_hunk_has_no_header() {+ let d = render_edit_diff(&[json!({"old_string": "foo", "new_string": "bar"})]);+ assert_eq!(d, "- foo\n+ bar");+ }++ #[test]+ fn edit_diff_multi_hunk_is_numbered_and_multiline() {+ let d = render_edit_diff(&[+ json!({"old_string": "a\nb", "new_string": "A"}),+ json!({"old_string": "c", "new_string": "C\nD"}),+ ]);+ assert_eq!(d, "@@ edit 1/2 @@\n- a\n- b\n+ A\n@@ edit 2/2 @@\n- c\n+ C\n+ D");+ }++ #[test]+ fn write_diff_headers_created_vs_overwrote() {+ assert_eq!(render_write_diff(None, "x\ny"), "@@ created file @@\n+ x\n+ y");+ assert_eq!(+ render_write_diff(Some("old"), "x"),+ "@@ overwrote file @@\n+ x"+ );+ }++ #[tokio::test]+ async fn edit_with_diff_appends_hunks_to_model_content() {+ let root = unique_root();+ std::fs::write(root.join("e.txt"), b"foo").unwrap();+ let (content, diff) = execute_builtin_with_diff(+ lookup("edit").unwrap(),+ &json!({"path": "e.txt", "edits": [{"old_string": "foo", "new_string": "bar"}]}),+ &root,+ )+ .await;+ assert_eq!(content, "Applied 1 edit(s) to e.txt\n\n- foo\n+ bar");+ assert_eq!(diff.as_deref(), Some("- foo\n+ bar"));+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn write_with_diff_keeps_content_concise() {+ let root = unique_root();+ let (content, diff) = execute_builtin_with_diff(+ lookup("write").unwrap(),+ &json!({"path": "w.txt", "content": "hello"}),+ &root,+ )+ .await;+ assert!(content.starts_with("Wrote"), "unexpected: {content}");+ assert!(!content.contains('+'), "write content must stay concise");+ assert_eq!(diff.as_deref(), Some("@@ created file @@\n+ hello"));+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn edit_error_yields_no_diff() {+ let root = unique_root();+ std::fs::write(root.join("err.txt"), b"foo").unwrap();+ let (content, diff) = execute_builtin_with_diff(+ lookup("edit").unwrap(),+ &json!({"path": "err.txt", "edits": [{"old_string": "nope", "new_string": "x"}]}),+ &root,+ )+ .await;+ assert!(content.starts_with("ERROR"), "unexpected: {content}");+ assert!(diff.is_none());+ let _ = std::fs::remove_dir_all(&root);+ }+#[tokio::test]async fn ls_lists_created_file() {let root = unique_root();diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 8ee164877..311c998e6 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -327,7 +327,10 @@ impl App {]));}StreamEvent::ToolResult {- content, is_error, ..+ content,+ is_error,+ diff,+ ..} => {self.flush_assistant();self.gap(Kind::Tool);@@ -342,6 +345,11 @@ impl App {Span::styled(format!("{tag} "), tag_style),Span::styled(summarize_result(&content, max), Style::new().dim()),]));+ if let Some(diff) = diff {+ for line in diff_lines(&diff, max) {+ self.push(line);+ }+ }}StreamEvent::PermissionRequest {request_id,@@ -438,6 +446,39 @@ fn summarize_result(s: &str, max: usize) -> String {}}+/// Max diff rows rendered under a tool result before collapsing the tail.+const DIFF_MAX_ROWS: usize = 20;++/// Render focused-diff text to styled transcript lines: `-` red, `+` green,+/// `@@` headers dim-cyan. Collapses to `DIFF_MAX_ROWS` with a `(+N more)` tail.+fn diff_lines(diff: &str, max: usize) -> Vec<Line<'static>> {+ let all: Vec<&str> = diff.lines().collect();+ let shown = all.len().min(DIFF_MAX_ROWS);+ let mut out = Vec::with_capacity(shown + 1);+ for line in &all[..shown] {+ let style = match line.as_bytes().first() {+ Some(b'-') => Style::new().red(),+ Some(b'+') => Style::new().green(),+ Some(b'@') => Style::new().cyan().dim(),+ _ => Style::new().dim(),+ };+ out.push(Line::from(vec![+ Span::styled("│ ", Style::new().dark_gray()),+ Span::styled(truncate(line, max), style),+ ]));+ }+ if all.len() > shown {+ out.push(Line::from(vec![+ Span::styled("│ ", Style::new().dark_gray()),+ Span::styled(+ format!("(+{} more)", all.len() - shown),+ Style::new().dim(),+ ),+ ]));+ }+ out+}+/// 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 {@@ -860,6 +901,14 @@ async fn handle_key(app.should_quit = true;}}+ // Alt+Enter (or Ctrl+J) inserts a newline for multi-line input; plain+ // Enter submits.+ KeyCode::Enter if app.status == Status::Idle && key.modifiers.contains(KeyModifiers::ALT) => {+ app.input.push('\n');+ }+ KeyCode::Char('j') if app.status == Status::Idle && ctrl => {+ app.input.push('\n');+ }KeyCode::Enter => {if app.status == Status::Idle {let text = app.input.trim().to_string();@@ -1185,10 +1234,11 @@ fn message_text(msg: &serde_json::Value) -> String {}fn draw(f: &mut Frame, app: &mut App) {+ let input_h = input_box_height(app, f.area().width);let chunks = Layout::vertical([Constraint::Length(1),Constraint::Min(1),- Constraint::Length(3),+ Constraint::Length(input_h),Constraint::Length(1),]).split(f.area());@@ -1222,7 +1272,18 @@ fn draw(f: &mut Frame, app: &mut App) {let scroll = max_back - app.scrollback;f.render_widget(body.scroll((scroll, 0)), chunks[1]);- f.render_widget(input_box(app), chunks[2]);+ // Keep the cursor row visible when the input outgrows the box.+ let input_scroll = if app.status == Status::Idle && app.picker.is_none() {+ let visible = chunks[2].height.saturating_sub(2);+ let total = Paragraph::new(input_content_lines(&app.input))+ .wrap(Wrap { trim: false })+ .line_count(chunks[2].width.saturating_sub(2).max(1))+ .min(u16::MAX as usize) as u16;+ total.saturating_sub(visible)+ } else {+ 0+ };+ f.render_widget(input_box(app).scroll((input_scroll, 0)), chunks[2]);f.render_widget(footer(app), chunks[3]);// Dock the permission prompt directly above the input box, growing upward@@ -1337,6 +1398,52 @@ fn header(app: &App) -> Paragraph<'static> {]))}+/// Max content rows the input box grows to before it scrolls internally.+const MAX_INPUT_ROWS: u16 = 8;++/// Height (incl. borders) the message box should occupy: 1 content row for the+/// idle/working placeholder, or the wrapped input height clamped to+/// `MAX_INPUT_ROWS` while editing.+fn input_box_height(app: &App, width: u16) -> u16 {+ let content = if app.status == Status::Idle && app.picker.is_none() {+ let inner = width.saturating_sub(2).max(1);+ let rows = Paragraph::new(input_content_lines(&app.input))+ .wrap(Wrap { trim: false })+ .line_count(inner)+ .max(1) as u16;+ rows.min(MAX_INPUT_ROWS)+ } else {+ 1+ };+ content + 2+}++/// Visible input as styled lines: `› ` on the first line, 2-space hang on+/// continuations, cursor `▏` appended to the last line. Wrapping is left to the+/// Paragraph so long single lines fold within the box width.+fn input_content_lines(input: &str) -> Vec<Line<'static>> {+ let arrow = Span::styled("› ", Style::new().cyan().bold());+ let segments: Vec<&str> = input.split('\n').collect();+ let last = segments.len() - 1;+ segments+ .into_iter()+ .enumerate()+ .map(|(i, seg)| {+ let prefix = if i == 0 {+ arrow.clone()+ } else {+ Span::raw(" ")+ };+ let text = if i == last {+ format!("{seg}▏")+ } else {+ seg.to_string()+ };+ Line::from(vec![prefix, Span::raw(text)])+ })+ .collect()+}+fn input_box(app: &App) -> Paragraph<'static> {let block = Block::default().borders(Borders::ALL).title(" message ");if app.picker.is_some() {@@ -1348,11 +1455,9 @@ fn input_box(app: &App) -> Paragraph<'static> {)).block(block)} else {- Paragraph::new(Line::from(vec![- Span::styled("› ", Style::new().cyan().bold()),- Span::raw(format!("{}▏", app.input)),- ]))- .block(block)+ Paragraph::new(input_content_lines(&app.input))+ .wrap(Wrap { trim: false })+ .block(block)}}@@ -1368,7 +1473,7 @@ fn footer(app: &App) -> Paragraph<'static> {}let hint = match app.status {Status::Running => "Esc/Ctrl-C cancel ↑/↓ scroll",- Status::Idle => "Enter send /help commands ↑/↓ scroll Ctrl-D quit",+ Status::Idle => "Enter send Alt+Enter newline /help ↑/↓ scroll Ctrl-D quit",};let detail = if app.detail.is_empty() {String::new()@@ -1381,8 +1486,8 @@ fn footer(app: &App) -> Paragraph<'static> {#[cfg(test)]mod tests {use super::{- format_tool_call, is_table_separator, message_text, parse_command, render_table,- split_reasoning, summarize_result, Pending,+ diff_lines, format_tool_call, input_content_lines, is_table_separator, message_text,+ parse_command, render_table, split_reasoning, summarize_result, Pending, DIFF_MAX_ROWS,};use crate::core::agent::tools::gate::PermissionDecision;use serde_json::json;@@ -1464,6 +1569,58 @@ mod tests {);}+ fn line_text(line: &ratatui::text::Line) -> String {+ line.spans.iter().map(|s| s.content.as_ref()).collect()+ }++ #[test]+ fn input_lines_single_line_has_arrow_and_cursor() {+ let lines = input_content_lines("hello");+ assert_eq!(lines.len(), 1);+ assert_eq!(line_text(&lines[0]), "› hello▏");+ }++ #[test]+ fn input_lines_multiline_hangs_and_cursor_on_last() {+ let lines = input_content_lines("one\ntwo\nthree");+ assert_eq!(lines.len(), 3);+ assert_eq!(line_text(&lines[0]), "› one");+ assert_eq!(line_text(&lines[1]), " two");+ assert_eq!(line_text(&lines[2]), " three▏");+ }++ #[test]+ fn input_lines_trailing_newline_gives_empty_cursor_row() {+ let lines = input_content_lines("hi\n");+ assert_eq!(lines.len(), 2);+ assert_eq!(line_text(&lines[0]), "› hi");+ assert_eq!(line_text(&lines[1]), " ▏");+ }++ #[test]+ fn diff_lines_renders_all_when_under_cap() {+ let out = diff_lines("- foo\n+ bar", 80);+ assert_eq!(out.len(), 2);+ }++ #[test]+ fn diff_lines_collapses_tail_past_cap() {+ let diff = (0..30)+ .map(|i| format!("+ line {i}"))+ .collect::<Vec<_>>()+ .join("\n");+ let out = diff_lines(&diff, 80);+ assert_eq!(out.len(), DIFF_MAX_ROWS + 1);+ let tail: String = out+ .last()+ .unwrap()+ .spans+ .iter()+ .map(|s| s.content.as_ref())+ .collect();+ assert!(tail.contains("(+10 more)"), "tail: {tail}");+ }+#[test]fn summarize_result_first_line_plus_count() {assert_eq!(summarize_result("only line", 80), "only line");