use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;
use serde_json::{Value, json};
use tokio::sync::mpsc::UnboundedSender;
use trusty_code_tui::{CommandDescriptor, CommandRouting, PickerRequest, ReplEvent, TuiEngine};
use super::discovery::discover_daemon_url;
use super::engine_state::EngineState;
use super::error::EngineError;
use super::rpc::RpcHttpClient;
use super::workstream_subscription::run_workstream_subscription;
pub(super) const SSE_IDLE_TIMEOUT: Duration = Duration::from_secs(45);
pub(super) const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
pub(super) const RECONNECT_BACKOFF: Duration = Duration::from_secs(2);
pub(super) const SESSION_STREAM_MAX_RECONNECTS: u32 = 5;
fn workstream_subcommand(line: &str) -> Option<&str> {
let trimmed = line.trim();
for prefix in ["/workstream", "/ws"] {
if trimmed == prefix {
return Some("");
}
if let Some(rest) = trimmed.strip_prefix(prefix)
&& let Some(rest) = rest.strip_prefix(' ')
{
return Some(rest.trim());
}
}
None
}
pub fn build_http_client() -> reqwest::Client {
reqwest::Client::builder()
.pool_idle_timeout(Duration::from_secs(90))
.connect_timeout(Duration::from_secs(5))
.build()
.unwrap_or_else(|_| reqwest::Client::new())
}
pub struct CodeEngine {
state: Arc<EngineState>,
}
impl CodeEngine {
pub async fn discover(project_path: Option<PathBuf>) -> Result<Self, EngineError> {
let http = build_http_client();
let base_url = discover_daemon_url(&http).await?;
Ok(Self::with_daemon_url(http, base_url, project_path))
}
pub fn with_daemon_url(
http: reqwest::Client,
base_url: impl Into<String>,
project_path: Option<PathBuf>,
) -> Self {
Self {
state: Arc::new(EngineState::new(
RpcHttpClient::new(http, base_url.into()),
project_path,
)),
}
}
pub fn daemon_url(&self) -> &str {
self.state.rpc.base_url()
}
}
#[async_trait::async_trait]
impl TuiEngine for CodeEngine {
async fn handle_input(
&self,
line: String,
tx: UnboundedSender<ReplEvent>,
) -> anyhow::Result<bool> {
if let Some(rest) = workstream_subcommand(&line) {
self.state.handle_workstream_command(rest, &tx).await?;
return Ok(true);
}
self.state.run_chat_turn(line.trim(), &tx).await?;
Ok(true)
}
async fn setup(&self, tx: UnboundedSender<ReplEvent>) -> anyhow::Result<()> {
let result = self
.state
.rpc
.call(
"session.create",
json!({
"task": "tcode tui session",
"project": self.state.project_path,
}),
)
.await?;
let session_id = result
.get("id")
.and_then(Value::as_str)
.ok_or_else(|| EngineError::Malformed("session.create: response missing `id`".into()))?
.to_string();
*self
.state
.session_id
.lock()
.unwrap_or_else(|e| e.into_inner()) = Some(session_id.clone());
*self
.state
.commands_cache
.lock()
.unwrap_or_else(|e| e.into_inner()) = vec![CommandDescriptor {
name: "workstream".to_string(),
summary: "List or activate the daemon's workstreams".to_string(),
routing: CommandRouting::Engine,
args_hint: Some("[list | activate <id>]".to_string()),
}];
if let Some(ws) = self.state.refresh_workstream_cache().await {
let _ = tx.send(ReplEvent::WorkstreamUpdated(ws));
let _ = tx.send(ReplEvent::StatuslineUpdate(
self.state.statusline_segments(),
));
}
let _ = tx.send(ReplEvent::StatusMessage(format!(
"connected to tcode daemon at {} (session {session_id})",
self.state.rpc.base_url(),
)));
Ok(())
}
async fn cancel_session(&self) -> anyhow::Result<()> {
let session_id = {
self.state
.session_id
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
};
let Some(session_id) = session_id else {
return Ok(());
};
self.state
.rpc
.call("session.cancel", json!({ "session_id": session_id }))
.await?;
Ok(())
}
async fn subscribe_workstream_events(
&self,
tx: UnboundedSender<ReplEvent>,
) -> anyhow::Result<()> {
let current_id = {
self.state
.active_workstream
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
.map(|ws| ws.id);
let Some(current_id) = current_id else {
return Ok(());
};
tokio::spawn(run_workstream_subscription(
self.state.clone(),
current_id,
tx,
));
Ok(())
}
async fn shutdown(&self) -> anyhow::Result<()> {
self.state.shutting_down.store(true, Ordering::SeqCst);
Ok(())
}
fn commands(&self) -> Vec<CommandDescriptor> {
self.state.commands()
}
fn picker(&self, name: &str) -> Option<PickerRequest> {
if name != "workstream" {
return None;
}
let items = self.state.picker_items("workstream")?;
Some(PickerRequest {
title: "Workstreams".to_string(),
items,
dispatch_command: "/workstream activate".to_string(),
})
}
}
#[cfg(test)]
#[path = "engine_tests.rs"]
mod engine_tests;