use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use serde_json::{Value, json};
use tokio::sync::mpsc::UnboundedSender;
use trusty_code_tui::{
CommandDescriptor, PickerItem, ReplEvent, StatuslineSegment, WorkstreamSummary,
};
use crate::events::SessionEventEnvelope;
use super::engine::{
CONNECT_TIMEOUT, RECONNECT_BACKOFF, SESSION_STREAM_MAX_RECONNECTS, SSE_IDLE_TIMEOUT,
};
use super::error::EngineError;
use super::rpc::RpcHttpClient;
use super::session_events::{
forward_session_event, is_retryable_status, terminal_stream_failure_event,
};
use super::sse::SseLines;
pub(super) struct EngineState {
pub(super) rpc: RpcHttpClient,
pub(super) project_path: Option<PathBuf>,
pub(super) session_id: Mutex<Option<String>>,
pub(super) active_workstream: Mutex<Option<WorkstreamSummary>>,
pub(super) commands_cache: Mutex<Vec<CommandDescriptor>>,
pub(super) picker_cache: Mutex<HashMap<String, Vec<PickerItem>>>,
pub(super) shutting_down: AtomicBool,
}
impl EngineState {
pub(super) fn new(rpc: RpcHttpClient, project_path: Option<PathBuf>) -> Self {
Self {
rpc,
project_path,
session_id: Mutex::new(None),
active_workstream: Mutex::new(None),
commands_cache: Mutex::new(Vec::new()),
picker_cache: Mutex::new(HashMap::new()),
shutting_down: AtomicBool::new(false),
}
}
pub(super) fn commands(&self) -> Vec<CommandDescriptor> {
self.commands_cache
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
pub(super) fn picker_items(&self, name: &str) -> Option<Vec<PickerItem>> {
self.picker_cache
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(name)
.cloned()
}
pub(super) fn statusline_segments(&self) -> Vec<StatuslineSegment> {
self.active_workstream
.lock()
.unwrap_or_else(|e| e.into_inner())
.as_ref()
.map(|ws| {
vec![StatuslineSegment::Workstream {
id: ws.id.clone(),
name: ws.name.clone(),
}]
})
.unwrap_or_default()
}
pub(super) async fn refresh_workstream_cache(&self) -> Option<WorkstreamSummary> {
let result = self.rpc.call("workstream.list", json!({})).await.ok()?;
let active_id = result
.get("active_workstream_id")
.and_then(Value::as_str)
.map(str::to_string);
let workstreams: Vec<Value> = result
.get("workstreams")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
let items: Vec<PickerItem> = workstreams
.iter()
.filter_map(|w| {
let id = w.get("id").and_then(Value::as_str)?.to_string();
let name = w.get("name").and_then(Value::as_str).unwrap_or_default();
let label = if name.is_empty() {
id.clone()
} else {
name.to_string()
};
Some(PickerItem {
id,
label,
description: None,
})
})
.collect();
*self.picker_cache.lock().unwrap_or_else(|e| e.into_inner()) = {
let mut map = HashMap::new();
map.insert("workstream".to_string(), items);
map
};
let active = active_id.and_then(|id| {
workstreams
.iter()
.find(|w| w.get("id").and_then(Value::as_str) == Some(id.as_str()))
.map(|w| WorkstreamSummary {
id: id.clone(),
name: w
.get("name")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
})
.or(Some(WorkstreamSummary {
id,
name: String::new(),
}))
});
*self
.active_workstream
.lock()
.unwrap_or_else(|e| e.into_inner()) = active.clone();
active
}
pub(super) async fn handle_workstream_command(
&self,
rest: &str,
tx: &UnboundedSender<ReplEvent>,
) -> Result<(), EngineError> {
if rest.is_empty() || rest == "list" {
let ws = self.refresh_workstream_cache().await;
let items = self.picker_items("workstream").unwrap_or_default();
let active_id = ws.as_ref().map(|w| w.id.as_str());
let rows: Vec<String> = items
.iter()
.map(|item| {
let marker = if Some(item.id.as_str()) == active_id {
"*"
} else {
" "
};
format!("{marker} {} {}", item.id, item.label)
})
.collect();
let msg = if rows.is_empty() {
"no workstreams".to_string()
} else {
rows.join("\n")
};
let _ = tx.send(ReplEvent::StatusMessage(msg));
return Ok(());
}
if let Some(id) = rest.strip_prefix("activate ") {
let id = id.trim().to_string();
let result = self
.rpc
.call("workstream.activate", json!({ "id": id }))
.await?;
let active_id = result
.get("active_id")
.and_then(Value::as_str)
.unwrap_or(&id)
.to_string();
let ws = self
.refresh_workstream_cache()
.await
.unwrap_or(WorkstreamSummary {
id: active_id.clone(),
name: String::new(),
});
let _ = tx.send(ReplEvent::WorkstreamUpdated(ws));
let _ = tx.send(ReplEvent::StatusMessage(format!(
"activated workstream {active_id}"
)));
return Ok(());
}
let _ = tx.send(ReplEvent::StatusMessage(format!(
"unknown /workstream subcommand: {rest} (try `list` or `activate <id>`)"
)));
Ok(())
}
pub(super) async fn run_chat_turn(
&self,
line: &str,
tx: &UnboundedSender<ReplEvent>,
) -> Result<(), EngineError> {
let session_id = {
self.session_id
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
.ok_or(EngineError::NoSession)?;
self.rpc
.call(
"task.run",
json!({
"task_description": line,
"session_id": session_id,
}),
)
.await?;
self.pump_session_events(&session_id, tx).await
}
pub(super) async fn pump_session_events(
&self,
session_id: &str,
tx: &UnboundedSender<ReplEvent>,
) -> Result<(), EngineError> {
let url = format!("{}/sessions/{session_id}/events", self.rpc.base_url());
let mut attempts = 0u32;
'reconnect: loop {
let resp = match self
.rpc
.authorize(self.rpc.http().get(&url))
.timeout(CONNECT_TIMEOUT)
.send()
.await
{
Ok(r) if r.status().is_success() => r,
Ok(r) => {
let status = r.status();
if is_retryable_status(status) && attempts < SESSION_STREAM_MAX_RECONNECTS {
attempts += 1;
let _ = tx.send(ReplEvent::ConnectionLost {
reason: format!("daemon returned {status}; reconnecting…"),
});
tokio::time::sleep(RECONNECT_BACKOFF).await;
continue 'reconnect;
}
let _ = tx.send(terminal_stream_failure_event(format!(
"daemon returned {status} after {SESSION_STREAM_MAX_RECONNECTS} \
reconnect attempts; giving up"
)));
return Err(EngineError::Status { url, status });
}
Err(source) => {
if attempts < SESSION_STREAM_MAX_RECONNECTS {
attempts += 1;
let _ = tx.send(ReplEvent::ConnectionLost {
reason: format!("connection failed: {source}; reconnecting…"),
});
tokio::time::sleep(RECONNECT_BACKOFF).await;
continue 'reconnect;
}
let _ = tx.send(terminal_stream_failure_event(format!(
"connection failed after {SESSION_STREAM_MAX_RECONNECTS} reconnect \
attempts: {source}; giving up"
)));
return Err(EngineError::Transport { url, source });
}
};
let mut lines = SseLines::new(resp);
loop {
match tokio::time::timeout(SSE_IDLE_TIMEOUT, lines.next_data()).await {
Ok(Ok(Some(payload))) => {
attempts = 0;
let Ok(envelope) = serde_json::from_str::<SessionEventEnvelope>(&payload)
else {
continue;
};
if forward_session_event(envelope, tx) {
return Ok(());
}
}
Ok(Ok(None)) => {
if attempts < SESSION_STREAM_MAX_RECONNECTS {
attempts += 1;
let _ = tx.send(ReplEvent::ConnectionLost {
reason: "daemon closed the event stream; reconnecting…".to_string(),
});
tokio::time::sleep(RECONNECT_BACKOFF).await;
continue 'reconnect;
}
let _ = tx.send(terminal_stream_failure_event(format!(
"daemon closed the event stream after \
{SESSION_STREAM_MAX_RECONNECTS} reconnect attempts without a \
terminal session event; giving up"
)));
return Err(EngineError::StreamClosed { url });
}
Ok(Err(source)) => {
if attempts < SESSION_STREAM_MAX_RECONNECTS {
attempts += 1;
let _ = tx.send(ReplEvent::ConnectionLost {
reason: format!("stream error: {source}; reconnecting…"),
});
tokio::time::sleep(RECONNECT_BACKOFF).await;
continue 'reconnect;
}
let _ = tx.send(terminal_stream_failure_event(format!(
"stream error after {SESSION_STREAM_MAX_RECONNECTS} reconnect \
attempts: {source}; giving up"
)));
return Err(EngineError::Transport { url, source });
}
Err(_elapsed) => {
if attempts < SESSION_STREAM_MAX_RECONNECTS {
attempts += 1;
let _ = tx.send(ReplEvent::ConnectionLost {
reason: "no data from daemon within the idle timeout; \
reconnecting…"
.to_string(),
});
tokio::time::sleep(RECONNECT_BACKOFF).await;
continue 'reconnect;
}
let _ = tx.send(terminal_stream_failure_event(format!(
"no data from daemon within the idle timeout after \
{SESSION_STREAM_MAX_RECONNECTS} reconnect attempts; giving up"
)));
return Err(EngineError::Status {
url,
status: reqwest::StatusCode::REQUEST_TIMEOUT,
});
}
}
}
}
}
}