use anyhow::anyhow;
use async_trait::async_trait;
use serde_json::json;
use std::fmt::Write as _;
use crate::pipeline::board::{TicketPhase, store as board_store};
use crate::tools::ToolAnswer;
use crate::tools::ticket::{GET_TICKET_COMMENT_MAX, GET_TICKET_DESC_MAX, GET_TICKET_LAST_N_FULL};
use crate::workspace::WorkspaceStore;
use crate::{Role, Tool, Workspace, WorkspaceStatus};
const OUTPUT_BYTE_LIMIT: usize = 24_000;
const BOARD_LINE_LIMIT: usize = 100;
const NO_WORKSPACE: &str = "No managed workspaces exist.";
pub(crate) struct WorkspaceTool;
fn schema() -> &'static serde_json::Value {
static SCHEMA: std::sync::LazyLock<serde_json::Value> = std::sync::LazyLock::new(build_schema);
&SCHEMA
}
fn build_schema() -> serde_json::Value {
super::tool_params_schema(
&json!({
"action": {
"type": "string",
"enum": [
"reference",
"list",
"show",
"add",
"delete",
"pause",
"resume",
"maintenance",
"rediscover",
"rediscover_diagnostics",
"set_diagnostics",
"set_rules",
"use",
"board",
"ticket",
"comment"
],
"description": "The operation; its `reference` action lists every one."
},
"workspace": {
"type": "string",
"description": "The managed workspace, spelled as `list` spells it."
},
"name": {
"type": "string",
"description": "(add) Short unique name."
},
"path": {
"type": "string",
"description": "(add) The project directory."
},
"phase": {
"type": "string",
"description": "(board) One ticket phase."
},
"ticket_id": {
"type": "string",
"description": "(ticket/comment) Full id `<workspace>-<number>`."
},
"full": {
"type": "boolean",
"description": "(ticket) Whole and unclipped. Default false."
},
"content": {
"type": "string",
"description": "(comment) The note to leave."
},
"rules": {
"type": "string",
"description": "(set_rules) Project rules; empty clears."
},
"maintenance": {
"type": "boolean",
"description": "(maintenance) Background maintainer on or off."
},
"format": {
"type": "string",
"description": "(set_diagnostics) Format command."
},
"format_check": {
"type": "string",
"description": "(set_diagnostics) Format-check command."
},
"lint": {
"type": "string",
"description": "(set_diagnostics) Lint command."
},
"lint_fix": {
"type": "string",
"description": "(set_diagnostics) Lint-fix command."
},
"type_check": {
"type": "string",
"description": "(set_diagnostics) Type-check command."
},
"build": {
"type": "string",
"description": "(set_diagnostics) Build command."
},
"unit_test": {
"type": "string",
"description": "(set_diagnostics) Unit-test command."
}
}),
&["action"],
)
}
#[async_trait]
impl Tool for WorkspaceTool {
fn name(&self) -> &'static str {
"workspace"
}
fn parameters_schema(&self) -> serde_json::Value {
schema().clone()
}
fn preserve_full_output(&self) -> bool {
true
}
async fn execute(&self, _ws: &Workspace, args: serde_json::Value) -> anyhow::Result<String> {
Ok(self.answer(args).await?.text)
}
async fn execute_answer(
&self,
_ws: &Workspace,
args: serde_json::Value,
) -> anyhow::Result<ToolAnswer> {
self.answer(args).await
}
}
impl WorkspaceTool {
async fn answer(&self, args: serde_json::Value) -> anyhow::Result<ToolAnswer> {
super::refuse_unknown_fields(schema(), &args, super::REFERENCE_ACTION_HINT)?;
match super::get_str(&args, "action")? {
"reference" => Ok(ToolAnswer::done(crate::settings::reference())),
"list" => Ok(ToolAnswer::done(
list_workspaces(super::get_opt_str_strict(&args, "workspace")?).await?,
)),
"show" => Ok(ToolAnswer::done(
show_workspace(super::get_str(&args, "workspace")?).await?,
)),
"add" => add_workspace(&args).await,
"delete" => Ok(ToolAnswer::done(
delete_workspace(super::get_str(&args, "workspace")?).await?,
)),
"pause" => pause_or_resume(write_address(&args, "pause")?, true).await,
"resume" => pause_or_resume(write_address(&args, "resume")?, false).await,
"maintenance" => Ok(ToolAnswer::done(set_maintenance(&args).await?)),
"rediscover" => Ok(ToolAnswer::done(
rediscover(super::get_str(&args, "workspace")?).await?,
)),
"rediscover_diagnostics" => Ok(ToolAnswer::done(
rediscover_diagnostics(super::get_str(&args, "workspace")?).await?,
)),
"set_diagnostics" => Ok(ToolAnswer::done(set_diagnostics(&args).await?)),
"set_rules" => Ok(ToolAnswer::done(set_rules(&args).await?)),
"use" => Ok(ToolAnswer::done(
use_workspace(super::get_str(&args, "workspace")?).await?,
)),
"board" => Ok(ToolAnswer::done(
list_board(
super::get_opt_str_strict(&args, "workspace")?,
super::get_opt_str_strict(&args, "phase")?,
)
.await?,
)),
"ticket" => Ok(ToolAnswer::done(
show_ticket(
super::get_str(&args, "ticket_id")?,
super::get_bool(&args, "full", false)?,
)
.await?,
)),
"comment" => Ok(ToolAnswer::done(
add_note(
super::get_str(&args, "ticket_id")?,
super::get_str(&args, "content")?,
)
.await?,
)),
other => Err(anyhow!(
"unknown action '{other}' — call the `reference` action for every action and field"
)),
}
}
}
fn write_address<'a>(args: &'a serde_json::Value, action: &str) -> anyhow::Result<Option<&'a str>> {
if let Some(address) = super::get_opt_str_strict(args, "workspace")? {
return Ok(Some(address));
}
if args.as_object().is_some_and(|obj| {
obj.iter()
.any(|(key, value)| key.as_str() != "action" && !value.is_null())
}) {
return Err(anyhow!(
"usage: with no \"workspace\" this `{action}` covers every managed workspace, so \
the call may name nothing else — hint: pass \"workspace\" to act on one workspace, or \
drop the extra field to really cover every managed workspace"
));
}
Ok(None)
}
async fn managed_workspace(name: &str) -> anyhow::Result<Workspace> {
let name = name.trim();
let workspaces = crate::users::managed_workspaces().await?;
if let Some(ws) = workspaces.iter().find(|ws| ws.name == name) {
return Ok(ws.clone());
}
let managed = if workspaces.is_empty() {
"none".to_string()
} else {
workspaces
.iter()
.map(|ws| ws.name.as_str())
.collect::<Vec<_>>()
.join(", ")
};
Err(if crate::users::is_personal_workspace(name) {
anyhow!(
"'{name}' is a personal space, not a managed workspace — personal spaces have \
no pipeline and no board; managed workspaces: {managed}"
)
} else {
anyhow!(
"No managed workspace exists under the name '{name}' — managed workspaces: {managed}"
)
})
}
async fn managed_ticket_id(raw: &str) -> anyhow::Result<String> {
let Ok((Some(prefix), full)) = crate::tools::ticket::parse_ticket_id(raw) else {
return Err(anyhow!(
"Ticket id '{}' is not a full '<workspace>-<number>' id — `ticket` and `comment` \
are addressed by a ticket's full id, which already carries its workspace.",
raw.trim()
));
};
managed_workspace(prefix).await?;
Ok(full.to_string())
}
async fn list_workspaces(only: Option<&str>) -> anyhow::Result<String> {
let workspaces = crate::users::managed_workspaces().await?;
if workspaces.is_empty() && only.is_none() {
return Ok(NO_WORKSPACE.to_string());
}
let resolved =
crate::users::resolve_selected_workspace_name(crate::users::ADMIN_USER_NAME).await;
let active = resolved
.as_deref()
.filter(|name| workspaces.iter().any(|ws| &ws.name == name));
let listed = match only {
Some(name) => vec![managed_workspace(name).await?],
None => workspaces,
};
let mut listing = String::from("Managed workspaces:\n");
for ws in &listed {
let paused = if ws.paused { ", paused" } else { "" };
let maintenance = if ws.maintenance_enabled {
", maintenance on"
} else {
""
};
let active_marker = if active == Some(ws.name.as_str()) {
" [active]"
} else {
""
};
let _ = writeln!(
listing,
"- {} ({}{paused}{maintenance}): {}{active_marker}",
ws.name, ws.status, ws.path
);
}
if resolved.is_none() {
let _ = writeln!(listing, "The active workspace could not be read.");
} else if active.is_none() {
let _ = writeln!(listing, "No workspace is active.");
}
Ok(listing.trim_end().to_string())
}
async fn add_workspace(args: &serde_json::Value) -> anyhow::Result<ToolAnswer> {
let name = super::get_str(args, "name")?;
let path = super::get_str(args, "path")?;
let added = crate::workspace::store().add(name, path).await?;
let path = added.path;
match crate::users::store()
.set_selected_workspace(crate::users::ADMIN_USER_NAME, Some(name))
.await
{
Ok(()) => Ok(ToolAnswer::done(format!(
"Added managed workspace '{name}' at {path} and made it your active workspace. \
The workspace is being picked up — if the model provider is configured its first \
discovery pass will start shortly."
))),
Err(e) => Ok(ToolAnswer::partial(format!(
"Added managed workspace '{name}' at {path}, but making it your active workspace \
failed: {e} — make it active again with the `use` action."
))),
}
}
async fn show_workspace(name: &str) -> anyhow::Result<String> {
let ws = managed_workspace(name).await?;
let active = crate::users::resolve_selected_workspace_name(crate::users::ADMIN_USER_NAME).await;
let commands = crate::workspace::store().get_diagnostics(&ws.name).await?;
let mut out = format!("Workspace '{}':\n", ws.name);
let _ = writeln!(out, "- path: {}", ws.path);
let _ = writeln!(out, "- status: {}", ws.status);
let _ = writeln!(
out,
"- pipeline: {}",
if ws.paused { "paused" } else { "running" }
);
let _ = writeln!(
out,
"- maintenance: {}",
if ws.maintenance_enabled { "on" } else { "off" }
);
let _ = writeln!(
out,
"- active project: {}",
match active.as_deref() {
Some(active) if active == ws.name => "yes",
Some(_) => "no",
None => "unknown (the selection could not be read)",
}
);
if ws.notes.trim().is_empty() {
let _ = writeln!(out, "- rules: none");
} else {
let _ = writeln!(out, "- rules:");
for line in ws.notes.lines() {
let _ = writeln!(out, " {line}");
}
}
match commands.as_ref().filter(|commands| !commands.is_empty()) {
Some(commands) => {
let _ = writeln!(out, "- diagnostics:");
write_commands(&mut out, commands, " ");
}
None => {
let _ = writeln!(out, "- diagnostics: not discovered");
}
}
Ok(out.trim_end().to_string())
}
async fn delete_workspace(name: &str) -> anyhow::Result<String> {
let ws = managed_workspace(name).await?;
let active = match crate::workspace::store().delete(&ws.name).await? {
Some(next) => format!("Your active project is now '{next}'."),
None => "You are back on your personal workspace.".to_string(),
};
Ok(format!(
"Deleted managed workspace '{name}'. Its jobs and its research runs are gone with it. \
{folder_note} The tickets filed against it stay in the board but are no longer listed. \
{active}",
name = ws.name,
folder_note = folder_note(&ws.path)
))
}
fn folder_note(path: &str) -> String {
let folder = std::path::Path::new(path);
if !folder.exists() {
format!("The project folder at {path} is gone.")
} else if crate::git::commands::is_git_repo(folder) {
format!("The project folder at {path} (git repository included) stays.")
} else {
format!("The project folder at {path} stays.")
}
}
async fn set_maintenance(args: &serde_json::Value) -> anyhow::Result<String> {
let Some(on) = super::get_opt_bool(args, "maintenance")? else {
return Err(anyhow!(
"usage: missing required argument \"maintenance\" (expected a boolean) — hint: pass \
true to run the background maintainer or false to stop it"
));
};
let ws = managed_workspace(super::get_str(args, "workspace")?).await?;
crate::workspace::store()
.set_maintenance_enabled(&ws.name, on)
.await?;
Ok(if on {
format!(
"Maintenance is now on for workspace '{}'. The debounce is cleared, so the maintainer \
runs on the next poll.",
ws.name
)
} else {
format!(
"Maintenance is now off for workspace '{}'. Any maintainer agent running there was \
cancelled.",
ws.name
)
})
}
async fn rediscover(name: &str) -> anyhow::Result<String> {
let ws = managed_workspace(name).await?;
crate::workspace::store().rediscover(&ws.name).await?;
Ok(format!(
"Discovery restarted for workspace '{}': its per-role contexts were cleared. The \
pipeline is paused until discovery finishes.",
ws.name
))
}
async fn rediscover_diagnostics(name: &str) -> anyhow::Result<String> {
let ws = managed_workspace(name).await?;
crate::workspace::store()
.rediscover_diagnostics(&ws.name)
.await?;
Ok(format!(
"Diagnostics discovery restarted for workspace '{}': its stored commands were cleared and \
are being re-detected — its status, its pause and its per-role contexts are untouched.",
ws.name
))
}
fn apply_command(slot: &mut Option<String>, given: Option<&str>) {
if let Some(value) = given {
*slot = crate::util::none_if_empty(value);
}
}
fn write_commands(out: &mut String, commands: &crate::DiagnosticsCommands, indent: &str) {
for (label, command) in commands.commands() {
let _ = writeln!(
out,
"{indent}- {label}: {}",
command.unwrap_or("not discovered")
);
}
}
async fn set_diagnostics(args: &serde_json::Value) -> anyhow::Result<String> {
let format = super::get_opt_str_strict(args, "format")?;
let format_check = super::get_opt_str_strict(args, "format_check")?;
let lint = super::get_opt_str_strict(args, "lint")?;
let lint_fix = super::get_opt_str_strict(args, "lint_fix")?;
let type_check = super::get_opt_str_strict(args, "type_check")?;
let build = super::get_opt_str_strict(args, "build")?;
let unit_test = super::get_opt_str_strict(args, "unit_test")?;
anyhow::ensure!(
[
format,
format_check,
lint,
lint_fix,
type_check,
build,
unit_test
]
.iter()
.any(Option::is_some),
"usage: name at least one command field — format, format_check, lint, lint_fix, \
type_check, build, unit_test (an empty string clears one)"
);
let ws = managed_workspace(super::get_str(args, "workspace")?).await?;
let mut commands = crate::workspace::store()
.get_diagnostics(&ws.name)
.await?
.unwrap_or_default();
apply_command(&mut commands.format, format);
apply_command(&mut commands.format_check, format_check);
apply_command(&mut commands.lint, lint);
apply_command(&mut commands.lint_fix, lint_fix);
apply_command(&mut commands.type_check, type_check);
apply_command(&mut commands.build, build);
apply_command(&mut commands.unit_test, unit_test);
crate::workspace::store()
.set_diagnostics(&ws.name, &commands)
.await?;
let mut out = format!("Diagnostics for workspace '{}':\n", ws.name);
write_commands(&mut out, &commands, "");
let _ = write!(
out,
"\nWriting invalidated any diagnostics discovery already in flight, so its stale result \
cannot overwrite these."
);
Ok(out)
}
async fn set_rules(args: &serde_json::Value) -> anyhow::Result<String> {
let rules = super::get_str(args, "rules")?;
let ws = managed_workspace(super::get_str(args, "workspace")?).await?;
crate::workspace::store().set_notes(&ws.name, rules).await?;
let stored = crate::workspace::truncate_workspace_notes(rules);
let mut out = if stored.is_empty() {
format!("The rules of workspace '{}' are now empty.", ws.name)
} else {
format!(
"The rules of workspace '{}' are now {} characters long.",
ws.name,
stored.chars().count()
)
};
if rules.chars().count() > stored.chars().count() {
let _ = write!(
out,
" They were truncated to {} characters.",
crate::workspace::MAX_WORKSPACE_NOTES_CHARS
);
}
Ok(out)
}
async fn use_workspace(name: &str) -> anyhow::Result<String> {
let ws = managed_workspace(name).await?;
crate::users::store()
.set_selected_workspace(crate::users::ADMIN_USER_NAME, Some(&ws.name))
.await?;
Ok(format!(
"'{}' is now your active project at {}. It takes effect without a restart — the \
dashboard reads the stored selection back on a users change.",
ws.name, ws.path
))
}
enum PipelineChange {
NotReady,
Already,
Write,
}
fn pipeline_change(ws: &Workspace, paused: bool) -> PipelineChange {
if ws.status != WorkspaceStatus::Ready {
PipelineChange::NotReady
} else if ws.paused == paused {
PipelineChange::Already
} else {
PipelineChange::Write
}
}
async fn pause_or_resume(name: Option<&str>, paused: bool) -> anyhow::Result<ToolAnswer> {
match name {
Some(name) => Ok(ToolAnswer::done(
set_one_pipeline_paused(name, paused).await?,
)),
None => set_all_pipelines_paused(paused).await,
}
}
async fn set_one_pipeline_paused(name: &str, paused: bool) -> anyhow::Result<String> {
let ws = managed_workspace(name).await?;
match pipeline_change(&ws, paused) {
PipelineChange::NotReady => Err(anyhow!(
"Workspace '{}' is {} — only a ready workspace has a pipeline to pause or resume.",
ws.name,
ws.status
)),
PipelineChange::Already => Ok(if paused {
format!("The pipeline of workspace '{}' is already paused.", ws.name)
} else {
format!(
"The pipeline of workspace '{}' is not paused — nothing to resume.",
ws.name
)
}),
PipelineChange::Write => {
crate::workspace::store()
.set_paused(&ws.name, paused)
.await?;
let verb = if paused { "paused" } else { "resumed" };
Ok(format!("Pipeline {verb} for workspace '{}'.", ws.name))
}
}
}
async fn set_pipelines_paused(
store: &WorkspaceStore,
workspaces: &[Workspace],
paused: bool,
) -> anyhow::Result<ToolAnswer> {
if workspaces.is_empty() {
return Ok(ToolAnswer::done(NO_WORKSPACE));
}
let header = if paused {
"Paused every managed workspace where possible:"
} else {
"Resumed every managed workspace where possible:"
};
let mut out = format!("{header}\n");
let mut incomplete = false;
for ws in workspaces {
let line = match pipeline_change(ws, paused) {
PipelineChange::NotReady => {
incomplete = true;
format!("- {}: skipped — not ready ({})", ws.name, ws.status)
}
PipelineChange::Already if paused => format!("- {}: already paused", ws.name),
PipelineChange::Already => format!("- {}: not paused", ws.name),
PipelineChange::Write => match store.set_paused(&ws.name, paused).await {
Ok(()) if paused => format!("- {}: paused", ws.name),
Ok(()) => format!("- {}: resumed", ws.name),
Err(e) => {
incomplete = true;
format!("- {}: failed — {e}", ws.name)
}
},
};
let _ = writeln!(out, "{line}");
}
let report = out.trim_end().to_string();
Ok(if incomplete {
ToolAnswer::partial(report)
} else {
ToolAnswer::done(report)
})
}
async fn set_all_pipelines_paused(paused: bool) -> anyhow::Result<ToolAnswer> {
let workspaces = crate::users::managed_workspaces().await?;
set_pipelines_paused(crate::workspace::store(), &workspaces, paused).await
}
async fn list_board(only: Option<&str>, phase: Option<&str>) -> anyhow::Result<String> {
let workspaces = crate::users::managed_workspaces().await?;
let phase_filter = match phase {
Some(s) if s.eq_ignore_ascii_case("archived") => {
anyhow::bail!(
"Archived tickets are never listed — archiving is a one-way visibility switch that hides a ticket from every listing, and a single archived ticket stays readable with `ticket` by its id."
);
}
Some(s) => Some(s.parse::<TicketPhase>()?),
None => None,
};
let only = match only {
Some(name) => Some(managed_workspace(name).await?.name),
None => None,
};
let mut tickets = board_store().list_all_tickets(None, phase_filter).await?;
tickets.retain(|t| {
workspaces.iter().any(|ws| ws.name == t.workspace_name)
&& only.as_ref().is_none_or(|name| name == &t.workspace_name)
});
if tickets.is_empty() {
return Ok("No tickets found.".to_string());
}
let total = tickets.len();
let mut lines = Vec::new();
let mut bytes = 0;
for t in &tickets {
let mut line = t.short_display();
if !lines.is_empty()
&& (lines.len() == BOARD_LINE_LIMIT || bytes + line.len() > OUTPUT_BYTE_LIMIT)
{
break;
}
line = crate::util::cut_bytes(&line, OUTPUT_BYTE_LIMIT);
bytes += line.len() + 1;
lines.push(line);
}
let shown = lines.len();
let mut out = String::from("Tickets:\n");
for line in &lines {
let _ = writeln!(out, "{line}");
}
if shown < total {
let _ = write!(
out,
"\n(partial listing: showing the first {shown} of {total} tickets — \
narrow it with `phase`, name a single `workspace`, or read one ticket with `ticket`.)"
);
}
Ok(out)
}
async fn show_ticket(ticket_id: &str, full: bool) -> anyhow::Result<String> {
let id = managed_ticket_id(ticket_id).await?;
let Some(ticket) = board_store().get_ticket(&id).await? else {
return Err(anyhow!("Ticket {id} not found."));
};
if full {
return Ok(ticket.detailed_display());
}
let shortened = ticket.detailed_display_limited(
GET_TICKET_DESC_MAX,
GET_TICKET_COMMENT_MAX,
GET_TICKET_LAST_N_FULL,
);
if shortened.len() <= OUTPUT_BYTE_LIMIT {
return Ok(shortened);
}
Ok(format!(
"{}…\n(shortened view cut short — pass `full: true` for the ticket whole and unclipped.)",
crate::util::truncate_bytes(&shortened, OUTPUT_BYTE_LIMIT)
))
}
async fn add_note(ticket_id: &str, content: &str) -> anyhow::Result<String> {
anyhow::ensure!(
!content.trim().is_empty(),
"usage: \"content\" is empty — hint: pass the note's text to leave on the ticket"
);
let id = managed_ticket_id(ticket_id).await?;
if board_store().get_ticket_phase(&id).await?.is_none() {
return Err(anyhow!("Ticket {id} not found — no note was left."));
}
board_store()
.add_comment(&id, Role::Assistant.as_str(), content)
.await?;
Ok(format!("Note added to ticket {id} as 'assistant'."))
}
#[cfg(test)]
mod tests {
use super::*;
fn tool_args(action: &str, name: Option<&str>) -> serde_json::Value {
match name {
Some(name) => json!({ "action": action, "workspace": name }),
None => json!({ "action": action }),
}
}
#[tokio::test]
async fn pause_and_resume_a_ready_workspace() {
let _guard = crate::util::test::STORE_LOCK.lock().await;
crate::util::test::init_test_stores().await;
let ws = crate::workspace::test_ws("/tmp/ws_ready");
let tool = WorkspaceTool;
crate::util::test::create_test_workspace("/tmp/ws_ready", "ws_ready").await;
crate::workspace::store()
.set_status("ws_ready", &WorkspaceStatus::Ready)
.await
.expect("mark ready");
let reply = tool
.execute(&ws, tool_args("pause", Some("ws_ready")))
.await
.expect("pause");
assert!(
reply.contains("ws_ready") && reply.contains("paused"),
"got: {reply}"
);
assert!(
crate::workspace::get_by_name("ws_ready")
.await
.expect("read")
.expect("exists")
.paused
);
let listing = tool
.execute(&ws, tool_args("list", None))
.await
.expect("list");
assert!(
listing.contains("- ws_ready (ready, paused):"),
"got: {listing}"
);
let reply = tool
.execute(&ws, tool_args("pause", Some("ws_ready")))
.await
.expect("re-pause");
assert!(reply.contains("already paused"), "got: {reply}");
let reply = tool
.execute(&ws, tool_args("resume", Some("ws_ready")))
.await
.expect("resume");
assert!(reply.contains("resumed"), "got: {reply}");
assert!(
!crate::workspace::get_by_name("ws_ready")
.await
.expect("read")
.expect("exists")
.paused
);
assert!(
!tool
.execute(&ws, tool_args("list", None))
.await
.expect("list")
.contains("- ws_ready (ready, paused)"),
"a resumed workspace must not carry the pause marker"
);
}
#[tokio::test]
async fn pause_every_managed_workspace_skips_not_ready() {
let (store, _dir) = crate::open_test_store!(WorkspaceStore, "workspace");
let root = crate::util::test::test_root();
let ready = root.join("ws_fleet");
let pending = root.join("ws_fleet_pending");
for dir in [&ready, &pending] {
std::fs::create_dir_all(dir).expect("create workspace dir");
}
let ready = ready.to_str().expect("utf-8 path");
store.add("ws_fleet", ready).await.expect("add ws_fleet");
store
.set_status("ws_fleet", &WorkspaceStatus::Ready)
.await
.expect("mark ready");
store.set_paused("ws_fleet", false).await.expect("unpause");
store
.add("ws_fleet_pending", pending.to_str().expect("utf-8 path"))
.await
.expect("add ws_fleet_pending");
store
.set_paused("ws_fleet_pending", false)
.await
.expect("unpause ws_fleet_pending");
let workspaces = store.list().await.expect("list");
let reply = set_pipelines_paused(&store, &workspaces, true)
.await
.expect("pause all");
assert!(
reply.text.contains("- ws_fleet: paused"),
"got: {}",
reply.text
);
assert!(
reply
.text
.contains("- ws_fleet_pending: skipped — not ready (pending)"),
"got: {}",
reply.text
);
assert!(
reply.partial,
"a workspace the call left untouched makes the fleet call partial: {}",
reply.text
);
assert!(
store
.get_by_name("ws_fleet")
.await
.expect("read")
.expect("exists")
.paused
);
assert!(
!store
.get_by_name("ws_fleet_pending")
.await
.expect("read")
.expect("exists")
.paused,
"a not-ready workspace must not be paused"
);
let workspaces = store.list().await.expect("list");
let reply = set_pipelines_paused(&store, &workspaces, false)
.await
.expect("resume all");
assert!(
reply.text.contains("- ws_fleet: resumed"),
"got: {}",
reply.text
);
assert!(
reply.partial,
"the not-ready workspace is left untouched by the resume too: {}",
reply.text
);
let reply = set_pipelines_paused(&store, &[], true)
.await
.expect("empty set");
assert_eq!(reply.text, NO_WORKSPACE);
}
#[tokio::test]
async fn a_misspelled_address_never_escalates_to_the_fleet() {
let _guard = crate::util::test::STORE_LOCK.lock().await;
crate::util::test::init_test_stores().await;
let tool = WorkspaceTool;
crate::util::test::create_test_workspace("/tmp/ws_address", "ws_address").await;
crate::workspace::store()
.set_status("ws_address", &WorkspaceStatus::Ready)
.await
.expect("mark ready");
let ws = crate::workspace::test_ws("/tmp/ws_address");
for call in [
json!({ "action": "pause", "name": "ws_address" }),
json!({ "action": "resume", "path": "/tmp/ws_address" }),
json!({ "action": "resume", "ticket_id": "ws_address-1" }),
crate::tools::normalize_tool_call(
"workspace",
json!({ "action": "pause", "id": "ws_address" }),
)
.1,
] {
let err = tool
.execute(&ws, call.clone())
.await
.unwrap_err()
.to_string();
assert!(err.contains("usage:"), "for {call}: {err}");
}
for call in [
json!({ "action": "pause", "workspace_name": "ws_address" }),
json!({ "action": "list", "workspace": "ws_address", "folder": "/tmp/ws_address" }),
] {
let err = tool
.execute(&ws, call.clone())
.await
.unwrap_err()
.to_string();
assert!(
err.contains("unknown field") && err.contains("reference"),
"for {call}: {err}"
);
}
for value in [
json!(3),
json!(["ws_address"]),
json!({ "name": "ws_address" }),
] {
let err = tool
.execute(&ws, json!({ "action": "resume", "workspace": value }))
.await
.unwrap_err()
.to_string();
assert!(
err.contains("usage:") && err.contains("workspace"),
"got: {err}"
);
}
assert!(
!crate::workspace::get_by_name("ws_address")
.await
.expect("read")
.expect("exists")
.paused,
"a refused address must not pause anything"
);
for args in [
json!({ "action": "list", "workspace": "ws_address" }),
json!({ "action": "list", "workspace": "ws_address", "phase": "done" }),
] {
let listing = tool.execute(&ws, args.clone()).await.expect("list");
assert!(
listing.starts_with("Managed workspaces:\n- ws_address ("),
"for {args}: {listing}"
);
}
let reply = tool
.execute(&ws, json!({ "action": "pause", "workspace": "ws_address" }))
.await
.expect("pause");
assert!(
reply.contains("Pipeline paused for workspace 'ws_address'"),
"got: {reply}"
);
}
#[tokio::test]
async fn ticket_actions_refuse_a_bare_number() {
crate::util::test::init_test_stores().await;
let ws = crate::workspace::test_ws("/tmp/ws_bare");
let tool = WorkspaceTool;
let err = tool
.execute(&ws, json!({ "action": "ticket", "ticket_id": "42" }))
.await
.unwrap_err()
.to_string();
assert!(err.contains("<workspace>-<number>"), "got: {err}");
let err = tool
.execute(
&ws,
json!({ "action": "comment", "ticket_id": "42", "content": "hi" }),
)
.await
.unwrap_err()
.to_string();
assert!(err.contains("<workspace>-<number>"), "got: {err}");
}
#[tokio::test]
async fn ticket_refuses_a_not_managed_workspace_and_missing_ticket() {
crate::util::test::init_test_stores().await;
let ws = crate::workspace::test_ws("/tmp/ws_ticket");
let tool = WorkspaceTool;
let err = tool
.execute(
&ws,
json!({ "action": "ticket", "ticket_id": "ws_ghost-1" }),
)
.await
.unwrap_err()
.to_string();
assert!(err.contains("No managed workspace exists"), "got: {err}");
crate::util::test::create_test_workspace("/tmp/ws_ticket", "ws_ticket").await;
let err = tool
.execute(
&ws,
json!({ "action": "ticket", "ticket_id": "ws_ticket-9999" }),
)
.await
.unwrap_err()
.to_string();
assert!(err.contains("not found"), "got: {err}");
}
#[tokio::test]
async fn comment_refuses_a_missing_ticket() {
crate::util::test::init_test_stores().await;
let tool = WorkspaceTool;
crate::util::test::create_test_workspace("/tmp/ws_note", "ws_note").await;
let ws = crate::workspace::test_ws("/tmp/ws_note");
let err = tool
.execute(
&ws,
json!({ "action": "comment", "ticket_id": "ws_note-9999", "content": " " }),
)
.await
.unwrap_err()
.to_string();
assert!(err.contains("usage:"), "got: {err}");
let err = tool
.execute(
&ws,
json!({ "action": "comment", "ticket_id": "ws_note-9999", "content": "hi" }),
)
.await
.unwrap_err()
.to_string();
assert!(
err.contains("not found") && err.contains("no note"),
"got: {err}"
);
assert!(
board_store()
.get_comments("ws_note-9999")
.await
.expect("read")
.is_empty(),
"a missing ticket must gain no note"
);
}
#[tokio::test]
async fn board_refuses_archived_and_skips_workspaces_that_are_not_managed() {
crate::util::test::init_test_stores().await;
let tool = WorkspaceTool;
let ws = crate::util::test::create_test_workspace("/tmp/ws_board", "ws_board").await;
let done_id = crate::util::test::make_ticket(
board_store(),
&ws,
"workspace board done",
TicketPhase::Done,
)
.await;
let ghost = crate::workspace::test_ws_named("/tmp/ws_ghost", "ws_ghost");
let ghost_id =
crate::util::test::make_ticket(board_store(), &ghost, "ghost done", TicketPhase::Done)
.await;
let err = tool
.execute(&ws, json!({ "action": "board", "phase": "archived" }))
.await
.unwrap_err()
.to_string();
assert!(
err.contains("Archived tickets are never listed"),
"got: {err}"
);
let listing = tool
.execute(&ws, json!({ "action": "board", "phase": "done" }))
.await
.expect("board");
assert!(
listing.contains(&done_id),
"a done ticket of a managed workspace must be listed: {listing}"
);
assert!(
!listing.contains(&ghost_id),
"a ticket of a workspace that is not managed must never be listed: {listing}"
);
let listing = tool
.execute(&ws, json!({ "action": "board" }))
.await
.expect("board");
assert!(
listing.contains(&done_id),
"a done ticket must be listed without a phase filter: {listing}"
);
}
#[tokio::test]
#[serial_test::serial(gui_admin_workspace)] async fn list_marks_the_active_workspace_or_says_none() {
crate::util::test::init_test_stores().await;
let tool = WorkspaceTool;
let ws = crate::workspace::test_ws("/tmp/ws_active");
crate::users::test_util::with_test_workspaces(
&[("/tmp/ws_active", "ws_active")],
crate::users::test_util::with_admin_workspace_restored(async {
crate::users::store()
.set_selected_workspace(crate::users::ADMIN_USER_NAME, Some("ws_active"))
.await
.expect("select");
let listing = tool
.execute(&ws, tool_args("list", None))
.await
.expect("list");
assert!(listing.contains("- ws_active ("), "got: {listing}");
assert!(listing.contains("[active]"), "got: {listing}");
assert!(
!listing.contains("No workspace is active."),
"got: {listing}"
);
crate::users::store()
.set_selected_workspace(crate::users::ADMIN_USER_NAME, Some("personal:admin"))
.await
.expect("select personal");
let listing = tool
.execute(&ws, tool_args("list", None))
.await
.expect("list");
assert!(
listing.contains("No workspace is active."),
"got: {listing}"
);
assert!(!listing.contains("[active]"), "got: {listing}");
}),
)
.await;
}
#[tokio::test]
async fn a_named_listing_answers_about_that_workspace() {
let _guard = crate::util::test::STORE_LOCK.lock().await;
crate::util::test::init_test_stores().await;
crate::users::test_util::with_test_workspaces(
&[("/tmp/ws_named", "ws_named"), ("/tmp/ws_other", "ws_other")],
async {
let listing = list_workspaces(Some("ws_named"))
.await
.expect("a named listing");
assert!(listing.contains("- ws_named ("), "got: {listing}");
assert!(
!listing.contains("- ws_other ("),
"a named listing narrows to the one named: {listing}"
);
let missing = list_workspaces(Some("ws_absent"))
.await
.expect_err("an unmanaged name")
.to_string();
assert!(missing.contains("ws_absent"), "got: {missing}");
assert!(
!missing.contains("No managed workspaces exist."),
"a named listing answers about the name, not the fleet: {missing}"
);
},
)
.await;
}
#[tokio::test]
async fn reference_is_the_settings_reference_verbatim() {
let ws = crate::workspace::test_ws("/tmp/ws_reference");
let reply = WorkspaceTool
.execute(&ws, json!({ "action": "reference" }))
.await
.expect("reference");
assert_eq!(reply, crate::settings::reference());
}
#[tokio::test]
async fn show_reports_a_workspaces_settings() {
let _guard = crate::util::test::STORE_LOCK.lock().await;
crate::util::test::init_test_stores().await;
let tool = WorkspaceTool;
let ws = crate::workspace::test_ws("/tmp/ws_show");
crate::util::test::create_test_workspace("/tmp/ws_show", "ws_show").await;
crate::workspace::store()
.set_maintenance_enabled("ws_show", true)
.await
.expect("maintenance on");
crate::workspace::store()
.set_notes("ws_show", "be nice to the fixtures")
.await
.expect("rules");
crate::workspace::store()
.set_diagnostics(
"ws_show",
&crate::DiagnosticsCommands {
format: Some("cargo fmt".to_string()),
..Default::default()
},
)
.await
.expect("diagnostics");
let reply = tool
.execute(&ws, tool_args("show", Some("ws_show")))
.await
.expect("show");
assert!(reply.starts_with("Workspace 'ws_show':"), "got: {reply}");
for expected in [
"- path: /tmp/ws_show",
"- status: pending",
"- pipeline: running",
"- maintenance: on",
"- active project: no",
"- rules:\n be nice to the fixtures",
" - format: cargo fmt",
" - build: not discovered",
] {
assert!(reply.contains(expected), "missing {expected:?} in: {reply}");
}
crate::util::test::create_test_workspace("/tmp/ws_show_bare", "ws_show_bare").await;
let reply = tool
.execute(&ws, tool_args("show", Some("ws_show_bare")))
.await
.expect("show bare");
assert!(reply.contains("- rules: none"), "got: {reply}");
assert!(
reply.contains("- diagnostics: not discovered"),
"got: {reply}"
);
assert!(reply.contains("- maintenance: off"), "got: {reply}");
}
#[tokio::test]
async fn set_rules_reports_the_stores_truncation() {
let _guard = crate::util::test::STORE_LOCK.lock().await;
crate::util::test::init_test_stores().await;
let tool = WorkspaceTool;
let ws = crate::workspace::test_ws("/tmp/ws_rules");
crate::util::test::create_test_workspace("/tmp/ws_rules", "ws_rules").await;
let cap = crate::workspace::MAX_WORKSPACE_NOTES_CHARS;
let short = tool
.execute(
&ws,
json!({ "action": "set_rules", "workspace": "ws_rules", "rules": "be nice" }),
)
.await
.expect("set rules");
assert!(
short.contains("now 7 characters long") && !short.contains("truncated"),
"got: {short}"
);
let long = "r".repeat(cap + 10);
let reply = tool
.execute(
&ws,
json!({ "action": "set_rules", "workspace": "ws_rules", "rules": long }),
)
.await
.expect("set long rules");
assert!(
reply.contains(&format!("now {cap} characters long"))
&& reply.contains(&format!("truncated to {cap} characters")),
"got: {reply}"
);
let stored = crate::workspace::get_by_name("ws_rules")
.await
.expect("read")
.expect("exists");
assert_eq!(stored.notes.chars().count(), cap);
}
#[tokio::test]
async fn set_diagnostics_keeps_an_omitted_field_and_clears_an_empty_one() {
let _guard = crate::util::test::STORE_LOCK.lock().await;
crate::util::test::init_test_stores().await;
let tool = WorkspaceTool;
let ws = crate::workspace::test_ws("/tmp/ws_cmds");
crate::util::test::create_test_workspace("/tmp/ws_cmds", "ws_cmds").await;
let reply = tool
.execute(
&ws,
json!({
"action": "set_diagnostics",
"workspace": "ws_cmds",
"format": "cargo fmt",
"unit_test": "cargo test",
}),
)
.await
.expect("set diagnostics");
assert!(
reply.contains("- format: cargo fmt")
&& reply.contains("- unit-test: cargo test")
&& reply.contains("- build: not discovered"),
"got: {reply}"
);
assert!(reply.contains("invalidated"), "got: {reply}");
let reply = tool
.execute(
&ws,
json!({ "action": "set_diagnostics", "workspace": "ws_cmds", "format": "" }),
)
.await
.expect("clear format");
assert!(reply.contains("- format: not discovered"), "got: {reply}");
let stored = crate::workspace::store()
.get_diagnostics("ws_cmds")
.await
.expect("read")
.expect("diagnostics");
assert_eq!(stored.format, None);
assert_eq!(stored.unit_test.as_deref(), Some("cargo test"));
}
#[tokio::test]
async fn maintenance_needs_its_switch_before_a_workspace() {
let _guard = crate::util::test::STORE_LOCK.lock().await;
crate::util::test::init_test_stores().await;
let ws = crate::workspace::test_ws("/tmp/ws_maint");
crate::util::test::create_test_workspace("/tmp/ws_maint", "ws_maint").await;
let err = WorkspaceTool
.execute(
&ws,
json!({ "action": "maintenance", "workspace": "ws_maint_ghost" }),
)
.await
.unwrap_err()
.to_string();
assert!(
err.contains("missing required argument \"maintenance\""),
"a bad call must not reach the workspace lookup: {err}"
);
let reply = WorkspaceTool
.execute(
&ws,
json!({ "action": "maintenance", "workspace": "ws_maint", "maintenance": true }),
)
.await
.expect("maintenance on");
assert!(
reply.contains("Maintenance is now on for workspace 'ws_maint'")
&& reply.contains("next poll"),
"got: {reply}"
);
assert!(
crate::workspace::get_by_name("ws_maint")
.await
.expect("read")
.expect("exists")
.maintenance_enabled
);
}
#[tokio::test]
async fn set_diagnostics_refuses_a_call_that_names_no_command() {
let _guard = crate::util::test::STORE_LOCK.lock().await;
crate::util::test::init_test_stores().await;
let ws = crate::workspace::test_ws("/tmp/ws_cmds_none");
crate::util::test::create_test_workspace("/tmp/ws_cmds_none", "ws_cmds_none").await;
for address in ["ws_cmds_none", "ws_cmds_ghost"] {
let err = WorkspaceTool
.execute(
&ws,
json!({ "action": "set_diagnostics", "workspace": address }),
)
.await
.unwrap_err()
.to_string();
assert!(
err.contains("at least one command field") && err.contains("unit_test"),
"got: {err}"
);
}
assert!(
crate::workspace::store()
.get_diagnostics("ws_cmds_none")
.await
.expect("read")
.is_none(),
"a refused call must not write anything"
);
}
#[test]
fn the_delete_answer_names_a_folder_only_as_it_really_is() {
let folder = tempfile::TempDir::new().expect("temp dir");
let path = folder.path().to_str().expect("utf-8 path");
assert_eq!(
folder_note(path),
format!("The project folder at {path} stays.")
);
std::fs::create_dir(folder.path().join(".git")).expect("make a repository");
assert_eq!(
folder_note(path),
format!("The project folder at {path} (git repository included) stays.")
);
std::fs::remove_dir_all(folder.path()).expect("remove the folder by hand");
assert_eq!(
folder_note(path),
format!("The project folder at {path} is gone.")
);
}
#[tokio::test]
#[serial_test::serial(gui_admin_workspace)] async fn delete_names_what_remains_on_disk() {
let _guard = crate::util::test::STORE_LOCK.lock().await;
crate::util::test::init_test_stores().await;
crate::users::test_util::with_admin_workspace_restored(async {
let tool = WorkspaceTool;
let ws = crate::workspace::test_ws("/tmp/ws_del_gone");
let gone =
crate::util::test::create_test_workspace("/tmp/ws_del_gone", "ws_del_gone").await;
crate::util::test::create_test_workspace("/tmp/ws_del_keep", "ws_del_keep").await;
let ticket = crate::util::test::make_ticket(
board_store(),
&gone,
"delete leaves me",
TicketPhase::Queued,
)
.await;
crate::users::store()
.set_selected_workspace(crate::users::ADMIN_USER_NAME, Some("ws_del_gone"))
.await
.expect("select");
let reply = tool
.execute(&ws, tool_args("delete", Some("ws_del_gone")))
.await
.expect("delete");
assert!(
reply.contains("Deleted managed workspace 'ws_del_gone'"),
"got: {reply}"
);
assert!(reply.contains("/tmp/ws_del_gone"), "got: {reply}");
assert_eq!(
reply.contains("git repository"),
crate::git::commands::is_git_repo(std::path::Path::new("/tmp/ws_del_gone")),
"the repository half must match what is on disk: {reply}"
);
assert!(reply.contains("tickets"), "got: {reply}");
assert!(
reply.contains("Your active project is now '"),
"another managed workspace survives, so the selection must move to it: {reply}"
);
assert!(
crate::workspace::get_by_name("ws_del_gone")
.await
.expect("read")
.is_none(),
"the row is gone"
);
assert!(
board_store()
.get_ticket(&ticket)
.await
.expect("read")
.is_some(),
"deleting a workspace must not delete its tickets"
);
assert_ne!(
crate::users::resolve_selected_workspace_name(crate::users::ADMIN_USER_NAME)
.await
.as_deref(),
Some("ws_del_gone"),
"the active project must not stay on the deleted workspace"
);
let err = tool
.execute(&ws, tool_args("delete", Some("ws_del_gone")))
.await
.unwrap_err()
.to_string();
assert!(err.contains("No managed workspace exists"), "got: {err}");
})
.await;
}
#[tokio::test]
#[serial_test::serial(gui_admin_workspace)] async fn use_makes_a_workspace_the_active_project() {
let _guard = crate::util::test::STORE_LOCK.lock().await;
crate::util::test::init_test_stores().await;
crate::users::test_util::with_test_workspaces(
&[("/tmp/ws_use", "ws_use")],
crate::users::test_util::with_admin_workspace_restored(async {
let ws = crate::workspace::test_ws("/tmp/ws_use");
let reply = WorkspaceTool
.execute(&ws, tool_args("use", Some("ws_use")))
.await
.expect("use");
assert!(
reply.contains("'ws_use' is now your active project")
&& reply.contains("without a restart"),
"got: {reply}"
);
assert_eq!(
crate::users::resolve_selected_workspace_name(crate::users::ADMIN_USER_NAME)
.await
.as_deref(),
Some("ws_use")
);
let err = WorkspaceTool
.execute(&ws, tool_args("use", Some("ws_ghost")))
.await
.unwrap_err()
.to_string();
assert!(err.contains("No managed workspace exists"), "got: {err}");
assert_eq!(
crate::users::resolve_selected_workspace_name(crate::users::ADMIN_USER_NAME)
.await
.as_deref(),
Some("ws_use")
);
}),
)
.await;
}
#[tokio::test]
#[serial_test::serial(gui_admin_workspace)]
async fn the_reanalysis_actions_report_what_they_started() {
let _guard = crate::util::test::STORE_LOCK.lock().await;
crate::util::test::init_test_stores().await;
crate::users::test_util::with_test_workspaces(
&[("/tmp/ws_reanalyse", "ws_reanalyse")],
async {
let ws = crate::workspace::test_ws("/tmp/ws_reanalyse");
let commands = crate::DiagnosticsCommands {
format: Some("cargo fmt".to_string()),
..crate::DiagnosticsCommands::default()
};
crate::workspace::store()
.set_diagnostics("ws_reanalyse", &commands)
.await
.expect("seed the commands");
let reply = WorkspaceTool
.execute(
&ws,
tool_args("rediscover_diagnostics", Some("ws_reanalyse")),
)
.await
.expect("rediscover_diagnostics");
assert!(
reply.contains("stored commands were cleared")
&& reply
.contains("status, its pause and its per-role contexts are untouched"),
"got: {reply}"
);
assert!(
crate::workspace::store()
.get_diagnostics("ws_reanalyse")
.await
.expect("read")
.is_none(),
"the stored commands are cleared while they are re-detected"
);
let reply = WorkspaceTool
.execute(&ws, tool_args("rediscover", Some("ws_reanalyse")))
.await
.expect("rediscover");
assert!(
reply.contains("per-role contexts were cleared")
&& reply.contains("pipeline is paused until discovery finishes"),
"got: {reply}"
);
let row = crate::workspace::store()
.get_by_name("ws_reanalyse")
.await
.expect("read")
.expect("the workspace is still there");
assert!(row.paused, "a full rediscovery pauses the pipeline");
},
)
.await;
}
#[tokio::test]
async fn an_unknown_action_and_field_name_the_reference() {
let ws = crate::workspace::test_ws("/tmp/ws_unknown");
let err = WorkspaceTool
.execute(&ws, json!({ "action": "explode" }))
.await
.unwrap_err()
.to_string();
assert!(
err.contains("unknown action 'explode'") && err.contains("`reference` action"),
"got: {err}"
);
let err = WorkspaceTool
.execute(
&ws,
json!({ "action": "list", "folder": "/tmp/ws_unknown" }),
)
.await
.unwrap_err()
.to_string();
assert!(
err.contains("unknown field 'folder'") && err.contains("reference"),
"got: {err}"
);
}
}