返回 CodeWhale
debug_operations.rs
根目录 / crates / tui / src / commands / contract / debug_operations.rs
1 //! Host operations moved out of `groups/debug/undo.rs` and `receipts.rs`.
2 //! Snapshot safety and authoritative state mutation remain here. The portable
3 //! commands receive typed observations/outcomes, never completed command text.
4 //! File undo is admitted by the asynchronous TUI owner before mutation.
5
6 use super::SharedCommandHost;
7 use crate::tui::app::App;
8 use crate::tui::app::StatusToastLevel;
9 use crate::tui::history::HistoryCell;
10 use codewhale_command_contract::facets::*;
11 use codewhale_dependencies::{ExternalTool, Git};
12 use std::path::PathBuf;
13
14 pub(super) struct DebugOperationsAdapter<'a> {
15 pub(super) host: SharedCommandHost<'a>,
16 }
17
18 impl CommandDebugReceiptsContext for DebugOperationsAdapter<'_> {
19 fn receipt(&self, turn: Option<&str>) -> Result<Receipt, DebugReceiptError> {
20 let app = self.host.app.borrow();
21 let approvals = match app.current_session_id.as_deref() {
22 Some(id) => codewhale_engine::approval_log::ApprovalReceiptStore::default_location()
23 .and_then(|store| store.load(id))
24 .map_err(|error| DebugReceiptError::ApprovalLog(error.to_string()))?,
25 None => Vec::new(),
26 };
27 let source = ReceiptSource {
28 kind: SourceKind::Session,
29 id: app
30 .current_session_id
31 .clone()
32 .unwrap_or_else(|| "unsaved".to_string()),
33 title: app.session_title.clone(),
34 workspace: Some(app.workspace.display().to_string()),
35 model: Some(app.model.clone()),
36 started_at: Some(app.session_started_at),
37 updated_at: None,
38 };
39 let receipt = codewhale_engine::receipts::session_receipt(
40 source,
41 &app.api_messages,
42 &approvals,
43 &app.session_turn_outcomes,
44 turn,
45 )
46 .map_err(|error| DebugReceiptError::Build(error.to_string()))?;
47 let usage = codewhale_engine::receipts::session_usage(
48 &super::debug_diagnostics::cost_projection(&app),
49 &app.session.accounted_usage_sources,
50 u64::from(app.session.displayed_total_tokens()),
51 );
52 Ok(codewhale_engine::receipts::with_usage(receipt, usage))
53 }
54 }
55
56 impl CommandDebugChangeContext for DebugOperationsAdapter<'_> {
57 fn change_projection(&self) -> DebugChangeProjection {
58 let app = self.host.app.borrow();
59 DebugChangeProjection {
60 changelog: crate::whats_new::BUNDLED_CHANGELOG,
61 is_english: app.ui_locale == codewhale_localization::Locale::En,
62 translation_available: !app.offline_mode && !app.onboarding_needs_api_key,
63 translation_target: app.ui_locale.translation_target_name(),
64 }
65 }
66 }
67
68 impl CommandDebugHistoryContext for DebugOperationsAdapter<'_> {
69 fn last_user_input(&self) -> Option<String> {
70 self.host
71 .app
72 .borrow()
73 .history
74 .iter()
75 .rev()
76 .find_map(|cell| match cell {
77 HistoryCell::User { content } => Some(content.clone()),
78 _ => None,
79 })
80 }
81 fn load_composer(&mut self, input: String) {
82 let mut app = self.host.app.borrow_mut();
83 // A queued follow-up still open for editing would otherwise stay bound
84 // to the composer and be overwritten, or sent in place of this edit.
85 // Return it to the queue first — the same hand-back as Esc.
86 if app.cancel_queued_draft_edit() {
87 app.show_command_result(
88 "Queued edit canceled; follow-up restored".to_string(),
89 StatusToastLevel::Warning,
90 );
91 }
92 app.input = input;
93 app.cursor_position = app.input.chars().count();
94 app.edit_in_progress = true;
95 }
96 fn undo_conversation(&mut self) -> DebugConversationUndo {
97 undo_conversation_for_engine(&mut self.host.app.borrow_mut())
98 }
99 }
100
101 impl CommandDebugUndoContext for DebugOperationsAdapter<'_> {}
102
103 impl CommandDebugDiffContext for DebugOperationsAdapter<'_> {
104 fn diff(&self) -> DebugDiffObservation {
105 let app = self.host.app.borrow();
106 if !Git::available() {
107 return DebugDiffObservation::GitUnavailable;
108 }
109 match session_diff(&app) {
110 Ok(Some(observation)) => observation,
111 Ok(None) => workspace_git_diff(&app.workspace),
112 Err(error) => DebugDiffObservation::Failed(error.to_string()),
113 }
114 }
115 }
116
117 /// Most patch text `/diff` hands to the pager. The file list and the stat
118 /// are never cut.
119 const MAX_DIFF_PATCH_BYTES: usize = 256 * 1024;
120
121 /// What changed in the workspace since this session's first restore point,
122 /// or `None` when the session has none here (no turn has run yet, or
123 /// snapshots are off for this workspace).
124 ///
125 /// The restore points are the session's own record of where it started, so
126 /// this works the same in a folder that is not a git repository, and it
127 /// includes files created since. Reads only: no snapshot is taken and the
128 /// side repo is not created.
129 fn session_diff(app: &App) -> std::io::Result<Option<DebugDiffObservation>> {
130 let Some(session_id) = app.current_session_id.as_deref() else {
131 return Ok(None);
132 };
133 let Some(repo) = codewhale_snapshot::SnapshotRepo::open_existing(&app.workspace)? else {
134 return Ok(None);
135 };
136 // Newest first, so the session's first restore point is the last match.
137 let Some(start) = repo
138 .list(usize::MAX)?
139 .into_iter()
140 .rev()
141 .find(|snapshot| snapshot.session_id.as_deref() == Some(session_id))
142 else {
143 return Ok(None);
144 };
145 let changes = repo.work_tree_changes_since(&start.tree, MAX_DIFF_PATCH_BYTES)?;
146 Ok(Some(DebugDiffObservation::Output {
147 names: changes.names,
148 stat: changes.stat,
149 patch: changes.patch,
150 patch_truncated: changes.patch_truncated,
151 }))
152 }
153
154 /// The workspace repository's own uncommitted changes: what `/diff` shows
155 /// before the session has a restore point to compare against.
156 fn workspace_git_diff(workspace: &std::path::Path) -> DebugDiffObservation {
157 let git =
158 |args: &[&str]| Git::output(&[&["-c", "core.quotePath=false"], args].concat(), workspace);
159 // Outside a repository `git diff` prints nothing on stdout, which would
160 // read as "no changes".
161 match git(&["rev-parse", "--is-inside-work-tree"]) {
162 Ok(probe)
163 if probe.status.success()
164 && String::from_utf8_lossy(&probe.stdout).trim() == "true" => {}
165 Ok(_) => return DebugDiffObservation::NoBaseline,
166 Err(error) => return DebugDiffObservation::Failed(error.to_string()),
167 }
168 let names = git(&["diff", "--name-only"]);
169 let stat = git(&["diff", "--stat"]);
170 let patch = git(&["diff", "--no-color", "--no-ext-diff", "--no-textconv"]);
171 match (names, stat, patch) {
172 (Ok(names), Ok(stat), Ok(patch)) => {
173 let (patch, patch_truncated) = codewhale_snapshot::repo::truncate_at_char_boundary(
174 &String::from_utf8_lossy(&patch.stdout),
175 MAX_DIFF_PATCH_BYTES,
176 );
177 DebugDiffObservation::Output {
178 names: String::from_utf8_lossy(&names.stdout).into_owned(),
179 stat: String::from_utf8_lossy(&stat.stdout).into_owned(),
180 patch,
181 patch_truncated,
182 }
183 }
184 (Err(error), _, _) | (_, Err(error), _) | (_, _, Err(error)) => {
185 DebugDiffObservation::Failed(error.to_string())
186 }
187 }
188 }
189
190 /// Prepare the rollback; the UI action owns Engine acknowledgement and save.
191 /// The last real user boundary includes following tool results/runtime notes.
192 pub(in crate::commands) fn undo_conversation_for_engine(app: &mut App) -> DebugConversationUndo {
193 let removed = app
194 .history
195 .iter()
196 .rposition(|cell| matches!(cell, HistoryCell::User { .. }))
197 .map_or(0, |index| app.history.len() - index);
198 let mut sync = session_sync_payload(app);
199 if let Some(index) = crate::tui::ui::backtrack_api_cut_index(app, 0) {
200 sync.messages.truncate(index);
201 } else if !sync.messages.is_empty() {
202 return DebugConversationUndo { removed: 0, sync };
203 }
204 DebugConversationUndo { removed, sync }
205 }
206
207 fn session_sync_payload(app: &App) -> SessionSyncPayload {
208 SessionSyncPayload {
209 session_id: app.current_session_id.clone(),
210 messages: app.api_messages.as_ref().clone(),
211 system_prompt: app.system_prompt.clone(),
212 model: app.model.clone(),
213 workspace: app.workspace.clone(),
214 mode: super::to_command_mode(app.mode),
215 agent_preset: app.agent_preset(),
216 }
217 }
218
219 /// Deepest fork chain [`snapshot_owners_from`] follows. A chain this long is
220 /// already unusual; the bound only stops a corrupt lineage from looping.
221 const MAX_FORK_ANCESTORS: usize = 32;
222
223 /// A session whose restore points this conversation owns.
224 #[derive(Debug, Clone, PartialEq, Eq)]
225 pub(in crate::commands) struct SnapshotOwner {
226 /// Session tag the snapshots carry.
227 pub(in crate::commands) session_id: String,
228 /// Newest snapshot time (Unix seconds) owned from this session: `None`
229 /// for the current session, the fork time for a session it was forked
230 /// from. The source keeps working after the fork, and its later
231 /// snapshots are not the fork's.
232 pub(in crate::commands) until: Option<i64>,
233 }
234
235 impl SnapshotOwner {
236 fn owns(&self, snapshot: &codewhale_snapshot::Snapshot) -> bool {
237 snapshot.session_id.as_deref() == Some(self.session_id.as_str())
238 && self.until.is_none_or(|until| snapshot.timestamp <= until)
239 }
240 }
241
242 /// The sessions whose restore points `/undo` may use: the current session,
243 /// and for a fork each session it was forked from, up to the fork. A fork
244 /// copies its source's turns, so the snapshots those turns took (tagged
245 /// with the source's id) are the fork's too, as the Runtime's thread-owned
246 /// restore points are (#6621).
247 ///
248 /// Lineage the saved sessions cannot prove ends the chain: fewer owners
249 /// means fewer restorable steps, never someone else's.
250 fn snapshot_owners_from(
251 session_id: Option<String>,
252 current_metadata: Option<codewhale_engine::session_manager::SessionMetadata>,
253 ) -> Vec<SnapshotOwner> {
254 let Some(current) = session_id else {
255 return Vec::new();
256 };
257 let manager = codewhale_engine::session_manager::SessionManager::default_location().ok();
258 let load = |id: &str| {
259 manager
260 .as_ref()
261 .and_then(|manager| manager.load_session_metadata_by_id(id).ok())
262 };
263 let mut metadata = current_metadata
264 .filter(|metadata| metadata.id == current)
265 .or_else(|| load(&current));
266 let mut owners = vec![SnapshotOwner {
267 session_id: current,
268 until: None,
269 }];
270 while let Some(child) = metadata.take() {
271 let Some(parent) = child.parent_session_id.clone() else {
272 break;
273 };
274 if owners.len() > MAX_FORK_ANCESTORS
275 || owners.iter().any(|owner| owner.session_id == parent)
276 {
277 break;
278 }
279 let forked_at = child.created_at.timestamp();
280 let until = owners
281 .last()
282 .and_then(|owner| owner.until)
283 .map_or(forked_at, |child_until| child_until.min(forked_at));
284 metadata = load(&parent);
285 owners.push(SnapshotOwner {
286 session_id: parent,
287 until: Some(until),
288 });
289 }
290 owners
291 }
292
293 pub(crate) struct UndoRangeInput {
294 workspace: PathBuf,
295 session_id: Option<String>,
296 metadata: Option<codewhale_engine::session_manager::SessionMetadata>,
297 requests: Vec<Option<String>>,
298 messages: std::sync::Arc<Vec<codewhale_models::Message>>,
299 boundaries: Vec<usize>,
300 first_request: usize,
301 delegated_writes: std::collections::BTreeMap<u64, Vec<String>>,
302 }
303
304 pub(crate) struct UndoRangePlan {
305 workspace: PathBuf,
306 turns: Vec<codewhale_engine::runtime_threads::manager::DroppedTurnSnapshots>,
307 pub(crate) undone_turn_seqs: Vec<u64>,
308 }
309
310 pub(crate) fn undo_range_input(app: &App, cut: usize) -> anyhow::Result<UndoRangeInput> {
311 let total = app
312 .history
313 .iter()
314 .filter(|cell| matches!(cell, HistoryCell::User { .. }))
315 .count();
316 let boundaries = (0..total).rev().map(|depth| crate::tui::ui::backtrack_api_cut_index(app, depth))
317 .collect::<Option<Vec<_>>>().ok_or_else(|| anyhow::anyhow!("The displayed requests no longer match the Engine conversation; nothing was undone."))?;
318 anyhow::ensure!(
319 boundaries.windows(2).all(|pair| pair[0] < pair[1]),
320 "The displayed request order changed; nothing was undone."
321 );
322 let first_request = boundaries
323 .iter()
324 .position(|index| *index == cut)
325 .ok_or_else(|| {
326 anyhow::anyhow!("The selected request is no longer present; nothing was undone.")
327 })?;
328 let requests = boundaries
329 .iter()
330 .map(|index| {
331 let message = &app.api_messages[*index];
332 let metadata = codewhale_models::turn_classify::turn_metadata_text(message)
333 .map(|(index, _)| index);
334 let mut content = message
335 .content
336 .iter()
337 .enumerate()
338 .filter(|(index, _)| Some(*index) != metadata);
339 match (content.next(), content.next()) {
340 (Some((_, codewhale_models::ContentBlock::Text { text, .. })), None) => {
341 Some(text.clone())
342 }
343 _ => None,
344 }
345 })
346 .collect();
347 Ok(UndoRangeInput {
348 workspace: app.workspace.clone(),
349 session_id: app.current_session_id.clone(),
350 metadata: app.current_session_metadata.clone(),
351 requests,
352 messages: app.api_messages.clone(),
353 boundaries,
354 first_request,
355 delegated_writes: app
356 .current_session_id
357 .as_ref()
358 .map(|session| {
359 app.delegated_writes
360 .iter()
361 .filter(|((owner, _), _)| owner == session)
362 .map(|((_, seq), paths)| (*seq, paths.iter().cloned().collect()))
363 .collect()
364 })
365 .unwrap_or_default(),
366 })
367 }
368
369 pub(crate) fn plan_undo_range(input: UndoRangeInput) -> anyhow::Result<UndoRangePlan> {
370 use codewhale_engine::core::turn::{parse_snapshot_label, snapshot_label_prompt_snippet};
371 use codewhale_engine::tools::spec::ToolSpec;
372 use codewhale_models::{ContentBlock, ToolCallKey};
373 use codewhale_snapshot::{WorkspaceSnapshotKind, WorkspaceSnapshotRef};
374 let owners = snapshot_owners_from(input.session_id, input.metadata);
375 let mut repo = None;
376 let mut snapshots = Vec::new();
377 let mut turns = Vec::new();
378 let mut undone_turn_seqs = Vec::new();
379 let mut previous_before = None;
380 let mut execution_ids = std::collections::BTreeSet::new();
381 let boundaries: Vec<_> = input
382 .boundaries
383 .iter()
384 .copied()
385 .chain(std::iter::once(input.messages.len()))
386 .collect();
387 for turn_index in input.first_request..input.requests.len() {
388 let messages = &input.messages[boundaries[turn_index]..boundaries[turn_index + 1]];
389 let has_tools = messages
390 .iter()
391 .flat_map(|message| &message.content)
392 .any(|block| {
393 matches!(
394 block,
395 ContentBlock::ToolUse { .. }
396 | ContentBlock::ServerToolUse { .. }
397 | ContentBlock::ToolResult { .. }
398 | ContentBlock::ToolSearchToolResult { .. }
399 | ContentBlock::CodeExecutionToolResult { .. }
400 | ContentBlock::WebSearchToolResult { .. }
401 | ContentBlock::WebFetchToolResult { .. }
402 | ContentBlock::WebSearchCall { .. }
403 | ContentBlock::ServerToolCalls { .. }
404 )
405 });
406 if !has_tools {
407 turns.push(
408 codewhale_engine::runtime_threads::manager::DroppedTurnSnapshots {
409 turn_id: format!("conversation-{}", boundaries[turn_index]),
410 may_change_files: false,
411 snapshots: Vec::new(),
412 declared_writes: Vec::new(),
413 delegated_writes: Vec::new(),
414 unrun_tool_calls: Default::default(),
415 },
416 );
417 continue;
418 }
419 let mut calls = std::collections::BTreeMap::new();
420 let mut declared_writes = Vec::new();
421 let mut all_readonly = true;
422 for message in messages {
423 for block in &message.content {
424 if let ContentBlock::ToolUse {
425 execution_id,
426 name,
427 input,
428 ..
429 } = block
430 {
431 let id = execution_id.as_deref().filter(|id| !id.trim().is_empty())
432 .ok_or_else(|| anyhow::anyhow!("A selected tool call has no recorded host execution identifier; nothing was undone. Use /restore or conversation backtracking."))?;
433 anyhow::ensure!(
434 execution_ids.insert(id),
435 "Selected tool calls have a repeated host execution identifier; nothing was undone."
436 );
437 all_readonly &= match name.as_str() {
438 "read" => {
439 codewhale_engine::tools::file_tool::ReadTool.is_read_only_for(input)
440 }
441 "read_file" => {
442 codewhale_engine::tools::file::ReadFileTool.is_read_only_for(input)
443 }
444 "list_dir" => {
445 codewhale_engine::tools::file::ListDirTool.is_read_only_for(input)
446 }
447 "File" => matches!(
448 codewhale_execpolicy::canonical_action::canonical_action_alias(
449 name, input
450 ),
451 "read_file" | "list_dir" | "file_search" | "grep_files"
452 ),
453 _ => false,
454 };
455 let writes =
456 codewhale_engine::core::engine::file_write_tool_target_paths(name, input);
457 declared_writes.extend(writes.iter().flatten().cloned());
458 calls.insert(id, writes);
459 }
460 }
461 }
462 let mut completed = std::collections::HashSet::new();
463 for block in messages.iter().flat_map(|message| &message.content) {
464 match block {
465 ContentBlock::ToolResult { .. } => match block.tool_call_key() {
466 Some(ToolCallKey::Execution(id)) if calls.contains_key(id) => {
467 all_readonly &= completed.insert(id);
468 }
469 _ => all_readonly = false,
470 },
471 ContentBlock::ServerToolUse { .. }
472 | ContentBlock::ToolSearchToolResult { .. }
473 | ContentBlock::CodeExecutionToolResult { .. }
474 | ContentBlock::WebSearchToolResult { .. }
475 | ContentBlock::WebFetchToolResult { .. }
476 | ContentBlock::WebSearchCall { .. }
477 | ContentBlock::ServerToolCalls { .. } => all_readonly = false,
478 _ => {}
479 }
480 }
481 if all_readonly && !calls.is_empty() && completed.len() == calls.len() {
482 turns.push(
483 codewhale_engine::runtime_threads::manager::DroppedTurnSnapshots {
484 turn_id: format!("read-only-{}", boundaries[turn_index]),
485 may_change_files: false,
486 snapshots: Vec::new(),
487 declared_writes: Vec::new(),
488 delegated_writes: Vec::new(),
489 unrun_tool_calls: Default::default(),
490 },
491 );
492 continue;
493 }
494 anyhow::ensure!(
495 !owners.is_empty(),
496 "This conversation has no owned restore points; nothing was undone. Use /restore or conversation backtracking."
497 );
498 if repo.is_none() {
499 anyhow::ensure!(
500 codewhale_snapshot::wait_for_pending_post_turn_snapshots(POST_TURN_SNAPSHOT_WAIT),
501 "A restore point is still being saved; nothing was undone. Try again when it finishes."
502 );
503 let opened = codewhale_snapshot::SnapshotRepo::open_existing(&input.workspace)?
504 .ok_or_else(|| anyhow::anyhow!("This request has no recorded file restore points; nothing was undone. Use /restore or conversation backtracking."))?;
505 snapshots = opened.list(usize::MAX)?;
506 repo = Some(opened);
507 }
508 let repo = repo.as_ref().unwrap();
509 let mut window = None;
510 for (id, writes) in &calls {
511 let label = format!("tool:{id}");
512 let matches: Vec<_> = snapshots
513 .iter()
514 .enumerate()
515 .filter(|(_, snapshot)| {
516 snapshot.label == label && owners.iter().any(|owner| owner.owns(snapshot))
517 })
518 .map(|(index, _)| index)
519 .collect();
520 if matches.is_empty() {
521 anyhow::ensure!(
522 writes.is_none(),
523 "A file-writing invocation has no owned restore point; nothing was undone. Use /restore or conversation backtracking."
524 );
525 continue;
526 }
527 anyhow::ensure!(
528 matches.len() == 1,
529 "A host execution has repeated restore points; nothing was undone."
530 );
531 let tool = matches[0];
532 let before = (tool + 1..snapshots.len()).find(|index| is_restore_point_label(&snapshots[*index].label))
533 .ok_or_else(|| anyhow::anyhow!("The file invocation has no complete request start; nothing was undone. Use /restore."))?;
534 let after = (0..tool).rev().find(|index| is_restore_point_label(&snapshots[*index].label))
535 .ok_or_else(|| anyhow::anyhow!("The file invocation has no complete request end; nothing was undone. Use /restore."))?;
536 anyhow::ensure!(
537 is_undo_step_label(&snapshots[before].label)
538 && snapshots[after].label.starts_with("post-turn:"),
539 "The file invocation has an incomplete request boundary; nothing was undone. Use /restore."
540 );
541 anyhow::ensure!(
542 window.is_none_or(|previous| previous == (before, after)),
543 "The request's host executions do not share one completed window; nothing was undone."
544 );
545 window = Some((before, after));
546 }
547 let (oldest, newest) = window.ok_or_else(|| anyhow::anyhow!("The request has no owned file-writer receipt; nothing was undone. Use conversation backtracking, or /restore for an explicit file restore."))?;
548 let before = &snapshots[oldest];
549 let after = &snapshots[newest];
550 let pre = parse_snapshot_label(&before.label);
551 let post = parse_snapshot_label(&after.label);
552 let snippet = input.requests[turn_index].as_deref().and_then(snapshot_label_prompt_snippet)
553 .ok_or_else(|| anyhow::anyhow!("The selected multipart request cannot be checked against its file restore point; nothing was undone. Use /restore or conversation backtracking."))?;
554 anyhow::ensure!(
555 pre.prompt_snippet.as_deref().map(str::trim_end) == Some(snippet.trim_end()),
556 "The file invocation's request text does not match the selected request; nothing was undone."
557 );
558 anyhow::ensure!(
559 pre.seq.is_some() && pre.seq == post.seq && before.session_id == after.session_id,
560 "The selected request has an incomplete restore point; nothing was undone. Use /restore."
561 );
562 anyhow::ensure!(
563 snapshots[newest..=oldest]
564 .iter()
565 .all(|snapshot| snapshot.session_id == before.session_id),
566 "The request's restore points mix different sessions; nothing was undone. Use /restore or conversation backtracking."
567 );
568 anyhow::ensure!(
569 newest < oldest && previous_before.is_none_or(|previous| oldest < previous),
570 "Selected file invocations do not follow the conversation; nothing was undone."
571 );
572 let range_oldest = previous_before.unwrap_or(oldest);
573 anyhow::ensure!(
574 snapshots[newest..=range_oldest]
575 .iter()
576 .all(|snapshot| owners.iter().any(|owner| owner.owns(snapshot))),
577 "Another conversation recorded workspace changes inside the selected range; nothing was undone."
578 );
579 previous_before = Some(oldest);
580 let mut receipts = Vec::new();
581 let mut previous_tree = None;
582 for snapshot in snapshots[newest..=oldest].iter().rev() {
583 let (kind, call) = if snapshot.id == before.id {
584 (WorkspaceSnapshotKind::PreTurn, None)
585 } else if snapshot.id == after.id {
586 (WorkspaceSnapshotKind::PostTurn, None)
587 } else if let Some(call) = snapshot.label.strip_prefix("tool:") {
588 (WorkspaceSnapshotKind::Tool, Some(call))
589 } else if let Some(call) = snapshot.label.strip_prefix("post-tool:") {
590 (WorkspaceSnapshotKind::PostTool, Some(call))
591 } else {
592 anyhow::bail!(
593 "An unrecognized restore point lies inside the selected request; nothing was undone."
594 )
595 };
596 let writes = call.map(|id| calls.get(id).ok_or_else(|| anyhow::anyhow!("A restore point cannot be bound to the selected request's recorded host execution; nothing was undone. Use /restore or conversation backtracking."))).transpose()?.cloned().flatten();
597 let changed_paths = previous_tree
598 .as_ref()
599 .map(|previous| repo.changed_paths_between(previous, &snapshot.tree))
600 .transpose()?
601 .map(|paths| {
602 paths
603 .into_iter()
604 .map(|path| path.to_string_lossy().into_owned())
605 .collect()
606 });
607 receipts.push(WorkspaceSnapshotRef {
608 kind,
609 snapshot_id: snapshot.id.as_str().to_string(),
610 tree_id: snapshot.tree.as_str().to_string(),
611 session_id: snapshot.session_id.clone().unwrap(),
612 tool_call_id: call.map(str::to_owned),
613 write_paths: writes,
614 changed_paths,
615 });
616 previous_tree = Some(snapshot.tree.clone());
617 }
618 for (index, receipt) in receipts
619 .iter()
620 .enumerate()
621 .filter(|(_, receipt)| receipt.kind == WorkspaceSnapshotKind::Tool)
622 {
623 anyhow::ensure!(
624 receipts[index + 1..]
625 .iter()
626 .any(|later| later.kind == WorkspaceSnapshotKind::PostTool
627 && later.tool_call_id == receipt.tool_call_id),
628 "The request has no closed per-tool restore point; nothing was undone. Use /restore or conversation backtracking."
629 );
630 }
631 if let Some(seq) = pre.seq {
632 undone_turn_seqs.push(seq);
633 }
634 turns.push(
635 codewhale_engine::runtime_threads::manager::DroppedTurnSnapshots {
636 turn_id: before.id.as_str().to_string(),
637 may_change_files: true,
638 snapshots: receipts,
639 declared_writes,
640 delegated_writes: input
641 .delegated_writes
642 .get(&pre.seq.unwrap_or_default())
643 .cloned()
644 .unwrap_or_default(),
645 unrun_tool_calls: Default::default(),
646 },
647 );
648 }
649 Ok(UndoRangePlan {
650 workspace: input.workspace,
651 turns,
652 undone_turn_seqs,
653 })
654 }
655
656 pub(crate) fn restore_undo_range(plan: UndoRangePlan) -> anyhow::Result<String> {
657 if plan.turns.iter().all(|turn| !turn.may_change_files) {
658 return Ok("Workspace files were left unchanged.".to_string());
659 }
660 let result =
661 codewhale_app_server::runtime_api::patch_undo_workspace_files(&plan.workspace, &plan.turns)
662 .map_err(|error| anyhow::anyhow!(error.message))?;
663 Ok(result
664 .summary
665 .unwrap_or_else(|| "No workspace file changes needed restoring.".to_string()))
666 }
667
668 /// Label a `/undo` step starts at: before one request (a turn). `/undo`,
669 /// `/retry`, Esc Esc and the Runtime's `patch-undo` all go back by request;
670 /// the per-tool `tool:` restore points stay available to `/restore`.
671 fn is_undo_step_label(label: &str) -> bool {
672 label.starts_with("pre-turn:")
673 }
674
675 /// Labels of the restore points that bound a request. A step runs from its
676 /// `pre-turn:` point to the next one of these the conversation owns.
677 fn is_restore_point_label(label: &str) -> bool {
678 is_undo_step_label(label) || label.starts_with("post-turn:")
679 }
680
681 /// How long `/undo` waits for a post-turn snapshot still being written.
682 const POST_TURN_SNAPSHOT_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
683
684 /// Why workspace files may not be rolled back right now, if they may not.
685 ///
686 /// A running turn is reading and writing this workspace: restoring files
687 /// under it discards the turn's in-flight work and leaves the model's view of
688 /// the files wrong. `/undo` and `/restore` refuse while one is active, like
689 /// the Runtime's restore routes.
690 pub(in crate::commands) fn active_turn_restore_refusal(app: &App) -> Option<String> {
691 let turn_active = app.is_loading
692 || app.is_compacting
693 || matches!(app.runtime_turn_status.as_deref(), Some("in_progress"));
694 turn_active.then(|| {
695 "A turn is still running in this workspace, so files were not restored and nothing was changed. Wait for it to finish, or press Esc to stop it, then run the command again."
696 .to_string()
697 })
698 }
699
699 lines RUST