rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The questions a session that reports to its starter asked without
//! waiting, kept on its job until a turn took their answers (see
//! `sessions/self_questions.rs`), so a daemon restart opens them again,
//! under the session that held each, and delivers an answer no turn took.

use serde::{Deserialize, Serialize};

use super::{persist, JobRecord, JobRegistry};
use crate::app::{daemon_host::jobs::JobId, self_questions::QuestionId};

/// One question as the job keeps it ([`JobRecord::questions`]).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(in crate::app::daemon_host) struct SavedQuestion {
    pub(in crate::app::daemon_host) id: QuestionId,
    /// The `questionnaire` call's arguments, which open it again.
    pub(in crate::app::daemon_host) arguments: serde_json::Value,
    /// What it asks: its title, else its first question's prompt.
    pub(in crate::app::daemon_host) ask: String,
    #[serde(flatten)]
    pub(in crate::app::daemon_host) state: QuestionState,
}

/// Where a saved question stands.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub(in crate::app::daemon_host) enum QuestionState {
    /// Its answer is still to come. `held_by` is the session that holds
    /// it, as last given it; `None` for the person. A holder that unloads
    /// gives its questions to the person in memory only, so this keeps who
    /// held it before a restart.
    Open {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        held_by: Option<HeldBy>,
    },
    /// It was answered with `answer`, as the model reads it, which no turn
    /// took yet; the question is dropped once one does.
    Answered { answer: String },
}

/// The session a question was given to.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(in crate::app::daemon_host) struct HeldBy {
    pub(in crate::app::daemon_host) session: rho_sdk::SessionId,
    /// The session that passed it up, having left it unanswered; `None`
    /// when the asking session's starter was told of it as it was asked.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(in crate::app::daemon_host) passed_by: Option<rho_sdk::SessionId>,
}

impl JobRegistry {
    /// Job `id`'s session asked `question`.
    pub(in crate::app::daemon_host) fn ask_question(&self, id: &JobId, question: SavedQuestion) {
        self.change_questions(id, |questions| {
            questions.push(question);
            true
        });
    }

    /// Job `id`'s question `question` was given to `held_by`.
    pub(in crate::app::daemon_host) fn hold_question(
        &self,
        id: &JobId,
        question: &QuestionId,
        held_by: Option<HeldBy>,
    ) {
        self.change_questions(id, |questions| {
            let Some(QuestionState::Open { held_by: saved }) =
                find(questions, question).map(|saved| &mut saved.state)
            else {
                return false;
            };
            let changed = *saved != held_by;
            *saved = held_by;
            changed
        });
    }

    /// Job `id`'s question `question` was answered with `answer`.
    pub(in crate::app::daemon_host) fn answer_saved_question(
        &self,
        id: &JobId,
        question: &QuestionId,
        answer: String,
    ) {
        self.change_questions(id, |questions| {
            find(questions, question).is_some_and(|saved| {
                saved.state = QuestionState::Answered { answer };
                true
            })
        });
    }

    /// A turn of job `id`'s session took the answer to `question`.
    pub(in crate::app::daemon_host) fn close_question(&self, id: &JobId, question: &QuestionId) {
        self.change_questions(id, |questions| {
            let before = questions.len();
            questions.retain(|saved| saved.id != *question);
            questions.len() != before
        });
    }

    /// The questions job `id`'s session asked whose answers no turn took
    /// yet, oldest first.
    pub(in crate::app::daemon_host) fn questions_of(&self, id: &JobId) -> Vec<SavedQuestion> {
        self.lock()
            .get(id)
            .map(|record| record.questions.clone())
            .unwrap_or_default()
    }

    /// Changes job `id`'s questions with `change`, saving the record when
    /// it says it changed them.
    fn change_questions(&self, id: &JobId, change: impl FnOnce(&mut Vec<SavedQuestion>) -> bool) {
        let mut jobs = self.lock();
        if let Some(record) = jobs.get_mut(id) {
            if change(&mut record.questions) {
                persist(&self.store, record);
            }
        }
    }
}

/// What the first of `record`'s questions still waiting for an answer
/// asks, if one waits.
pub(super) fn waits_on(record: &JobRecord) -> Option<String> {
    record
        .questions
        .iter()
        .find(|saved| matches!(saved.state, QuestionState::Open { .. }))
        .map(|saved| saved.ask.clone())
}

fn find<'a>(questions: &'a mut [SavedQuestion], id: &QuestionId) -> Option<&'a mut SavedQuestion> {
    questions.iter_mut().find(|saved| saved.id == *id)
}

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