eclipse-web 0.13.2

Local web dashboard for eclipse
Documentation
//! `#173` in the dashboard: the gateway owns the timer.
//!
//! A loop started from the browser is not owned by the browser. The tab can be closed, the page
//! reloaded, the laptop shut — the record lives in `<root>/state/loops/<session>.json`, and this
//! module is the thing that reads it on a clock and sends the prompt back into the session. That
//! is the whole difference from the terminal: there, the timer dies with the process that owns the
//! conversation, which is the honest answer for a CLI. Here the process outlives the window.
//!
//! Two rules shape it.
//!
//! **A tick has nobody watching its stream.** The chat route streams a turn to a browser tab over
//! SSE; a tick fires while no tab is listening, so it runs with a sink that drops its events and
//! its reply lands in the store, where the page shows it on the next load. That is stated on the
//! row `/loop` answers with rather than left to be discovered.
//!
//! **A tick cannot ask for an approval.** `WebApprover` parks a call until a browser answers it,
//! and there is no browser; parking forever would be worse than refusing. So a tick runs under
//! [`Unattended`], which denies every call that would have needed a card — with the reason, so the
//! model can say what it could not do instead of failing silently.

use crate::app::{AppState, Shared};
use eclipse_core::approvals::Decision;
use eclipse_core::loops::{self, Owner, State, Status};
use eclipse_core::runtime::{AgentEvent, RunOptions};
use eclipse_core::tools::Approver;
use eclipse_core::{approvals::Pending, cancel::Cancel, Agent};
use std::path::PathBuf;
use std::sync::Arc;

/// How often the record is looked at. A loop's shortest interval is a minute, so a few seconds of
/// lag is invisible and a tighter poll would read the disk for nothing.
const POLL: std::time::Duration = std::time::Duration::from_secs(5);

/// Start the sweeper. Called once, by whatever serves the dashboard, and it runs for the life of
/// the process: an ended loop writes `Ended` to its record, so there is nothing to cancel per loop.
pub fn spawn(st: Shared) {
    tokio::spawn(async move {
        loop {
            sweep(&st).await;
            tokio::time::sleep(POLL).await;
        }
    });
}

/// One pass: everything due, fired off. Each tick runs in its own task so a slow turn in one
/// session does not delay the next tick of another.
///
/// Two kinds of work are due here, and they are the same machinery: a `/loop` record whose
/// `next_due_ms` has passed, and a `/goal` row that is active and under its budget (`#172`). A
/// goal is "due" the moment the previous turn was judged "continue", which is why it needs no
/// clock — the row is the schedule.
async fn sweep(st: &Shared) {
    sweep_goals(st).await;
    sweep_loops(st).await;
}

/// `#172`: every active goal that owes a turn gets one.
async fn sweep_goals(st: &Shared) {
    let live = match st.store.live_goals() {
        Ok(live) => live,
        Err(_) => return,
    };
    for goal in live {
        if !goal.wants_turn() {
            continue;
        }
        let session = goal.session.clone();
        if !st.claim_tick(&session) {
            continue;
        }
        let st = st.clone();
        let prompt = goal.continuation_prompt();
        tokio::spawn(async move {
            goal_turn(st.clone(), &session, &prompt).await;
            st.release_tick(&session);
        });
    }
}

/// One goal turn: the run, and nothing else — the judge happens inside the runtime, at the end of
/// the run, so a goal's next turn is decided by the same code whichever front started it.
async fn goal_turn(st: Shared, session: &str, prompt: &str) {
    let Some(agent) = st.agent.clone() else {
        return;
    };
    let _ = run_turn(&st, &agent, session, prompt).await;
}

/// `#173`: every loop record whose next tick has passed.
async fn sweep_loops(st: &Shared) {
    let Some(root) = st.cron_root.clone() else {
        return;
    };
    let now = eclipse_core::session::now_ms() as i64;
    let found = match loops::all(&root) {
        Ok(found) => found,
        Err(_) => return,
    };
    for state in found {
        if state.owner != Owner::Gateway || state.status != Status::Running || !state.due(now) {
            continue;
        }
        // Claimed before the spawn, released when the tick ends: two sweeps cannot both fire the
        // same loop, and the record on disk is not read-and-written by two of them at once.
        let session = state.session.clone();
        if !st.claim_tick(&session) {
            continue;
        }
        let st = st.clone();
        let root = root.clone();
        tokio::spawn(async move {
            tick(st.clone(), root, state, now).await;
            st.release_tick(&session);
        });
    }
}

/// One tick: probe, run, record.
async fn tick(st: Shared, root: PathBuf, mut state: State, now: i64) {
    let Some(agent) = st.agent.clone() else {
        return;
    };
    let session = state.session.clone();
    match agent.loop_tick_begin(&root, &mut state, now) {
        Ok(true) => {}
        Ok(false) => {
            // Busy: the record already says so, and the next tick still fires on schedule.
            return;
        }
        Err(_) => return,
    }
    let prompt = state.prompt.clone();
    let result = run_turn(&st, &agent, &session, &prompt).await;
    let _ = agent.loop_tick_end(&root, &mut state, now, result).await;
}

/// One turn, quiet: no SSE stream to feed, and an approver that refuses rather than waits.
async fn run_turn(
    st: &Shared,
    agent: &Arc<Agent>,
    session: &str,
    prompt: &str,
) -> Result<Option<String>, String> {
    let Some(_permit) = st.try_chat_slot() else {
        return Err("every chat slot was busy".to_string());
    };
    let cancel = Cancel::new();
    let sink = |_: AgentEvent| {};
    let opts = RunOptions {
        resume: false,
        // A tick is not the session's opening message: the name belongs to whoever opened it.
        title: false,
        ..RunOptions::default()
    };
    match agent
        .run_cancellable_with(Some(session), prompt, &Unattended, &sink, &cancel, &opts)
        .await
    {
        Ok(_) => Ok(last_reply(agent, session)),
        Err(eclipse_core::Error::Cancelled) => Err("the tick was cancelled".to_string()),
        Err(e) => Err(format!("{e:#}")),
    }
}

/// The reply the check reads. The transcript is the place it still exists once the sink has been
/// dropped, and it is the same text the page will show.
fn last_reply(agent: &Agent, session: &str) -> Option<String> {
    let records = agent.store().load_records(session).ok()?;
    records.iter().rev().find_map(|record| {
        let text = record.message.content.clone().unwrap_or_default();
        (record.message.role == eclipse_core::message::Role::Assistant && !text.trim().is_empty())
            .then_some(text)
    })
}

/// The approver a tick runs under: every call that would have needed a card is refused.
///
/// Denying is the only honest answer. Allowing would turn a scheduled prompt into unattended
/// consent to run anything the model chose; parking would hold the run open until the server
/// stopped. The refusal's own words reach the model as the tool result, so the turn can report
/// what it could not do.
struct Unattended;

#[async_trait::async_trait]
impl Approver for Unattended {
    async fn decide(&self, _call: &Pending) -> Decision {
        Decision::Deny(
            "a `/loop` tick in the gateway runs with nobody watching, so this call is refused: \
             approvals need a person, and a person is at the terminal, not on a timer"
                .to_string(),
        )
    }
}

/// The row `/loop …` answers with, from the record: the same verb handling the terminal gets,
/// with `Owner::Gateway` so the record names the process that will actually drive it.
pub fn manage(st: &AppState, session: Option<&str>, arg: &str) -> Result<String, String> {
    let root = st
        .cron_root
        .clone()
        .ok_or_else(|| "this dashboard was started without an install root".to_string())?;
    // A loop belongs to a session, and the page only has one after its first message: a loop
    // started now would tick into a session the page is not showing, and the browser has no way to
    // name it back. So the refusal says what to do instead of quietly making one.
    let Some(id) = session.filter(|s| !s.is_empty()) else {
        return Ok(
            "no session yet — send a message first, then `/loop 2m <prompt>` starts a loop in it"
                .to_string(),
        );
    };
    let now = eclipse_core::session::now_ms() as i64;
    loops::manage(&root, id, arg, Owner::Gateway, now).map_err(|e| format!("{e:#}"))
}