Skip to main content

subspace_chat/
agent_chat.rs

1//! App-wide conversation. The actor survives hiding this view.
2//! The reveal takes layout space; GPUI honors the platform reduced-motion setting.
3//!
4//! Every chat setting lives in the composer toolbar under the input, so the
5//! panel itself shows only the transcript, approvals and errors.
6
7mod 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/// Offline runtime injection for shell integration tests only.
76#[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>>;
81/// The app's tools for ACP sessions, read when a runtime starts.
82pub type ChatToolsProvider = Rc<dyn Fn(&App) -> Option<Arc<dyn subspace_agent::ChatToolServer>>>;
83
84/// What the shell supplies: the visible board's reference and the tools
85/// ACP sessions receive.
86#[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.;
96/// Leave a title/tab lane beside header actions; their measured row overflows.
97const HEADER_ACTION_MAX_SHARE: f32 = 0.75;
98/// The first chat id the panel assigns itself. The runtime numbers the tabs
99/// it restores from 1, so the panel's own ids start past that range and never
100/// collide with them.
101const 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);
113/// What a read-only cloud replay says above its disabled input. The SDK
114/// reports the events at load time, so the transcript carries no agent times.
115const 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/// What a submitted line means. Slash commands never reach the runtime as
133/// text; a skill runs through `RunCommand`.
134#[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    /// The message joins a turn that is already running, so the turn's timer
154    /// and status phrase keep going instead of restarting.
155    steering: bool,
156    answer_id: Option<String>,
157    /// The message this submission sends, which Retry can send again.
158    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    /// The config file selects Copilot, which this build does not include:
171    /// the panel is off and says why, and the file keeps the choice.
172    copilot_kept: bool,
173    /// The configured ACP agent, which names the engine when it is ACP.
174    acp_agent: subspace_agent::AcpAgent,
175    handle: Option<AgentHandle>,
176    input: Entity<ChatInput>,
177    toolbar: Entity<ChatToolbar>,
178    slash: Entity<SlashList>,
179    /// The open chats, in strip order, and the one shown.
180    tabs: Vec<Tab>,
181    active: usize,
182    /// The next chat id the panel hands to the runtime.
183    next_chat: ChatId,
184    /// The tab whose title is being edited, if any.
185    renaming: Option<ChatId>,
186    rename_input: Entity<InputState>,
187    /// How wide the tab strip was last laid out, so the tabs can share it.
188    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    /// The Sessions tab replaces the transcript and the composer while it is
192    /// selected; the chat tabs keep their state behind it.
193    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    /// A failure that belongs to no single chat, such as a startup error.
205    error: Option<String>,
206    errors: error_logging::AcceptedErrors,
207    /// The sign-in that would give chat a working GitHub account.
208    sign_in: Option<SignIn>,
209    /// Failures a reconnect keeps until the new runtime restores their chats.
210    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    /// Follows the shared Sign in with GitHub.
219    _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    /// The chat the panel shows. The panel always keeps at least one tab, so
302    /// closing the last one opens an empty chat rather than leaving none.
303    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    // qual:api — GPUI lifecycle callback.
314    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    /// Only stores an already loaded snapshot; no service requests or notifications.
329    // qual:api — shell passes loaded dashboard snapshots, with no UI notification.
330    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    /// The app's tools for ACP sessions. A running runtime keeps the ones
341    /// it started with; Reconnect reads them again.
342    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    /// Whether any chat tab is running a turn.
351    pub fn is_busy(&self) -> bool {
352        self.tabs.iter().any(Tab::is_busy)
353    }
354
355    /// Whether any chat tab waits for an approval or an answer.
356    // qual:api — read by the app shell's status bar.
357    pub fn needs_attention(&self) -> bool {
358        self.tabs.iter().any(Tab::needs_attention)
359    }
360
361    /// Opens or shuts a foldable transcript row of the chat shown.
362    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    /// Push the panel's state into the toolbar and the input after every
370    /// change, so both follow the tab that is shown.
371    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    /// Publishes the saved sessions, with the tabs that hold them, for the
381    /// dashboards that list them (see [`shared`]).
382    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
404/// The saved panel width, or the default when none was saved.
405fn 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
412/// Stops the runtime when the application quits.
413fn 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}