rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use std::{collections::HashMap, path::Path};

use anyhow::Context as _;
use rho_protocol::{RewindConversation, SessionRewindPreviewResponse, TreeNodeId};

use crate::tui::{daemon_requests::REWIND_FAILED, DefaultTerminal};

use crate::{
    app::workspace_rewind::{action_label, uncaptured_line, untracked_label},
    commands::CommandInvocation,
    session::{tree::SessionTree, workspace_checkpoint::WorkspaceCheckpointStore},
};

use super::{
    daemon_events::{Moved, PreviewAsked},
    picker::OverlayChrome,
    App, ComposerMode, Entry, PickerBadge, PickerBadgeTone, PickerItem, PickerLayout, UiPicker,
};

/// What a rewind confirmation's one row holds as its value: the checkpoint,
/// and the conversation's node its preview was planned at, which the
/// rewind is held to.
#[derive(Debug, PartialEq, Eq)]
pub(super) struct RewindConfirmation {
    pub(super) checkpoint: TreeNodeId,
    pub(super) tip: TreeNodeId,
}

impl RewindConfirmation {
    pub(super) fn value(&self) -> String {
        format!("{} {}", self.checkpoint, self.tip)
    }

    /// Node ids are generated without spaces, so the tip is after the last.
    pub(super) fn parse(value: &str) -> anyhow::Result<Self> {
        let (checkpoint, tip) = value
            .rsplit_once(' ')
            .context("the rewind confirmation names no tip")?;
        Ok(Self {
            checkpoint: TreeNodeId::new(checkpoint),
            tip: TreeNodeId::new(tip),
        })
    }
}

impl Moved {
    fn why(self) -> &'static str {
        match self {
            Self::Session => "the session moved on",
            Self::Conversation => "the conversation moved on since the rewind preview",
        }
    }
}

impl App {
    /// The rewind confirmation on screen, if one is, whatever its filter
    /// hides.
    pub(super) fn open_rewind_confirmation(&self) -> Option<RewindConfirmation> {
        match self.input_ui.composer() {
            ComposerMode::Picker(picker) if picker.is_confirm_rewind() => picker
                .items
                .first()
                .and_then(|item| RewindConfirmation::parse(&item.value).ok()),
            _ => None,
        }
    }

    /// Previews the rewind confirmation on screen again once the session
    /// came to rest, so it never confirms a preview from before a turn that
    /// since ended, or a conversation a reattach replayed moved.
    pub(super) fn refresh_rewind_confirmation(&mut self) {
        if let Some(open) = self.open_rewind_confirmation() {
            self.preview_rewind_again(open.checkpoint, Moved::Session);
        }
    }

    /// Whether a preview of `checkpoint`, asked for as `asked` says, may
    /// open its confirmation: over an empty composer, or a rewind
    /// confirmation it replaces, any for a checkpoint just picked, else only
    /// that checkpoint's; never over a draft, where the next Enter would
    /// confirm a rewind unseen, nor over another picker.
    fn can_show_rewind_preview(&self, checkpoint: &TreeNodeId, asked: PreviewAsked) -> bool {
        match (self.open_rewind_confirmation(), asked) {
            (Some(_), PreviewAsked::Picked) => true,
            (Some(open), PreviewAsked::Again(_)) => open.checkpoint == *checkpoint,
            (None, _) => {
                matches!(self.input_ui.composer(), ComposerMode::Input)
                    && self.input_ui.text().is_empty()
                    && self.input_ui.attachments().is_empty()
            }
        }
    }

    /// Asks the daemon to preview the rewind of `checkpoint` again, as
    /// `moved` says why, closing the confirmation on screen meanwhile so
    /// its stale plan cannot be confirmed. Only where the answer may open
    /// (see [`Self::can_show_rewind_preview`]); elsewhere it says to run
    /// `/rewind` again.
    pub(super) fn preview_rewind_again(&mut self, checkpoint: TreeNodeId, moved: Moved) {
        let why = moved.why();
        if !self.can_show_rewind_preview(&checkpoint, PreviewAsked::Again(moved)) {
            self.set_status(format!("{why}; run /rewind again"));
            return;
        }
        self.input_ui.set_composer(ComposerMode::Input);
        match self
            .info
            .session
            .daemon
            .preview_rewind(checkpoint, PreviewAsked::Again(moved))
        {
            Ok(()) => self.set_status(format!("{why}; previewing the rewind again")),
            Err(error) => self.set_status(format!(
                "{why}; the rewind can no longer be previewed: {error:#}"
            )),
        }
    }

    /// The followed session's checkpoint store, or `None` when it has saved
    /// nothing or keeps no checkpoints.
    fn checkpoint_store(&self) -> anyhow::Result<Option<WorkspaceCheckpointStore>> {
        match self.current_session_id() {
            Some(id) => crate::session::Session::workspace_checkpoint_store_by_id(
                &self.info.runtime.cwd,
                &id,
            ),
            None => Ok(None),
        }
    }

    /// The followed session's saved tree, or `None` when it has none.
    fn session_tree(&self) -> anyhow::Result<Option<SessionTree>> {
        self.current_session_id()
            .map(|id| crate::session::Session::tree_by_id(&self.info.runtime.cwd, &id))
            .transpose()
    }

    pub(super) fn execute_rewind_command(
        &mut self,
        invocation: CommandInvocation,
    ) -> anyhow::Result<()> {
        if self.info.session.no_save {
            self.set_status("workspace rewind unavailable with --no-save");
            return Ok(());
        }
        // The daemon holds the session open; its checkpoints and tree are
        // read from the files both share. A rewind undoes the turns of the
        // conversation's current branch, so only its checkpoints are listed.
        let tree = self.session_tree()?;
        let path = match &tree {
            Some(tree) => tree.active_path_ids()?,
            None => Vec::new(),
        };
        let checkpoints: Vec<_> = match self.checkpoint_store()? {
            Some(store) => store
                .list()?
                .into_iter()
                .filter(|checkpoint| path.contains(&checkpoint.node_id))
                .collect(),
            None => Vec::new(),
        };
        // A turn's checkpoint names the node the turn ended on, which later
        // saves, such as a settings change, may follow.
        let prompts: HashMap<_, _> = checkpoints
            .iter()
            .filter_map(|checkpoint| {
                let prompt = tree.as_ref()?.turn_prompt(&checkpoint.node_id)?;
                Some((checkpoint.node_id.clone(), prompt))
            })
            .collect();
        // The session takes the setting when it opens, so one opened after
        // a change may have checkpoints the configured setting would not
        // expect: the setting only explains an empty list. A config that
        // cannot be read explains nothing.
        if checkpoints.is_empty()
            && self
                .info
                .services
                .config_repository
                .load()
                .is_ok_and(|config| !config.workspace_rewind)
        {
            self.set_status(
                "workspace rewind is off; set behavior.workspace_rewind = true and start a new session",
            );
            return Ok(());
        }
        if checkpoints.is_empty() {
            self.set_status("this branch of the session has no workspace checkpoints");
            return Ok(());
        }
        if !invocation.args.is_empty() {
            let matching = checkpoints
                .iter()
                .filter(|checkpoint| checkpoint.node_id.as_str().starts_with(&invocation.args))
                .collect::<Vec<_>>();
            anyhow::ensure!(
                matching.len() == 1,
                "turn '{}' must match exactly one workspace checkpoint",
                invocation.args
            );
            return self.submit_rewind_preview(matching[0].node_id.as_str());
        }

        let items = checkpoints
            .into_iter()
            .rev()
            .map(|checkpoint| {
                let id = checkpoint.node_id.to_string();
                let short_id = &id[..id.len().min(8)];
                let preview = prompts
                    .get(&checkpoint.node_id)
                    .cloned()
                    .unwrap_or_else(|| format!("turn {short_id}"));
                PickerItem {
                    detail: Some(
                        format!(
                            "checkpoint time: {}\ntracked files: {}\noutcome: {:?}",
                            checkpoint.finalized_at, checkpoint.file_count, checkpoint.outcome
                        )
                        .into(),
                    ),
                    badge: (!checkpoint.limitations.is_empty()).then_some(PickerBadge {
                        text: "limited".into(),
                        tone: PickerBadgeTone::Warning,
                    }),
                    ..PickerItem::new(preview, id)
                }
            })
            .collect();
        let picker = UiPicker::rewind_checkpoint("Workspace rewind", items)
            .with_layout(PickerLayout::Overlay)
            .with_overlay_chrome(OverlayChrome {
                nav_label: " REWIND".into(),
                detail_label: Some("CHECKPOINT".into()),
                nav_keys_hint: "↑↓ turns".into(),
            })
            .with_confirm_verb("preview");
        self.input_ui.set_composer(ComposerMode::Picker(picker));
        self.set_status("select workspace checkpoint");
        Ok(())
    }

    /// Asks the daemon to preview the rewind of the picked checkpoint
    /// `value`. It goes behind the changes this TUI queued before it, such
    /// as a `!` command's context, so it plans against the conversation
    /// those left, which the rewind is then held to; read from the session's
    /// file instead, it could miss a row the daemon had yet to save.
    pub(super) fn submit_rewind_preview(&mut self, value: &str) -> anyhow::Result<()> {
        self.input_ui.set_composer(ComposerMode::Input);
        self.info
            .session
            .daemon
            .preview_rewind(TreeNodeId::new(value), PreviewAsked::Picked)?;
        self.set_status("previewing workspace rewind");
        Ok(())
    }

    /// Opens the confirmation of the daemon's `answer` to a preview of
    /// `checkpoint`, where it may open (see
    /// [`Self::can_show_rewind_preview`]), or says why it did not.
    pub(super) fn show_rewind_preview(
        &mut self,
        checkpoint: TreeNodeId,
        asked: PreviewAsked,
        answer: Result<Box<SessionRewindPreviewResponse>, String>,
    ) {
        let preview = match (answer, asked) {
            (Ok(preview), _) => preview,
            (Err(error), PreviewAsked::Picked) => {
                self.insert_entry(&Entry::Error(format!(
                    "could not preview the workspace rewind: {error}"
                )));
                return;
            }
            (Err(error), PreviewAsked::Again(moved)) => {
                // Asking again closed it, but an answer to an earlier ask
                // may have opened it since.
                if self
                    .open_rewind_confirmation()
                    .is_some_and(|open| open.checkpoint == checkpoint)
                {
                    self.input_ui.set_composer(ComposerMode::Input);
                }
                self.set_status(format!(
                    "{}; the rewind can no longer be previewed: {error}",
                    moved.why()
                ));
                return;
            }
        };
        if !self.can_show_rewind_preview(&checkpoint, asked) {
            self.set_status(match asked {
                PreviewAsked::Picked => {
                    "the rewind preview arrived while the composer was in use; run /rewind again"
                        .into()
                }
                PreviewAsked::Again(moved) => format!("{}; run /rewind again", moved.why()),
            });
            return;
        }
        let root = self.info.runtime.cwd.clone();
        let detail = rewind_preview_text(&checkpoint, &preview, &root);
        let blocked = !matches!(preview.conversation, RewindConversation::Moves { .. });
        let confirmation = RewindConfirmation {
            checkpoint,
            tip: preview.tip,
        };
        let item = PickerItem {
            detail: Some(detail.into()),
            badge: blocked.then_some(PickerBadge {
                text: "partial".into(),
                tone: PickerBadgeTone::Warning,
            }),
            ..PickerItem::new(
                if blocked {
                    "Confirm safe paths; conflicts stay unchanged".into()
                } else {
                    "Confirm workspace rewind".into()
                },
                confirmation.value(),
            )
        };
        let picker = UiPicker::confirm_rewind("Confirm workspace rewind", vec![item])
            .with_layout(PickerLayout::Overlay)
            .with_overlay_chrome(OverlayChrome {
                nav_label: " CONFIRM".into(),
                detail_label: Some("RESTORE PREVIEW".into()),
                nav_keys_hint: "Esc cancel".into(),
            })
            .with_confirm_verb("rewind");
        self.input_ui.set_composer(ComposerMode::Picker(picker));
        self.set_status(match asked {
            PreviewAsked::Picked => "confirm workspace rewind".into(),
            PreviewAsked::Again(moved) => format!("{}; review the rewind again", moved.why()),
        });
    }

    /// The daemon restores the files, says what became of each, and has
    /// every client replay the conversation it returned to.
    pub(super) async fn submit_rewind_confirmation(
        &mut self,
        value: &str,
        _terminal: &mut DefaultTerminal,
    ) -> anyhow::Result<()> {
        let RewindConfirmation { checkpoint, tip } = RewindConfirmation::parse(value)?;
        self.input_ui.set_composer(ComposerMode::Input);
        if let Err(error) = self.info.session.daemon.rewind(checkpoint, tip) {
            self.insert_entry(&Entry::Error(format!("{REWIND_FAILED}: {error}")));
        }
        Ok(())
    }
}

/// The confirmation's detail: what the daemon's `preview` of the rewind
/// of `checkpoint` would do, with paths shown relative to `workspace`.
fn rewind_preview_text(
    checkpoint: &TreeNodeId,
    preview: &SessionRewindPreviewResponse,
    workspace: &Path,
) -> String {
    let short_id: String = checkpoint.as_str().chars().take(8).collect();
    let mut lines = vec![
        format!("target turn: {short_id}"),
        match preview.turns.len().saturating_sub(1) {
            0 => "turns undone: this one".into(),
            later => format!("turns undone: this one and {later} later on this branch"),
        },
        match preview.conversation {
            RewindConversation::Moves { .. } => {
                "conversation: return to before this turn and preserve the existing branch".into()
            }
            RewindConversation::Stays => {
                "conversation: unchanged, because some paths will not be restored".into()
            }
            _ => "conversation: this rho cannot tell where the rewind leaves it".into(),
        },
    ];
    let display = |path: &Path| rho_tools::compact_display_path(workspace, &path.to_string_lossy());
    for file in &preview.files {
        lines.push(format!(
            "{}  {}",
            action_label(file.action),
            display(&file.path)
        ));
    }
    for file in &preview.files {
        if let Some(budget) = file.over_budget {
            lines.push(format!(
                "warning  per-file capture budget: limit {} bytes, asked {} bytes ({})",
                budget.limit,
                budget.asked,
                display(&file.path)
            ));
        }
    }
    if preview.files.is_empty() {
        lines.push("skip  no native file changes were captured".into());
    }
    lines.extend(uncaptured_line(
        usize::try_from(preview.uncaptured_turns).unwrap_or(usize::MAX),
    ));
    for effect in &preview.untracked {
        lines.push(format!(
            "warning  {} effects from '{}' cannot be restored",
            untracked_label(effect.kind),
            effect.tool
        ));
    }
    lines.join("\n")
}

#[cfg(test)]
#[path = "rewind_actions_tests.rs"]
mod tests;