aboutsummaryrefslogtreecommitdiffstats
path: root/crates/atuin-ai/src/tui
diff options
context:
space:
mode:
authorMichelle Tilley <michelle@michelletilley.net>2026-04-21 10:53:31 -0700
committerGitHub <noreply@github.com>2026-04-21 10:53:31 -0700
commit33c779aa9894e1347aeaa4c73e536cf842aee684 (patch)
treebfe0f60252518798ccf4621c7bea06021e64d2f4 /crates/atuin-ai/src/tui
parentfeat: AI tool rendering overhaul + edit_file tool (#3423) (diff)
downloadatuin-33c779aa9894e1347aeaa4c73e536cf842aee684.zip
feat: Implement write_file tool with overwrite safety (#3432)
## Summary Implements the `write_file` client-side tool — creates new files or overwrites existing ones with an explicit `overwrite` flag for safety. - **Overwrite flag**: Writing to an existing file without `overwrite: true` returns an error directing the LLM to set the flag or use `edit_file` for targeted changes. Prevents accidental overwrites. - **Snapshots**: Existing files are backed up before overwriting (same infrastructure as `edit_file`). - **Content preview**: Completed writes show the first 10 lines in gray with line numbers, plus "+ N more lines" for longer files. - **Atomic writes**: Uses `tempfile` + fsync + rename (same as `edit_file`). - **File tracker update**: After writing, the file is registered in the tracker so subsequent `edit_file` calls work without a separate read. - **Permission**: Shares the `"Write"` rule with `edit_file` — one permission covers both tools.
Diffstat (limited to 'crates/atuin-ai/src/tui')
-rw-r--r--crates/atuin-ai/src/tui/dispatch.rs67
-rw-r--r--crates/atuin-ai/src/tui/view/mod.rs68
-rw-r--r--crates/atuin-ai/src/tui/view/turn.rs6
3 files changed, 131 insertions, 10 deletions
diff --git a/crates/atuin-ai/src/tui/dispatch.rs b/crates/atuin-ai/src/tui/dispatch.rs
index fea26953..46eebd9b 100644
--- a/crates/atuin-ai/src/tui/dispatch.rs
+++ b/crates/atuin-ai/src/tui/dispatch.rs
@@ -232,6 +232,10 @@ fn execute_tool(
let edit_call = edit_call.clone();
execute_edit_tool(handle, tx, tool_id, edit_call);
}
+ ClientToolCall::Write(write_call) => {
+ let write_call = write_call.clone();
+ execute_write_tool(handle, tx, tool_id, write_call);
+ }
_ => {
execute_simple_tool(handle, tx, tool_id, tool, db);
}
@@ -387,6 +391,69 @@ fn execute_edit_tool(
});
}
+/// Execute a write_file tool call.
+///
+/// Snapshots the existing file (if any) before overwriting, writes atomically,
+/// stores a content preview on the tracker, and updates the file tracker.
+fn execute_write_tool(
+ handle: &Handle<Session>,
+ tx: &mpsc::Sender<AiTuiEvent>,
+ tool_id: String,
+ write_call: crate::tools::WriteToolCall,
+) {
+ let h = handle.clone();
+ let tx = tx.clone();
+
+ tokio::spawn(async move {
+ let resolved = write_call.resolved_path();
+
+ // 1. Snapshot the existing file before overwriting (if it exists).
+ if resolved.exists()
+ && let Ok(original_content) = std::fs::read(&resolved)
+ {
+ let snap_path = resolved.clone();
+ h.update(move |state| {
+ if let Some(ref mut store) = state.snapshot_store
+ && let Err(e) = store.ensure_snapshot(&snap_path, &original_content)
+ {
+ tracing::warn!("failed to create file snapshot: {e}");
+ }
+ });
+ }
+
+ // 2. Execute: check exists/overwrite, atomic write
+ let (outcome, new_bytes) = write_call.execute(&resolved);
+
+ // 3. Build content preview on success
+ let write_preview = if new_bytes.is_some() {
+ Some(crate::diff::WritePreview::from_content(&write_call.content))
+ } else {
+ None
+ };
+
+ // 4. Update tracker, store preview, and finish
+ let tc_id = tool_id;
+ h.update(move |state| {
+ if let Some(ref new_bytes) = new_bytes
+ && let Ok(mtime) = std::fs::metadata(&resolved).and_then(|m| m.modified())
+ {
+ state
+ .file_tracker
+ .update_after_edit(&resolved, new_bytes, mtime);
+ }
+ if let Some(preview) = write_preview
+ && let Some(tracked) = state.tool_tracker.get_mut(&tc_id)
+ {
+ tracked.write_preview = Some(preview);
+ }
+ state.finish_tool_call(&tc_id, outcome);
+ if !state.tool_tracker.has_pending() {
+ let _ = tx.send(AiTuiEvent::ContinueAfterTools);
+ }
+ });
+ });
+}
+
/// Execute a shell tool with streaming VT100 preview.
fn execute_shell_tool(
handle: &Handle<Session>,
diff --git a/crates/atuin-ai/src/tui/view/mod.rs b/crates/atuin-ai/src/tui/view/mod.rs
index bdbece9c..6e13e406 100644
--- a/crates/atuin-ai/src/tui/view/mod.rs
+++ b/crates/atuin-ai/src/tui/view/mod.rs
@@ -175,7 +175,7 @@ fn tool_call_view(tool_call: &TrackedTool, in_git_project: bool) -> Elements {
/// keep the standard set.
fn permission_options_for_tool(tool: &ClientToolCall, in_git_project: bool) -> Vec<SelectOption> {
match tool {
- ClientToolCall::Edit(_) => vec![
+ ClientToolCall::Edit(_) | ClientToolCall::Write(_) => vec![
SelectOption::builder()
.label("Allow")
.value(PermissionResult::Allow.as_value_str())
@@ -296,8 +296,8 @@ fn agent_turn_view(events: &[turn::UiEvent], busy: bool) -> Elements {
turn::ToolRenderData::FileEdit { path, preview } => {
file_edit_tool_view(&tool_key, &details.status, path, preview.as_ref())
},
- turn::ToolRenderData::FileWrite { path } => {
- file_write_tool_view(&details.status, path)
+ turn::ToolRenderData::FileWrite { path, preview } => {
+ file_write_tool_view(&tool_key, &details.status, path, preview.as_ref())
},
turn::ToolRenderData::Remote => {
tool_status_view(&details.name, &details.status)
@@ -577,10 +577,16 @@ fn file_edit_tool_view(
}
}
-/// Render a file write tool call status with the target path.
-fn file_write_tool_view(status: &turn::ToolResultStatus, path: &std::path::Path) -> Elements {
- let display_path = path.display();
- match status {
+/// Render a file write tool call with content preview.
+fn file_write_tool_view(
+ key: &str,
+ status: &turn::ToolResultStatus,
+ path: &std::path::Path,
+ preview: Option<&crate::diff::WritePreview>,
+) -> Elements {
+ let display_path = format_path_for_display(path);
+
+ let status_line = match status {
turn::ToolResultStatus::Pending => {
element! {
Spinner(
@@ -591,18 +597,62 @@ fn file_write_tool_view(status: &turn::ToolResultStatus, path: &std::path::Path)
}
}
turn::ToolResultStatus::Success => {
+ let line_info = preview
+ .map(|p| format!(" ({} lines)", p.total_lines))
+ .unwrap_or_default();
element! {
- Spinner(label: format!("Wrote: {display_path}"), done: true)
+ Spinner(label: format!("Wrote: {display_path}{line_info}"), done: true)
}
}
turn::ToolResultStatus::Error => {
element! {
Text {
Span(text: "✗ ", style: Style::default().fg(Color::Red))
- Span(text: format!("Write {display_path}: denied"), style: Style::default().fg(Color::Red))
+ Span(text: format!("Write {display_path}: failed"), style: Style::default().fg(Color::Red))
}
}
}
+ };
+
+ let Some(preview) = preview else {
+ return status_line;
+ };
+ if preview.lines.is_empty() {
+ return status_line;
+ }
+
+ let gutter_width = preview.total_lines.to_string().len().max(2) as u16 + 1;
+ let remaining = preview.remaining_lines();
+
+ element! {
+ View(key: key.to_string()) {
+ #(status_line)
+
+ View(key: format!("{key}-content"), padding_left: Cells::from(2)) {
+ #(for (idx, line) in preview.lines.iter().enumerate() {
+ HStack(key: format!("{key}-line-{idx}")) {
+ View(width: WidthConstraint::Fixed(gutter_width)) {
+ Text { Span(
+ text: format!("{:>width$}", idx + 1, width = (gutter_width - 1) as usize),
+ style: Style::default().fg(Color::DarkGray)
+ ) }
+ }
+ View {
+ Text { Span(text: line, style: Style::default().fg(Color::DarkGray)) }
+ }
+ }
+ })
+
+ #(if remaining > 0 {
+ Text {
+ Span(
+ text: format!(" ... +{remaining} more lines"),
+ style: Style::default().fg(Color::DarkGray)
+ )
+ }
+ })
+ }
+ }
}
}
diff --git a/crates/atuin-ai/src/tui/view/turn.rs b/crates/atuin-ai/src/tui/view/turn.rs
index 1c19a6b2..6c3d5c29 100644
--- a/crates/atuin-ai/src/tui/view/turn.rs
+++ b/crates/atuin-ai/src/tui/view/turn.rs
@@ -141,7 +141,10 @@ pub(crate) enum ToolRenderData {
preview: Option<crate::diff::EditPreview>,
},
/// File write/create operation.
- FileWrite { path: PathBuf },
+ FileWrite {
+ path: PathBuf,
+ preview: Option<crate::diff::WritePreview>,
+ },
/// Atuin history search.
HistorySearch {
query: String,
@@ -449,6 +452,7 @@ impl<'a> TurnBuilder<'a> {
},
ClientToolCall::Write(write) => ToolRenderData::FileWrite {
path: write.path.clone(),
+ preview: tracked.write_preview.clone(),
},
ClientToolCall::AtuinHistory(history) => ToolRenderData::HistorySearch {
query: history.query.clone(),