use rho_protocol::{
self as wire, ErrorCode, RpcError, SessionCapability, SessionRewindPreviewParams,
SessionRewindPreviewResponse, SessionTreeParams, SessionTreeResponse, TreeNodeId,
};
use super::Sessions;
use crate::{
app::{
session_events::row_user_message_id,
session_runtime::{
RewindError, RewindPreview, RewoundConversation, TreeRow, WorkspaceRewind,
},
},
session::{
tree::{NodeId, RowPrompt, SessionTreeItemContent, TurnEnd},
workspace_checkpoint::{
AuditResult, CheckpointFileBudgetExceeded, RestoreClassification, RestorePlanEntry,
UntrackedEffect, UntrackedEffectKind, WorkspaceCheckpointSummary,
},
},
};
const PROMPT_CHARS: usize = 200;
impl Sessions {
pub(in crate::app::daemon_host) async fn tree(
&self,
params: SessionTreeParams,
) -> Result<SessionTreeResponse, RpcError> {
let session = self
.between_turns(¶ms.session, SessionCapability::Rewind)
.await?;
let runtime = session.engine.lock().await;
let runtime = runtime
.as_ref()
.ok_or_else(super::inspect::not_loaded)?
.rho_for(SessionCapability::Rewind)?;
let rows = runtime.tree_rows().map_err(|error| {
RpcError::new(
ErrorCode::InternalError,
format!("could not read the session's tree: {error:#}"),
)
})?;
let current = rows
.iter()
.find(|row| row.item.active)
.map(|row| node_to_wire(&row.item.id));
Ok(SessionTreeResponse::new(
rows.into_iter().map(row_to_wire).collect(),
current,
))
}
pub(in crate::app::daemon_host) async fn rewind_preview(
&self,
params: SessionRewindPreviewParams,
) -> Result<SessionRewindPreviewResponse, RpcError> {
let target = node_from_wire(¶ms.checkpoint)?;
let session = self
.between_turns(¶ms.session, SessionCapability::Rewind)
.await?;
let runtime = session.engine.lock().await;
let runtime = runtime
.as_ref()
.ok_or_else(super::inspect::not_loaded)?
.rho_for(SessionCapability::Rewind)?;
let RewindPreview {
tip,
turns,
plan,
returns_to,
} = runtime
.preview_rewind(&target)
.map_err(|error| rewind_error(error, "plan the workspace rewind"))?;
Ok(SessionRewindPreviewResponse::new(
turns.iter().map(node_to_wire).collect(),
node_to_wire(&tip),
u32::try_from(plan.uncaptured_turns).unwrap_or(u32::MAX),
plan.entries.into_iter().map(file_to_wire).collect(),
plan.limitations.iter().map(untracked_to_wire).collect(),
match returns_to {
Some(row) => wire::RewindConversation::Moves {
to: node_to_wire(&row),
},
None => wire::RewindConversation::Stays,
},
))
}
}
pub(super) fn rewind_error(error: RewindError, doing: &str) -> RpcError {
match error {
RewindError::Refused(error) => {
RpcError::new(ErrorCode::InvalidParams, format!("{error:#}"))
}
RewindError::Failed(error) => RpcError::new(
ErrorCode::InternalError,
format!("could not {doing}: {error:#}"),
),
moved @ RewindError::Moved { .. } => {
RpcError::new(ErrorCode::ConversationMoved, moved.to_string())
}
}
}
pub(super) fn rewind_to_wire(rewind: WorkspaceRewind) -> wire::SessionRewindResponse {
let WorkspaceRewind {
turns,
audit,
conversation,
} = rewind;
let files = audit
.entries
.into_iter()
.map(|entry| {
let result = match entry.result() {
AuditResult::Written => wire::RewoundFileResult::Written,
AuditResult::Left => wire::RewoundFileResult::Left,
AuditResult::Failed(error) => wire::RewoundFileResult::Failed {
error: error.to_owned(),
},
};
wire::RewoundFile::new(entry.path, action_to_wire(entry.classification), result)
})
.collect();
let conversation = match conversation {
RewoundConversation::Moved { row } => wire::RewoundConversation::Moved {
to: node_to_wire(&row),
},
RewoundConversation::Stayed => wire::RewoundConversation::Stayed,
RewoundConversation::MoveFailed(error) => wire::RewoundConversation::MoveFailed {
error: error.to_string(),
},
};
wire::SessionRewindResponse::new(
turns.iter().map(node_to_wire).collect(),
files,
audit.limitations.iter().map(untracked_to_wire).collect(),
u32::try_from(audit.uncaptured_turns).unwrap_or(u32::MAX),
conversation,
)
}
pub(super) fn node_from_wire(id: &TreeNodeId) -> Result<NodeId, RpcError> {
NodeId::from_string(id.as_str())
.map_err(|error| RpcError::new(ErrorCode::InvalidParams, format!("{error:#}")))
}
fn node_to_wire(node: &NodeId) -> TreeNodeId {
TreeNodeId::new(node.as_str())
}
fn row_to_wire(TreeRow { item, checkpoints }: TreeRow) -> wire::SessionTreeRow {
let content = match &item.content {
SessionTreeItemContent::SessionStart => wire::TreeRowContent::SessionStart,
SessionTreeItemContent::Turn { prompt, end } => {
wire::TreeRowContent::Turn(wire::TreeTurn::new(
prompt.as_ref().map(prompt_to_wire),
end.map(turn_end_to_wire),
))
}
SessionTreeItemContent::Compaction(facts) => {
wire::TreeRowContent::Compaction(facts.counts())
}
};
wire::SessionTreeRow::new(
node_to_wire(&item.id),
item.parent.as_ref().map(node_to_wire),
item.saved_at,
content,
checkpoints.iter().map(checkpoint_to_wire).collect(),
)
}
fn prompt_to_wire(prompt: &RowPrompt) -> wire::TreePrompt {
let text = prompt.text.as_deref().unwrap_or_default();
let text = match text.char_indices().nth(PROMPT_CHARS) {
Some((cut, _)) => format!("{}…", &text[..cut]),
None => text.to_owned(),
};
wire::TreePrompt::new(
row_user_message_id(&prompt.origin, prompt.key.as_ref()),
text,
)
}
fn turn_end_to_wire(end: TurnEnd) -> wire::TreeTurnEnd {
match end {
TurnEnd::Completed => wire::TreeTurnEnd::Completed,
TurnEnd::Cancelled => wire::TreeTurnEnd::Cancelled,
TurnEnd::Failed => wire::TreeTurnEnd::Failed,
TurnEnd::Unknown => wire::TreeTurnEnd::Unknown,
}
}
fn checkpoint_to_wire(checkpoint: &WorkspaceCheckpointSummary) -> wire::TurnCheckpoint {
wire::TurnCheckpoint::new(
node_to_wire(&checkpoint.node_id),
u32::try_from(checkpoint.file_count).unwrap_or(u32::MAX),
checkpoint
.limitations
.iter()
.map(untracked_to_wire)
.collect(),
)
}
fn untracked_to_wire(effect: &UntrackedEffect) -> wire::UntrackedEffect {
let kind = match effect.kind {
UntrackedEffectKind::ShellCommand => wire::UntrackedEffectKind::Shell,
UntrackedEffectKind::UntrackedMutatingTool | UntrackedEffectKind::ExternalEffect => {
wire::UntrackedEffectKind::Tool
}
};
wire::UntrackedEffect::new(kind, effect.source.clone())
}
fn file_to_wire(entry: RestorePlanEntry) -> wire::RewindFile {
wire::RewindFile::new(
entry.path,
action_to_wire(entry.classification),
entry
.over_budget
.map(|CheckpointFileBudgetExceeded { asked, limit }| {
wire::CaptureBudget::new(asked, limit)
}),
)
}
fn action_to_wire(classification: RestoreClassification) -> wire::RewindAction {
match classification {
RestoreClassification::Modify => wire::RewindAction::Restore,
RestoreClassification::Create => wire::RewindAction::Recreate,
RestoreClassification::Delete => wire::RewindAction::Delete,
RestoreClassification::Conflict => wire::RewindAction::Conflict,
RestoreClassification::Unsupported => wire::RewindAction::Unsupported,
RestoreClassification::Skipped => wire::RewindAction::Unchanged,
}
}
#[cfg(test)]
#[path = "tree_tests.rs"]
mod tests;