use std::path::Path;
use std::time::Duration;
use anyhow::Result;
use serde_json::json;
use trusty_code::cli_client::render::{WorkstreamRow, render_workstream_table};
use trusty_code::cli_client::{RpcClientError, StdioRpcClient};
use super::tcode_exe;
pub async fn list(project: &Path, include_closed: bool) -> Result<()> {
let exe = tcode_exe::resolve()?;
let mut client = StdioRpcClient::spawn(&exe, project)?;
let result = client
.call("workstream.list", json!({"include_closed": include_closed}))
.await;
client.shutdown(Duration::from_secs(5)).await?;
let result = result?;
let rows: Vec<WorkstreamRow> = serde_json::from_value(
result
.get("workstreams")
.cloned()
.unwrap_or(serde_json::Value::Null),
)
.map_err(|e| anyhow::anyhow!("tcode workstream list: malformed daemon response: {e}"))?;
println!("{}", render_workstream_table(&rows));
Ok(())
}
pub async fn get(project: &Path, id: &str) -> Result<()> {
let exe = tcode_exe::resolve()?;
let mut client = StdioRpcClient::spawn(&exe, project)?;
let result = client.call("workstream.get", json!({"id": id})).await;
client.shutdown(Duration::from_secs(5)).await?;
let result = result?;
println!(
"{}",
serde_json::to_string_pretty(&result)
.map_err(|e| anyhow::anyhow!("tcode workstream get: failed to render JSON: {e}"))?
);
Ok(())
}
pub async fn create(project: &Path, name: Option<String>) -> Result<()> {
let exe = tcode_exe::resolve()?;
let mut client = StdioRpcClient::spawn(&exe, project)?;
let result = client
.call("workstream.create", json!({"name": name}))
.await;
client.shutdown(Duration::from_secs(5)).await?;
let result = result?;
let id = result.get("id").and_then(|v| v.as_str()).unwrap_or("?");
println!("created workstream {id}");
Ok(())
}
pub async fn activate(project: &Path, id: &str, force: bool) -> Result<()> {
let exe = tcode_exe::resolve()?;
let mut client = StdioRpcClient::spawn(&exe, project)?;
let result = client
.call("workstream.activate", json!({"id": id, "force": force}))
.await;
client.shutdown(Duration::from_secs(5)).await?;
let value = result.map_err(|e| explain_activation_error(e, id))?;
match value.get("prior_id").and_then(|v| v.as_str()) {
Some(prior_id) => println!("activated workstream {id} (switched from {prior_id})"),
None => println!("activated workstream {id}"),
}
Ok(())
}
pub async fn deactivate(project: &Path) -> Result<()> {
let exe = tcode_exe::resolve()?;
let mut client = StdioRpcClient::spawn(&exe, project)?;
let list_result = client.call("workstream.list", json!({})).await;
let list_result = match list_result {
Ok(v) => v,
Err(e) => {
client.shutdown(Duration::from_secs(5)).await?;
return Err(e.into());
}
};
let active_id = list_result
.get("active_workstream_id")
.and_then(|v| v.as_str())
.map(str::to_string);
let Some(active_id) = active_id else {
client.shutdown(Duration::from_secs(5)).await?;
println!("no workstream is active");
return Ok(());
};
let result = client
.call("workstream.deactivate", json!({"id": active_id}))
.await;
client.shutdown(Duration::from_secs(5)).await?;
result?;
println!("deactivated workstream {active_id}");
Ok(())
}
pub async fn close(project: &Path, id: &str) -> Result<()> {
let exe = tcode_exe::resolve()?;
let mut client = StdioRpcClient::spawn(&exe, project)?;
let result = client.call("workstream.close", json!({"id": id})).await;
client.shutdown(Duration::from_secs(5)).await?;
result?;
println!("closed workstream {id}");
Ok(())
}
fn explain_activation_error(err: RpcClientError, target_id: &str) -> anyhow::Error {
if let RpcClientError::Rpc {
code: -32008,
ref data,
..
} = err
{
let active_id = data
.as_ref()
.and_then(|d| d.get("active_id"))
.and_then(|v| v.as_str())
.unwrap_or("<unknown>");
return anyhow::anyhow!(
"workstream {active_id} is already active; pass --force to switch to {target_id}"
);
}
err.into()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn explain_activation_error_names_the_active_workstream_and_suggests_force() {
let err = RpcClientError::Rpc {
code: -32008,
message: "another workstream is active: a1b2c3d4-e5f6-4748-9a0b-1c2d3e4f5a6b"
.to_string(),
data: Some(json!({
"error_type": "active_conflict",
"active_id": "a1b2c3d4-e5f6-4748-9a0b-1c2d3e4f5a6b",
})),
};
let message =
explain_activation_error(err, "b2c3d4e5-f6a1-4748-9a0b-1c2d3e4f5a6b").to_string();
assert!(
message.contains("a1b2c3d4-e5f6-4748-9a0b-1c2d3e4f5a6b"),
"must name the currently-active workstream: {message}"
);
assert!(
message.contains("--force"),
"must suggest --force: {message}"
);
assert!(
message.contains("b2c3d4e5-f6a1-4748-9a0b-1c2d3e4f5a6b"),
"must name the target workstream: {message}"
);
}
#[test]
fn explain_activation_error_passes_through_other_errors() {
let err = RpcClientError::Rpc {
code: -32002,
message: "workstream not found: nonexistent".to_string(),
data: None,
};
let message = explain_activation_error(err, "nonexistent").to_string();
assert!(
message.contains("workstream not found"),
"a non-active_conflict error must pass through unchanged: {message}"
);
}
}