1use axum::extract::{Query, State};
17use axum::http::StatusCode;
18use axum::response::Json;
19use serde::Deserialize;
20use serde_json::{json, Value};
21
22use agentmux_common::time::now_ms;
23
24use crate::backend::storage::work_board_stages as stages;
25use crate::backend::storage::work_boards::{Board, BoardEdit, BoardEvent, Deletion, DELETE_COUNTDOWN_MS};
26
27use super::AppState;
28
29#[derive(Debug, Deserialize, Default)]
30pub(super) struct BoardsQuery {
31 #[serde(default)]
33 pub archived: bool,
34}
35
36#[derive(Debug, Deserialize, Default)]
38pub(crate) struct BoardsRequest {
39 pub action: String,
40 #[serde(default)]
41 pub board: Option<String>,
42 #[serde(default)]
43 pub name: Option<String>,
44 #[serde(default)]
45 pub slug: Option<String>,
46 #[serde(default)]
47 pub tier: Option<String>,
48 #[serde(default)]
49 pub readable: Option<bool>,
50 #[serde(default)]
52 pub agents: Option<Vec<String>>,
53 #[serde(default)]
55 pub stages: Option<Value>,
56 #[serde(default)]
58 pub stages_reset: Option<bool>,
59 #[serde(default)]
61 pub stages_rev: Option<i64>,
62}
63
64pub(crate) fn board_json(b: &Board) -> Value {
67 let (set, error) = match stages::parse_stored(&b.stages) {
68 Ok(set) => (set, None),
69 Err(why) => (stages::default_set(), Some(why)),
70 };
71 json!({
72 "id": b.id, "slug": b.slug, "name": b.name, "tier": b.tier, "readable": b.readable,
73 "agents": b.agents, "default": b.is_default, "archived": b.archived,
74 "open": b.open, "total": b.total, "pending_delete_at": b.pending_delete_at,
75 "stages": set, "stages_rev": b.stages_rev,
76 "stages_default": b.stages.trim().is_empty() || error.is_some(), "stages_error": error,
77 })
78}
79
80const HISTORY_SHOWN: usize = 8;
82
83pub(crate) fn board_with_history(store: &crate::backend::storage::store::Store, b: &Board) -> Value {
86 let mut v = board_json(b);
87 v["history"] = json!(store.work_board_events(&b.id, HISTORY_SHOWN).unwrap_or_default());
88 v
89}
90
91fn note_stages_change(state: &AppState, who: Option<(&str, &str)>, before: &Board, after: &Board, reset: bool, now: i64) {
94 let set_of = |b: &Board| stages::parse_stored(&b.stages).unwrap_or_else(|_| stages::default_set());
95 let (old, new) = (set_of(before), set_of(after));
96 let what = if reset { "reset the stages to the default" } else { "changed the stages" };
97 let (actor, actor_kind) = match who {
98 Some((id, _)) => (id.to_string(), "agent"),
99 None => (String::new(), "operator"),
100 };
101 let ev = BoardEvent {
102 at: now,
103 actor,
104 actor_kind: actor_kind.to_string(),
105 kind: "stages".to_string(),
106 body: format!("{what}: {} → {}", old.stages.len(), new.stages.len()),
107 detail: json!({ "from": old, "to": new }).to_string(),
108 };
109 if let Err(e) = state.work_store.work_board_event_add(&after.id, &ev) {
110 tracing::warn!(target: "workqueue", board = %after.slug, error = %e, "could not record the stages change in the board's history");
111 }
112}
113
114pub(crate) fn boards_view(state: &AppState, who: Option<(&str, &str)>, include_archived: bool) -> Result<Value, String> {
116 let boards = state.work_store.work_boards_list(include_archived, now_ms()).map_err(|e| e.to_string())?;
117 let seen: Vec<Value> = boards
118 .iter()
119 .filter(|b| who.map_or(true, |(a, u)| b.visible_to(a, u)))
120 .map(|b| board_with_history(&state.work_store, b))
121 .collect();
122 let default = boards.iter().find(|b| b.is_default).map(|b| b.slug.clone());
123 Ok(json!({ "boards": seen, "default": default }))
124}
125
126pub(crate) fn board_act(state: &AppState, who: Option<(&str, &str)>, actor: &str, req: BoardsRequest) -> Result<Value, String> {
129 let store = &state.work_store;
130 let now = now_ms();
131 let on = |key: &Option<String>| -> Result<Board, String> {
132 let key = key.as_deref().map(str::trim).filter(|k| !k.is_empty()).ok_or("which board? name it with board")?;
133 super::work_tasks::pick_board(state, Some(key), who, false)
134 };
135 let edit = BoardEdit {
136 name: req.name.clone(),
137 slug: req.slug.clone(),
138 tier: req.tier.clone(),
139 readable: req.readable,
140 agents: req.agents.clone(),
141 stages: req.stages.clone(),
142 stages_reset: req.stages_reset.unwrap_or(false),
143 stages_rev: req.stages_rev,
144 };
145 let out = match req.action.as_str() {
146 "create" => {
147 let b = store.work_board_create(&edit, actor, now).map_err(|e| e.to_string())?;
148 json!({ "ok": true, "board": board_json(&b) })
149 }
150 "edit" => {
151 let before = on(&req.board)?;
152 let b = store.work_board_edit(&before.id, &edit, now).map_err(|e| e.to_string())?;
153 if edit.stages.is_some() || edit.stages_reset {
154 note_stages_change(state, who, &before, &b, edit.stages_reset, now);
155 }
156 json!({ "ok": true, "board": board_json(&b) })
157 }
158 "archive" | "unarchive" => {
159 let b = on(&req.board)?;
160 let b = store.work_board_archive(&b.id, req.action == "archive", now).map_err(|e| e.to_string())?;
161 json!({ "ok": true, "board": board_json(&b) })
162 }
163 "default" => {
164 let b = on(&req.board)?;
165 let b = store.work_board_set_default(&b.id, now).map_err(|e| e.to_string())?;
166 json!({ "ok": true, "board": board_json(&b) })
167 }
168 "delete" => {
169 let b = on(&req.board)?;
170 match store.work_board_delete(&b.id, now).map_err(|e| e.to_string())? {
171 Deletion::Deleted => json!({ "ok": true, "deleted": true }),
172 Deletion::Pending(at) => json!({
173 "ok": true,
174 "deleted": false,
175 "pending_until": at,
176 "note": format!(
177 "board {} and its {} task(s) will be deleted in {} seconds; the Kanban shows a countdown with a veto. Cancel with board_cancel_delete",
178 b.slug, b.total, DELETE_COUNTDOWN_MS / 1000
179 ),
180 }),
181 }
182 }
183 "cancel_delete" => {
184 let b = on(&req.board)?;
185 let b = store.work_board_cancel_delete(&b.id, now).map_err(|e| e.to_string())?;
186 json!({ "ok": true, "board": board_json(&b) })
187 }
188 other => return Err(format!("unknown board action {other:?}: create, edit, archive, unarchive, delete, cancel_delete or default")),
189 };
190 let stages_changed = req.action == "edit" && (req.stages.is_some() || req.stages_reset == Some(true));
191 tracing::info!(target: "workqueue", actor, action = %req.action, board = ?req.board.as_deref().or(req.name.as_deref()), stages_changed, "board changed");
192 super::work_queue::publish_changed(state);
193 Ok(out)
194}
195
196pub(super) async fn handle_boards_list(
197 State(state): State<AppState>,
198 caller: Option<axum::Extension<super::caller::Caller>>,
199 Query(q): Query<BoardsQuery>,
200) -> (StatusCode, Json<Value>) {
201 let who = super::work_tasks::viewer(&state, caller.as_deref());
202 let who = who.as_ref().map(|(a, u)| (a.as_str(), u.as_str()));
203 match boards_view(&state, who, q.archived) {
204 Ok(v) => (StatusCode::OK, Json(v)),
205 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e }))),
206 }
207}
208
209pub(super) async fn handle_boards_act(
210 State(state): State<AppState>,
211 caller: Option<axum::Extension<super::caller::Caller>>,
212 Json(req): Json<BoardsRequest>,
213) -> (StatusCode, Json<Value>) {
214 let who = super::work_tasks::viewer(&state, caller.as_deref());
215 let actor = who.as_ref().map(|(a, _)| a.clone()).unwrap_or_else(|| "agent".to_string());
216 let who = who.as_ref().map(|(a, u)| (a.as_str(), u.as_str()));
217 match board_act(&state, who, &actor, req) {
218 Ok(v) => (StatusCode::OK, Json(v)),
219 Err(e) => (StatusCode::CONFLICT, Json(json!({ "ok": false, "error": e }))),
220 }
221}
222
223#[cfg(test)]
224#[path = "work_boards_tests.rs"]
225mod tests;