Skip to main content

agentmux_srv/server/prep/
window.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One window's task: ask the agent, then wait for whichever comes first (spec ยง3.5). It is the only
5//! place a window's closure is taken and run, so it runs once, and the deadline is the one thing that
6//! always ends the wait: no state of the agent holds the person's action back.
7
8use std::time::Duration;
9use tokio::time::Instant;
10
11use crate::server::AppState;
12
13use super::ledger::{self, audit, clear_meta, finish_row};
14use super::{note, How, AUDIT_ANSWERED, EXTENDED_WINDOW, WINDOW};
15
16/// How often the window looks for the end of the turn once the agent has answered.
17#[cfg(not(test))]
18const POLL: Duration = Duration::from_millis(250);
19#[cfg(test)]
20const POLL: Duration = Duration::from_millis(10);
21
22/// Whether any of the agent's panes is in a turn.
23async fn in_a_turn(state: &AppState, blocks: Vec<String>) -> bool {
24    let state = state.clone();
25    tokio::task::spawn_blocking(move || blocks.iter().any(|b| crate::backend::agent_state::in_turn(&state.mstore, b))).await.unwrap_or(false)
26}
27
28/// One system note that starts a turn on the agent `route`. Tests catch the notes for the routes they name.
29pub(super) fn send_note(state: &AppState, route: &str, text: &str) -> Result<(), String> {
30    #[cfg(test)]
31    if let Some(sent) = super::tests::sink::deliver(route, text) {
32        return sent;
33    }
34    state.reactive_handler.deliver_system_note(route, text)
35}
36
37/// Send the note that starts the agent's turn. `false` when it could not be delivered.
38async fn ask(state: &AppState, def_id: &str, id: &str) -> bool {
39    let Some(prep) = ledger::with(def_id, id, |e| e.prep.clone()) else { return true };
40    let text = note::ask(&prep, id, WINDOW.as_secs(), EXTENDED_WINDOW.as_secs());
41    let route = agentmux_common::slug::agent_route_name(&prep.agent_name);
42    let state = state.clone();
43    match tokio::task::spawn_blocking(move || send_note(&state, &route, &text)).await {
44        Ok(Ok(())) => true,
45        Ok(Err(e)) => {
46            tracing::warn!(agent = %prep.agent_name, error = %e, "prep: the agent could not be asked; the change goes ahead");
47            false
48        }
49        Err(_) => false,
50    }
51}
52
53/// End the window: take it out of the ledger, clear the chip, write the row, and run the closure.
54async fn finish(state: &AppState, def_id: &str, id: &str, how: How) {
55    let (state, def_id, id) = (state.clone(), def_id.to_string(), id.to_string());
56    let _ = tokio::task::spawn_blocking(move || {
57        let Some((mut entry, _closing)) = ledger::take(&def_id, &id) else { return };
58        let proceed = entry.proceed.take();
59        let (who, reason) = finish_row(&entry, how);
60        clear_meta(&state, &entry.prep);
61        audit(&state, &entry.prep, &entry.id, &who, AUDIT_ANSWERED, &reason);
62        tracing::info!(agent = %entry.prep.agent_name, prep = %entry.id, how = ?how, "prep: the window ended");
63        if let Some(proceed) = proceed {
64            proceed(how);
65        }
66    })
67    .await;
68}
69
70/// What one look at the window found.
71struct Snapshot {
72    until: Instant,
73    ready: bool,
74    now: bool,
75    blocks: Vec<String>,
76}
77
78pub(super) async fn run(state: AppState, def_id: String, id: String) {
79    let Some(wake) = ledger::with(&def_id, &id, |e| e.wake.clone()) else { return };
80    if !ask(&state, &def_id, &id).await {
81        return finish(&state, &def_id, &id, How::NotAsked).await;
82    }
83    loop {
84        let Some(snap) = ledger::with(&def_id, &id, |e| Snapshot { until: e.until, ready: e.ready, now: e.now, blocks: e.prep.blocks.clone() }) else {
85            return; // cancelled, or replaced by a newer window
86        };
87        let how = if snap.now {
88            Some(How::PersonSaidNow)
89        } else if snap.ready && !in_a_turn(&state, snap.blocks).await {
90            Some(How::Ready)
91        } else if Instant::now() >= snap.until {
92            Some(How::TimedOut)
93        } else {
94            None
95        };
96        if let Some(how) = how {
97            return finish(&state, &def_id, &id, how).await;
98        }
99        let left = snap.until.saturating_duration_since(Instant::now());
100        let nap = if snap.ready { POLL.min(left) } else { left };
101        tokio::select! {
102            _ = wake.notified() => {}
103            _ = tokio::time::sleep(nap) => {}
104        }
105    }
106}