Skip to main content

subspace_agent/failure/
turn.rs

1//! What a chat knows about its running turn, for failure reports.
2
3use std::sync::Arc;
4use std::time::Instant;
5
6use serde_json::Value;
7
8use crate::ChatEvent;
9
10/// What the runtime knows about the turn that is running, or about the chat
11/// when no turn runs.
12#[derive(Clone, Debug, Default, PartialEq, Eq)]
13pub struct TurnContext {
14    /// When the turn was sent; `None` while no turn runs.
15    pub sent: Option<Instant>,
16    /// Context references and images sent with the turn, steering included.
17    pub attachments: usize,
18    /// Whether any reply or reasoning text arrived.
19    pub delta_received: bool,
20    pub model: Option<String>,
21    pub effort: Option<String>,
22    /// The texts the turn sent: the message and each context item. They are
23    /// kept only to remove them from what a failure shows or logs.
24    pub submitted: Arc<Vec<String>>,
25}
26
27impl TurnContext {
28    /// A new turn. The chat's model and effort carry over.
29    pub fn begin(&mut self, attachments: usize, submitted: Vec<String>) {
30        self.sent = Some(Instant::now());
31        self.attachments = attachments;
32        self.delta_received = false;
33        self.submitted = Arc::new(submitted);
34    }
35
36    /// A steering message joins the running turn with its attachments.
37    pub fn steer(&mut self, attachments: usize, submitted: Vec<String>) {
38        self.attachments += attachments;
39        Arc::make_mut(&mut self.submitted).extend(submitted);
40    }
41
42    /// The runtime went on with a turn the watchdog had ended: the same
43    /// message, timed from now.
44    pub fn resume(&mut self) {
45        self.sent = Some(Instant::now());
46    }
47
48    /// The turn ended. The model and effort stay for the next one.
49    pub fn finish(&mut self) {
50        self.sent = None;
51    }
52
53    /// Takes what one SDK event says about the turn: whether text arrived,
54    /// and the model and effort Copilot used or switched to.
55    pub fn observe(&mut self, event: &Value) {
56        let data = &event["data"];
57        match event["type"].as_str().unwrap_or_default() {
58            "assistant.message_delta" | "assistant.reasoning_delta" => self.delta_received = true,
59            "assistant.message" => {
60                self.delta_received |= data["content"]
61                    .as_str()
62                    .is_some_and(|text| !text.is_empty())
63            }
64            "assistant.usage" => {
65                self.select(data["model"].as_str(), data["reasoningEffort"].as_str())
66            }
67            "session.model_change" => {
68                self.select(data["newModel"].as_str(), data["reasoningEffort"].as_str())
69            }
70            _ => {}
71        }
72    }
73
74    /// Keeps the model selection the runtime confirmed for the chat.
75    pub fn confirm(&mut self, event: Option<&ChatEvent>) {
76        if let Some(ChatEvent::SelectedModel { model, effort }) = event {
77            self.model = Some(model.clone());
78            self.effort = effort.clone();
79        }
80    }
81
82    /// Keeps a model the runtime reported, with its effort.
83    pub fn select(&mut self, model: Option<&str>, effort: Option<&str>) {
84        let Some(model) = model.filter(|model| !model.is_empty()) else {
85            return;
86        };
87        self.model = Some(model.to_owned());
88        self.effort = effort.map(str::to_owned);
89    }
90}