rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! `rho/job/list`: every job the daemon keeps, read once or followed.
//!
//! A followed list comes from one feed the daemon shares across
//! connections. While any connection follows, one task builds the list
//! again whenever a job is added, moves or is forgotten, and every
//! [`LIVE_TICK`] while a turn is under way or a session is loaded, for what
//! changes without the registry hearing of it: a job's `live` state, such
//! as a title written after its turn, its place in a queue, a workflow
//! result delivered. It publishes the list when it differs; each
//! connection's forwarder sends what changed of it (`rho_protocol`'s
//! `watch_forward.rs`). With no connection following, nothing runs; with
//! nothing loaded or under way, only registry changes do, and a worktree
//! gone stale shows at the next one.

use std::{
    sync::{Arc, Mutex, PoisonError},
    time::Duration,
};

use rho_protocol::{JobListResponse, JobWatch};
use tokio::sync::watch;

use super::{
    jobs::{self, JobRegistry, JobState, JobSubject},
    sessions::{worktree_stale, Sessions},
    wire,
};

/// How often a followed list is built again for what changes without the
/// registry hearing of it, such as a running turn's elapsed time or a
/// loaded session's title.
//
// Measured on a live daemon (2026-11-30): a whole `rho/job/list` of 786
// jobs took 2.27 ms at the median, 2.55 ms at p90 and 4.27 ms at most over
// 200 round trips, so a tick costs well under 1% of a core, once for all
// followers. Half a second matches the poll it replaces (`RAIL_POLL` in
// `tui/daemon_jobs.rs`).
const LIVE_TICK: Duration = Duration::from_millis(500);

/// Every job, as `rho/job/list` reports them, oldest first.
pub(super) fn list(registry: &JobRegistry, sessions: &Sessions) -> JobListResponse {
    // A drive marks its run finished before its job ends, so a job read
    // first that has ended is already in the tracker read second.
    let records = registry.list();
    let parents = wire::ParentJob::of(&records);
    let undelivered = sessions.undelivered_workflow_runs();
    let in_use = sessions.worktrees_in_use(&records);
    let now = jobs::unix_now();
    JobListResponse {
        jobs: records
            .into_iter()
            .zip(parents)
            .map(|(record, parent)| {
                // Only a job clients see queued is in line: a requeued
                // turn whose background tool asked shows waiting for input.
                let queue = match record.state {
                    JobState::Queued | JobState::Requeued => {
                        sessions.subagents().queue_place(&record.id)
                    }
                    JobState::Idle
                    | JobState::Running
                    | JobState::WaitingForInput
                    | JobState::Ended(_) => None,
                };
                let live = match &record.subject {
                    JobSubject::Session { session } => sessions.session_live(session),
                    // Only the run under way: an ended run of the same
                    // session, as a workflow node that ran again has, is
                    // followed no more.
                    JobSubject::Subagent {
                        session: Some(session),
                        run: _,
                        worktree: _,
                        started_by: _,
                    } if record.state.in_progress() => sessions.subagents().feeds().live(session),
                    JobSubject::Subagent { .. } | JobSubject::Workflow { .. } => None,
                };
                let worktree_stale = worktree_stale(&record, &in_use, now);
                wire::job_summary(record, parent, queue, &undelivered, live, worktree_stale)
            })
            .collect(),
    }
}

/// The followed job list every connection shares.
pub(super) struct JobFeed {
    registry: Arc<JobRegistry>,
    sessions: Arc<Sessions>,
    sender: watch::Sender<Arc<JobListResponse>>,
    /// Whether the task that builds the list runs. Checked with the
    /// receiver count under this lock, so a follower that subscribes as the
    /// last one leaves never finds a task that is about to stop.
    building: Mutex<bool>,
}

impl JobFeed {
    pub(super) fn new(registry: Arc<JobRegistry>, sessions: Arc<Sessions>) -> Arc<Self> {
        let (sender, _) = watch::channel(Arc::new(JobListResponse { jobs: Vec::new() }));
        Arc::new(Self {
            registry,
            sessions,
            sender,
            building: Mutex::new(false),
        })
    }

    /// A follower's watch of the list, built afresh for its answer, and the
    /// task that keeps it current, started if none runs.
    pub(super) fn follow(self: &Arc<Self>) -> JobWatch {
        JobWatch::new(self.subscribe())
    }

    fn subscribe(self: &Arc<Self>) -> watch::Receiver<Arc<JobListResponse>> {
        let mut building = self.building();
        let receiver = self.sender.subscribe();
        self.publish();
        if !*building {
            *building = true;
            tokio::spawn(Arc::clone(self).build());
        }
        receiver
    }

    /// Builds the list again on every change, and every tick while a turn
    /// is under way or a session is loaded, until no connection follows
    /// it.
    async fn build(self: Arc<Self>) {
        let mut tick = tokio::time::interval(LIVE_TICK);
        tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
        loop {
            // Enabled before the list is read, so a change while it builds
            // builds it again.
            let changed = self.registry.changed();
            tokio::pin!(changed);
            changed.as_mut().enable();
            self.publish();
            let live = self.registry.in_progress() > 0 || self.sessions.any_loaded();
            tokio::select! {
                () = changed => {}
                _ = tick.tick(), if live => {}
                () = self.sender.closed() => {
                    let mut building = self.building();
                    if self.sender.receiver_count() == 0 {
                        *building = false;
                        return;
                    }
                }
            }
        }
    }

    /// Publishes the list as it is now, if it differs from the last. Built
    /// under the watch's lock, so of two publishes the later one read
    /// wins.
    fn publish(&self) {
        self.sender.send_if_modified(|current| {
            let next = list(&self.registry, &self.sessions);
            let differs = **current != next;
            if differs {
                *current = Arc::new(next);
            }
            differs
        });
    }

    fn building(&self) -> std::sync::MutexGuard<'_, bool> {
        // Only a bool is written under it, so a panic cannot leave it
        // half-changed.
        self.building.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

#[cfg(test)]
#[path = "job_feed_tests.rs"]
mod tests;