1mod attachments;
8mod attention;
9mod bridge;
10mod canvas;
11mod carry;
12mod content;
13mod copilot_only;
14mod effects;
15mod engine;
16mod error_logging;
17mod external;
18mod failure_view;
19mod ingestion;
20mod interaction;
21mod lifecycle;
22mod logic;
23mod rename;
24mod sessions;
25mod sign_in;
26mod slash;
27mod state;
28mod status;
29mod status_words;
30mod strip;
31mod tab_run;
32mod tabbing;
33mod tabs;
34#[cfg(test)]
35mod test_menu;
36mod toolbar;
37mod transcript;
38mod view;
39
40use interaction::{new_input, new_slash, new_toolbar, polling_task};
41use logic::activity_label;
42use sessions::SessionsView;
43use sign_in::{SignIn, subscriptions as sign_in_subscriptions};
44use tabs::Tab;
45
46use std::sync::Arc;
47use std::time::Duration;
48use std::{cell::RefCell, rc::Rc};
49
50use gpui_kit::component::button::{Button, ButtonVariants as _};
51use gpui_kit::component::input::InputState;
52use gpui_kit::component::{Sizable as _, h_flex, v_flex};
53use gpui_kit::{
54 Animation, App, AppContext as _, ClipboardItem, Context, Div, DragMoveEvent, ElementId,
55 EmptyView, Entity, EventEmitter, PathPromptOptions, Render, ScrollHandle, SharedString,
56 Stateful, Subscription, Task, Window, div, ease_out_quint, px, relative,
57};
58use subspace_agent::{
59 AgentHandle, ChatCommand, ChatEngine, ChatEvent, ChatId, ChatMode, Choice, Command, ContextRef,
60 Entry, EntryKind, Event, ModelChoice, SessionSummary, SlashCommand, ToolCall, ToolStatus,
61 TranscriptEntry,
62};
63
64use crate::measure;
65use crate::rich::{Format, rich_text};
66use crate::{Tokens, prefs, services};
67
68use crate::{input, shared};
69use input::ChatInput;
70use slash::SlashList;
71use toolbar::ChatToolbar;
72
73pub use attention::{ChatAttentionKind, ChatPanelEvent};
74
75#[cfg(feature = "test-support")]
77pub mod test_support;
78
79pub const OPEN_KEY: &str = "chat.open";
80pub type ContextProvider = Rc<dyn Fn(&App) -> Option<ContextRef>>;
81pub type ChatToolsProvider = Rc<dyn Fn(&App) -> Option<Arc<dyn subspace_agent::ChatToolServer>>>;
83
84#[derive(Default)]
87struct Providers {
88 context: Option<ContextProvider>,
89 tools: Option<ChatToolsProvider>,
90}
91const WIDTH_KEY: &str = "chat.width";
92const POLL_INTERVAL: Duration = Duration::from_millis(75);
93const REVEAL_DURATION: Duration = Duration::from_millis(180);
94const DEFAULT_WIDTH: f32 = 420.;
95const DEFAULT_CANVAS_WIDTH: f32 = 380.;
96const HEADER_ACTION_MAX_SHARE: f32 = 0.75;
98const FIRST_CHAT: ChatId = subspace_agent::MAX_CHATS as ChatId + 1;
102const MIN_WIDTH: f32 = 300.;
103const MAX_WIDTH_FRACTION: f32 = 0.6;
104
105const PENDING_HEIGHT: f32 = 240.;
106const HANDLE_LEFT: f32 = -3.;
107const HANDLE_WIDTH: f32 = 6.;
108const FULL_FRACTION: f32 = 1.;
109const YOLO_WARNING: &str = concat!(
110 "YOLO grants full host access and permits service writes and shell commands without ordinary approval. ",
111 "Enterprise restrictions still apply. Enable for this conversation?"
112);
113const REPLAY_BANNER: &str = "Replay of the last cloud agent session; times are from loading";
116
117struct ChatResize;
118
119#[derive(Clone)]
120enum Pending {
121 Approval {
122 id: String,
123 summary: String,
124 },
125 Question {
126 id: String,
127 text: String,
128 choices: Vec<String>,
129 },
130}
131
132#[derive(Debug, PartialEq, Eq)]
135enum InputIntent {
136 AddContext,
137 EnableYolo,
138 DisableYolo,
139 NewChat,
140 CloseChat,
141 Rename(String),
142 OpenSessions,
143 OpenModels,
144 RunSkill { name: String, args: String },
145 UnknownCommand,
146 Message(String),
147}
148
149struct Submission {
150 command: Option<Command>,
151 clear: bool,
152 starts_turn: bool,
153 steering: bool,
156 answer_id: Option<String>,
157 last_turn: Option<tabs::LastTurn>,
159}
160
161#[derive(Clone, Copy)]
162enum Preference {
163 Tools,
164 Thinking,
165 AutoContext,
166}
167
168pub struct ChatPanel {
169 engine: ChatEngine,
170 copilot_kept: bool,
173 acp_agent: subspace_agent::AcpAgent,
175 handle: Option<AgentHandle>,
176 input: Entity<ChatInput>,
177 toolbar: Entity<ChatToolbar>,
178 slash: Entity<SlashList>,
179 tabs: Vec<Tab>,
181 active: usize,
182 next_chat: ChatId,
184 renaming: Option<ChatId>,
186 rename_input: Entity<InputState>,
187 strip_width: Entity<f32>,
189 header_toolbar: RefCell<Option<Entity<subspace_dashboard::overflow_toolbar::OverflowToolbar>>>,
190 canvas_toolbar: RefCell<Option<Entity<subspace_dashboard::overflow_toolbar::OverflowToolbar>>>,
191 sessions_open: bool,
194 view: SessionsView,
195 current: Option<ContextRef>,
196 providers: Providers,
197 auto_context: bool,
198 show_tools: bool,
199 show_thinking: bool,
200 models: Vec<ModelChoice>,
201 agents: Vec<Choice>,
202 sessions: Vec<SessionSummary>,
203 commands: Vec<SlashCommand>,
204 error: Option<String>,
206 errors: error_logging::AcceptedErrors,
207 sign_in: Option<SignIn>,
209 carried: Vec<carry::Carried>,
211 attachment_ingestion_busy: bool,
212 width: f32,
213 canvas_width: f32,
214 canvas_focus: gpui_kit::FocusHandle,
215 reveal: u64,
216 scroll: ScrollHandle,
217 _subscriptions: Vec<Subscription>,
218 _sign_in: Vec<Subscription>,
220 _poller: Task<()>,
221 _shutdown: Subscription,
222}
223
224impl EventEmitter<ChatPanelEvent> for ChatPanel {}
225
226impl ChatPanel {
227 pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
228 let (engine, copilot_kept) =
229 engine::runnable(configured_engine(cx), subspace_agent::COPILOT_BUILT_IN);
230 Self {
231 copilot_kept,
232 ..Self::with_engine(engine, window, cx)
233 }
234 }
235
236 fn with_engine(engine: ChatEngine, window: &mut Window, cx: &mut Context<Self>) -> Self {
237 let toolbar = new_toolbar(window, cx);
238 let input = new_input(engine, configured_acp_agent(cx), &toolbar, window, cx);
239 let slash = new_slash(engine, window, cx);
240 let rename_input = cx.new(|cx| InputState::new(window, cx));
241 let session_search =
242 cx.new(|cx| InputState::new(window, cx).placeholder("Search sessions"));
243 let session_rename = cx.new(|cx| InputState::new(window, cx));
244 let subscriptions = vec![
245 cx.subscribe_in(&input, window, Self::on_input_event),
246 cx.subscribe_in(&toolbar, window, Self::on_toolbar_event),
247 cx.subscribe_in(&slash, window, Self::on_slash_event),
248 cx.subscribe_in(&rename_input, window, Self::on_rename_event),
249 cx.subscribe_in(&session_search, window, Self::on_search_event),
250 cx.subscribe_in(&session_rename, window, Self::on_session_rename_event),
251 ];
252 Self {
253 engine,
254 copilot_kept: false,
255 acp_agent: configured_acp_agent(cx),
256 handle: None,
257 input,
258 toolbar,
259 slash,
260 tabs: vec![Tab::new(1)],
261 active: 0,
262 next_chat: FIRST_CHAT,
263 renaming: None,
264 rename_input,
265 strip_width: measure::unmeasured(cx),
266 header_toolbar: RefCell::new(None),
267 canvas_toolbar: RefCell::new(None),
268 sessions_open: false,
269 view: SessionsView::new(session_search, session_rename, measure::unmeasured(cx)),
270 current: None,
271 providers: Providers::default(),
272 auto_context: prefs::get(cx, "chat.auto-context").as_deref() != Some("0"),
273 show_tools: prefs::get(cx, "chat.tools").as_deref() != Some("0"),
274 show_thinking: prefs::get(cx, "chat.thinking").as_deref() == Some("1"),
275 models: Vec::new(),
276 agents: Vec::new(),
277 sessions: Vec::new(),
278 commands: Vec::new(),
279 error: None,
280 errors: Default::default(),
281 sign_in: None,
282 carried: Vec::new(),
283 attachment_ingestion_busy: false,
284 width: panel_width(cx),
285 canvas_width: DEFAULT_CANVAS_WIDTH,
286 canvas_focus: cx.focus_handle(),
287 reveal: 0,
288 scroll: ScrollHandle::new(),
289 _subscriptions: subscriptions,
290 _sign_in: sign_in_subscriptions(cx),
291 _poller: polling_task(cx),
292 _shutdown: shutdown_hook(cx),
293 }
294 }
295
296 #[cfg(test)]
297 fn new_copilot(window: &mut Window, cx: &mut Context<Self>) -> Self {
298 Self::with_engine(ChatEngine::Copilot, window, cx)
299 }
300
301 fn tab(&self) -> &Tab {
304 let index = self.active.min(self.tabs.len().saturating_sub(1));
305 &self.tabs[index]
306 }
307
308 fn tab_mut(&mut self) -> &mut Tab {
309 let index = self.active.min(self.tabs.len().saturating_sub(1));
310 &mut self.tabs[index]
311 }
312
313 pub fn on_open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
315 self.reveal = self.reveal.wrapping_add(1);
316 if self.is_disabled() {
317 cx.notify();
318 return;
319 }
320 if self.handle.is_none() {
321 self.start(cx);
322 }
323 self.input.update(cx, |input, cx| input.focus(window, cx));
324 self.sync_toolbar(cx);
325 cx.notify();
326 }
327
328 pub fn set_context(&mut self, context: Option<ContextRef>, _cx: &mut Context<Self>) {
331 if self.current != context {
332 self.current = context;
333 }
334 }
335
336 pub fn set_context_provider(&mut self, provider: ContextProvider) {
337 self.providers.context = Some(provider);
338 }
339
340 pub fn set_chat_tools(&mut self, provider: ChatToolsProvider) {
343 self.providers.tools = Some(provider);
344 }
345
346 pub fn indicator(&self) -> &'static str {
347 activity_label(self.is_busy(), self.needs_attention())
348 }
349
350 pub fn is_busy(&self) -> bool {
352 self.tabs.iter().any(Tab::is_busy)
353 }
354
355 pub fn needs_attention(&self) -> bool {
358 self.tabs.iter().any(Tab::needs_attention)
359 }
360
361 fn toggle_expanded(&mut self, key: &str) {
363 let expanded = &mut self.tab_mut().expanded;
364 if !expanded.remove(key) {
365 expanded.insert(key.to_owned());
366 }
367 }
368
369 pub(crate) fn sync_toolbar(&mut self, cx: &mut Context<Self>) {
372 let model = self.toolbar_model();
373 let read_only = self.tab().read_only;
374 self.toolbar
375 .update(cx, |toolbar, cx| toolbar.set_model(model, cx));
376 self.input
377 .update(cx, |input, cx| input.set_disabled(read_only, cx));
378 }
379
380 pub(crate) fn publish_sessions(&self, cx: &mut App) {
383 let open: Vec<(String, bool)> = self
384 .tabs
385 .iter()
386 .filter_map(|tab| Some((tab.session.clone()?, tab.is_busy())))
387 .collect();
388 shared::publish(cx, shared::with_tabs(&self.sessions, &open));
389 }
390}
391
392fn configured_acp_agent(cx: &App) -> subspace_agent::AcpAgent {
393 services(cx)
394 .map(|services| services.config.chat.acp.agent)
395 .unwrap_or_default()
396}
397
398fn configured_engine(cx: &App) -> ChatEngine {
399 services(cx)
400 .map(|services| services.config.chat.engine)
401 .unwrap_or_default()
402}
403
404fn panel_width(cx: &App) -> f32 {
406 prefs::get(cx, WIDTH_KEY)
407 .and_then(|width| width.parse().ok())
408 .filter(|width: &f32| width.is_finite())
409 .unwrap_or(DEFAULT_WIDTH)
410}
411
412fn shutdown_hook(cx: &mut Context<ChatPanel>) -> Subscription {
414 cx.on_app_quit(|chat, _| {
415 let _ = chat
416 .handle
417 .as_ref()
418 .map(|handle| handle.send(Command::Shutdown));
419 async {}
420 })
421}
422
423fn control(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Button {
424 let label = label.into();
425 Button::new(id)
426 .ghost()
427 .xsmall()
428 .accessibility_label(label.clone())
429 .label(label)
430}