use std::path::Path;
use rho_protocol::{
methods::{JobList, SessionAttach, SessionObserve},
Client, ClientError, Cursor, DaemonNotification, DetachReason, ErrorCode, JobId, JobKind,
JobListParams, JobState, JobSummary, Replay, SessionAttachParams, SessionAttachResponse,
SessionEvent, SessionId, SessionObserveParams, SessionSetup,
};
use super::{
follow::{Ending, Follow},
terminal::{Line, Lines, Terminal},
text::TextView,
};
use crate::{
app::{
automation::{self, AutomationExit},
automation_protocol::{JsonlStream, TerminalReason},
shutdown_signal::ShutdownSignals,
},
cli::{AttachInput, AttachOutput},
daemon::{self, ConnectAs, Connection},
};
pub(in crate::app) async fn run(
id: &str,
output: AttachOutput,
input: AttachInput,
) -> anyhow::Result<()> {
let mut view = View::new(output);
let exit = attach(id, &mut view, Lines::of(input)).await;
Ok(view.end(exit)?)
}
enum View {
Text(TextView),
Jsonl(JsonlStream),
}
impl View {
fn new(output: AttachOutput) -> Self {
match output {
AttachOutput::Text => Self::Text(TextView::terminal()),
AttachOutput::Jsonl => Self::Jsonl(JsonlStream::stdout()),
}
}
fn terminal(&self, target: &Target, lines: Lines) -> Result<Option<Terminal>, AutomationExit> {
match (self, target) {
(Self::Text(_), Target::Session(_)) => Terminal::open(lines).map(Some),
(Self::Text(_), Target::Run { .. }) | (Self::Jsonl(_), _) => Ok(None),
}
}
fn started(&mut self, session: &SessionId, workspace: &Path) -> Result<(), AutomationExit> {
match self {
Self::Text(_) => Ok(()),
Self::Jsonl(stream) => {
stream.run_started(session.as_str(), workspace);
automation::stream_written(stream)
}
}
}
fn restart(&mut self) -> Result<(), AutomationExit> {
match self {
Self::Text(view) => view.restart().map_err(automation::write_failed),
Self::Jsonl(_) => Ok(()),
}
}
fn show(&mut self, event: &SessionEvent) -> Result<(), AutomationExit> {
match self {
Self::Text(view) => view.show(event).map_err(automation::write_failed),
Self::Jsonl(stream) => {
stream.event(event);
automation::stream_written(stream)
}
}
}
fn end(&mut self, exit: Result<(), AutomationExit>) -> Result<(), AutomationExit> {
match self {
Self::Text(view) => {
let _ = view.finish();
exit
}
Self::Jsonl(stream) => automation::end_stream(stream, exit),
}
}
}
async fn attach(id: &str, view: &mut View, lines: Lines) -> Result<(), AutomationExit> {
let mut signals = ShutdownSignals::install().map_err(|error| {
AutomationExit::other(format!("could not install signal handlers: {error}"))
})?;
tokio::select! {
exit = follow(id, view, lines) => exit,
signal = signals.recv() => {
let signal =
signal.map_err(|error| AutomationExit::other(format!("could not wait for signals: {error}")))?;
Err(AutomationExit::new(
signal.exit_code(),
TerminalReason::Detached,
format!("detached on {signal}; the turn runs on in the daemon"),
))
}
}
}
async fn follow(id: &str, view: &mut View, lines: Lines) -> Result<(), AutomationExit> {
let paths = daemon::DaemonPaths::of_this_process()
.map_err(|error| AutomationExit::other(format!("{error:#}")))?;
let Connection {
client,
mut notifications,
..
} = daemon::connect(&paths, ConnectAs::Frontend.hello())
.await
.map_err(|error| AutomationExit::other(format!("{error:#}")))?;
let jobs = client
.request::<JobList>(&JobListParams {})
.await
.map_err(|error| {
AutomationExit::other(format!("could not list the daemon's jobs: {error}"))
})?
.jobs;
let target = resolve(&jobs, id)?;
let session = target.session().clone();
let response = loop {
match (request_attach(&client, &target, None).await, &target) {
(Ok(response), _) => break response,
(Err(refused), Target::Run { job, .. }) => {
if let Some(end) = run_end(&client, job).await? {
return end;
}
if refused.error_code() != Some(ErrorCode::SessionBusy) {
return Err(attach_refused(&target, &refused));
}
tokio::time::sleep(RUN_OPEN_POLL).await;
}
(Err(refused), Target::Session(_)) => return Err(attach_refused(&target, &refused)),
}
};
view.started(&session, &response.workspace)?;
let (mut follow, ending) = Follow::attached(&response);
if let Some(ending) = ending {
return ended(ending);
}
let mut terminal = view.terminal(&target, lines)?;
let mut pending = Some(response);
loop {
if let Some(terminal) = terminal.as_mut().filter(|_| !follow.replaying()) {
if let Some(response) = pending.take() {
terminal.attached(&response.inputs, response.replay)?;
}
}
let ending = tokio::select! {
notification = notifications.recv() => match notification {
None => return Err(AutomationExit::other("lost the connection to the rho daemon")),
Some(DaemonNotification::SessionEvent(params))
if params.session == session =>
{
view.show(¶ms.event)?;
if let Some(terminal) = terminal.as_mut().filter(|_| !follow.replaying()) {
terminal.event(¶ms.event)?;
}
follow.observe(params.seq, ¶ms.event)
}
Some(DaemonNotification::SessionDetached(params))
if params.session == session =>
{
match params.reason {
DetachReason::Lagged => {
let response =
request_attach(&client, &target, follow.cursor())
.await
.map_err(|refused| attach_refused(&target, &refused))?;
if response.replay == Replay::Reset {
view.restart()?;
}
let ending = follow.reattached(&response);
pending = Some(response);
ending
}
DetachReason::DaemonStopping | DetachReason::Restarting => {
Some(Ending::Interrupted)
}
DetachReason::Deleted => {
return Err(AutomationExit::other("the session was deleted"))
}
DetachReason::NotLoaded => match &target {
Target::Run { job, .. } => {
return run_end(&client, job).await?.unwrap_or_else(|| {
Err(AutomationExit::other(
"the rho daemon detached this client",
))
})
}
Target::Session(_) => {
return Err(AutomationExit::other(
"the rho daemon detached this client",
))
}
},
_ => return Err(AutomationExit::other("the rho daemon detached this client")),
}
}
Some(_) => None,
},
typed = next_line(&mut terminal), if pending.is_none() => {
let (terminal, line) = typed?;
terminal.line(&client, &session, &line).await?;
None
}
};
if let Some(ending) = ending {
return ended(ending);
}
}
}
async fn next_line(
terminal: &mut Option<Terminal>,
) -> Result<(&mut Terminal, Line), AutomationExit> {
match terminal {
Some(terminal) => {
let line = terminal.next_line().await?;
Ok((terminal, line))
}
None => std::future::pending().await,
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Target {
Session(SessionId),
Run { job: JobId, session: SessionId },
}
impl Target {
fn session(&self) -> &SessionId {
match self {
Self::Session(session) | Self::Run { session, .. } => session,
}
}
}
const RUN_OPEN_POLL: std::time::Duration = std::time::Duration::from_millis(500);
async fn request_attach(
client: &Client,
target: &Target,
after: Option<&Cursor>,
) -> Result<SessionAttachResponse, ClientError> {
match target {
Target::Session(session) => {
let params = SessionAttachParams {
session: session.clone(),
after: after.cloned(),
environment: rho_protocol::ClientEnvironment::of_this_process(),
setup: SessionSetup::default(),
};
client.request::<SessionAttach>(¶ms).await
}
Target::Run { session, .. } => {
let params = SessionObserveParams {
session: session.clone(),
after: after.cloned(),
};
client.request::<SessionObserve>(¶ms).await
}
}
}
fn attach_refused(target: &Target, refused: &ClientError) -> AutomationExit {
AutomationExit::other(format!(
"could not attach to session {}: {refused}",
target.session()
))
}
async fn run_end(
client: &Client,
job: &JobId,
) -> Result<Option<Result<(), AutomationExit>>, AutomationExit> {
let jobs = client
.request::<JobList>(&JobListParams {})
.await
.map_err(|error| {
AutomationExit::other(format!("could not list the daemon's jobs: {error}"))
})?
.jobs;
let ended = |how: &str| Some(Err(AutomationExit::other(format!("job {job}'s run {how}"))));
Ok(match jobs.iter().find(|listed| &listed.id == job) {
Some(listed) if listed.state.in_progress() => None,
Some(JobSummary {
state: JobState::Completed,
..
}) => Some(Ok(())),
Some(JobSummary {
state: JobState::Cancelled,
..
}) => ended("was cancelled"),
Some(JobSummary {
error: Some(error), ..
}) => ended(&format!("failed: {error}")),
Some(_) | None => ended("ended without completing"),
})
}
fn resolve(jobs: &[JobSummary], id: &str) -> Result<Target, AutomationExit> {
let wrote = |job: &&JobSummary| job.session.as_ref().is_some_and(|s| s.as_str() == id);
let named = jobs.iter().find(|job| job.id.as_str() == id).or_else(|| {
let under_way = jobs
.iter()
.filter(wrote)
.find(|job| job.state.in_progress());
under_way.or_else(|| jobs.iter().rev().find(wrote))
});
let Some(job) = named else {
return Ok(Target::Session(SessionId::new(id)));
};
let why = match (job.kind, &job.session) {
(JobKind::Session, Some(session)) => return Ok(Target::Session(session.clone())),
(JobKind::Session, None) => {
return Err(AutomationExit::other(format!(
"session job {} has no session",
job.id
)))
}
(JobKind::Subagent, Some(session)) => {
let writing = jobs.iter().find(|other| {
other.id != job.id
&& other.session.as_ref() == Some(session)
&& other.state.in_progress()
});
if let Some(writing) = writing {
return Err(AutomationExit::other(format!(
"job {} ended, and job {} now runs in the same session; attach to that one",
job.id, writing.id
)));
}
return Ok(Target::Run {
job: job.id.clone(),
session: session.clone(),
});
}
(JobKind::Subagent, None) => {
"is a subagent run on another runtime, which keeps no rho session to follow"
}
(JobKind::Workflow, _) => "drives a workflow run, whose events are its agent nodes' jobs'",
_ => {
return Err(AutomationExit::other(format!(
"job {} is of a kind this rho cannot attach to",
job.id
)))
}
};
let place = match session_of(jobs, job) {
Some(session) => format!("; it runs in session {session}"),
None => String::new(),
};
Err(AutomationExit::other(format!(
"job {} {why}{place}",
job.id
)))
}
fn session_of<'a>(jobs: &'a [JobSummary], job: &JobSummary) -> Option<&'a SessionId> {
let mut parent = job.parent.as_ref()?;
for _ in 0..jobs.len() {
let ancestor = jobs.iter().find(|job| &job.id == parent)?;
if ancestor.kind == JobKind::Session {
return ancestor.session.as_ref();
}
parent = ancestor.parent.as_ref()?;
}
None
}
fn ended(ending: Ending) -> Result<(), AutomationExit> {
match ending {
Ending::Turn(outcome) => automation::outcome_exit(&outcome),
Ending::Interrupted => Err(AutomationExit::new(
1,
TerminalReason::Interrupted,
"the rho daemon stopped before the turn ended",
)),
Ending::Unreported => Err(AutomationExit::other(
"the rho daemon's replay ended after the turn without saying how it ended",
)),
}
}
#[cfg(test)]
#[path = "client_tests.rs"]
mod tests;