Skip to main content

eclipse_web/
loops_gateway.rs

1//! `#173` in the dashboard: the gateway owns the timer.
2//!
3//! A loop started from the browser is not owned by the browser. The tab can be closed, the page
4//! reloaded, the laptop shut — the record lives in `<root>/state/loops/<session>.json`, and this
5//! module is the thing that reads it on a clock and sends the prompt back into the session. That
6//! is the whole difference from the terminal: there, the timer dies with the process that owns the
7//! conversation, which is the honest answer for a CLI. Here the process outlives the window.
8//!
9//! Two rules shape it.
10//!
11//! **A tick has nobody watching its stream.** The chat route streams a turn to a browser tab over
12//! SSE; a tick fires while no tab is listening, so it runs with a sink that drops its events and
13//! its reply lands in the store, where the page shows it on the next load. That is stated on the
14//! row `/loop` answers with rather than left to be discovered.
15//!
16//! **A tick cannot ask for an approval.** `WebApprover` parks a call until a browser answers it,
17//! and there is no browser; parking forever would be worse than refusing. So a tick runs under
18//! [`Unattended`], which denies every call that would have needed a card — with the reason, so the
19//! model can say what it could not do instead of failing silently.
20
21use crate::app::{AppState, Shared};
22use eclipse_core::approvals::Decision;
23use eclipse_core::loops::{self, Owner, State, Status};
24use eclipse_core::runtime::{AgentEvent, RunOptions};
25use eclipse_core::tools::Approver;
26use eclipse_core::{approvals::Pending, cancel::Cancel, Agent};
27use std::path::PathBuf;
28use std::sync::Arc;
29
30/// How often the record is looked at. A loop's shortest interval is a minute, so a few seconds of
31/// lag is invisible and a tighter poll would read the disk for nothing.
32const POLL: std::time::Duration = std::time::Duration::from_secs(5);
33
34/// Start the sweeper. Called once, by whatever serves the dashboard, and it runs for the life of
35/// the process: an ended loop writes `Ended` to its record, so there is nothing to cancel per loop.
36pub fn spawn(st: Shared) {
37    tokio::spawn(async move {
38        loop {
39            sweep(&st).await;
40            tokio::time::sleep(POLL).await;
41        }
42    });
43}
44
45/// One pass: everything due, fired off. Each tick runs in its own task so a slow turn in one
46/// session does not delay the next tick of another.
47///
48/// Two kinds of work are due here, and they are the same machinery: a `/loop` record whose
49/// `next_due_ms` has passed, and a `/goal` row that is active and under its budget (`#172`). A
50/// goal is "due" the moment the previous turn was judged "continue", which is why it needs no
51/// clock — the row is the schedule.
52async fn sweep(st: &Shared) {
53    sweep_goals(st).await;
54    sweep_loops(st).await;
55}
56
57/// `#172`: every active goal that owes a turn gets one.
58async fn sweep_goals(st: &Shared) {
59    let live = match st.store.live_goals() {
60        Ok(live) => live,
61        Err(_) => return,
62    };
63    for goal in live {
64        if !goal.wants_turn() {
65            continue;
66        }
67        let session = goal.session.clone();
68        if !st.claim_tick(&session) {
69            continue;
70        }
71        let st = st.clone();
72        let prompt = goal.continuation_prompt();
73        tokio::spawn(async move {
74            goal_turn(st.clone(), &session, &prompt).await;
75            st.release_tick(&session);
76        });
77    }
78}
79
80/// One goal turn: the run, and nothing else — the judge happens inside the runtime, at the end of
81/// the run, so a goal's next turn is decided by the same code whichever front started it.
82async fn goal_turn(st: Shared, session: &str, prompt: &str) {
83    let Some(agent) = st.agent.clone() else {
84        return;
85    };
86    let _ = run_turn(&st, &agent, session, prompt).await;
87}
88
89/// `#173`: every loop record whose next tick has passed.
90async fn sweep_loops(st: &Shared) {
91    let Some(root) = st.cron_root.clone() else {
92        return;
93    };
94    let now = eclipse_core::session::now_ms() as i64;
95    let found = match loops::all(&root) {
96        Ok(found) => found,
97        Err(_) => return,
98    };
99    for state in found {
100        if state.owner != Owner::Gateway || state.status != Status::Running || !state.due(now) {
101            continue;
102        }
103        // Claimed before the spawn, released when the tick ends: two sweeps cannot both fire the
104        // same loop, and the record on disk is not read-and-written by two of them at once.
105        let session = state.session.clone();
106        if !st.claim_tick(&session) {
107            continue;
108        }
109        let st = st.clone();
110        let root = root.clone();
111        tokio::spawn(async move {
112            tick(st.clone(), root, state, now).await;
113            st.release_tick(&session);
114        });
115    }
116}
117
118/// One tick: probe, run, record.
119async fn tick(st: Shared, root: PathBuf, mut state: State, now: i64) {
120    let Some(agent) = st.agent.clone() else {
121        return;
122    };
123    let session = state.session.clone();
124    match agent.loop_tick_begin(&root, &mut state, now) {
125        Ok(true) => {}
126        Ok(false) => {
127            // Busy: the record already says so, and the next tick still fires on schedule.
128            return;
129        }
130        Err(_) => return,
131    }
132    let prompt = state.prompt.clone();
133    let result = run_turn(&st, &agent, &session, &prompt).await;
134    let _ = agent.loop_tick_end(&root, &mut state, now, result).await;
135}
136
137/// One turn, quiet: no SSE stream to feed, and an approver that refuses rather than waits.
138async fn run_turn(
139    st: &Shared,
140    agent: &Arc<Agent>,
141    session: &str,
142    prompt: &str,
143) -> Result<Option<String>, String> {
144    let Some(_permit) = st.try_chat_slot() else {
145        return Err("every chat slot was busy".to_string());
146    };
147    let cancel = Cancel::new();
148    let sink = |_: AgentEvent| {};
149    let opts = RunOptions {
150        resume: false,
151        // A tick is not the session's opening message: the name belongs to whoever opened it.
152        title: false,
153        ..RunOptions::default()
154    };
155    match agent
156        .run_cancellable_with(Some(session), prompt, &Unattended, &sink, &cancel, &opts)
157        .await
158    {
159        Ok(_) => Ok(last_reply(agent, session)),
160        Err(eclipse_core::Error::Cancelled) => Err("the tick was cancelled".to_string()),
161        Err(e) => Err(format!("{e:#}")),
162    }
163}
164
165/// The reply the check reads. The transcript is the place it still exists once the sink has been
166/// dropped, and it is the same text the page will show.
167fn last_reply(agent: &Agent, session: &str) -> Option<String> {
168    let records = agent.store().load_records(session).ok()?;
169    records.iter().rev().find_map(|record| {
170        let text = record.message.content.clone().unwrap_or_default();
171        (record.message.role == eclipse_core::message::Role::Assistant && !text.trim().is_empty())
172            .then_some(text)
173    })
174}
175
176/// The approver a tick runs under: every call that would have needed a card is refused.
177///
178/// Denying is the only honest answer. Allowing would turn a scheduled prompt into unattended
179/// consent to run anything the model chose; parking would hold the run open until the server
180/// stopped. The refusal's own words reach the model as the tool result, so the turn can report
181/// what it could not do.
182struct Unattended;
183
184#[async_trait::async_trait]
185impl Approver for Unattended {
186    async fn decide(&self, _call: &Pending) -> Decision {
187        Decision::Deny(
188            "a `/loop` tick in the gateway runs with nobody watching, so this call is refused: \
189             approvals need a person, and a person is at the terminal, not on a timer"
190                .to_string(),
191        )
192    }
193}
194
195/// The row `/loop …` answers with, from the record: the same verb handling the terminal gets,
196/// with `Owner::Gateway` so the record names the process that will actually drive it.
197pub fn manage(st: &AppState, session: Option<&str>, arg: &str) -> Result<String, String> {
198    let root = st
199        .cron_root
200        .clone()
201        .ok_or_else(|| "this dashboard was started without an install root".to_string())?;
202    // A loop belongs to a session, and the page only has one after its first message: a loop
203    // started now would tick into a session the page is not showing, and the browser has no way to
204    // name it back. So the refusal says what to do instead of quietly making one.
205    let Some(id) = session.filter(|s| !s.is_empty()) else {
206        return Ok(
207            "no session yet — send a message first, then `/loop 2m <prompt>` starts a loop in it"
208                .to_string(),
209        );
210    };
211    let now = eclipse_core::session::now_ms() as i64;
212    loops::manage(&root, id, arg, Owner::Gateway, now).map_err(|e| format!("{e:#}"))
213}