Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): show diff preview in write/edit permission prompt
Akarshan Biswas244cf756e277
diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex 3768415c4..97598ce39 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -46,6 +46,10 @@ pub enum StreamEvent {/// "allow always" grant); `None` for non-exec tools.#[serde(default, skip_serializing_if = "Option::is_none")]command: Option<String>,+ /// Focused diff preview for `write`/`edit` prompts so the user sees the+ /// change before approving; `None` for other tools.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ diff: Option<String>,prompt_kind: String,offers_always: bool,},@@ -257,6 +261,7 @@ mod tests {capability: "write".into(),path: Some("out.txt".into()),command: None,+ diff: Some("@@ created file @@\n+ hi".into()),prompt_kind: "write".into(),offers_always: true,})@@ -269,6 +274,7 @@ mod tests {"tool_name": "write","capability": "write","path": "out.txt",+ "diff": "@@ created file @@\n+ hi","prompt_kind": "write","offers_always": true})diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex a5812b8a9..7fc7263ff 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -160,7 +160,7 @@ impl ToolInvoker for CompositeToolInvoker {) -> Result<Vec<ToolOutcome>, String> {use crate::core::agent::tools::{gate::{resolve_decision, Decision, PromptKind},- handlers::execute_builtin_with_diff,+ handlers::{execute_builtin_with_diff, preview_diff},is_builtin, lookup, Capability,};let mut out: Vec<ToolOutcome> = Vec::with_capacity(tool_calls.len());@@ -227,12 +227,14 @@ impl ToolInvoker for CompositeToolInvoker {.then(|| args.get("command").and_then(|v| v.as_str())).flatten().map(String::from);+ let diff = preview_diff(tool, &args, &self.project_root).await;let _ = self.events.send(StreamEvent::PermissionRequest {request_id: request_id.clone(),tool_name: name.to_string(),capability: capability.to_string(),path,command,+ diff,prompt_kind: prompt_kind.to_string(),offers_always: true,});diff --git a/src-tauri/src/core/agent/tools/handlers.rs b/src-tauri/src/core/agent/tools/handlers.rsindex a6de77fc5..e18ff6ddc 100644--- a/src-tauri/src/core/agent/tools/handlers.rs+++ b/src-tauri/src/core/agent/tools/handlers.rs@@ -89,6 +89,34 @@ pub async fn execute_builtin(}}+/// Focused diff previewing what a `write`/`edit` call would change, without+/// running it. Line-prefixed (`-`/`+`) hunk text; `None` for other tools or when+/// nothing would change. Used to show the change in the permission prompt. For+/// `write` it reads the prior file so an overwrite shows its `created`/`overwrote`+/// header; `edit` is a pure preview of the `edits` args (no I/O).+pub(crate) async fn preview_diff(+ tool: &BuiltinTool,+ args: &serde_json::Value,+ project_root: &Path,+) -> Option<String> {+ match tool.name {+ "edit" => args+ .get("edits")+ .and_then(|v| v.as_array())+ .map(|e| render_edit_diff(e))+ .filter(|d| !d.is_empty()),+ "write" => {+ let prior = match arg_str(args, "path") {+ Some(p) => tokio::fs::read_to_string(resolve(project_root, p)).await.ok(),+ None => None,+ };+ let new = arg_str(args, "content").unwrap_or("");+ Some(render_write_diff(prior.as_deref(), new))+ }+ _ => None,+ }+}+/// 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@@ -105,27 +133,18 @@ pub(crate) async fn execute_builtin_with_diff(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 {+ match preview_diff(tool, args, project_root).await {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 diff = preview_diff(tool, args, project_root).await;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)))+ (content, diff)}_ => (execute_builtin(tool, args, project_root).await, None),}@@ -772,6 +791,35 @@ mod tests {);}+ #[tokio::test]+ async fn preview_diff_does_not_write_and_matches_execution_diff() {+ let root = unique_root();+ // edit preview: pure, no file needed, no file created.+ let edit_preview = preview_diff(+ lookup("edit").unwrap(),+ &json!({"path": "p.txt", "edits": [{"old_string": "foo", "new_string": "bar"}]}),+ &root,+ )+ .await;+ assert_eq!(edit_preview.as_deref(), Some("- foo\n+ bar"));++ // write preview reflects prior-file state and does not create the file.+ let write_preview = preview_diff(+ lookup("write").unwrap(),+ &json!({"path": "new.txt", "content": "hello"}),+ &root,+ )+ .await;+ assert_eq!(write_preview.as_deref(), Some("@@ created file @@\n+ hello"));+ assert!(!root.join("new.txt").exists(), "preview must not write");++ // non-mutating tools have no preview.+ assert!(preview_diff(lookup("read").unwrap(), &json!({"path": "x"}), &root)+ .await+ .is_none());+ let _ = std::fs::remove_dir_all(&root);+ }+#[tokio::test]async fn edit_with_diff_appends_hunks_to_model_content() {let root = unique_root();diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 956a237d7..5d0dc8ca9 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -1145,12 +1145,16 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {capability,path,command,+ diff,..} => {let detail = command.map(|c| format!(" ({c})")).or_else(|| path.map(|p| format!(" on {p}"))).unwrap_or_default();+ if let Some(diff) = diff {+ eprintln!("\x1b[2m{diff}\x1b[0m");+ }let decision = prompt_permission(tool_name, capability, detail).await;if let Some(sender) = registry.lock().await.remove(&request_id) {let _ = sender.send(decision);diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 2c6313596..6d321df9d 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -51,6 +51,9 @@ struct Pending {path: Option<String>,/// Shell command for exec prompts; drives the command-scoped always-grant.command: Option<String>,+ /// Focused diff preview for write/edit prompts, shown so the user approves+ /// with the change in view; `None` for other tools.+ diff: Option<String>,offers_always: bool,/// Highlighted option in the docked prompt (index into `options()`).selected: usize,@@ -83,6 +86,16 @@ impl Pending {}}+ /// Boxed diff preview for the prompt, sized to `inner` width; empty when the+ /// tool carries no diff (exec/read). No gutter: the panel sits flush in the+ /// prompt box, unlike the tool-row-aligned result diff.+ fn diff_preview(&self, inner: u16) -> Vec<Line<'static>> {+ match &self.diff {+ Some(d) => diff_lines(d, (inner as usize).saturating_sub(4).max(1), ""),+ None => Vec::new(),+ }+ }+/// 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())];@@ -495,7 +508,7 @@ impl App {Span::styled(summarize_result(&content, max), Style::new().dim()),]));if let Some(diff) = diff {- for line in diff_lines(&diff, max) {+ for line in diff_lines(&diff, max, "│ ") {self.push(line);}}@@ -506,6 +519,7 @@ impl App {capability,path,command,+ diff,offers_always,..} => {@@ -518,6 +532,7 @@ impl App {capability,path,command,+ diff,offers_always,selected: 0,});@@ -629,8 +644,9 @@ const DIFF_MAX_ROWS: usize = 20;/// Render focused-diff text as a boxed panel: a light rule frames the change,/// `-` lines red, `+` green, `@@` headers dim-cyan. Content is truncated to/// `max` and each row padded so the right border aligns. Collapses to-/// `DIFF_MAX_ROWS` with a `(+N more)` tail before the closing rule.-fn diff_lines(diff: &str, max: usize) -> Vec<Line<'static>> {+/// `DIFF_MAX_ROWS` with a `(+N more)` tail before the closing rule. `gutter`+/// indents the panel (tool-row alignment under a result; empty in the prompt).+fn diff_lines(diff: &str, max: usize, gutter: &'static str) -> Vec<Line<'static>> {let all: Vec<&str> = diff.lines().collect();let shown = all.len().min(DIFF_MAX_ROWS);let truncated = all.len() > shown;@@ -651,7 +667,7 @@ fn diff_lines(diff: &str, max: usize) -> Vec<Line<'static>> {Style::new().dim(),));}- boxed_panel(rows, max, "│ ")+ boxed_panel(rows, max, gutter)}/// Frame `(text, style)` rows in a light box, right-padded to the widest row@@ -1853,7 +1869,9 @@ fn draw(f: &mut Frame, app: &mut App) {// 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 diff_rows = pending.diff_preview(chunks[2].width.saturating_sub(2)).len() as u16;+ let height =+ (pending.options().len() as u16 + detail_rows + diff_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,@@ -1900,12 +1918,17 @@ fn draw_permission(f: &mut Frame, area: ratatui::layout::Rect, pending: &Pendingf.render_widget(Clear, area);f.render_widget(block, area);+ let diff = pending.diff_preview(inner.width);let rows = Layout::vertical([Constraint::Length(detail.len() as u16),- Constraint::Min(1),+ Constraint::Min(diff.len() as u16),+ Constraint::Length(pending.options().len() as u16),]).split(inner);f.render_widget(Paragraph::new(detail).wrap(Wrap { trim: false }), rows[0]);+ if !diff.is_empty() {+ f.render_widget(Paragraph::new(diff), rows[1]);+ }let items: Vec<ListItem> = pending.options()@@ -1917,7 +1940,7 @@ fn draw_permission(f: &mut Frame, area: ratatui::layout::Rect, pending: &Pending.highlight_symbol("▶ ");let mut state = ListState::default();state.select(Some(pending.selected));- f.render_stateful_widget(list, rows[1], &mut state);+ f.render_stateful_widget(list, rows[2], &mut state);}fn draw_picker(f: &mut Frame, area: ratatui::layout::Rect, picker: &Picker) {@@ -2090,6 +2113,7 @@ mod tests {capability: "execute".into(),path: None,command: Some("git status".into()),+ diff: None,offers_always,selected: 0,}@@ -2114,6 +2138,44 @@ mod tests {assert_eq!(opts[1].0, PermissionDecision::AllowAlways);}+ #[test]+ fn write_permission_prompt_carries_diff_into_pending() {+ let mut app = test_app();+ app.apply(StreamEvent::PermissionRequest {+ request_id: "w1".into(),+ tool_name: "write".into(),+ capability: "write".into(),+ path: Some("out.txt".into()),+ command: None,+ diff: Some("@@ created file @@\n+ hi".into()),+ prompt_kind: "write".into(),+ offers_always: true,+ });+ let p = app.pending.as_ref().unwrap();+ assert_eq!(p.diff.as_deref(), Some("@@ created file @@\n+ hi"));+ let preview = p.diff_preview(60);+ assert!(preview.len() >= 4, "boxed diff expected, got {preview:?}");+ let text: String = preview.iter().map(line_text).collect();+ assert!(text.contains('┌') && text.contains('┘'), "no box frame: {text}");+ assert!(text.contains("+ hi"), "diff content missing: {text}");+ }++ #[test]+ fn exec_permission_prompt_has_no_diff_preview() {+ let mut app = test_app();+ app.apply(StreamEvent::PermissionRequest {+ request_id: "e1".into(),+ tool_name: "bash".into(),+ capability: "exec".into(),+ path: None,+ command: Some("ls".into()),+ diff: None,+ prompt_kind: "exec".into(),+ offers_always: true,+ });+ assert!(app.pending.as_ref().unwrap().diff_preview(60).is_empty());+ }+#[test]fn pending_selection_wraps_both_directions() {let mut p = pending(true); // 3 options@@ -2318,7 +2380,7 @@ mod tests {#[test]fn diff_lines_renders_all_when_under_cap() {- let out = diff_lines("- foo\n+ bar", 80);+ let out = diff_lines("- foo\n+ bar", 80, "│ ");// 2 content rows framed by a top and bottom border.assert_eq!(out.len(), 4);assert!(line_text(&out[0]).contains('┌'), "top: {}", line_text(&out[0]));@@ -2335,7 +2397,7 @@ mod tests {.map(|i| format!("+ line {i}")).collect::<Vec<_>>().join("\n");- let out = diff_lines(&diff, 80);+ let out = diff_lines(&diff, 80, "│ ");// DIFF_MAX_ROWS content rows + a `(+N more)` row, framed by 2 borders.assert_eq!(out.len(), DIFF_MAX_ROWS + 1 + 2);// The tail sits just above the closing border.@@ -2640,6 +2702,7 @@ mod tests {capability: "exec".into(),path: None,command: Some("grep -n foo src/".into()),+ diff: None,prompt_kind: "exec".into(),offers_always: true,});diff --git a/web-app/src/services/agent/types.ts b/web-app/src/services/agent/types.tsindex 31d69dbc0..48a144522 100644--- a/web-app/src/services/agent/types.ts+++ b/web-app/src/services/agent/types.ts@@ -21,6 +21,8 @@ export type StreamEvent =tool_name: stringcapability: stringpath?: string | null+ command?: string | null+ diff?: string | nullprompt_kind: stringoffers_always: boolean}