1use super::logic::{
2 apply_transcript, became_ready, bool_preference, change_preference, clamped_width,
3 context_snapshot, include_current, input_intent, latest_commands, remove_reference,
4 resolve_pending, skill_commands,
5};
6use super::tabs::{Tab, tab_index};
7use super::{
8 AgentHandle, ChatCommand, ChatPanel, ChatPanelEvent, Command, Context, InputIntent, Preference,
9 WIDTH_KEY, Window, prefs,
10};
11
12impl ChatPanel {
13 pub fn refresh_sessions(&mut self, cx: &mut Context<Self>) {
16 self.send(Command::ListSessions, cx);
17 }
18
19 pub(super) fn reconnect(&mut self, window: &mut Window, cx: &mut Context<Self>) {
20 self.restart_runtime(cx);
21 self.input.update(cx, |input, cx| input.clear(window, cx));
22 self.input.update(cx, |input, cx| input.focus(window, cx));
23 }
24
25 pub(super) fn restart_runtime(&mut self, cx: &mut Context<Self>) {
28 let _ = self
29 .handle
30 .take()
31 .map(|handle| handle.send(Command::Shutdown));
32 let carried = super::carry::take(&mut self.tabs);
33 self.start(cx);
34 self.carried = carried;
35 self.sync_toolbar(cx);
36 cx.notify();
37 }
38
39 pub(super) fn refresh_context(&mut self, cx: &mut Context<Self>) {
40 let _ = self.providers.context.clone().map(|provider| {
41 let context = provider(cx);
42 let changed = self.replace_current(context);
43 let _ = changed.then(|| cx.notify());
44 });
45 }
46
47 pub(super) fn send(&mut self, command: Command, cx: &mut Context<Self>) -> bool {
48 if self.is_disabled() {
49 return false;
50 }
51 let engine = self.engine_label();
52 let result = self
53 .handle
54 .as_ref()
55 .ok_or_else(|| format!("Open chat to connect {engine}."))
56 .and_then(|handle| handle.send(command));
57 let sent = self.command_result(result);
58 self.log_accepted_errors(cx);
59 cx.notify();
60 sent
61 }
62
63 pub(super) fn send_chat(&mut self, command: ChatCommand, cx: &mut Context<Self>) -> bool {
65 let command = self.chat_command(command);
66 self.send(command, cx)
67 }
68
69 pub(super) fn add_current(&mut self, cx: &mut Context<Self>) {
70 self.refresh_context(cx);
71 let current = self.current.clone();
72 let tab = self.tab_mut();
73 tab.context = context_snapshot(&tab.context, current, true);
74 cx.notify();
75 }
76
77 pub(super) fn remove_context(&mut self, key: &str, cx: &mut Context<Self>) {
78 self.refresh_context(cx);
79 let current = self.current.clone();
80 let mut automatic = self.auto_context;
81 let disabled = remove_reference(
82 &mut self.tab_mut().context,
83 current.as_ref(),
84 &mut automatic,
85 key,
86 );
87 self.auto_context = automatic;
88 let _ = disabled.then(|| prefs::set(cx, "chat.auto-context", "0"));
89 self.sync_toolbar(cx);
90 cx.notify();
91 }
92
93 fn handled_here(
95 &mut self,
96 intent: &InputIntent,
97 window: &mut Window,
98 cx: &mut Context<Self>,
99 ) -> bool {
100 match intent {
101 InputIntent::NewChat => self.new_tab(window, cx),
102 InputIntent::CloseChat => self.close_tab(self.tab().id, window, cx),
103 InputIntent::OpenSessions => self.show_sessions(window, cx),
104 InputIntent::OpenModels => self
105 .toolbar
106 .update(cx, |toolbar, cx| toolbar.open_models(window, cx)),
107 _ => return false,
108 }
109 true
110 }
111
112 pub(super) fn submit(&mut self, text: String, window: &mut Window, cx: &mut Context<Self>) {
113 self.refresh_context(cx);
114 let intent = input_intent(&text, &self.commands);
115 if self.handled_here(&intent, window, cx) {
116 self.clear_input(window, cx);
117 return;
118 }
119 let context = context_snapshot(
120 &self.tab().context,
121 self.current.clone(),
122 include_current(&intent, self.auto_context),
123 );
124 let mut submission = self.prepare_submission(intent, context);
125 self.log_accepted_errors(cx);
126 let accepted = submission
127 .command
128 .take()
129 .map(|command| self.send(command, cx))
130 .unwrap_or(submission.clear);
131 let _ = submission
132 .answer_id
133 .as_deref()
134 .filter(|_| accepted)
135 .map(|id| resolve_pending(&mut self.tab_mut().pending, id));
136 let clear = self.finish_submission(submission, accepted);
137 let _ = clear.then(|| self.clear_input(window, cx));
138 self.sync_toolbar(cx);
139 cx.notify();
140 }
141
142 fn clear_input(&mut self, window: &mut Window, cx: &mut Context<Self>) {
143 self.tab_mut().draft.clear();
144 self.input.update(cx, |input, cx| input.clear(window, cx));
145 self.slash.update(cx, |slash, cx| slash.set_text("", cx));
146 self.input
147 .update(cx, |input, cx| input.set_completing(false, cx));
148 }
149
150 pub(super) fn remember_draft(&mut self, cx: &mut Context<Self>) {
152 let draft = self.input.read(cx).text(cx);
153 self.tab_mut().draft = draft;
154 }
155
156 pub(super) fn show_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
157 let draft = self.tab().draft.clone();
158 self.input
159 .update(cx, |input, cx| input.set_text(&draft, window, cx));
160 self.input.update(cx, |input, cx| input.focus(window, cx));
161 }
162
163 pub(super) fn request_yolo(&mut self, approve_all: bool, cx: &mut Context<Self>) {
164 if self.reject_unavailable_copilot_controls(cx) {
165 return;
166 }
167 self.tab_mut().confirm_yolo = approve_all;
168 if !approve_all {
169 self.send_chat(ChatCommand::SetYolo(false), cx);
170 }
171 cx.notify();
172 }
173
174 pub(super) fn confirm_mode(&mut self, cx: &mut Context<Self>) {
175 if self.reject_unavailable_copilot_controls(cx) {
176 self.tab_mut().confirm_yolo = false;
177 return;
178 }
179 self.send_chat(ChatCommand::SetYolo(true), cx);
180 self.tab_mut().confirm_yolo = false;
181 cx.notify();
182 }
183
184 pub(super) fn toggle_preference(&mut self, preference: Preference, cx: &mut Context<Self>) {
185 let (key, enabled) = change_preference(
186 preference,
187 &mut self.show_tools,
188 &mut self.show_thinking,
189 &mut self.auto_context,
190 );
191 prefs::set(cx, key, bool_preference(enabled));
192 self.sync_toolbar(cx);
193 cx.notify();
194 }
195
196 pub(super) fn resize(&mut self, width: f32, window: &Window, cx: &mut Context<Self>) {
197 self.width = clamped_width(width, f32::from(window.viewport_size().width));
198 prefs::set(cx, WIDTH_KEY, self.width.to_string());
199 cx.notify();
200 }
201
202 pub(super) fn answer(&mut self, id: String, answer: String, cx: &mut Context<Self>) -> bool {
203 let accepted = self.send(
204 Command::Answer {
205 request_id: id.clone(),
206 answer,
207 },
208 cx,
209 );
210 let _ = accepted.then(|| resolve_pending(&mut self.tab_mut().pending, &id));
211 cx.notify();
212 accepted
213 }
214
215 pub(super) fn approve(&mut self, id: String, allow: bool, cx: &mut Context<Self>) {
216 let accepted = self.send(
217 Command::Approve {
218 request_id: id.clone(),
219 allow,
220 },
221 cx,
222 );
223 let _ = accepted.then(|| resolve_pending(&mut self.tab_mut().pending, &id));
224 cx.notify();
225 }
226
227 pub(super) fn receive(&mut self, event: super::Event, cx: &mut Context<Self>) {
229 self.persist_confirmed_model(&event, cx);
230 let update = self.apply_event(event);
231 self.log_accepted_errors(cx);
232 let Some((chat, update)) = update else {
233 return;
234 };
235 let Some(index) = tab_index(&self.tabs, chat) else {
236 return;
237 };
238 if let Some(tab) = self.tabs.get_mut(index) {
239 apply_transcript(&mut tab.entries, update.transcript);
240 }
241 let _ = update
242 .attention
243 .map(|kind| cx.emit(ChatPanelEvent::Attention { kind, chat }));
244 }
245
246 fn persist_confirmed_model(&self, event: &super::Event, cx: &mut Context<Self>) {
247 persist_confirmed_model(self.engine, event, cx);
248 }
249
250 fn advance_status(&mut self) -> bool {
253 let mut changed = false;
254 for turn in self.tabs.iter_mut().filter_map(Tab::running_mut) {
255 changed |= turn.advance();
256 }
257 changed
258 }
259
260 fn flush_queued(&mut self, cx: &mut Context<Self>) {
262 for (chat, queued) in self.strip().ready_to_send() {
263 let command = queued.clone().into_command();
264 let sent = self.send(Command::Chat { chat, command }, cx);
265 let _ = sent
266 .then(|| tab_index(&self.tabs, chat))
267 .flatten()
268 .and_then(|index| self.tabs.get_mut(index))
269 .map(|tab| tab.sent(queued));
270 }
271 }
272
273 pub(super) fn poll(&mut self, cx: &mut Context<Self>) {
274 self.refresh_context(cx);
275 let _ = self.end_stopped_turns().then(|| cx.notify());
276 let events = self
277 .handle
278 .as_ref()
279 .map(AgentHandle::take_events)
280 .unwrap_or_default();
281 if events.is_empty() {
282 let _ = self.advance_status().then(|| cx.notify());
284 return;
285 }
286 let skills = latest_commands(&events);
287 let ready = became_ready(&events);
288 for event in events {
289 self.receive(event, cx);
290 }
291 let _ = skills.map(|skills| {
292 let skills = skill_commands(&skills);
293 self.slash
294 .update(cx, |slash, cx| slash.set_skills(&skills, cx));
295 });
296 let _ = ready.then(|| self.send(Command::ListSessions, cx));
297 self.flush_queued(cx);
298 self.advance_status();
299 self.sync_toolbar(cx);
300 self.publish_sessions(cx);
301 self.scroll.scroll_to_bottom();
302 cx.notify();
303 }
304}
305
306fn persist_confirmed_model(engine: super::ChatEngine, event: &super::Event, cx: &mut super::App) {
307 let Some(model) = confirmed_model(event) else {
308 return;
309 };
310 let key = match engine {
311 super::ChatEngine::Off => return,
312 super::ChatEngine::Copilot => "chat.default-model.copilot",
313 super::ChatEngine::Pi => "chat.default-model.pi",
314 super::ChatEngine::Acp => "chat.default-model.acp",
315 };
316 prefs::set(cx, key, model);
317 let _ = prefs::save(cx);
318}
319
320fn confirmed_model(event: &super::Event) -> Option<&str> {
321 match event {
322 super::Event::Chat {
323 event: super::ChatEvent::ModelConfirmed { model },
324 ..
325 } => Some(model),
326 _ => None,
327 }
328}
329
330#[cfg(test)]
331mod tests {
332 use super::{confirmed_model, persist_confirmed_model};
333 use crate::prefs;
334 use subspace_agent::{ChatEvent, Event, ModelChoice};
335
336 #[test]
337 fn only_the_explicit_confirmation_event_is_persistable() {
338 assert_eq!(
339 confirmed_model(&Event::Chat {
340 chat: 1,
341 event: ChatEvent::ModelConfirmed {
342 model: "gpt-5".into()
343 }
344 }),
345 Some("gpt-5")
346 );
347 assert_eq!(
348 confirmed_model(&Event::Models(Vec::<ModelChoice>::new())),
349 None
350 );
351 assert_eq!(
352 confirmed_model(&Event::Chat {
353 chat: 1,
354 event: ChatEvent::SelectedModel {
355 model: "catalog".into(),
356 effort: None,
357 }
358 }),
359 None
360 );
361 }
362
363 #[gpui_kit::test]
364 fn confirmed_model_uses_the_shared_prefs_owner_and_survives_later_save(
365 cx: &mut gpui_kit::TestAppContext,
366 ) {
367 let directory = tempfile::tempdir().unwrap();
368 let file = directory.path().join("prefs.json");
369 cx.update(|cx| {
370 prefs::init_file(Some(file.clone()), cx);
371 persist_confirmed_model(
372 subspace_agent::ChatEngine::Copilot,
373 &Event::Chat {
374 chat: 1,
375 event: ChatEvent::ModelConfirmed {
376 model: "gpt-5".into(),
377 },
378 },
379 cx,
380 );
381 prefs::set(cx, "unrelated.preference", "later");
382 prefs::save(cx).unwrap();
383 assert_eq!(
384 prefs::get(cx, "chat.default-model.copilot").as_deref(),
385 Some("gpt-5")
386 );
387 assert_eq!(
388 prefs::get(cx, "unrelated.preference").as_deref(),
389 Some("later")
390 );
391 prefs::init_file(Some(file), cx);
392 assert_eq!(
393 prefs::get(cx, "chat.default-model.copilot").as_deref(),
394 Some("gpt-5")
395 );
396 assert_eq!(
397 prefs::get(cx, "unrelated.preference").as_deref(),
398 Some("later")
399 );
400 persist_confirmed_model(
401 subspace_agent::ChatEngine::Copilot,
402 &Event::Models(Vec::new()),
403 cx,
404 );
405 assert_eq!(
406 prefs::get(cx, "chat.default-model.copilot").as_deref(),
407 Some("gpt-5")
408 );
409 });
410 }
411}