Skip to main content

subspace_chat/agent_chat/
attention.rs

1//! Pure selection and deduplication of chat events that need user attention.
2
3use subspace_agent::{ChatEvent, ChatId, FailureCategory, TurnFailure};
4
5use super::Pending;
6use super::tab_run::ShownFailure;
7use super::tabs::Tab;
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum ChatAttentionKind {
11    TurnCompleted,
12    WaitingForInput,
13}
14
15pub enum ChatPanelEvent {
16    Close,
17    Attention {
18        kind: ChatAttentionKind,
19        chat: ChatId,
20    },
21}
22
23pub(super) struct TabUpdate {
24    pub(super) transcript: Option<ChatEvent>,
25    pub(super) attention: Option<ChatAttentionKind>,
26}
27
28/// What one chat's event changes in its own tab.
29pub(super) fn apply_chat_event(tab: &mut Tab, event: ChatEvent) -> TabUpdate {
30    match event {
31        request @ (ChatEvent::Approval { .. } | ChatEvent::Question { .. }) => {
32            apply_request_event(tab, request)
33        }
34        selected @ (ChatEvent::Usage(_)
35        | ChatEvent::Mode(_)
36        | ChatEvent::SelectedModel { .. }
37        | ChatEvent::ModelConfirmed { .. }
38        | ChatEvent::SelectedAgent(_)
39        | ChatEvent::SelectedMode(_)) => apply_selection(tab, selected),
40        canvas @ (ChatEvent::CanvasOpened(_)
41        | ChatEvent::CanvasRemembered(_)
42        | ChatEvent::CanvasClosed(_)) => apply_canvas(tab, canvas),
43        event => apply_tab_event(tab, event),
44    }
45}
46
47fn apply_tab_event(tab: &mut Tab, event: ChatEvent) -> TabUpdate {
48    let mut update = empty_update();
49    match event {
50        ChatEvent::Ready { session_id } => {
51            tab.ready();
52            tab.session = Some(session_id);
53        }
54        ChatEvent::History(entries) => tab.entries = entries,
55        entry @ ChatEvent::Entry(_) => {
56            recovered(tab);
57            update.transcript = Some(entry);
58        }
59        delta @ ChatEvent::Delta { .. } => {
60            recovered(tab);
61            tab.resume();
62            update.transcript = Some(delta);
63        }
64        ChatEvent::TurnDone => {
65            update.attention = tab.end().then_some(ChatAttentionKind::TurnCompleted);
66        }
67        ChatEvent::AttachmentsAccepted(ids) => {
68            tab.images.retain(|image| !ids.contains(&image.id));
69        }
70        // A notice: a turn the runtime is still running goes on.
71        ChatEvent::Error(error) => tab.set_error(error),
72        ChatEvent::Failure(failure) => apply_failure(tab, *failure),
73        ChatEvent::Title(title) => tab.title = title.into(),
74        _ => {}
75    }
76    update
77}
78
79/// A failure is shown until the next turn. The runtime ends a turn that
80/// failed with its own `TurnDone`, and a failed steering message leaves the
81/// turn running. A stopped or silent runtime disconnects the chat at once:
82/// it cannot take this chat's messages until a new one has it ready.
83fn apply_failure(tab: &mut Tab, failure: TurnFailure) {
84    let details = super::failure_view::tab_error_details(&failure, tab);
85    tab.errors.accept_failure(details);
86    let reconnect = failure.category.needs_reconnect();
87    tab.failure = Some(ShownFailure::new(failure));
88    if reconnect {
89        tab.disconnect();
90    }
91}
92
93/// A stopped runtime finishes no turn: every tab disconnects, so the status
94/// line ends, open requests go and Reconnect is enabled. No tab is ready
95/// until a new runtime opens it. Returns whether a turn ended.
96pub(super) fn end_turns(tabs: &mut [Tab], stopped: bool) -> bool {
97    let mut ended = false;
98    if stopped {
99        for tab in tabs {
100            ended |= tab.disconnect();
101        }
102    }
103    ended
104}
105
106/// Output after a "not responding" failure means the runtime recovered and
107/// re-armed the turn: the failure no longer holds, the chat is usable and
108/// the turn runs again until its own end.
109fn recovered(tab: &mut Tab) {
110    let silent = tab
111        .failure
112        .as_ref()
113        .is_some_and(|shown| shown.failure.category == FailureCategory::NotResponding);
114    if silent {
115        tab.failure = None;
116        tab.ready();
117        tab.resume();
118    }
119}
120
121fn apply_canvas(tab: &mut Tab, event: ChatEvent) -> TabUpdate {
122    match event {
123        ChatEvent::CanvasOpened(canvas) => {
124            remember_canvas(tab, canvas.clone());
125            if let Err(error) = tab.canvases.open(canvas) {
126                tab.set_error(error);
127            }
128        }
129        ChatEvent::CanvasRemembered(canvas) => remember_canvas(tab, canvas),
130        ChatEvent::CanvasClosed(id) => tab.canvases.close(&id),
131        _ => {}
132    }
133    empty_update()
134}
135
136fn remember_canvas(tab: &mut Tab, canvas: std::sync::Arc<subspace_agent::canvas::Canvas>) {
137    if tab.canvas_history.len() >= subspace_agent::canvas::MAX_CANVAS_HISTORY {
138        let evicted = tab
139            .canvas_history
140            .keys()
141            .find(|id| !tab.canvases.items.iter().any(|open| &open.id == *id))
142            .cloned();
143        if let Some(id) = evicted {
144            tab.canvas_history.remove(&id);
145        }
146    }
147    tab.canvas_history.insert(canvas.id.clone(), canvas);
148}
149
150fn apply_request_event(tab: &mut Tab, event: ChatEvent) -> TabUpdate {
151    match event {
152        ChatEvent::Approval {
153            request_id,
154            summary,
155        } => add_request(
156            tab,
157            request_id.clone(),
158            Pending::Approval {
159                id: request_id,
160                summary,
161            },
162        ),
163        ChatEvent::Question {
164            request_id,
165            question,
166            choices,
167        } => add_request(
168            tab,
169            request_id.clone(),
170            Pending::Question {
171                id: request_id,
172                text: question,
173                choices,
174            },
175        ),
176        _ => empty_update(),
177    }
178}
179
180fn add_request(tab: &mut Tab, request_id: String, pending: Pending) -> TabUpdate {
181    if !tab.notified_requests.insert(request_id) {
182        return empty_update();
183    }
184    tab.pending.push(pending);
185    TabUpdate {
186        transcript: None,
187        attention: tab
188            .running()
189            .is_some_and(|turn| turn.notify)
190            .then_some(ChatAttentionKind::WaitingForInput),
191    }
192}
193
194/// What the runtime confirmed for one chat's own settings.
195fn apply_selection(tab: &mut Tab, event: ChatEvent) -> TabUpdate {
196    match event {
197        ChatEvent::Usage(usage) => tab.usage = usage,
198        ChatEvent::Mode(yolo) => {
199            tab.yolo = yolo;
200            tab.confirm_yolo = false;
201        }
202        ChatEvent::SelectedModel { model, effort } => {
203            tab.model = Some(model);
204            tab.effort = effort;
205        }
206        ChatEvent::ModelConfirmed { model } => tab.model = Some(model),
207        ChatEvent::SelectedAgent(agent) => tab.agent = Some(agent),
208        ChatEvent::SelectedMode(mode) => tab.mode = mode,
209        _ => {}
210    }
211    empty_update()
212}
213
214fn empty_update() -> TabUpdate {
215    TabUpdate {
216        transcript: None,
217        attention: None,
218    }
219}
220
221#[cfg(test)]
222mod attachment_tests {
223    use super::apply_chat_event;
224    use crate::agent_chat::tabs::Tab;
225    use subspace_agent::{ChatEvent, ImageAttachment};
226
227    fn image(id: u64) -> ImageAttachment {
228        ImageAttachment {
229            id,
230            data: vec![id as u8].into(),
231            mime_type: "image/png".into(),
232            display_name: format!("{id}.png"),
233        }
234    }
235
236    #[test]
237    fn failed_send_keeps_drafts_and_acceptance_removes_only_sent_ids() {
238        let mut tab = Tab::new(1);
239        tab.images = vec![image(10), image(20)];
240        apply_chat_event(&mut tab, ChatEvent::Error("send failed".into()));
241        assert_eq!(
242            tab.images.iter().map(|image| image.id).collect::<Vec<_>>(),
243            vec![10, 20],
244            "runtime rejection must retain every draft"
245        );
246        apply_chat_event(&mut tab, ChatEvent::AttachmentsAccepted(vec![10]));
247        assert_eq!(
248            tab.images.iter().map(|image| image.id).collect::<Vec<_>>(),
249            vec![20],
250            "an accepted send must not remove a newer or unrelated draft"
251        );
252    }
253}