Skip to main content

agentmux_srv/server/
reviews_handler.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `GET /api/v1/reviews`: every pull request a Kanban task names, with the review, checks and merge state this srv
5//! was told of and what it waits on (`backend::reviews`, spec `SPEC_REVIEWS_PANE_2026_11_15.md`). A thin route over the
6//! rows the board shows on a card (the card store keeps what each notice said, across restarts), plus the pull
7//! requests only a recent notice named. It calls no GitHub API.
8//!
9//! A caller that is an agent gets the tasks of the boards `Tasks list` shows it and no others, and a PR only an event
10//! named only when the notice went to that agent: a private repository's PR is never given to a caller that can't
11//! see its task. A caller with no token (the app's own windows) gets everything.
12//!
13//! Query: `agent` (the task's holder or the notified agent), `waits_on` (`person`, `author`, ...), `task` (`12`,
14//! `#12`, `work#12`) and `repo` (`owner/repo`), each narrowing the list.
15
16use std::collections::HashSet;
17
18use axum::extract::{Query, State};
19use axum::response::{IntoResponse, Json};
20use serde::Deserialize;
21
22use super::AppState;
23use crate::backend::kanban::FINISHED_WINDOW_MS;
24use crate::backend::pr_flow::PrFlowBy;
25use crate::backend::reviews::{self, ReviewRow, ReviewsChecks, ReviewsList, ReviewsTask, ReviewsVerdict, WaitsOn};
26use crate::backend::storage::work_board::BoardTask;
27
28/// The most tasks read from one board. Each board is read on its own, so a busy board cannot push another's
29/// tasks out of the cut, and a caller's visible boards are the only ones read.
30const TASKS_LIMIT: usize = 500;
31
32#[derive(Debug, Default, Deserialize)]
33pub struct ReviewsQuery {
34    pub agent: Option<String>,
35    pub waits_on: Option<String>,
36    pub task: Option<String>,
37    pub repo: Option<String>,
38}
39
40/// A row for each pull request the cards of `tasks` hold, from what the card store keeps of it (the review, checks and
41/// merge notices it was told of and what it waits on): the same rows the board shows on a card.
42fn card_rows(tasks: &[BoardTask]) -> Vec<ReviewRow> {
43    let by = |name: &str| match name {
44        "bot" => PrFlowBy::Bot,
45        "codex" => PrFlowBy::Codex,
46        _ => PrFlowBy::Person,
47    };
48    let head = |h: &str| (!h.is_empty()).then(|| h.to_string());
49    let mut rows = Vec::new();
50    for t in tasks {
51        let holder = if t.item.claimed_by.is_empty() { &t.item.target_agent } else { &t.item.claimed_by };
52        let task_ref = if t.card.task_ref.is_empty() { format!("#{}", t.card.num) } else { t.card.task_ref.clone() };
53        let released_in = t.card.pr.as_ref().map(|p| p.released_in.clone()).unwrap_or_default();
54        for p in &t.card.prs {
55            let verdicts: Vec<ReviewsVerdict> = p
56                .verdicts
57                .iter()
58                .map(|v| ReviewsVerdict { by: by(&v.by), state: v.state.clone(), head: head(&v.head), at_ms: v.at.max(0) as u64, stale: v.stale })
59                .collect();
60            let checks = (p.checks != "none").then(|| ReviewsChecks { state: p.checks.clone(), head: head(&p.checks_head), at_ms: p.checks_at.max(0) as u64 });
61            let changed = verdicts.iter().map(|v| v.at_ms as i64).chain([p.checks_at, p.flow_at, p.updated_at, t.card.updated_at]).max().unwrap_or(0);
62            rows.push(ReviewRow {
63                repo: Some(p.repo.clone()),
64                repo_id: p.repo_id.map(|id| id as u64),
65                number: p.number,
66                url: Some(p.url.clone()),
67                task: Some(ReviewsTask { task_ref: task_ref.clone(), num: t.card.num, title: t.item.title.clone(), state: t.item.state.clone() }),
68                agent: Some(holder.to_ascii_lowercase()).filter(|a| !a.is_empty()),
69                branch: t.card.branch.clone(),
70                reviews: verdicts,
71                checks,
72                merge: p.merge.clone(),
73                merged_at_ms: p.merged_at,
74                released_in: released_in.clone(),
75                waits_on: WaitsOn::parse(&p.waits_on),
76                why: p.why.clone(),
77                updated_at_ms: changed,
78            });
79        }
80    }
81    rows
82}
83
84/// Whether `task` names `row`'s task. Task numbers are per board, so a bare `12` or `#12` is the default board's
85/// task 12 and another board's is `work#12`.
86fn is_task(row: &ReviewRow, task: &str) -> bool {
87    let want = task.trim().to_ascii_lowercase();
88    let want = if !want.is_empty() && want.trim_start_matches('#').bytes().all(|b| b.is_ascii_digit()) { format!("#{}", want.trim_start_matches('#')) } else { want };
89    row.task.as_ref().is_some_and(|t| t.task_ref.to_ascii_lowercase() == want)
90}
91
92/// Narrows `list` to what `q` asks for.
93fn narrow(mut list: ReviewsList, q: &ReviewsQuery) -> ReviewsList {
94    let lower = |s: &Option<String>| s.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_ascii_lowercase);
95    let (agent, repo) = (lower(&q.agent), lower(&q.repo));
96    let waits = lower(&q.waits_on);
97    let task = q.task.as_deref().map(str::trim).filter(|s| !s.is_empty());
98    list.rows.retain(|r| {
99        agent.as_ref().map_or(true, |a| r.agent.as_deref().map(str::to_ascii_lowercase).as_ref() == Some(a))
100            && repo.as_ref().map_or(true, |p| r.repo.as_deref().map(str::to_ascii_lowercase).as_ref() == Some(p))
101            && waits.as_ref().map_or(true, |w| serde_json::to_value(r.waits_on).ok().and_then(|v| v.as_str().map(str::to_string)).as_deref() == Some(w.as_str()))
102            && task.map_or(true, |t| is_task(r, t))
103    });
104    list
105}
106
107/// The rows of the cards, and after them the pull requests only a notice named (`orphans`: a list built from the
108/// notices alone), newest change first. A notice whose repository id a card settled is that card's, not a row of its
109/// own; a pull request no visible task holds is the caller's only when the notice went to it.
110fn join(mut rows: Vec<ReviewRow>, orphans: ReviewsList, caller: Option<&str>) -> ReviewsList {
111    let held: HashSet<(u64, u64)> = rows.iter().filter_map(|r| r.repo_id.map(|id| (id, r.number))).collect();
112    rows.extend(orphans.rows.into_iter().filter(|r| {
113        let settled = r.repo_id.is_some_and(|id| held.contains(&(id, r.number)));
114        !settled && caller.map_or(true, |c| r.agent.as_deref().is_some_and(|a| a.eq_ignore_ascii_case(c)))
115    }));
116    rows.sort_by(|a, b| b.updated_at_ms.cmp(&a.updated_at_ms).then(a.number.cmp(&b.number)));
117    ReviewsList { rows, as_of_ms: orphans.as_of_ms, last_notice_at_ms: orphans.last_notice_at_ms }
118}
119
120pub async fn handle_reviews(
121    State(state): State<AppState>,
122    caller: Option<axum::Extension<super::caller::Caller>>,
123    Query(q): Query<ReviewsQuery>,
124) -> impl IntoResponse {
125    let who = super::work_tasks::viewer(&state, caller.as_deref());
126    let work = state.work_store.clone();
127    let now = agentmux_common::time::now_ms();
128    let list = tokio::task::spawn_blocking(move || {
129        let boards = work.work_boards_list(true, now).unwrap_or_default();
130        let seen: Vec<_> = boards.into_iter().filter(|b| who.as_ref().map_or(true, |(agent, uid)| b.visible_to(agent, uid))).collect();
131        let mut tasks: Vec<_> = Vec::new();
132        let mut read: HashSet<String> = HashSet::new();
133        for board in &seen {
134            if read.insert(board.id.clone()) {
135                tasks.extend(work.work_board_list_in(Some(board.id.as_str()), now - FINISHED_WINDOW_MS, TASKS_LIMIT, now).unwrap_or_default());
136            }
137        }
138        join(card_rows(&tasks), reviews::build(&[], &crate::backend::pr_flow::recent(), now), who.as_ref().map(|(agent, _)| agent.as_str()))
139    })
140    .await
141    .unwrap_or_default();
142    Json(narrow(list, &q))
143}
144
145#[cfg(test)]
146#[path = "reviews_handler_tests.rs"]
147mod tests;