Skip to main content

ag_session/
question.rs

1//! Frontend-neutral clarification question models and selection helpers.
2
3use std::fmt::Write as _;
4
5use ag_protocol::AgentResponse;
6pub use ag_protocol::QuestionItem;
7
8/// Returns the initial highlighted option for a clarification question.
9///
10/// Questions with predefined options begin on the first option; free-text
11/// questions begin with no highlighted option.
12#[must_use]
13pub fn default_option_index(questions: &[QuestionItem], question_index: usize) -> Option<usize> {
14    questions
15        .get(question_index)
16        .filter(|item| !item.options.is_empty())
17        .map(|_| 0)
18}
19
20/// Returns the chat message announcing one graph node's clarification
21/// questions, after the answer they refer to, or `None` when every question
22/// is blank. The numbered questions record what was asked; the frontend
23/// answers them in its question panel, as for an ordinary turn.
24///
25/// Storage records it with the node's response so the visible question and
26/// the reply routing that depends on it commit together.
27#[must_use]
28pub fn node_question_notice(node_id: &str, response: &AgentResponse) -> Option<String> {
29    if response
30        .questions
31        .iter()
32        .all(|question| question.text.trim().is_empty())
33    {
34        return None;
35    }
36    let mut text = String::new();
37    let answer = response.answer.trim();
38    if !answer.is_empty() {
39        let _ = write!(text, "{answer}\n\n");
40    }
41    let _ = write!(text, "`{node_id}` needs your input:");
42    push_numbered_questions(&mut text, &response.questions);
43
44    Some(text)
45}
46
47/// Appends each question on its own numbered line, with any predefined
48/// options in parentheses.
49pub fn push_numbered_questions(text: &mut String, questions: &[QuestionItem]) {
50    for (index, question) in questions.iter().enumerate() {
51        let _ = write!(text, "\n{}. {}", index + 1, question.text);
52        if !question.options.is_empty() {
53            let _ = write!(text, " ({})", question.options.join(" / "));
54        }
55    }
56}
57
58#[cfg(test)]
59#[path = "question_test.rs"]
60mod tests;