use std::path::{Path, PathBuf};
use rho_protocol::{
self as wire, Cursor, DetachReason, ErrorCode, RpcError, SessionAttachAnswer, Subscription,
};
use rho_sdk::SessionId;
use super::{
acp_turns, attach_response, child_feeds::turn_end, feed::Feed, options, store::store_blocking,
};
use crate::{
app::{
daemon_host::{
jobs::{JobRecord, JobState, TurnEnd},
subagents::{outcome, run_end},
},
session_events::{external_options, ExternalEvents},
},
run_artifacts::{AttachmentEvent, AttachmentReader},
session::{Session as StoredSession, SessionEngine},
subagent::{self, RunStatus, ATTACHMENT_FILE_NAME, RESULT_FILE_NAME},
};
pub(super) async fn saved_engine(
workspace: PathBuf,
id: &SessionId,
) -> Result<Option<SessionEngine>, RpcError> {
let id = id.clone();
store_blocking("read the session's engine", move || {
StoredSession::engine_by_id(&workspace, id.as_str())
})
.await
}
pub(super) async fn read(
id: &SessionId,
workspace: &Path,
engine: SessionEngine,
after: Option<&Cursor>,
run: Option<&JobRecord>,
) -> Result<(SessionAttachAnswer, Subscription), RpcError> {
let (artifacts, permission_mode, keeps_choice) = match engine {
SessionEngine::Acp {
artifacts,
permission_mode,
} => (artifacts, permission_mode, false),
SessionEngine::AcpSession {
artifacts,
permission_mode,
} => (artifacts, permission_mode, true),
SessionEngine::Unknown => {
return Err(RpcError::new(
ErrorCode::SessionOpenFailed,
format!("session {id} ran on an engine this daemon does not know"),
));
}
};
let (status, events, started) = store_blocking("read the run's events", move || {
let directory = artifacts.directory(&crate::paths::rho_dir()?);
let started = keeps_choice.then(|| acp_turns::started::read(&directory));
let (status, events) = read_run(&directory)?;
Ok((status, events, started))
})
.await?;
let ended = run.and_then(|job| match &job.state {
JobState::Ended(end) => Some(end.clone()),
JobState::Idle
| JobState::Queued
| JobState::Running
| JobState::Requeued
| JobState::WaitingForInput => None,
});
let feed = replay(&status, &events, permission_mode, ended);
if let Some(started) = started {
feed.seed_started_session_defaults(options::started_session_defaults(&started));
}
feed.close(DetachReason::NotLoaded);
Ok(attach_response(
workspace,
feed.attach(super::ResumeFrom::cursor(after)),
))
}
fn read_run(directory: &Path) -> anyhow::Result<(RunStatus, Vec<AttachmentEvent>)> {
let status = subagent::read_status(&directory.join(RESULT_FILE_NAME)).ok_or_else(|| {
anyhow::anyhow!(
"the run in {} has no status that reads",
directory.display()
)
})?;
let events = AttachmentReader::new(directory.join(ATTACHMENT_FILE_NAME)).read_new()?;
Ok((status, events))
}
fn replay(
status: &RunStatus,
events: &[AttachmentEvent],
mode: wire::PermissionMode,
ended: Option<TurnEnd>,
) -> Feed {
let options = external_options(
status.provider.as_deref().unwrap_or_default(),
status.model.as_deref(),
mode,
);
let turn = wire::TurnId::new(uuid::Uuid::new_v4().hyphenated().to_string());
let feed = Feed::new(
wire::JobState::Running,
Some(turn.clone()),
status.title.clone(),
options,
status.agent_id.clone().unwrap_or_default(),
);
publish_journal(&feed, events);
let end = ended
.or_else(|| run_end(status, false))
.unwrap_or(TurnEnd::Interrupted);
let outcome = outcome(&end, status);
feed.publish(turn_end(&turn, outcome, (&JobState::Ended(end)).into()));
feed.update_activity(|| false);
feed
}
pub(super) fn publish_journal(feed: &Feed, events: &[AttachmentEvent]) {
let mut mapped = ExternalEvents::default();
feed.publish(
events
.iter()
.flat_map(|event| mapped.map(event))
.map(without_terminals)
.map(unsteered),
);
feed.publish(mapped.cut_short());
}
fn unsteered(mut event: wire::SessionEvent) -> wire::SessionEvent {
if let wire::SessionEvent::UserMessage { steer, .. } = &mut event {
*steer = None;
}
event
}
fn without_terminals(mut event: wire::SessionEvent) -> wire::SessionEvent {
if let wire::SessionEvent::ToolCall(update) = &mut event {
if let Some(content) = &mut update.content {
content.retain(|content| !matches!(content, wire::ToolContent::Terminal { .. }));
}
}
event
}
#[cfg(test)]
#[path = "engine_replay_tests.rs"]
mod tests;