Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / infra / agents / agentd / src / ui.rs
ui.rs1779 lines · 63.2 KiBRaw
| 1 | //! Server-rendered HTML UI (maud; auto-escaped) plus SSE live events. |
| 2 | //! |
| 3 | //! Routes: |
| 4 | //! * `GET /healthz` — unauthenticated, body `ok`. |
| 5 | //! * `GET /login`, `POST /login`, `POST /logout`. |
| 6 | //! * `GET /` — dashboard ("Needs you" first, then running, then recent). |
| 7 | //! * `GET /tasks/new`, `POST /tasks` — new-task form + creation. |
| 8 | //! * `GET /tasks/:id` — task page (chat timeline + side panel + cards). |
| 9 | //! * `GET /tasks/:id/events` — SSE stream of the task's events. |
| 10 | //! * `GET /tasks/:id/timeline?after=<seq>` — fragment: new timeline events. |
| 11 | //! * `GET /tasks/:id/panel` — fragment: side panel (status, todos, budget…). |
| 12 | //! * `GET /tasks/:id/cards` — fragment: pending/review cards. |
| 13 | //! * `GET /fragments/dashboard` — fragment: dashboard sections + title. |
| 14 | //! * `GET /static/app.js`, `GET /static/app.css` — bundled assets. |
| 15 | //! * `POST /tasks/:id/messages` — inbox a user message (answer or steering). |
| 16 | //! * `POST /tasks/:id/stop` (alias `/cancel`) — park with work kept. |
| 17 | //! * `POST /tasks/:id/discard` — terminal discard. |
| 18 | //! * `POST /tasks/:id/retry`. |
| 19 | //! * `POST /tasks/:id/plan/approve`, `POST /tasks/:id/plan/changes`. |
| 20 | //! * `POST /tasks/:id/approve` — approve the review (push). |
| 21 | //! |
| 22 | //! All state-changing routes are POST and additionally require an `Origin` |
| 23 | //! header exactly equal to `AGENTD_PUBLIC_ORIGIN`. Auth is a session cookie |
| 24 | //! (HttpOnly; Secure; SameSite=Strict). Security headers (CSP self-only, |
| 25 | //! nosniff, no-referrer, frame-ancestors none) are attached to every |
| 26 | //! response. |
| 27 | //! |
| 28 | //! Rendering contract: every page is server-rendered maud (auto-escaped). |
| 29 | //! Agent-authored text goes through [`crate::markdown::render_markdown`] |
| 30 | //! (safe subset) or plain escaped text — never raw HTML. There is no inline |
| 31 | //! `<script>` and no inline `style=` anywhere; `/static/app.js` wires live |
| 32 | //! updates by fetching the fragment routes above and swapping them in (it |
| 33 | //! never builds HTML from event JSON). Every action is a plain `<form>` |
| 34 | //! POST, so the UI works without JS. |
| 35 | |
| 36 | use axum::extract::{Path, Query, State}; |
| 37 | use axum::http::{header, HeaderMap, StatusCode}; |
| 38 | use axum::response::sse::{Event as SseEvent, KeepAlive, Sse}; |
| 39 | use axum::response::{Html, IntoResponse, Response}; |
| 40 | use axum::{Form, Router}; |
| 41 | use maud::{html, Markup, PreEscaped}; |
| 42 | use serde::Deserialize; |
| 43 | use tokio_stream::wrappers::BroadcastStream; |
| 44 | use tokio_stream::StreamExt; |
| 45 | |
| 46 | use crate::auth::{client_ip, origin_allowed, session_token_from_cookie, SESSION_COOKIE}; |
| 47 | use crate::markdown::render_markdown; |
| 48 | use crate::models::{ |
| 49 | branch_name, Event, Task, TaskStatus, EVENT_ASSISTANT, EVENT_PLAN, EVENT_QUESTION, |
| 50 | EVENT_REVIEW, EVENT_STATUS, EVENT_TODOS, EVENT_TOOL_CALL, EVENT_TOOL_RESULT, |
| 51 | EVENT_USER_MESSAGE, INBOX_PLAN_CHANGES, INBOX_REVIEW_CHANGES, PENDING_BUDGET, PENDING_CHAT, |
| 52 | PENDING_ERROR, PENDING_PLAN, PENDING_QUESTION, PENDING_STOPPED, |
| 53 | }; |
| 54 | use crate::state::AppState; |
| 55 | |
| 56 | pub fn router(state: AppState) -> Router { |
| 57 | use axum::routing::{get, post}; |
| 58 | Router::new() |
| 59 | .route("/healthz", get(healthz)) |
| 60 | .route("/login", get(login_page).post(login_submit)) |
| 61 | .route("/logout", post(logout)) |
| 62 | .route("/", get(task_list)) |
| 63 | .route("/tasks/new", get(new_task_page)) |
| 64 | .route("/tasks", post(create_task)) |
| 65 | .route("/tasks/:id", get(task_page)) |
| 66 | .route("/tasks/:id/events", get(task_events_sse)) |
| 67 | .route("/tasks/:id/timeline", get(task_timeline_fragment)) |
| 68 | .route("/tasks/:id/panel", get(task_panel_fragment)) |
| 69 | .route("/tasks/:id/cards", get(task_cards_fragment)) |
| 70 | .route("/fragments/dashboard", get(dashboard_fragment)) |
| 71 | .route("/static/app.js", get(static_js)) |
| 72 | .route("/static/app.css", get(static_css)) |
| 73 | .route("/tasks/:id/messages", post(messages_route)) |
| 74 | .route("/tasks/:id/stop", post(stop_route)) |
| 75 | .route("/tasks/:id/cancel", post(stop_route)) |
| 76 | .route("/tasks/:id/discard", post(discard_route)) |
| 77 | .route("/tasks/:id/retry", post(retry_route)) |
| 78 | .route("/tasks/:id/plan/approve", post(plan_approve_route)) |
| 79 | .route("/tasks/:id/plan/changes", post(plan_changes_route)) |
| 80 | .route("/tasks/:id/approve", post(review_approve_route)) |
| 81 | .route("/triage/:issue/fix", post(crate::triage_ui::fix_route)) |
| 82 | .with_state(state) |
| 83 | .layer(axum::middleware::from_fn(security_headers)) |
| 84 | } |
| 85 | |
| 86 | async fn security_headers( |
| 87 | req: axum::extract::Request, |
| 88 | next: axum::middleware::Next, |
| 89 | ) -> Response { |
| 90 | let mut resp = next.run(req).await; |
| 91 | let h = resp.headers_mut(); |
| 92 | // No 'unsafe-inline' anywhere: styling lives in /static/app.css and |
| 93 | // behavior in /static/app.js. `img-src data:` covers no remote images |
| 94 | // (markdown images render as alt text); favicon-less pages need nothing. |
| 95 | h.insert( |
| 96 | header::CONTENT_SECURITY_POLICY, |
| 97 | "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" |
| 98 | .parse() |
| 99 | .unwrap(), |
| 100 | ); |
| 101 | h.insert(header::X_CONTENT_TYPE_OPTIONS, "nosniff".parse().unwrap()); |
| 102 | h.insert(header::REFERRER_POLICY, "no-referrer".parse().unwrap()); |
| 103 | h.insert(header::X_FRAME_OPTIONS, "DENY".parse().unwrap()); |
| 104 | resp |
| 105 | } |
| 106 | |
| 107 | async fn healthz() -> &'static str { |
| 108 | "ok" |
| 109 | } |
| 110 | |
| 111 | // ---- static assets (bundled via include_str!) ---- |
| 112 | |
| 113 | const APP_JS: &str = include_str!("static/app.js"); |
| 114 | const APP_CSS: &str = include_str!("static/app.css"); |
| 115 | |
| 116 | async fn static_js() -> Response { |
| 117 | ( |
| 118 | [ |
| 119 | ( |
| 120 | header::CONTENT_TYPE, |
| 121 | "application/javascript; charset=utf-8", |
| 122 | ), |
| 123 | (header::CACHE_CONTROL, "public, max-age=60"), |
| 124 | ], |
| 125 | APP_JS, |
| 126 | ) |
| 127 | .into_response() |
| 128 | } |
| 129 | |
| 130 | async fn static_css() -> Response { |
| 131 | ( |
| 132 | [ |
| 133 | (header::CONTENT_TYPE, "text/css; charset=utf-8"), |
| 134 | (header::CACHE_CONTROL, "public, max-age=60"), |
| 135 | ], |
| 136 | APP_CSS, |
| 137 | ) |
| 138 | .into_response() |
| 139 | } |
| 140 | |
| 141 | // ---- auth plumbing ---- |
| 142 | |
| 143 | fn session_token(headers: &HeaderMap) -> Option<String> { |
| 144 | headers |
| 145 | .get(header::COOKIE) |
| 146 | .and_then(|v| v.to_str().ok()) |
| 147 | .and_then(session_token_from_cookie) |
| 148 | } |
| 149 | |
| 150 | fn authed(state: &AppState, headers: &HeaderMap) -> bool { |
| 151 | session_token(headers) |
| 152 | .map(|t| state.auth.check_token(&t)) |
| 153 | .unwrap_or(false) |
| 154 | } |
| 155 | |
| 156 | /// `None` = OK; `Some(response)` = reject (login redirect or 401 for SSE). |
| 157 | pub(crate) fn require_auth(state: &AppState, headers: &HeaderMap) -> Option<Response> { |
| 158 | if authed(state, headers) { |
| 159 | return None; |
| 160 | } |
| 161 | let accept: &str = headers |
| 162 | .get(header::ACCEPT) |
| 163 | .and_then(|v| v.to_str().ok()) |
| 164 | .unwrap_or(""); |
| 165 | if accept.contains("text/event-stream") { |
| 166 | Some((StatusCode::UNAUTHORIZED, "login required").into_response()) |
| 167 | } else { |
| 168 | Some( |
| 169 | ( |
| 170 | StatusCode::FOUND, |
| 171 | [(header::LOCATION, "/login")], |
| 172 | "redirect to /login", |
| 173 | ) |
| 174 | .into_response(), |
| 175 | ) |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | /// Fragment routes (`/tasks/:id/timeline|panel|cards`, `/fragments/dashboard`) |
| 180 | /// are only ever fetched by `app.js`: reject unauthenticated callers with a |
| 181 | /// plain 401 (never a login-page redirect, which the script would swap into |
| 182 | /// the page). |
| 183 | fn require_auth_fragment(state: &AppState, headers: &HeaderMap) -> Option<Response> { |
| 184 | if authed(state, headers) { |
| 185 | None |
| 186 | } else { |
| 187 | Some((StatusCode::UNAUTHORIZED, "login required").into_response()) |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | pub(crate) fn require_origin(state: &AppState, headers: &HeaderMap) -> Option<Response> { |
| 192 | let origin = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()); |
| 193 | if origin_allowed(origin, &state.config.public_origin) { |
| 194 | None |
| 195 | } else { |
| 196 | Some((StatusCode::FORBIDDEN, "bad or missing Origin").into_response()) |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | fn peer_ip(headers: &HeaderMap) -> String { |
| 201 | // Cloudflare sets CF-Connecting-IP to the real client (Caddy forwards it |
| 202 | // untouched); Caddy rewrites X-Forwarded-For to the CF edge address. Direct |
| 203 | // hits that forge it are still bounded by the limiter's global cap. |
| 204 | if let Some(ip) = headers |
| 205 | .get("cf-connecting-ip") |
| 206 | .and_then(|v| v.to_str().ok()) |
| 207 | .map(str::trim) |
| 208 | .filter(|s| !s.is_empty()) |
| 209 | { |
| 210 | return ip.to_string(); |
| 211 | } |
| 212 | let ff = headers.get("x-forwarded-for").and_then(|v| v.to_str().ok()); |
| 213 | client_ip(ff, None) |
| 214 | } |
| 215 | |
| 216 | /// Sanitize a module-scope form value (same charset rule as before). |
| 217 | fn scope_from_form(raw: &str) -> Result<String, String> { |
| 218 | let scope: String = raw |
| 219 | .trim() |
| 220 | .chars() |
| 221 | .filter(|c| { |
| 222 | c.is_ascii_alphanumeric() || *c == '/' || *c == ':' || *c == '-' || *c == '_' |
| 223 | }) |
| 224 | .collect(); |
| 225 | if scope.is_empty() { |
| 226 | return Err("module scope is required".to_string()); |
| 227 | } |
| 228 | Ok(scope) |
| 229 | } |
| 230 | |
| 231 | // ---- small pure helpers (unit-tested via the render fns below) ---- |
| 232 | |
| 233 | /// Escape `&<>"` for embedding a pre-escaped fragment (diff lines). Agent |
| 234 | /// text rendered through maud `(…)` or `render_markdown` never needs this. |
| 235 | fn esc_html(s: &str) -> String { |
| 236 | let mut out = String::with_capacity(s.len() + 8); |
| 237 | for c in s.chars() { |
| 238 | match c { |
| 239 | '&' => out.push_str("&"), |
| 240 | '<' => out.push_str("<"), |
| 241 | '>' => out.push_str(">"), |
| 242 | '"' => out.push_str("""), |
| 243 | _ => out.push(c), |
| 244 | } |
| 245 | } |
| 246 | out |
| 247 | } |
| 248 | |
| 249 | /// Cap to `n` chars (char-boundary safe). Callers add their own truncation |
| 250 | /// marker so inline chips (`…`) and blocks (`[truncated]`) read naturally. |
| 251 | fn cap_chars(s: &str, n: usize) -> String { |
| 252 | if s.chars().count() <= n { |
| 253 | s.to_string() |
| 254 | } else { |
| 255 | s.chars().take(n).collect() |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | fn ev_str<'a>(body: &'a serde_json::Value, key: &str) -> &'a str { |
| 260 | body.get(key).and_then(|v| v.as_str()).unwrap_or("") |
| 261 | } |
| 262 | |
| 263 | // ---- page shell ---- |
| 264 | |
| 265 | /// Full-page shell. `doc_title` is the complete `<title>` text (dashboard |
| 266 | /// passes `"(N) agentd"`). Styling is `/static/app.css`, behavior is |
| 267 | /// `/static/app.js` (deferred); no inline `<script>` or `<style>` anywhere. |
| 268 | pub(crate) fn layout(doc_title: &str, release: bool, body: Markup) -> Markup { |
| 269 | html! { |
| 270 | (maud::DOCTYPE) |
| 271 | html lang="en" { |
| 272 | head { |
| 273 | meta charset="utf-8"; |
| 274 | meta name="viewport" content="width=device-width, initial-scale=1"; |
| 275 | title { (doc_title) } |
| 276 | link rel="stylesheet" href="/static/app.css"; |
| 277 | script src="/static/app.js" defer {} |
| 278 | } |
| 279 | body { |
| 280 | header class="top" { |
| 281 | a href="/" { "agentd" } |
| 282 | span class="sep" { "·" } |
| 283 | a href="/tasks/new" { "new task" } |
| 284 | form method="post" action="/logout" class="inline" { |
| 285 | button type="submit" class="link" { "logout" } |
| 286 | } |
| 287 | } |
| 288 | @if release { |
| 289 | div class="banner" { "A production release build is running — new builds will wait (up to 60 min) or be preempted." } |
| 290 | } |
| 291 | main { (body) } |
| 292 | } |
| 293 | } |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | fn release_banner(state: &AppState) -> bool { |
| 298 | crate::agent::release_active(&state.config) |
| 299 | } |
| 300 | |
| 301 | async fn login_page() -> Html<String> { |
| 302 | Html( |
| 303 | layout( |
| 304 | "login — agentd", |
| 305 | false, |
| 306 | html! { |
| 307 | h1 { "agentd login" } |
| 308 | form method="post" action="/login" class="card" { |
| 309 | label { "Password" input type="password" name="password" autofocus autocomplete="current-password"; } |
| 310 | button type="submit" { "Sign in" } |
| 311 | } |
| 312 | }, |
| 313 | ) |
| 314 | .into_string(), |
| 315 | ) |
| 316 | } |
| 317 | |
| 318 | #[derive(Deserialize)] |
| 319 | struct LoginForm { |
| 320 | password: String, |
| 321 | } |
| 322 | |
| 323 | async fn login_submit( |
| 324 | State(state): State<AppState>, |
| 325 | headers: HeaderMap, |
| 326 | Form(form): Form<LoginForm>, |
| 327 | ) -> Response { |
| 328 | let ip = peer_ip(&headers); |
| 329 | if let Some(retry) = state.auth.login_gate(&ip) { |
| 330 | return ( |
| 331 | StatusCode::TOO_MANY_REQUESTS, |
| 332 | [("Retry-After", retry.as_secs().to_string())], |
| 333 | "too many login attempts; slow down", |
| 334 | ) |
| 335 | .into_response(); |
| 336 | } |
| 337 | if !state.auth.verify_password(&form.password) { |
| 338 | state.auth.login_failed(&ip); |
| 339 | return ( |
| 340 | StatusCode::UNAUTHORIZED, |
| 341 | Html( |
| 342 | layout( |
| 343 | "login — agentd", |
| 344 | false, |
| 345 | html! { |
| 346 | h1 { "agentd login" } |
| 347 | p class="pill failed" { "Wrong password." } |
| 348 | form method="post" action="/login" class="card" { |
| 349 | label { "Password" input type="password" name="password" autofocus autocomplete="current-password"; } |
| 350 | button type="submit" { "Sign in" } |
| 351 | } |
| 352 | }, |
| 353 | ) |
| 354 | .into_string(), |
| 355 | ), |
| 356 | ) |
| 357 | .into_response(); |
| 358 | } |
| 359 | state.auth.login_ok(&ip); |
| 360 | let token = match state.auth.issue_session() { |
| 361 | Ok(t) => t, |
| 362 | Err(e) => { |
| 363 | tracing::error!("issue session: {e}"); |
| 364 | return (StatusCode::INTERNAL_SERVER_ERROR, "login failed").into_response(); |
| 365 | } |
| 366 | }; |
| 367 | ( |
| 368 | StatusCode::FOUND, |
| 369 | [ |
| 370 | (header::LOCATION, "/".to_string()), |
| 371 | ( |
| 372 | header::SET_COOKIE, |
| 373 | format!( |
| 374 | "{SESSION_COOKIE}={token}; Path=/; Max-Age=604800; HttpOnly; Secure; SameSite=Strict" |
| 375 | ), |
| 376 | ), |
| 377 | ], |
| 378 | "ok", |
| 379 | ) |
| 380 | .into_response() |
| 381 | } |
| 382 | |
| 383 | async fn logout(State(state): State<AppState>, headers: HeaderMap) -> Response { |
| 384 | if let Some(reject) = require_origin(&state, &headers) { |
| 385 | return reject; |
| 386 | } |
| 387 | if let Some(t) = session_token(&headers) { |
| 388 | state.auth.revoke_token(&t); |
| 389 | } |
| 390 | ( |
| 391 | StatusCode::FOUND, |
| 392 | [ |
| 393 | (header::LOCATION, "/login".to_string()), |
| 394 | ( |
| 395 | header::SET_COOKIE, |
| 396 | format!("{SESSION_COOKIE}=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Strict"), |
| 397 | ), |
| 398 | ], |
| 399 | "logged out", |
| 400 | ) |
| 401 | .into_response() |
| 402 | } |
| 403 | |
| 404 | fn status_pill(s: TaskStatus) -> Markup { |
| 405 | html! { span class=(format!("pill {}", s.as_str())) { (s.as_str()) } } |
| 406 | } |
| 407 | |
| 408 | // ---- dashboard ---- |
| 409 | |
| 410 | /// Split tasks into "needs you" (needs_input of any kind + review), |
| 411 | /// running/queued, and recent finished (capped at 20, newest first). |
| 412 | fn split_dashboard(tasks: &[Task]) -> (Vec<&Task>, Vec<&Task>, Vec<&Task>) { |
| 413 | let mut needs = Vec::new(); |
| 414 | let mut active = Vec::new(); |
| 415 | let mut done = Vec::new(); |
| 416 | for t in tasks { |
| 417 | match t.status { |
| 418 | TaskStatus::NeedsInput | TaskStatus::Review => needs.push(t), |
| 419 | TaskStatus::Queued | TaskStatus::Running => active.push(t), |
| 420 | _ => done.push(t), |
| 421 | } |
| 422 | } |
| 423 | done.truncate(20); |
| 424 | (needs, active, done) |
| 425 | } |
| 426 | |
| 427 | /// `<title>` text: `"(N) agentd"` when N tasks need the operator. |
| 428 | pub(crate) fn dashboard_title(needs: usize) -> String { |
| 429 | if needs == 0 { |
| 430 | "agentd".to_string() |
| 431 | } else { |
| 432 | format!("({needs}) agentd") |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | /// One-line reason a task needs the operator (pending kind + excerpt). |
| 437 | fn need_reason(t: &Task) -> String { |
| 438 | if t.status == TaskStatus::Review { |
| 439 | let s = t.summary.as_deref().unwrap_or("").trim(); |
| 440 | return if s.is_empty() { |
| 441 | "review: awaiting approval".to_string() |
| 442 | } else { |
| 443 | format!("review: {}", cap_chars(s, 80)) |
| 444 | }; |
| 445 | } |
| 446 | let pending = match t.pending.as_ref() { |
| 447 | Some(p) => p, |
| 448 | None => return "waiting for you".to_string(), |
| 449 | }; |
| 450 | match pending.kind.as_str() { |
| 451 | PENDING_QUESTION => { |
| 452 | let q = pending |
| 453 | .payload |
| 454 | .get("question") |
| 455 | .and_then(|v| v.as_str()) |
| 456 | .unwrap_or("") |
| 457 | .trim(); |
| 458 | if q.is_empty() { |
| 459 | "question: awaiting answer".to_string() |
| 460 | } else { |
| 461 | format!("question: {}", cap_chars(q, 80)) |
| 462 | } |
| 463 | } |
| 464 | PENDING_PLAN => "plan: awaiting approval".to_string(), |
| 465 | PENDING_CHAT => "replied — waiting for you".to_string(), |
| 466 | PENDING_BUDGET => { |
| 467 | let m = pending |
| 468 | .payload |
| 469 | .get("message") |
| 470 | .and_then(|v| v.as_str()) |
| 471 | .unwrap_or("") |
| 472 | .trim(); |
| 473 | if m.is_empty() { |
| 474 | "budget exhausted".to_string() |
| 475 | } else { |
| 476 | format!("budget: {}", cap_chars(m, 100)) |
| 477 | } |
| 478 | } |
| 479 | PENDING_ERROR => { |
| 480 | let m = pending |
| 481 | .payload |
| 482 | .get("message") |
| 483 | .and_then(|v| v.as_str()) |
| 484 | .unwrap_or("") |
| 485 | .trim(); |
| 486 | if m.is_empty() { |
| 487 | "error — parked".to_string() |
| 488 | } else { |
| 489 | format!("error: {}", cap_chars(m, 100)) |
| 490 | } |
| 491 | } |
| 492 | PENDING_STOPPED => "stopped — work kept".to_string(), |
| 493 | _ => format!("waiting ({})", pending.kind), |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | fn dashboard_task_row(t: &Task, reason: Option<String>) -> Markup { |
| 498 | html! { |
| 499 | div class="task-row" { |
| 500 | @if t.kind == crate::models::TASK_KIND_TRIAGE { |
| 501 | span class="badge" { "triage" } |
| 502 | } |
| 503 | a href=(format!("/tasks/{}", t.id)) { "#" (t.id) " " (&t.title) } |
| 504 | (status_pill(t.status)) |
| 505 | @if let Some(r) = reason { |
| 506 | span class="reason" { (r) } |
| 507 | } |
| 508 | span class="cost" { "$" (format!("{:.4}", t.cost_usd)) " · " (&t.model) } |
| 509 | } |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | /// Dashboard body sections; `triage` is the pre-rendered "Triage" section. |
| 514 | fn render_dashboard_sections(tasks: &[Task], triage: &Markup) -> Markup { |
| 515 | let (needs, active, done) = split_dashboard(tasks); |
| 516 | html! { |
| 517 | (triage) |
| 518 | @if !needs.is_empty() { |
| 519 | section class="dash-section" { |
| 520 | h2 { "Needs you (" (needs.len()) ")" } |
| 521 | @for t in &needs { |
| 522 | (dashboard_task_row(t, Some(need_reason(t)))) |
| 523 | } |
| 524 | } |
| 525 | } |
| 526 | @if !active.is_empty() { |
| 527 | section class="dash-section" { |
| 528 | h2 { "Running" } |
| 529 | @for t in &active { |
| 530 | (dashboard_task_row(t, None)) |
| 531 | } |
| 532 | } |
| 533 | } |
| 534 | section class="dash-section" { |
| 535 | h2 { "Recent" } |
| 536 | @for t in &done { |
| 537 | (dashboard_task_row(t, None)) |
| 538 | } |
| 539 | @if tasks.is_empty() { |
| 540 | p class="muted" { "No tasks yet." } |
| 541 | } |
| 542 | } |
| 543 | } |
| 544 | } |
| 545 | |
| 546 | /// Extension anchor for the parallel triage worker's dashboard "Triage" |
| 547 | /// section (separate `triage_ui.rs` + small hooks here). No-op until that |
| 548 | /// lands, so the dashboard stays structured around one extra section call. |
| 549 | fn triage_section(state: &AppState) -> Markup { |
| 550 | let rows = state.store.triage_recent(10).unwrap_or_default(); |
| 551 | crate::triage_ui::dashboard_section(&rows, &state.config.github_repo) |
| 552 | } |
| 553 | |
| 554 | /// Full dashboard page (pure; the handler only loads tasks). Returns the |
| 555 | /// complete document markup; the `<title>` carries the needs-you count. |
| 556 | #[cfg(test)] |
| 557 | pub(crate) fn render_dashboard_page(tasks: &[Task], release: bool) -> Markup { |
| 558 | render_dashboard_page_with(tasks, release, &html! {}) |
| 559 | } |
| 560 | |
| 561 | fn render_dashboard_page_with(tasks: &[Task], release: bool, triage: &Markup) -> Markup { |
| 562 | let (needs, _, _) = split_dashboard(tasks); |
| 563 | let title = dashboard_title(needs.len()); |
| 564 | layout( |
| 565 | &title, |
| 566 | release, |
| 567 | html! { |
| 568 | h1 { "Tasks" } |
| 569 | p { a href="/tasks/new" { "+ New task" } } |
| 570 | div id="dashboard" { |
| 571 | (render_dashboard_sections(tasks, triage)) |
| 572 | } |
| 573 | }, |
| 574 | ) |
| 575 | } |
| 576 | |
| 577 | async fn task_list(State(state): State<AppState>, headers: HeaderMap) -> Response { |
| 578 | if let Some(reject) = require_auth(&state, &headers) { |
| 579 | return reject; |
| 580 | } |
| 581 | let tasks = state.store.list_tasks(100).unwrap_or_default(); |
| 582 | let banner = release_banner(&state); |
| 583 | Html(render_dashboard_page_with(&tasks, banner, &triage_section(&state)).into_string()).into_response() |
| 584 | } |
| 585 | |
| 586 | /// Dashboard fragment for `app.js` polling: the sections plus the document |
| 587 | /// title (carried as an attribute; the script applies it to |
| 588 | /// `document.title`). Auth is a plain 401 (see `require_auth_fragment`). |
| 589 | async fn dashboard_fragment(State(state): State<AppState>, headers: HeaderMap) -> Response { |
| 590 | if let Some(reject) = require_auth_fragment(&state, &headers) { |
| 591 | return reject; |
| 592 | } |
| 593 | let tasks = state.store.list_tasks(100).unwrap_or_default(); |
| 594 | let (needs, _, _) = split_dashboard(&tasks); |
| 595 | let title = dashboard_title(needs.len()); |
| 596 | Html( |
| 597 | html! { |
| 598 | div data-dash-body="1" data-doc-title=(title) { |
| 599 | (render_dashboard_sections(&tasks, &triage_section(&state))) |
| 600 | } |
| 601 | } |
| 602 | .into_string(), |
| 603 | ) |
| 604 | .into_response() |
| 605 | } |
| 606 | |
| 607 | async fn new_task_page(State(state): State<AppState>, headers: HeaderMap) -> Response { |
| 608 | if let Some(reject) = require_auth(&state, &headers) { |
| 609 | return reject; |
| 610 | } |
| 611 | let banner = release_banner(&state); |
| 612 | let default_model = state.config.default_model.clone(); |
| 613 | Html( |
| 614 | layout( |
| 615 | "new task — agentd", |
| 616 | banner, |
| 617 | html! { |
| 618 | h1 { "New task" } |
| 619 | form method="post" action="/tasks" class="card newtask" { |
| 620 | label { "Title (or leave blank with a GitHub issue # below)" input type="text" name="title" maxlength="120"; } |
| 621 | label { "Module scope (e.g. notes, games/logicgate)" |
| 622 | input type="text" name="module_scope" value="notes" maxlength="80"; } |
| 623 | label { "Model" |
| 624 | input type="text" name="model" value=(default_model) maxlength="120"; } |
| 625 | label { "Prompt (or leave blank with a GitHub issue # below)" textarea name="prompt" rows="12" {} } |
| 626 | label { "GitHub issue # (optional — prefills title/prompt/module from the issue)" |
| 627 | input type="number" name="issue_number" min="1" max="1000000"; } |
| 628 | div class="row" { |
| 629 | label { "Budget steps" input type="number" name="budget_steps" value="60" min="1" max="500"; } |
| 630 | label { "Budget USD" input type="number" name="budget_usd" value="2.00" min="0.1" max="50" step="0.5"; } |
| 631 | } |
| 632 | label class="row" { |
| 633 | input type="checkbox" name="require_plan" value="1" checked; |
| 634 | "Plan first (agent proposes a plan and waits for approval before editing)" |
| 635 | } |
| 636 | button type="submit" class="primary" { "Queue task" } |
| 637 | } |
| 638 | }, |
| 639 | ) |
| 640 | .into_string(), |
| 641 | ) |
| 642 | .into_response() |
| 643 | } |
| 644 | |
| 645 | #[derive(Deserialize, Default)] |
| 646 | struct NewTaskForm { |
| 647 | #[serde(default)] |
| 648 | title: String, |
| 649 | #[serde(default)] |
| 650 | prompt: String, |
| 651 | #[serde(default)] |
| 652 | module_scope: String, |
| 653 | #[serde(default)] |
| 654 | model: String, |
| 655 | #[serde(default)] |
| 656 | budget_steps: Option<i64>, |
| 657 | #[serde(default)] |
| 658 | budget_usd: Option<f64>, |
| 659 | /// Optional GitHub issue number: prefills title/prompt/module from the |
| 660 | /// issue (typed form values win) and stores `issue_number` so `finish` |
| 661 | /// requires the ` (#<n>)` commit suffix. |
| 662 | #[serde(default)] |
| 663 | issue_number: Option<i64>, |
| 664 | /// "Plan first" checkbox (default checked in the form). `Option` because |
| 665 | /// unchecked boxes are omitted from the form body entirely. |
| 666 | #[serde(default)] |
| 667 | require_plan: Option<String>, |
| 668 | } |
| 669 | |
| 670 | async fn create_task( |
| 671 | State(state): State<AppState>, |
| 672 | headers: HeaderMap, |
| 673 | Form(form): Form<NewTaskForm>, |
| 674 | ) -> Response { |
| 675 | if let Some(reject) = require_auth(&state, &headers) { |
| 676 | return reject; |
| 677 | } |
| 678 | if let Some(reject) = require_origin(&state, &headers) { |
| 679 | return reject; |
| 680 | } |
| 681 | let title = form.title.trim().to_string(); |
| 682 | let prompt = form.prompt.trim().to_string(); |
| 683 | let issue_number = form.issue_number.filter(|n| *n > 0); |
| 684 | // Start-from-issue: fetch the issue and prefill title/prompt/module from |
| 685 | // it — but values the user typed win. The issue link is stored so |
| 686 | // `finish` requires the ` (#<n>)` commit suffix. |
| 687 | let (title, prompt, scope) = if let Some(n) = issue_number { |
| 688 | if title.is_empty() && prompt.is_empty() { |
| 689 | // Both blank: require the issue lookup up front so the task is |
| 690 | // never created with empty content. |
| 691 | match crate::issues::fetch_issue(&state.config, n as u64).await { |
| 692 | Ok(issue) => { |
| 693 | let (t, p, m) = crate::issues::prefill_from_issue(&issue); |
| 694 | let scope = scope_from_form(&form.module_scope).unwrap_or_else(|_| { |
| 695 | m.unwrap_or_else(|| scope_from_form(&form.module_scope).unwrap_or_default()) |
| 696 | }); |
| 697 | (t, p, scope) |
| 698 | } |
| 699 | Err(e) => { |
| 700 | return ( |
| 701 | StatusCode::BAD_GATEWAY, |
| 702 | format!("could not fetch GitHub issue #{n}: {e}"), |
| 703 | ) |
| 704 | .into_response(); |
| 705 | } |
| 706 | } |
| 707 | } else { |
| 708 | // User typed something: still link the issue when it exists. |
| 709 | let mut title = title; |
| 710 | let mut prompt = prompt; |
| 711 | let mut scope = scope_from_form(&form.module_scope).unwrap_or_default(); |
| 712 | if let Ok(issue) = crate::issues::fetch_issue(&state.config, n as u64).await { |
| 713 | let (it, ip, im) = crate::issues::prefill_from_issue(&issue); |
| 714 | if title.is_empty() { |
| 715 | title = it; |
| 716 | } |
| 717 | if prompt.is_empty() { |
| 718 | prompt = ip; |
| 719 | } |
| 720 | if form.module_scope.trim().is_empty() { |
| 721 | if let Some(m) = im { |
| 722 | scope = m; |
| 723 | } |
| 724 | } |
| 725 | } |
| 726 | (title, prompt, scope) |
| 727 | } |
| 728 | } else { |
| 729 | if title.is_empty() || prompt.is_empty() { |
| 730 | return (StatusCode::BAD_REQUEST, "title and prompt are required").into_response(); |
| 731 | } |
| 732 | match scope_from_form(&form.module_scope) { |
| 733 | Ok(scope) => (title, prompt, scope), |
| 734 | Err(e) => return (StatusCode::BAD_REQUEST, e).into_response(), |
| 735 | } |
| 736 | }; |
| 737 | if title.is_empty() || prompt.is_empty() { |
| 738 | return (StatusCode::BAD_REQUEST, "title and prompt are required").into_response(); |
| 739 | } |
| 740 | if scope.is_empty() { |
| 741 | return (StatusCode::BAD_REQUEST, "module scope is required").into_response(); |
| 742 | } |
| 743 | let model = if form.model.trim().is_empty() { |
| 744 | state.config.default_model.clone() |
| 745 | } else { |
| 746 | form.model.trim().to_string() |
| 747 | }; |
| 748 | let steps = form.budget_steps.unwrap_or(60).clamp(1, 500); |
| 749 | let usd = form.budget_usd.unwrap_or(2.0).clamp(0.1, 50.0); |
| 750 | let id = match state |
| 751 | .store |
| 752 | .create_task(&title, &prompt, &scope, &model, steps, usd) |
| 753 | { |
| 754 | Ok(id) => id, |
| 755 | Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e).into_response(), |
| 756 | }; |
| 757 | let branch = branch_name(id, &title); |
| 758 | let _ = state.store.set_branch(id, &branch); |
| 759 | // "Plan first" checkbox: the form renders it checked by default. |
| 760 | // Browsers omit unchecked boxes from the body, so present ("1") means |
| 761 | // on and absent means off. |
| 762 | let require_plan = form.require_plan.as_deref() == Some("1"); |
| 763 | let _ = state.store.set_plan_gate(id, require_plan); |
| 764 | if let Some(n) = issue_number { |
| 765 | let _ = state.store.set_issue_number(id, n); |
| 766 | } |
| 767 | state |
| 768 | .driver() |
| 769 | .emit(id, EVENT_STATUS, serde_json::json!({"message": "task queued"})); |
| 770 | ( |
| 771 | StatusCode::FOUND, |
| 772 | [(header::LOCATION, format!("/tasks/{id}"))], |
| 773 | "queued", |
| 774 | ) |
| 775 | .into_response() |
| 776 | } |
| 777 | |
| 778 | // ---- task page: chat timeline + cards + side panel ---- |
| 779 | |
| 780 | /// Full task page (pure; the handler only loads the task + events). The |
| 781 | /// timeline carries `data-task-id` + `data-after` (max rendered seq) for |
| 782 | /// `app.js`, which appends `/timeline?after=` fragments and swaps `/panel` |
| 783 | /// and `/cards` in place. |
| 784 | pub(crate) fn render_task_page( |
| 785 | task: &Task, |
| 786 | events: &[Event], |
| 787 | release: bool, |
| 788 | github_repo: &str, |
| 789 | ) -> Markup { |
| 790 | let task_id = task.id; |
| 791 | let after = events.last().map(|e| e.seq).unwrap_or(-1); |
| 792 | layout( |
| 793 | &format!("task #{task_id} — agentd"), |
| 794 | release, |
| 795 | html! { |
| 796 | h1 { "#" (task_id) " " (&task.title) } |
| 797 | div class="meta-row" { |
| 798 | (status_pill(task.status)) |
| 799 | span class="small muted" { (&task.model) } |
| 800 | } |
| 801 | @if let Some(err) = &task.error { |
| 802 | p class="pill failed" { "Error: " (err) } |
| 803 | } |
| 804 | div id="cards" { |
| 805 | (render_cards(task)) |
| 806 | } |
| 807 | div class="task-grid" { |
| 808 | div class="main" { |
| 809 | @if task.status != TaskStatus::Review { |
| 810 | @if let Some(sum) = &task.summary { |
| 811 | @if task.status != TaskStatus::NeedsInput { |
| 812 | h2 { "Summary" } |
| 813 | p { (sum) } |
| 814 | } |
| 815 | } |
| 816 | } |
| 817 | h2 { "Timeline" } |
| 818 | div id="timeline" data-task-id=(task_id) data-after=(after) { |
| 819 | (render_timeline_events(events)) |
| 820 | } |
| 821 | (render_composer(task)) |
| 822 | (render_stop_row(task)) |
| 823 | p class="small muted" { |
| 824 | "Live updates stream automatically when JavaScript is on; otherwise reload to refresh." |
| 825 | } |
| 826 | } |
| 827 | aside id="panel" { |
| 828 | (render_panel(task, github_repo)) |
| 829 | } |
| 830 | } |
| 831 | }, |
| 832 | ) |
| 833 | } |
| 834 | |
| 835 | async fn task_page( |
| 836 | State(state): State<AppState>, |
| 837 | headers: HeaderMap, |
| 838 | Path(id): Path<i64>, |
| 839 | ) -> Response { |
| 840 | if let Some(reject) = require_auth(&state, &headers) { |
| 841 | return reject; |
| 842 | } |
| 843 | let Some(task) = state.store.get_task(id).unwrap_or(None) else { |
| 844 | return (StatusCode::NOT_FOUND, "task not found").into_response(); |
| 845 | }; |
| 846 | let events = state.store.list_events(id, None).unwrap_or_default(); |
| 847 | let banner = release_banner(&state); |
| 848 | Html(render_task_page(&task, &events, banner, &state.config.github_repo).into_string()) |
| 849 | .into_response() |
| 850 | } |
| 851 | |
| 852 | // ---- timeline ---- |
| 853 | |
| 854 | /// Chat timeline. `todos` events render only in the side panel (skipped |
| 855 | /// here); question/plan/review events become short note lines (the live |
| 856 | /// pending/review cards above carry the full UI). A `tool_call` merges with |
| 857 | /// the directly following `tool_result` for the same tool into one collapsed |
| 858 | /// `<details>` chip — an orphan result (fragment boundary, rejected mixed |
| 859 | /// turn) renders on its own. |
| 860 | pub(crate) fn render_timeline_events(events: &[Event]) -> Markup { |
| 861 | let mut items: Vec<Markup> = Vec::new(); |
| 862 | let mut skip_next_result = false; |
| 863 | for (i, ev) in events.iter().enumerate() { |
| 864 | if skip_next_result && ev.kind == EVENT_TOOL_RESULT { |
| 865 | skip_next_result = false; |
| 866 | continue; |
| 867 | } |
| 868 | skip_next_result = false; |
| 869 | match ev.kind.as_str() { |
| 870 | EVENT_USER_MESSAGE => items.push(render_user_msg(ev)), |
| 871 | EVENT_ASSISTANT => { |
| 872 | if let Some(m) = render_assistant_msg(ev) { |
| 873 | items.push(m); |
| 874 | } |
| 875 | } |
| 876 | EVENT_TOOL_CALL => { |
| 877 | let name = ev_str(&ev.body, "name"); |
| 878 | let args = ev_str(&ev.body, "args"); |
| 879 | // Merge only with the directly following result for the SAME |
| 880 | // tool (dispatch emits call,result,… in order, so adjacency |
| 881 | // plus the name check attributes results correctly). |
| 882 | let merged = events.get(i + 1).filter(|n| { |
| 883 | n.kind == EVENT_TOOL_RESULT && ev_str(&n.body, "name") == name |
| 884 | }); |
| 885 | match merged { |
| 886 | Some(res) => { |
| 887 | items.push(render_tool_pair( |
| 888 | name, |
| 889 | args, |
| 890 | Some((ev_str(&res.body, "result"), res_truncated(res))), |
| 891 | ev.seq, |
| 892 | )); |
| 893 | skip_next_result = true; |
| 894 | } |
| 895 | None => items.push(render_tool_pair(name, args, None, ev.seq)), |
| 896 | } |
| 897 | } |
| 898 | EVENT_TOOL_RESULT => items.push(render_tool_pair( |
| 899 | ev_str(&ev.body, "name"), |
| 900 | "", |
| 901 | Some((ev_str(&ev.body, "result"), res_truncated(ev))), |
| 902 | ev.seq, |
| 903 | )), |
| 904 | EVENT_STATUS => { |
| 905 | let msg = ev_str(&ev.body, "message"); |
| 906 | if !msg.trim().is_empty() { |
| 907 | items.push(html! { |
| 908 | div class="ev status-line" data-seq=(ev.seq) { "· " (cap_chars(msg.trim(), 500)) } |
| 909 | }); |
| 910 | } |
| 911 | } |
| 912 | EVENT_QUESTION => { |
| 913 | let q = ev_str(&ev.body, "question"); |
| 914 | items.push(html! { |
| 915 | div class="ev note-line" data-seq=(ev.seq) { |
| 916 | "asked: " @if q.trim().is_empty() { "(question)" } @else { (cap_chars(q.trim(), 140)) } |
| 917 | } |
| 918 | }); |
| 919 | } |
| 920 | EVENT_PLAN => { |
| 921 | items.push(html! { |
| 922 | div class="ev note-line" data-seq=(ev.seq) { "plan proposed — see the card above." } |
| 923 | }); |
| 924 | } |
| 925 | EVENT_REVIEW => { |
| 926 | let s = ev_str(&ev.body, "summary"); |
| 927 | items.push(html! { |
| 928 | div class="ev note-line" data-seq=(ev.seq) { |
| 929 | "review ready" @if !s.trim().is_empty() { ": " (cap_chars(s.trim(), 140)) } |
| 930 | } |
| 931 | }); |
| 932 | } |
| 933 | EVENT_TODOS => { |
| 934 | // Panel only (the checklist is live state, not history). |
| 935 | } |
| 936 | _ => { |
| 937 | let raw = ev.body.to_string(); |
| 938 | items.push(html! { |
| 939 | div class="ev note-line" data-seq=(ev.seq) { |
| 940 | (&ev.kind) ": " (cap_chars(raw.trim(), 300)) |
| 941 | } |
| 942 | }); |
| 943 | } |
| 944 | } |
| 945 | } |
| 946 | html! { |
| 947 | @for m in items { |
| 948 | (m) |
| 949 | } |
| 950 | } |
| 951 | } |
| 952 | |
| 953 | /// User message: right-aligned bubble, plain escaped text (never markdown — |
| 954 | /// the operator's own words need no formatting, and pre-wrap keeps layout). |
| 955 | fn render_user_msg(ev: &Event) -> Markup { |
| 956 | let text = cap_chars(ev_str(&ev.body, "text").trim(), 8000); |
| 957 | html! { |
| 958 | div class="ev msg-user" data-seq=(ev.seq) { |
| 959 | div class="bubble user" { (text) } |
| 960 | } |
| 961 | } |
| 962 | } |
| 963 | |
| 964 | /// Assistant text: left bubble through the safe markdown subset (raw HTML |
| 965 | /// escaped, `javascript:` links dropped). Empty text (tool-only turn) renders |
| 966 | /// nothing — the tool chips carry those turns. |
| 967 | fn render_assistant_msg(ev: &Event) -> Option<Markup> { |
| 968 | let text = ev_str(&ev.body, "text"); |
| 969 | if text.trim().is_empty() { |
| 970 | return None; |
| 971 | } |
| 972 | Some(html! { |
| 973 | div class="ev msg-assistant" data-seq=(ev.seq) { |
| 974 | div class="bubble assistant" { (PreEscaped(render_markdown(text))) } |
| 975 | } |
| 976 | }) |
| 977 | } |
| 978 | |
| 979 | fn res_truncated(ev: &Event) -> bool { |
| 980 | ev.body |
| 981 | .get("truncated") |
| 982 | .and_then(|v| v.as_bool()) |
| 983 | .unwrap_or(false) |
| 984 | } |
| 985 | |
| 986 | /// Collapsed tool chip: `▸ <name> <args…>`, escaped and capped, with the |
| 987 | /// (capped) result inside. `result=None` means the call is still running. |
| 988 | fn render_tool_pair(name: &str, args: &str, result: Option<(&str, bool)>, seq: i64) -> Markup { |
| 989 | let name = if name.is_empty() { "tool" } else { name }; |
| 990 | let chip_args = cap_chars(args.trim(), 80); |
| 991 | let chip = if chip_args.is_empty() { |
| 992 | format!("▸ {name}") |
| 993 | } else { |
| 994 | format!("▸ {name} {chip_args}") |
| 995 | }; |
| 996 | html! { |
| 997 | div class="ev" data-seq=(seq) { |
| 998 | details class="tool" { |
| 999 | summary class="tool-chip" { (chip) } |
| 1000 | div class="tool-body" { |
| 1001 | @if !args.trim().is_empty() { |
| 1002 | p class="small muted" { "args: " code { (cap_chars(args.trim(), 400)) } } |
| 1003 | } |
| 1004 | @match result { |
| 1005 | Some((text, truncated)) => { |
| 1006 | (render_capped_result(text, truncated)) |
| 1007 | } |
| 1008 | None => { |
| 1009 | p class="small muted" { "(running…)" } |
| 1010 | } |
| 1011 | } |
| 1012 | } |
| 1013 | } |
| 1014 | } |
| 1015 | } |
| 1016 | } |
| 1017 | |
| 1018 | fn render_capped_result(text: &str, flagged: bool) -> Markup { |
| 1019 | let shown = cap_chars(text.trim(), 2000); |
| 1020 | let cut = flagged || shown.len() < text.trim().len(); |
| 1021 | html! { |
| 1022 | pre { (shown) } |
| 1023 | @if cut { |
| 1024 | p class="small muted" { "…[result truncated]" } |
| 1025 | } |
| 1026 | } |
| 1027 | } |
| 1028 | |
| 1029 | // ---- cards (pending question / plan / review + parked explanations) ---- |
| 1030 | |
| 1031 | /// Pending + review cards (pure; also served as the `/cards` fragment). |
| 1032 | /// Only one card shows at a time: review wins, then the active pending kind, |
| 1033 | /// then a short explanation for the parked-but-textless kinds |
| 1034 | /// (chat/budget/error/stopped — the composer below is their answer path). |
| 1035 | pub(crate) fn render_cards(task: &Task) -> Markup { |
| 1036 | if task.status == TaskStatus::Review { |
| 1037 | return render_review_card(task); |
| 1038 | } |
| 1039 | let Some(pending) = task.pending.as_ref() else { |
| 1040 | return html! {}; |
| 1041 | }; |
| 1042 | if task.status.is_terminal() { |
| 1043 | return html! {}; |
| 1044 | } |
| 1045 | match pending.kind.as_str() { |
| 1046 | PENDING_QUESTION => render_question_card(task.id, pending), |
| 1047 | PENDING_PLAN => render_plan_card(task.id, pending), |
| 1048 | PENDING_CHAT => html! { |
| 1049 | div class="card" { |
| 1050 | p class="small muted" { "Waiting for you (chat)" } |
| 1051 | p { "The agent replied and is waiting for you. Send a message below to continue." } |
| 1052 | } |
| 1053 | }, |
| 1054 | PENDING_BUDGET => { |
| 1055 | let m = pending |
| 1056 | .payload |
| 1057 | .get("message") |
| 1058 | .and_then(|v| v.as_str()) |
| 1059 | .unwrap_or("") |
| 1060 | .trim() |
| 1061 | .to_string(); |
| 1062 | html! { |
| 1063 | div class="card" { |
| 1064 | h3 { "Budget exhausted" } |
| 1065 | p class="small muted" { "Waiting for you (budget)" } |
| 1066 | @if !m.is_empty() { |
| 1067 | p class="small" { (m) } |
| 1068 | } |
| 1069 | p { "Reply below to add 20 steps and $1.00 and resume — or Discard the task." } |
| 1070 | } |
| 1071 | } |
| 1072 | } |
| 1073 | PENDING_ERROR => { |
| 1074 | let m = pending |
| 1075 | .payload |
| 1076 | .get("message") |
| 1077 | .and_then(|v| v.as_str()) |
| 1078 | .unwrap_or("") |
| 1079 | .trim() |
| 1080 | .to_string(); |
| 1081 | html! { |
| 1082 | div class="card" { |
| 1083 | h3 { "Parked on error" } |
| 1084 | @if !m.is_empty() { |
| 1085 | p class="small" { (m) } |
| 1086 | } |
| 1087 | p { "Reply below to retry — or Discard the task." } |
| 1088 | } |
| 1089 | } |
| 1090 | } |
| 1091 | PENDING_STOPPED => html! { |
| 1092 | div class="card" { |
| 1093 | h3 { "Stopped" } |
| 1094 | p { "Stopped by the operator; work is kept. Reply below to resume — or Discard the task." } |
| 1095 | } |
| 1096 | }, |
| 1097 | _ => html! { |
| 1098 | div class="card" { |
| 1099 | p { "Waiting for you (" (pending.kind.clone()) "). Send a message below." } |
| 1100 | } |
| 1101 | }, |
| 1102 | } |
| 1103 | } |
| 1104 | |
| 1105 | /// Question card: one form per option (posts the option text to |
| 1106 | /// `/messages`), plus — for `multi_select` — a checkboxes form whose values |
| 1107 | /// the server joins, plus a free-text box. Question text goes through the |
| 1108 | /// safe markdown subset. |
| 1109 | fn render_question_card(task_id: i64, pending: &crate::models::Pending) -> Markup { |
| 1110 | let action = format!("/tasks/{task_id}/messages"); |
| 1111 | let q = pending |
| 1112 | .payload |
| 1113 | .get("question") |
| 1114 | .and_then(|v| v.as_str()) |
| 1115 | .unwrap_or(""); |
| 1116 | let options: Vec<String> = pending |
| 1117 | .payload |
| 1118 | .get("options") |
| 1119 | .and_then(|v| v.as_array()) |
| 1120 | .map(|a| { |
| 1121 | a.iter() |
| 1122 | .filter_map(|v| v.as_str().map(|s| s.to_string())) |
| 1123 | .collect() |
| 1124 | }) |
| 1125 | .unwrap_or_default(); |
| 1126 | let multi = pending |
| 1127 | .payload |
| 1128 | .get("multi_select") |
| 1129 | .and_then(|v| v.as_bool()) |
| 1130 | .unwrap_or(false); |
| 1131 | html! { |
| 1132 | div class="card" { |
| 1133 | h3 { "Question — waiting for your answer" } |
| 1134 | p class="small muted" { "Waiting for you (question)" } |
| 1135 | div class="q-text" { (PreEscaped(render_markdown(q))) } |
| 1136 | @if !options.is_empty() { |
| 1137 | div class="options" { |
| 1138 | @for opt in &options { |
| 1139 | form method="post" action=(action.clone()) class="inline" { |
| 1140 | input type="hidden" name="text" value=(opt); |
| 1141 | button type="submit" { (opt) } |
| 1142 | } |
| 1143 | } |
| 1144 | } |
| 1145 | } |
| 1146 | @if multi && !options.is_empty() { |
| 1147 | form method="post" action=(action.clone()) { |
| 1148 | fieldset class="optlist" { |
| 1149 | legend { "Or select all that apply" } |
| 1150 | @for opt in &options { |
| 1151 | label class="check" { |
| 1152 | input type="checkbox" name="options" value=(opt); |
| 1153 | (opt) |
| 1154 | } |
| 1155 | } |
| 1156 | } |
| 1157 | button type="submit" { "Send selected" } |
| 1158 | } |
| 1159 | } |
| 1160 | form method="post" action=(action) { |
| 1161 | label { "Or answer in your own words" |
| 1162 | textarea name="text" rows="3" required maxlength="8000" {} } |
| 1163 | button type="submit" class="primary" { "Send answer" } |
| 1164 | } |
| 1165 | } |
| 1166 | } |
| 1167 | } |
| 1168 | |
| 1169 | /// Plan card: rendered markdown + Approve form + changes textarea (posts to |
| 1170 | /// `/plan/changes`, which resumes the pending `propose_plan` call with the |
| 1171 | /// feedback and keeps the plan gate shut). |
| 1172 | fn render_plan_card(task_id: i64, pending: &crate::models::Pending) -> Markup { |
| 1173 | let plan = pending |
| 1174 | .payload |
| 1175 | .get("plan_markdown") |
| 1176 | .and_then(|v| v.as_str()) |
| 1177 | .unwrap_or(""); |
| 1178 | html! { |
| 1179 | div class="card" { |
| 1180 | h3 { "Proposed plan — waiting for approval" } |
| 1181 | p class="small muted" { "Waiting for you (plan)" } |
| 1182 | div class="plan-md" { (PreEscaped(render_markdown(plan))) } |
| 1183 | div class="row" { |
| 1184 | form method="post" action=(format!("/tasks/{task_id}/plan/approve")) class="inline" { |
| 1185 | button type="submit" class="primary" { "Approve plan" } |
| 1186 | } |
| 1187 | } |
| 1188 | form method="post" action=(format!("/tasks/{task_id}/plan/changes")) { |
| 1189 | label { "Request changes" |
| 1190 | textarea name="text" rows="3" required maxlength="8000" {} } |
| 1191 | button type="submit" { "Request changes" } |
| 1192 | } |
| 1193 | } |
| 1194 | } |
| 1195 | } |
| 1196 | |
| 1197 | /// Review card (only in `review`): summary, commit message `<pre>`, capped |
| 1198 | /// diff in an open `<details>` with +/- line classes, Approve & push / |
| 1199 | /// Discard buttons, and a changes box (a normal message while in review → |
| 1200 | /// the task resumes and the pending `finish` call gets "User reviewed the |
| 1201 | /// change and requested: …"). |
| 1202 | fn render_review_card(task: &Task) -> Markup { |
| 1203 | let task_id = task.id; |
| 1204 | let diff = task.final_diff.as_deref().unwrap_or("(no diff stored)"); |
| 1205 | html! { |
| 1206 | div class="card" { |
| 1207 | h3 { "Review — waiting for approval" } |
| 1208 | @if let Some(sum) = &task.summary { |
| 1209 | p { strong { "Summary: " } (sum) } |
| 1210 | } |
| 1211 | @if let Some(cm) = &task.commit_message { |
| 1212 | p { strong { "Commit message:" } pre class="log" { (cm) } } |
| 1213 | } |
| 1214 | details class="diff" open="open" { |
| 1215 | summary { "Diff (" (diff.len()) " bytes)" } |
| 1216 | (render_diff_lines(diff)) |
| 1217 | } |
| 1218 | div class="row" { |
| 1219 | form method="post" action=(format!("/tasks/{task_id}/approve")) class="inline" { |
| 1220 | button type="submit" class="primary" { "Approve & push" } |
| 1221 | } |
| 1222 | form method="post" action=(format!("/tasks/{task_id}/discard")) class="inline" { |
| 1223 | button type="submit" { "Discard" } |
| 1224 | } |
| 1225 | } |
| 1226 | form method="post" action=(format!("/tasks/{task_id}/messages")) { |
| 1227 | label { "Request changes" |
| 1228 | textarea name="text" rows="3" required maxlength="8000" {} } |
| 1229 | button type="submit" { "Request changes" } |
| 1230 | } |
| 1231 | } |
| 1232 | } |
| 1233 | } |
| 1234 | |
| 1235 | /// Diff viewer: each line escaped individually, `+`/`-` lines classed for |
| 1236 | /// coloring, hunk headers dimmed. Capped (~2000 lines / 20k chars) so a big |
| 1237 | /// diff can't blow up the page; the full diff lives in the branch. |
| 1238 | pub(crate) fn render_diff_lines(diff: &str) -> Markup { |
| 1239 | const MAX_LINES: usize = 2000; |
| 1240 | const MAX_CHARS: usize = 20_000; |
| 1241 | let mut out = String::new(); |
| 1242 | let mut chars = 0usize; |
| 1243 | let mut clamped = false; |
| 1244 | for (i, line) in diff.lines().enumerate() { |
| 1245 | if i >= MAX_LINES || chars + line.len() + 1 > MAX_CHARS { |
| 1246 | clamped = true; |
| 1247 | break; |
| 1248 | } |
| 1249 | let class = if line.starts_with('+') && !line.starts_with("+++") { |
| 1250 | "add" |
| 1251 | } else if line.starts_with('-') && !line.starts_with("---") { |
| 1252 | "del" |
| 1253 | } else if line.starts_with("@@") { |
| 1254 | "hunk" |
| 1255 | } else { |
| 1256 | "" |
| 1257 | }; |
| 1258 | let e = esc_html(line); |
| 1259 | if class.is_empty() { |
| 1260 | out.push_str(&e); |
| 1261 | } else { |
| 1262 | out.push_str(&format!("<span class=\"{class}\">{e}</span>")); |
| 1263 | } |
| 1264 | out.push('\n'); |
| 1265 | chars += line.len() + 1; |
| 1266 | } |
| 1267 | if clamped { |
| 1268 | out.push_str("… [diff view clamped; full diff in the branch]"); |
| 1269 | } |
| 1270 | html! { |
| 1271 | pre class="difflines" { (PreEscaped(out)) } |
| 1272 | } |
| 1273 | } |
| 1274 | |
| 1275 | // ---- composer + stop/discard ---- |
| 1276 | |
| 1277 | /// Message box for non-terminal tasks (hidden while a question/plan/review |
| 1278 | /// card owns answering) and for `succeeded` tasks (follow-up placeholder). |
| 1279 | fn render_composer(task: &Task) -> Markup { |
| 1280 | let task_id = task.id; |
| 1281 | let pending_kind = task.pending.as_ref().map(|p| p.kind.as_str()); |
| 1282 | let show = match task.status { |
| 1283 | TaskStatus::Succeeded => true, |
| 1284 | s if s.is_terminal() => false, |
| 1285 | TaskStatus::Review => false, |
| 1286 | _ => !matches!(pending_kind, Some(PENDING_QUESTION) | Some(PENDING_PLAN)), |
| 1287 | }; |
| 1288 | if !show { |
| 1289 | return html! {}; |
| 1290 | } |
| 1291 | let placeholder = if task.status == TaskStatus::Succeeded { |
| 1292 | "Follow-up (re-queues the task from the pushed tip)" |
| 1293 | } else { |
| 1294 | "Message the agent (steering, or the answer when the task waits)" |
| 1295 | }; |
| 1296 | html! { |
| 1297 | h2 { "Message the agent" } |
| 1298 | form method="post" action=(format!("/tasks/{task_id}/messages")) class="card" { |
| 1299 | label { (placeholder) |
| 1300 | textarea name="text" rows="3" required maxlength="8000" {} } |
| 1301 | button type="submit" class="primary" { "Send" } |
| 1302 | } |
| 1303 | } |
| 1304 | } |
| 1305 | |
| 1306 | /// Stop while running/queued; Discard for any non-terminal task. |
| 1307 | fn render_stop_row(task: &Task) -> Markup { |
| 1308 | if task.status.is_terminal() { |
| 1309 | let task_id = task.id; |
| 1310 | return html! { |
| 1311 | div class="row" { |
| 1312 | form method="post" action=(format!("/tasks/{task_id}/retry")) class="inline" { |
| 1313 | button type="submit" { "Retry as new task" } |
| 1314 | } |
| 1315 | } |
| 1316 | }; |
| 1317 | } |
| 1318 | let task_id = task.id; |
| 1319 | let running = matches!(task.status, TaskStatus::Running | TaskStatus::Queued); |
| 1320 | html! { |
| 1321 | div class="row" { |
| 1322 | @if running { |
| 1323 | form method="post" action=(format!("/tasks/{task_id}/stop")) class="inline" { |
| 1324 | button type="submit" { "Stop" } |
| 1325 | } |
| 1326 | } |
| 1327 | form method="post" action=(format!("/tasks/{task_id}/discard")) class="inline" { |
| 1328 | button type="submit" { "Discard" } |
| 1329 | } |
| 1330 | @if task.pushed { |
| 1331 | p class="small muted" { |
| 1332 | "Note: this task was pushed before — discarding removes the local work, but the remote branch " |
| 1333 | code { (&task.branch) } " remains on git.maproj.org; the agent token can't delete it." |
| 1334 | } |
| 1335 | } |
| 1336 | } |
| 1337 | } |
| 1338 | } |
| 1339 | |
| 1340 | // ---- side panel ---- |
| 1341 | |
| 1342 | /// Side panel: status, todo checklist (todos events render ONLY here), |
| 1343 | /// model, scope, branch + copyable `git fetch` line, issue link, plan-first |
| 1344 | /// flag, steps/cost vs budget, tokens. |
| 1345 | pub(crate) fn render_panel(task: &Task, github_repo: &str) -> Markup { |
| 1346 | let todos: Vec<crate::models::TodoItem> = task |
| 1347 | .todos_json |
| 1348 | .as_deref() |
| 1349 | .and_then(|raw| serde_json::from_str(raw).ok()) |
| 1350 | .unwrap_or_default(); |
| 1351 | let fetch_cmd = format!("git fetch origin {}", task.branch); |
| 1352 | html! { |
| 1353 | @if task.kind == crate::models::TASK_KIND_TRIAGE { |
| 1354 | (crate::triage_ui::task_panel_block(task, github_repo)) |
| 1355 | } |
| 1356 | h3 { "Status" } |
| 1357 | div class="p-row" { |
| 1358 | span class="k" { "state" } |
| 1359 | span class="v" { |
| 1360 | (status_pill(task.status)) |
| 1361 | @if let Some(p) = &task.pending { |
| 1362 | " " span class="small muted" { "waiting: " (p.kind.clone()) } |
| 1363 | } |
| 1364 | } |
| 1365 | } |
| 1366 | @if task.pushed { |
| 1367 | div class="p-row" { |
| 1368 | span class="k" { "pushed" } |
| 1369 | span class="v" { code { (&task.branch) } " on the remote" } |
| 1370 | } |
| 1371 | } |
| 1372 | h3 { "Todos" } |
| 1373 | @if todos.is_empty() { |
| 1374 | p class="small muted" { "No todos yet." } |
| 1375 | } @else { |
| 1376 | ul class="todos" { |
| 1377 | @for t in &todos { |
| 1378 | @match t.status.as_str() { |
| 1379 | "done" => { li class="done" { "☑ " (&t.text) } } |
| 1380 | "in_progress" => { li class="doing" { "▶ " (&t.text) } } |
| 1381 | _ => { li { "☐ " (&t.text) } } |
| 1382 | } |
| 1383 | } |
| 1384 | } |
| 1385 | } |
| 1386 | h3 { "Run" } |
| 1387 | div class="p-row" { span class="k" { "model" } span class="v small" { (&task.model) } } |
| 1388 | div class="p-row" { span class="k" { "scope" } span class="v" { code { (&task.module_scope) } } } |
| 1389 | div class="p-row" { span class="k" { "branch" } span class="v" { code { (&task.branch) } } } |
| 1390 | div class="p-row" { |
| 1391 | span class="k" { "fetch" } |
| 1392 | span class="v fetchline" { |
| 1393 | input readonly value=(fetch_cmd) aria-label="copyable git fetch command"; |
| 1394 | } |
| 1395 | } |
| 1396 | @if let Some(n) = &task.issue_number { |
| 1397 | div class="p-row" { |
| 1398 | span class="k" { "issue" } |
| 1399 | span class="v" { |
| 1400 | a href=(format!("https://github.com/{github_repo}/issues/{n}")) { "#" (n) } |
| 1401 | } |
| 1402 | } |
| 1403 | } |
| 1404 | @if let Some(sha) = &task.commit_sha { |
| 1405 | div class="p-row" { |
| 1406 | span class="k" { "commit" } |
| 1407 | span class="v small" { |
| 1408 | code { (sha) } " " (if task.pushed { "(pushed)" } else { "(not pushed)" }) |
| 1409 | } |
| 1410 | } |
| 1411 | } |
| 1412 | @if let Some(wip) = &task.wip_sha { |
| 1413 | div class="p-row" { |
| 1414 | span class="k" { "wip" } |
| 1415 | span class="v small" { code { (wip) } } |
| 1416 | } |
| 1417 | } |
| 1418 | div class="p-row" { |
| 1419 | span class="k" { "plan" } |
| 1420 | span class="v small" { |
| 1421 | @if task.require_plan { |
| 1422 | "plan-first" @if task.plan_approved { " (approved)" } @else { " (awaiting approval)" } |
| 1423 | } @else { |
| 1424 | "plan-first off" |
| 1425 | } |
| 1426 | } |
| 1427 | } |
| 1428 | h3 { "Budget" } |
| 1429 | div class="p-row" { |
| 1430 | span class="k" { "steps" } |
| 1431 | span class="v" { (task.steps) "/" (task.budget_steps) } |
| 1432 | } |
| 1433 | div class="p-row" { |
| 1434 | span class="k" { "cost" } |
| 1435 | span class="v" { "$" (format!("{:.4}", task.cost_usd)) "/$" (format!("{:.2}", task.budget_usd)) } |
| 1436 | } |
| 1437 | div class="p-row" { |
| 1438 | span class="k" { "tokens" } |
| 1439 | span class="v" { (task.prompt_tokens) "+" (task.completion_tokens) } |
| 1440 | } |
| 1441 | } |
| 1442 | } |
| 1443 | |
| 1444 | // ---- fragments (auth-protected, fetched by app.js) ---- |
| 1445 | |
| 1446 | #[derive(Deserialize)] |
| 1447 | struct EventsQuery { |
| 1448 | after: Option<i64>, |
| 1449 | } |
| 1450 | |
| 1451 | async fn task_timeline_fragment( |
| 1452 | State(state): State<AppState>, |
| 1453 | headers: HeaderMap, |
| 1454 | Path(id): Path<i64>, |
| 1455 | Query(q): Query<EventsQuery>, |
| 1456 | ) -> Response { |
| 1457 | if let Some(reject) = require_auth_fragment(&state, &headers) { |
| 1458 | return reject; |
| 1459 | } |
| 1460 | if state.store.get_task(id).unwrap_or(None).is_none() { |
| 1461 | return (StatusCode::NOT_FOUND, "task not found").into_response(); |
| 1462 | } |
| 1463 | let events = state.store.list_events(id, q.after).unwrap_or_default(); |
| 1464 | Html(render_timeline_events(&events).into_string()).into_response() |
| 1465 | } |
| 1466 | |
| 1467 | async fn task_panel_fragment( |
| 1468 | State(state): State<AppState>, |
| 1469 | headers: HeaderMap, |
| 1470 | Path(id): Path<i64>, |
| 1471 | ) -> Response { |
| 1472 | if let Some(reject) = require_auth_fragment(&state, &headers) { |
| 1473 | return reject; |
| 1474 | } |
| 1475 | let Some(task) = state.store.get_task(id).unwrap_or(None) else { |
| 1476 | return (StatusCode::NOT_FOUND, "task not found").into_response(); |
| 1477 | }; |
| 1478 | Html(render_panel(&task, &state.config.github_repo).into_string()).into_response() |
| 1479 | } |
| 1480 | |
| 1481 | async fn task_cards_fragment( |
| 1482 | State(state): State<AppState>, |
| 1483 | headers: HeaderMap, |
| 1484 | Path(id): Path<i64>, |
| 1485 | ) -> Response { |
| 1486 | if let Some(reject) = require_auth_fragment(&state, &headers) { |
| 1487 | return reject; |
| 1488 | } |
| 1489 | let Some(task) = state.store.get_task(id).unwrap_or(None) else { |
| 1490 | return (StatusCode::NOT_FOUND, "task not found").into_response(); |
| 1491 | }; |
| 1492 | Html(render_cards(&task).into_string()).into_response() |
| 1493 | } |
| 1494 | |
| 1495 | // ---- SSE ---- |
| 1496 | |
| 1497 | async fn task_events_sse( |
| 1498 | State(state): State<AppState>, |
| 1499 | headers: HeaderMap, |
| 1500 | Path(id): Path<i64>, |
| 1501 | Query(q): Query<EventsQuery>, |
| 1502 | ) -> Response { |
| 1503 | if let Some(reject) = require_auth(&state, &headers) { |
| 1504 | return reject; |
| 1505 | } |
| 1506 | if state.store.get_task(id).unwrap_or(None).is_none() { |
| 1507 | return (StatusCode::NOT_FOUND, "task not found").into_response(); |
| 1508 | } |
| 1509 | // Replay backlog, then stream new events. |
| 1510 | let backlog = state.store.list_events(id, q.after).unwrap_or_default(); |
| 1511 | let rx = state.events_tx.subscribe(); |
| 1512 | let stream = BroadcastStream::new(rx).filter_map(move |res| { |
| 1513 | let (tid, ev) = res.ok()?; |
| 1514 | if tid == id { |
| 1515 | Some(Ok::<_, axum::Error>(SseEvent::default().data( |
| 1516 | serde_json::to_string(&ev).unwrap_or_else(|_| "{}".to_string()), |
| 1517 | ))) |
| 1518 | } else { |
| 1519 | None |
| 1520 | } |
| 1521 | }); |
| 1522 | let backlog_stream = tokio_stream::iter( |
| 1523 | backlog |
| 1524 | .into_iter() |
| 1525 | .map(|ev| { |
| 1526 | Ok::<_, axum::Error>(SseEvent::default().data( |
| 1527 | serde_json::to_string(&ev).unwrap_or_else(|_| "{}".to_string()), |
| 1528 | )) |
| 1529 | }) |
| 1530 | .collect::<Vec<_>>(), |
| 1531 | ); |
| 1532 | Sse::new(backlog_stream.chain(stream)) |
| 1533 | .keep_alive(KeepAlive::default()) |
| 1534 | .into_response() |
| 1535 | } |
| 1536 | |
| 1537 | /// `POST /tasks/:id/messages` — inbox a user message (an answer while |
| 1538 | /// parked, or steering while running). Re-queues parked / review / succeeded |
| 1539 | /// tasks in the same transaction. |
| 1540 | /// |
| 1541 | /// While in `review`, a normal message is request-changes: the row is tagged |
| 1542 | /// so the resume formats the pending `finish` result as "User reviewed the |
| 1543 | /// change and requested: …". |
| 1544 | async fn messages_route( |
| 1545 | State(state): State<AppState>, |
| 1546 | headers: HeaderMap, |
| 1547 | Path(id): Path<i64>, |
| 1548 | Form(pairs): Form<Vec<(String, String)>>, |
| 1549 | ) -> Response { |
| 1550 | if let Some(reject) = require_auth(&state, &headers) { |
| 1551 | return reject; |
| 1552 | } |
| 1553 | if let Some(reject) = require_origin(&state, &headers) { |
| 1554 | return reject; |
| 1555 | } |
| 1556 | // Fold the raw pairs by hand: checkboxes post repeated `options` keys |
| 1557 | // (which struct deserialization rejects as duplicates), and the |
| 1558 | // checkboxes-only form omits `text` entirely. |
| 1559 | let mut text = String::new(); |
| 1560 | let mut options: Vec<String> = Vec::new(); |
| 1561 | for (k, v) in pairs { |
| 1562 | match k.as_str() { |
| 1563 | "text" => text = v, |
| 1564 | "options" => options.push(v), |
| 1565 | _ => {} |
| 1566 | } |
| 1567 | } |
| 1568 | let text = if text.trim().is_empty() { |
| 1569 | options.join(", ").trim().to_string() |
| 1570 | } else { |
| 1571 | text.trim().to_string() |
| 1572 | }; |
| 1573 | if text.is_empty() { |
| 1574 | return (StatusCode::BAD_REQUEST, "message text is required").into_response(); |
| 1575 | } |
| 1576 | if state.store.get_task(id).unwrap_or(None).is_none() { |
| 1577 | return (StatusCode::NOT_FOUND, "task not found").into_response(); |
| 1578 | } |
| 1579 | // Tag request-changes while in review so the resume formats the pending |
| 1580 | // `finish` tool result ("User reviewed the change and requested: …"). |
| 1581 | let kind = match state.store.get_task(id).unwrap_or(None) { |
| 1582 | Some(t) if t.status == TaskStatus::Review => INBOX_REVIEW_CHANGES, |
| 1583 | _ => "", |
| 1584 | }; |
| 1585 | match state.store.inbox_post_kind(id, &text, kind) { |
| 1586 | Ok(requeued) => { |
| 1587 | state.driver().emit(id, EVENT_STATUS, |
| 1588 | serde_json::json!({"message": format!("user message received{}", if requeued { " (task re-queued)" } else { "" })}), |
| 1589 | ); |
| 1590 | ( |
| 1591 | StatusCode::FOUND, |
| 1592 | [(header::LOCATION, format!("/tasks/{id}"))], |
| 1593 | "message received", |
| 1594 | ) |
| 1595 | .into_response() |
| 1596 | } |
| 1597 | Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e).into_response(), |
| 1598 | } |
| 1599 | } |
| 1600 | |
| 1601 | async fn stop_route( |
| 1602 | State(state): State<AppState>, |
| 1603 | headers: HeaderMap, |
| 1604 | Path(id): Path<i64>, |
| 1605 | ) -> Response { |
| 1606 | if let Some(reject) = require_auth(&state, &headers) { |
| 1607 | return reject; |
| 1608 | } |
| 1609 | if let Some(reject) = require_origin(&state, &headers) { |
| 1610 | return reject; |
| 1611 | } |
| 1612 | match crate::scheduler::stop_task(&state.driver(), id).await { |
| 1613 | Ok(_) => ( |
| 1614 | StatusCode::FOUND, |
| 1615 | [(header::LOCATION, format!("/tasks/{id}"))], |
| 1616 | "stop requested", |
| 1617 | ) |
| 1618 | .into_response(), |
| 1619 | Err(e) => (StatusCode::NOT_FOUND, e).into_response(), |
| 1620 | } |
| 1621 | } |
| 1622 | |
| 1623 | async fn discard_route( |
| 1624 | State(state): State<AppState>, |
| 1625 | headers: HeaderMap, |
| 1626 | Path(id): Path<i64>, |
| 1627 | ) -> Response { |
| 1628 | if let Some(reject) = require_auth(&state, &headers) { |
| 1629 | return reject; |
| 1630 | } |
| 1631 | if let Some(reject) = require_origin(&state, &headers) { |
| 1632 | return reject; |
| 1633 | } |
| 1634 | match crate::scheduler::discard_task(&state.driver(), id).await { |
| 1635 | Ok(_) => ( |
| 1636 | StatusCode::FOUND, |
| 1637 | [(header::LOCATION, format!("/tasks/{id}"))], |
| 1638 | "discarded", |
| 1639 | ) |
| 1640 | .into_response(), |
| 1641 | Err(e) => (StatusCode::NOT_FOUND, e).into_response(), |
| 1642 | } |
| 1643 | } |
| 1644 | |
| 1645 | async fn retry_route( |
| 1646 | State(state): State<AppState>, |
| 1647 | headers: HeaderMap, |
| 1648 | Path(id): Path<i64>, |
| 1649 | ) -> Response { |
| 1650 | if let Some(reject) = require_auth(&state, &headers) { |
| 1651 | return reject; |
| 1652 | } |
| 1653 | if let Some(reject) = require_origin(&state, &headers) { |
| 1654 | return reject; |
| 1655 | } |
| 1656 | let Some(old) = state.store.get_task(id).unwrap_or(None) else { |
| 1657 | return (StatusCode::NOT_FOUND, "task not found").into_response(); |
| 1658 | }; |
| 1659 | if !old.status.is_terminal() { |
| 1660 | return (StatusCode::BAD_REQUEST, "task is still running").into_response(); |
| 1661 | } |
| 1662 | let new_id = match state.store.create_task( |
| 1663 | &old.title, |
| 1664 | &old.prompt, |
| 1665 | &old.module_scope, |
| 1666 | &old.model, |
| 1667 | old.budget_steps, |
| 1668 | old.budget_usd, |
| 1669 | ) { |
| 1670 | Ok(v) => v, |
| 1671 | Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e).into_response(), |
| 1672 | }; |
| 1673 | let branch = branch_name(new_id, &old.title); |
| 1674 | let _ = state.store.set_branch(new_id, &branch); |
| 1675 | state.driver().emit(new_id, EVENT_STATUS, |
| 1676 | serde_json::json!({"message": format!("retried from task #{id}")}), |
| 1677 | ); |
| 1678 | ( |
| 1679 | StatusCode::FOUND, |
| 1680 | [(header::LOCATION, format!("/tasks/{new_id}"))], |
| 1681 | "queued", |
| 1682 | ) |
| 1683 | .into_response() |
| 1684 | } |
| 1685 | |
| 1686 | /// `POST /tasks/:id/plan/approve` — approve the parked plan (only in |
| 1687 | /// `needs_input(plan)`). Sets `plan_approved=1` and posts "approved" via the |
| 1688 | /// tagged inbox/requeue path, so races behave like other messages and the |
| 1689 | /// pending `propose_plan` call resumes with "Plan approved. Proceed.". |
| 1690 | async fn plan_approve_route( |
| 1691 | State(state): State<AppState>, |
| 1692 | headers: HeaderMap, |
| 1693 | Path(id): Path<i64>, |
| 1694 | ) -> Response { |
| 1695 | if let Some(reject) = require_auth(&state, &headers) { |
| 1696 | return reject; |
| 1697 | } |
| 1698 | if let Some(reject) = require_origin(&state, &headers) { |
| 1699 | return reject; |
| 1700 | } |
| 1701 | match crate::scheduler::approve_task(&state.driver(), id, "plan").await { |
| 1702 | Ok(_) => ( |
| 1703 | StatusCode::FOUND, |
| 1704 | [(header::LOCATION, format!("/tasks/{id}"))], |
| 1705 | "plan approved", |
| 1706 | ) |
| 1707 | .into_response(), |
| 1708 | Err(e) => (StatusCode::BAD_REQUEST, e).into_response(), |
| 1709 | } |
| 1710 | } |
| 1711 | |
| 1712 | #[derive(Deserialize)] |
| 1713 | struct PlanChangesForm { |
| 1714 | text: String, |
| 1715 | } |
| 1716 | |
| 1717 | /// `POST /tasks/:id/plan/changes` — request plan changes (only in |
| 1718 | /// `needs_input(plan)`). The text goes through the tagged inbox/requeue path; |
| 1719 | /// the pending `propose_plan` call resumes with "User requested changes to |
| 1720 | /// the plan: …" and `plan_approved` stays 0. |
| 1721 | async fn plan_changes_route( |
| 1722 | State(state): State<AppState>, |
| 1723 | headers: HeaderMap, |
| 1724 | Path(id): Path<i64>, |
| 1725 | Form(form): Form<PlanChangesForm>, |
| 1726 | ) -> Response { |
| 1727 | if let Some(reject) = require_auth(&state, &headers) { |
| 1728 | return reject; |
| 1729 | } |
| 1730 | if let Some(reject) = require_origin(&state, &headers) { |
| 1731 | return reject; |
| 1732 | } |
| 1733 | let text = form.text.trim().to_string(); |
| 1734 | if text.is_empty() { |
| 1735 | return (StatusCode::BAD_REQUEST, "changes text is required").into_response(); |
| 1736 | } |
| 1737 | let Some(task) = state.store.get_task(id).unwrap_or(None) else { |
| 1738 | return (StatusCode::NOT_FOUND, "task not found").into_response(); |
| 1739 | }; |
| 1740 | if task.status != TaskStatus::NeedsInput |
| 1741 | || task.pending.as_ref().map(|p| p.kind.as_str()) != Some(crate::models::PENDING_PLAN) |
| 1742 | { |
| 1743 | return (StatusCode::BAD_REQUEST, "no plan awaiting review").into_response(); |
| 1744 | } |
| 1745 | match state.store.inbox_post_kind(id, &text, INBOX_PLAN_CHANGES) { |
| 1746 | Ok(_) => ( |
| 1747 | StatusCode::FOUND, |
| 1748 | [(header::LOCATION, format!("/tasks/{id}"))], |
| 1749 | "changes requested", |
| 1750 | ) |
| 1751 | .into_response(), |
| 1752 | Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e).into_response(), |
| 1753 | } |
| 1754 | } |
| 1755 | |
| 1756 | /// `POST /tasks/:id/approve` — approve the review (only in `review`): push |
| 1757 | /// `refs/agent-wip/<id>` → `refs/heads/<branch>`, mark `succeeded`. On push |
| 1758 | /// failure the task stays in `review` and the error is shown. |
| 1759 | async fn review_approve_route( |
| 1760 | State(state): State<AppState>, |
| 1761 | headers: HeaderMap, |
| 1762 | Path(id): Path<i64>, |
| 1763 | ) -> Response { |
| 1764 | if let Some(reject) = require_auth(&state, &headers) { |
| 1765 | return reject; |
| 1766 | } |
| 1767 | if let Some(reject) = require_origin(&state, &headers) { |
| 1768 | return reject; |
| 1769 | } |
| 1770 | match crate::scheduler::approve_task(&state.driver(), id, "review").await { |
| 1771 | Ok(_) => ( |
| 1772 | StatusCode::FOUND, |
| 1773 | [(header::LOCATION, format!("/tasks/{id}"))], |
| 1774 | "approved and pushed", |
| 1775 | ) |
| 1776 | .into_response(), |
| 1777 | Err(e) => (StatusCode::BAD_REQUEST, e).into_response(), |
| 1778 | } |
| 1779 | } |