Skip to main content

subspace_chat/agent_chat/
lifecycle.rs

1//! Transient surfaces close when the chat owner is hidden or deactivated.
2
3use super::{ChatPanel, Context, Window};
4
5impl ChatPanel {
6    /// Dismiss toolbar surfaces before the panel is hidden or deactivated.
7    pub fn dismiss_popups(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8        self.toolbar
9            .update(cx, |toolbar, cx| toolbar.dismiss_popups(window, cx));
10    }
11}
12
13#[cfg(test)]
14mod tests {
15    use super::ChatPanel;
16    use crate::prefs;
17    use gpui_kit::base::GlobalState;
18    use gpui_kit::test::TestWindowExt as _;
19    use gpui_kit::{Entity, TestAppContext, VisualTestContext};
20    use subspace_agent::{ChatEvent, Command, Event, SessionSummary};
21    use subspace_core::config::ChatEngine;
22
23    fn setup(cx: &mut TestAppContext) -> (Entity<ChatPanel>, &mut VisualTestContext) {
24        setup_engine(cx, ChatEngine::Copilot)
25    }
26
27    fn setup_engine(
28        cx: &mut TestAppContext,
29        engine: ChatEngine,
30    ) -> (Entity<ChatPanel>, &mut VisualTestContext) {
31        cx.update(|cx| {
32            cx.set_reduce_motion(true);
33            gpui_kit::init(cx);
34            prefs::init_file(None, cx);
35        });
36        let (chat, cx) =
37            cx.add_window_view(move |window, cx| ChatPanel::with_engine(engine, window, cx));
38        settle(cx);
39        (chat, cx)
40    }
41
42    #[gpui_kit::test]
43    fn opening_chat_while_off_shows_setup_guidance_without_starting_a_runtime(
44        cx: &mut TestAppContext,
45    ) {
46        let (chat, cx) = setup_engine(cx, ChatEngine::default());
47        cx.update(|window, cx| {
48            chat.update(cx, |chat, cx| {
49                chat.on_open(window, cx);
50                assert!(chat.is_disabled());
51                assert!(chat.handle.is_none());
52                assert!(!chat.is_unavailable());
53            });
54        });
55        settle(cx);
56        cx.update(|window, _| {
57            assert!(window.find("chat-off").visible());
58            assert!(window.try_find("chat-new-tab").is_none());
59            assert!(window.try_find("chat-reconnect").is_none());
60        });
61    }
62
63    /// A build without Copilot opens a saved Copilot choice as Chat off, says
64    /// why, and starts nothing; a build with Copilot keeps the engine.
65    #[gpui_kit::test]
66    fn a_saved_copilot_choice_follows_whether_the_build_includes_copilot(cx: &mut TestAppContext) {
67        cx.update(|cx| {
68            cx.set_reduce_motion(true);
69            gpui_kit::init(cx);
70            prefs::init_file(None, cx);
71            let mut config = subspace_core::config::Config::default();
72            config.chat.engine = ChatEngine::Copilot;
73            cx.set_global(subspace_dashboard::Services {
74                credentials: std::sync::Arc::new(
75                    subspace_core::credentials::Credentials::from_system(&config),
76                ),
77                config: std::sync::Arc::new(config),
78                tools: Default::default(),
79                search: None,
80                config_file: Default::default(),
81            });
82        });
83        let (chat, cx) = cx.add_window_view(ChatPanel::new);
84        if subspace_agent::COPILOT_BUILT_IN {
85            chat.read_with(cx, |chat, _| {
86                assert_eq!(chat.engine(), ChatEngine::Copilot);
87                assert!(!chat.copilot_kept);
88            });
89            return;
90        }
91        cx.update(|window, cx| {
92            chat.update(cx, |chat, cx| {
93                assert!(chat.is_disabled());
94                assert!(chat.copilot_kept);
95                assert_eq!(chat.engine_label(), "Chat");
96                chat.on_open(window, cx);
97                assert!(chat.handle.is_none(), "nothing starts");
98                assert!(chat.sign_in.is_none(), "nothing offers a sign-in");
99            });
100        });
101        settle(cx);
102        cx.update(|window, _| {
103            assert!(window.find("chat-off").visible());
104            assert!(window.try_find("chat-reconnect").is_none());
105        });
106        chat.read_with(cx, |chat, _| {
107            assert_eq!(chat.guidance(), subspace_agent::COPILOT_UNAVAILABLE);
108        });
109    }
110
111    fn settle(cx: &mut VisualTestContext) {
112        for _ in 0..3 {
113            cx.update(|window, cx| window.draw(cx).clear(cx));
114            cx.run_until_parked();
115        }
116    }
117
118    #[gpui_kit::test]
119    fn sessions_dismisses_retained_and_keyed_toolbar_hosts_before_composer_reopens(
120        cx: &mut TestAppContext,
121    ) {
122        let (chat, cx) = setup(cx);
123        for (trigger, body) in [
124            ("chat-usage", "chat-usage-body"),
125            ("chat-add", "popup-menu"),
126        ] {
127            cx.update(|window, cx| window.click(trigger, cx));
128            settle(cx);
129            cx.update(|window, cx| {
130                assert!(window.find(body).visible());
131                assert!(GlobalState::is_in_deferred_context(cx));
132                chat.update(cx, |chat, cx| chat.show_sessions(window, cx));
133            });
134            settle(cx);
135            cx.update(|window, cx| {
136                assert!(window.try_find(trigger).is_none());
137                assert!(!GlobalState::is_in_deferred_context(cx));
138                chat.update(cx, |chat, cx| chat.focus_chat(0, window, cx));
139            });
140            settle(cx);
141            cx.update(|window, _| {
142                assert!(window.find(trigger).visible());
143                assert!(window.try_find(body).is_none());
144            });
145        }
146        cx.update(|window, cx| window.click("chat-add", cx));
147        settle(cx);
148        cx.update(|window, _| assert!(window.find("popup-menu").visible()));
149    }
150
151    #[gpui_kit::test]
152    fn reopen_retains_runtime_and_reconnect_shuts_it_down(cx: &mut TestAppContext) {
153        let directory = tempfile::tempdir().unwrap();
154        let (handle, mut commands) =
155            subspace_agent::AgentHandle::test_offline(directory.path().into(), Vec::new());
156        let original = handle.clone();
157        let (chat, cx) = setup(cx);
158        cx.update(|window, cx| {
159            chat.update(cx, |chat, cx| {
160                chat.connected(Ok(handle));
161                chat.on_open(window, cx);
162                chat.dismiss_popups(window, cx);
163                chat.on_open(window, cx);
164                assert!(chat.handle.as_ref().unwrap().same_runtime(&original));
165                assert!(
166                    commands.try_recv().is_err(),
167                    "hide/reopen must not restart the runtime"
168                );
169                chat.reconnect(window, cx);
170                assert!(matches!(commands.try_recv(), Ok(Command::Shutdown)));
171                assert!(commands.try_recv().is_err());
172                assert!(chat.handle.is_none());
173                assert_eq!(
174                    chat.error.as_deref(),
175                    Some("Service configuration is unavailable.")
176                );
177            })
178        });
179    }
180
181    #[gpui_kit::test]
182    fn startup_rejection_reaches_panel_polling_and_reconnect_clears_sign_in(
183        cx: &mut TestAppContext,
184    ) {
185        let directory = tempfile::tempdir().unwrap();
186        let rejection = "GitHub rejected the gh CLI token for test-user. Click Sign in to GitHub.";
187        let (handle, mut commands) = subspace_agent::AgentHandle::test_offline(
188            directory.path().into(),
189            vec![
190                Event::SignInRequired(subspace_agent::SignInOffer::GhRefresh {
191                    login: "test-user".into(),
192                }),
193                Event::Error(rejection.into()),
194            ],
195        );
196        let (chat, cx) = setup(cx);
197        cx.update(|window, cx| chat.update(cx, |chat, cx| {
198            chat.connected(Ok(handle));
199            chat.poll(cx);
200            assert_eq!(chat.error.as_deref(), Some(rejection));
201            assert!(matches!(&chat.sign_in, Some(super::super::sign_in::SignIn::Offered { offer: subspace_agent::SignInOffer::GhRefresh { login }, .. }) if login == "test-user"));
202            assert!(!chat.tab().is_ready());
203            chat.reconnect(window, cx);
204            assert!(matches!(commands.try_recv(), Ok(Command::Shutdown)));
205            assert!(chat.sign_in.is_none());
206        }));
207    }
208
209    #[gpui_kit::test]
210    fn restored_runtime_events_publish_saved_sessions_with_tab_activity(cx: &mut TestAppContext) {
211        let directory = tempfile::tempdir().unwrap();
212        let events = vec![
213            Event::of(2, ChatEvent::History(Vec::new())),
214            Event::of(2, ChatEvent::Title("Restored second".into())),
215            Event::of(
216                2,
217                ChatEvent::Ready {
218                    session_id: "saved-second".into(),
219                },
220            ),
221            Event::of(
222                1,
223                ChatEvent::Ready {
224                    session_id: "saved-first".into(),
225                },
226            ),
227            Event::Restore {
228                tabs: vec![(1, "saved-first".into()), (2, "saved-second".into())],
229                active: 2,
230            },
231            Event::Sessions(vec![SessionSummary {
232                id: "saved-second".into(),
233                title: "Saved second".into(),
234                modified: "now".into(),
235                modified_at: "2026-11-04T00:00:00Z".into(),
236                created_at: "2026-11-03T00:00:00Z".into(),
237            }]),
238        ];
239        let (handle, mut commands) =
240            subspace_agent::AgentHandle::test_offline(directory.path().into(), events);
241        let (chat, cx) = setup(cx);
242        cx.update(|_, cx| {
243            chat.update(cx, |chat, cx| {
244                chat.connected(Ok(handle));
245                chat.poll(cx);
246                assert_eq!(
247                    chat.tabs.iter().map(|tab| tab.id).collect::<Vec<_>>(),
248                    [1, 2]
249                );
250                assert_eq!(chat.tab().title.as_ref(), "Restored second");
251                assert_eq!(chat.tab().session.as_deref(), Some("saved-second"));
252                assert!(matches!(commands.try_recv(), Ok(Command::ListSessions)));
253                chat.tab_mut().begin();
254                chat.publish_sessions(cx);
255                let sessions = crate::shared::sessions(cx);
256                assert_eq!(sessions.len(), 1);
257                assert!(sessions[0].open && sessions[0].busy);
258                assert_eq!(sessions[0].id, "saved-second");
259            })
260        });
261    }
262
263    #[gpui_kit::test]
264    fn application_quit_sends_shutdown_to_the_retained_runtime(cx: &mut TestAppContext) {
265        let directory = tempfile::tempdir().unwrap();
266        let (handle, mut commands) =
267            subspace_agent::AgentHandle::test_offline(directory.path().into(), Vec::new());
268        cx.update(|cx| {
269            gpui_kit::init(cx);
270            prefs::init_file(None, cx);
271        });
272        let window = cx.add_window(ChatPanel::new);
273        window
274            .update(cx, |chat, _, _| chat.connected(Ok(handle)))
275            .unwrap();
276        cx.quit();
277        assert!(matches!(commands.try_recv(), Ok(Command::Shutdown)));
278        assert!(commands.try_recv().is_err());
279    }
280
281    /// An error the runtime reports during a turn leaves it running, so the
282    /// next message steers it rather than starting a new turn.
283    #[gpui_kit::test]
284    fn a_message_after_an_error_during_a_turn_steers_it(cx: &mut TestAppContext) {
285        let directory = tempfile::tempdir().unwrap();
286        let (handle, _commands) =
287            subspace_agent::AgentHandle::test_offline(directory.path().into(), Vec::new());
288        let (chat, cx) = setup(cx);
289        chat.update(cx, |chat, cx| {
290            chat.connected(Ok(handle));
291            chat.tab_mut().ready();
292            let mut first = chat.prepare_submission(
293                super::super::InputIntent::Message("Fix it".into()),
294                Vec::new(),
295            );
296            let command = first.command.take().expect("a send");
297            let sent = chat.send(command, cx);
298            chat.finish_submission(first, sent);
299            let running = chat.tab().running().copied();
300            super::super::attention::apply_chat_event(
301                chat.tab_mut(),
302                ChatEvent::Error("refused".into()),
303            );
304            let steer = chat.prepare_submission(
305                super::super::InputIntent::Message("Also".into()),
306                Vec::new(),
307            );
308            assert!(steer.steering, "the turn is still running");
309            assert!(steer.last_turn.is_none(), "Retry keeps the first message");
310            assert_eq!(chat.tab().running().copied(), running, "and its timer");
311        });
312    }
313}