1use axum::extract::{Path, State};
15use axum::http::StatusCode;
16use axum::response::{IntoResponse, Response};
17use axum::Json;
18use serde::Deserialize;
19use serde_json::json;
20
21use agentmux_common::api_types::UiAutomationAuth;
22use agentmux_common::time::now_ms;
23
24use super::app_api::kanban::{accept_task, send_back_task, Decider};
25use super::caller::Caller;
26use super::work_tasks::resolve_id;
27use super::AppState;
28use crate::backend::kanban_delegate::{self as delegate, Refusal};
29use crate::backend::reactive::sanitize::is_sensitive_message;
30use crate::backend::reactive::types::AgentRegistration;
31use crate::backend::storage::work_board::BoardTask;
32use crate::backend::storage::work_queue::work_state;
33
34#[derive(Debug, Deserialize)]
35pub(crate) struct DecisionRequest {
36 #[serde(flatten)]
37 auth: UiAutomationAuth,
38 #[serde(default)]
40 text: String,
41}
42
43#[derive(Clone, Copy, PartialEq, Eq)]
44enum Verb {
45 Accept,
46 SendBack,
47}
48
49impl Verb {
50 fn audit_action(self) -> &'static str {
51 match self {
52 Verb::Accept => "kanban.accept",
53 Verb::SendBack => "kanban.send_back",
54 }
55 }
56}
57
58pub(crate) async fn handle_work_accept(
59 State(state): State<AppState>,
60 Path(id): Path<String>,
61 caller: Option<axum::Extension<Caller>>,
62 Json(req): Json<DecisionRequest>,
63) -> Response {
64 decide(&state, caller.as_deref(), &id, req, Verb::Accept).await
65}
66
67pub(crate) async fn handle_work_send_back(
68 State(state): State<AppState>,
69 Path(id): Path<String>,
70 caller: Option<axum::Extension<Caller>>,
71 Json(req): Json<DecisionRequest>,
72) -> Response {
73 decide(&state, caller.as_deref(), &id, req, Verb::SendBack).await
74}
75
76fn refused(r: &Refusal) -> Response {
77 (StatusCode::FORBIDDEN, Json(json!({ "error": r.words, "code": r.code }))).into_response()
78}
79
80fn is_own_work(t: &BoardTask, reg: &AgentRegistration, events: &[crate::backend::storage::work_board::WorkEvent]) -> bool {
82 let uid = reg.uid.as_deref().unwrap_or("");
83 let holds = if t.item.claimed_by_uid.is_empty() {
84 t.item.claimed_by.eq_ignore_ascii_case(®.agent_id)
85 } else {
86 !uid.is_empty() && t.item.claimed_by_uid == uid
87 };
88 holds || events.iter().any(|e| e.kind == "submitted" && e.actor.eq_ignore_ascii_case(®.agent_id))
89}
90
91async fn decide(state: &AppState, caller: Option<&Caller>, id: &str, req: DecisionRequest, verb: Verb) -> Response {
92 let block_id = match super::ui_handlers::verified_block_id(state, caller, &req.auth) {
93 Ok(b) => b,
94 Err(e) => return (StatusCode::UNAUTHORIZED, Json(json!({ "error": e }))).into_response(),
95 };
96 let regs = state.reactive_handler.list_agents();
97 let Some(reg) = regs.iter().find(|r| r.block_id == block_id).cloned() else {
98 return (StatusCode::UNAUTHORIZED, Json(json!({ "error": "your pane isn't registered with AgentMux" }))).into_response();
99 };
100 let task_id = resolve_id(state, id);
101 let task = match state.work_store.work_board_get(&task_id) {
102 Ok(Some(t)) => t,
103 Ok(None) => return (StatusCode::NOT_FOUND, Json(json!({ "error": "no such task" }))).into_response(),
104 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() }))).into_response(),
105 };
106 if let Ok(Some((board, _))) = state.work_store.work_task_board(&task.item.id) {
108 if !board.visible_to(®.agent_id, reg.uid.as_deref().unwrap_or("")) {
109 return (StatusCode::NOT_FOUND, Json(json!({ "error": "no such task" }))).into_response();
110 }
111 }
112 let num = task.card.num;
113 let events = state.work_store.work_events(&task.item.id, 200).unwrap_or_default();
114 let own_work = is_own_work(&task, ®, &events);
115
116 let outcome = check(&task, &req.text, verb);
117 let request_id = uuid::Uuid::new_v4().to_string();
119 let note = format!("{}{}", task.card.name(), if own_work { " (its own work)" } else { "" });
120 match &outcome {
121 Err(r) => {
122 tracing::info!(agent = %reg.agent_id, task = num, why = r.code, "kanban: an agent's decision was refused");
123 state.reactive_handler.log_fleet_action_audit(
124 Some(®.agent_id),
125 ®.agent_id,
126 &block_id,
127 verb.audit_action(),
128 false,
129 Some(r.code),
130 &request_id,
131 Some(¬e),
132 );
133 refused(r)
134 }
135 Ok(()) => {
136 let slug = reg.uid.as_deref().and_then(|u| state.mstore.agent_names_by_id(u).ok().flatten()).map(|r| r.slug);
138 let by = Decider::agent(slug.as_deref().unwrap_or(®.agent_id), own_work);
139 let text = super::work_tasks::clean(&req.text);
140 let now = now_ms();
141 let done = match verb {
142 Verb::Accept => accept_task(state, &task, &by, &text, now),
143 Verb::SendBack => send_back_task(state, ®s, &task, &by, &text, now).await,
144 };
145 state.reactive_handler.log_fleet_action_audit(
146 Some(®.agent_id),
147 ®.agent_id,
148 &block_id,
149 verb.audit_action(),
150 done.is_ok(),
151 done.as_ref().err().map(String::as_str),
152 &request_id,
153 Some(¬e),
154 );
155 tracing::info!(agent = %reg.agent_id, task = num, action = verb.audit_action(), ok = done.is_ok(), "kanban: an agent decided");
156 super::work_queue::publish_changed(state);
157 match done {
158 Ok(v) => Json(v).into_response(),
159 Err(e) => (StatusCode::CONFLICT, Json(json!({ "error": e }))).into_response(),
160 }
161 }
162 }
163}
164
165fn check(task: &BoardTask, text: &str, verb: Verb) -> Result<(), Refusal> {
167 if task.item.state != work_state::REVIEW {
168 return Err(delegate::not_in_review(&task.card.name(), &task.item.state));
169 }
170 if verb == Verb::SendBack && text.trim().is_empty() {
171 return Err(Refusal { code: "reason_required", words: "send_back needs a reason: it goes to the task's holder.".to_string() });
172 }
173 if is_sensitive_message(text) {
175 return Err(delegate::sensitive_quote());
176 }
177 Ok(())
178}
179
180#[cfg(test)]
181#[path = "work_delegate_tests.rs"]
182mod tests;