eclipse-cli 0.13.4

Command-line interface for eclipse
//! `/retry`: run the last question again, without asking it twice.
//!
//! A failed turn — a 502, a refusal, a cancelled run, a tool that died — is the common case, and
//! the old way to try again was ↑ Enter, which appends the same text to the transcript *and* to the
//! session store. The session then reads as if the question was asked twice, and compaction sees
//! two questions where there was one.
//!
//! The store is the only place that can answer "what was the last question", because the store is
//! what the model is fed: the readline history knows what was typed, not what the session actually
//! contains. So `/retry` reads it from there and runs it with `RunOptions::resume`, which appends
//! no user message — the second attempt's assistant and tool rows join the same question.
//!
//! Both front ends ask this module, so the refusals are worded once.

use eclipse_core::message::Role;
use eclipse_core::session::SessionStore;

/// What `/retry` decided: the question to run again, or why it will not.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Retry {
    /// The last question, as it was stored.
    Ask(String),
    /// Shown to the person. A retry that silently does nothing is worse than one that says why.
    Refused(String),
}

/// The last question in `session`, or a refusal that names what is in the way.
pub fn target(store: &SessionStore, session: Option<&str>) -> Retry {
    let Some(id) = session else {
        return Retry::Refused("nothing to retry: this session has no turns yet".into());
    };
    let records = match store.load_records(id) {
        Ok(records) => records,
        // A session id the store does not know is one this process made up and never wrote to.
        Err(e) => return Retry::Refused(format!("nothing to retry: {e}")),
    };
    // A run answering its own approval prompt is not finished: it is waiting for a person. Running
    // the question again underneath it would put two loops on the same history.
    if let Some(last) = records.last() {
        if last.message.role == Role::Assistant && !last.message.tool_calls.is_empty() {
            return Retry::Refused(
                "the last run is parked on a tool call: answer the approval prompt, then /retry"
                    .into(),
            );
        }
    }
    match records
        .iter()
        .rev()
        .find(|r| r.message.role == Role::User)
        .map(|r| r.message.content.clone().unwrap_or_default())
    {
        Some(text) if !text.trim().is_empty() => Retry::Ask(text),
        Some(_) => Retry::Refused("nothing to retry: the last question was empty".into()),
        None => Retry::Refused("nothing to retry: no question in this session yet".into()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use eclipse_core::message::{Message, ToolCall};

    fn store() -> (SessionStore, tempfile::TempDir) {
        let dir = tempfile::tempdir().unwrap();
        let store = SessionStore::new(dir.path());
        (store, dir)
    }

    fn tool_call() -> ToolCall {
        ToolCall {
            id: "call_1".into(),
            kind: "function".into(),
            function: eclipse_core::message::FunctionCall {
                name: "shell".into(),
                arguments: "{}".into(),
            },
        }
    }

    #[test]
    fn a_session_with_only_a_question_retries_that_question() {
        let (store, _dir) = store();
        store
            .append("s", &Message::user("why is the sky blue"))
            .unwrap();
        assert_eq!(
            target(&store, Some("s")),
            Retry::Ask("why is the sky blue".into())
        );
    }

    /// The newest **user** row, not the newest row: a failed turn leaves tool results and a partial
    /// reply behind, and the question to send again is still the one that started it.
    #[test]
    fn the_newest_question_is_found_under_the_debris_of_a_failed_turn() {
        let (store, _dir) = store();
        store.append("s", &Message::user("first")).unwrap();
        store.append("s", &Message::assistant("an answer")).unwrap();
        store.append("s", &Message::user("second")).unwrap();
        store
            .append("s", &Message::tool_result("call_1", "boom"))
            .unwrap();
        assert_eq!(target(&store, Some("s")), Retry::Ask("second".into()));
    }

    #[test]
    fn a_run_parked_on_a_tool_call_is_refused_and_named() {
        let (store, _dir) = store();
        store.append("s", &Message::user("do it")).unwrap();
        store
            .append("s", &Message::assistant_tool_calls(None, vec![tool_call()]))
            .unwrap();
        match target(&store, Some("s")) {
            Retry::Refused(why) => {
                assert!(why.contains("parked on a tool call"), "{why}");
                assert!(
                    why.contains("approval"),
                    "and says where to answer it: {why}"
                );
            }
            other => panic!("a parked run must be refused: {other:?}"),
        }
    }

    #[test]
    fn no_session_and_no_question_are_two_different_refusals() {
        let (store, _dir) = store();
        assert!(matches!(target(&store, None), Retry::Refused(_)));
        store.append("s", &Message::assistant("hi")).unwrap();
        match target(&store, Some("s")) {
            Retry::Refused(why) => assert!(why.contains("no question"), "{why}"),
            other => panic!("{other:?}"),
        }
        // An id the store never wrote is a refusal too, not an empty question.
        assert!(matches!(target(&store, Some("ghost")), Retry::Refused(_)));
    }
}