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,
};
#[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)
}
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 {
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,
}
}
pub(super) fn refresh_rewind_confirmation(&mut self) {
if let Some(open) = self.open_rewind_confirmation() {
self.preview_rewind_again(open.checkpoint, Moved::Session);
}
}
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()
}
}
}
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:#}"
)),
}
}
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),
}
}
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(());
}
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(),
};
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();
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(())
}
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(())
}
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)) => {
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()),
});
}
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(())
}
}
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;