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 effects;
14mod engine;
15mod error_logging;
16mod external;
17mod failure_view;
18mod ingestion;
19mod interaction;
20mod lifecycle;
21mod logic;
22mod rename;
23mod sessions;
24mod sign_in;
25mod slash;
26mod state;
27mod status;
28mod status_words;
29mod strip;
30mod tab_run;
31mod tabbing;
32mod tabs;
33#[cfg(test)]
34mod test_menu;
35mod toolbar;
36mod transcript;
37mod view;
38
39use interaction::{new_input, new_slash, new_toolbar, polling_task};
40use logic::activity_label;
41use sessions::SessionsView;
42use sign_in::{SignIn, subscriptions as sign_in_subscriptions};
43use tabs::Tab;
44
45use std::sync::Arc;
46use std::time::Duration;
47use std::{cell::RefCell, rc::Rc};
48
49use gpui_kit::component::button::{Button, ButtonVariants as _};
50use gpui_kit::component::input::InputState;
51use gpui_kit::component::{Sizable as _, h_flex, v_flex};
52use gpui_kit::{
53    Animation, App, AppContext as _, ClipboardItem, Context, Div, DragMoveEvent, ElementId,
54    EmptyView, Entity, EventEmitter, PathPromptOptions, Render, ScrollHandle, SharedString,
55    Stateful, Subscription, Task, Window, div, ease_out_quint, px, relative,
56};
57use subspace_agent::{
58    AgentHandle, ChatCommand, ChatEngine, ChatEvent, ChatId, ChatMode, Choice, Command, ContextRef,
59    Entry, EntryKind, Event, ModelChoice, SessionSummary, SlashCommand, ToolCall, ToolStatus,
60    TranscriptEntry,
61};
62
63use crate::measure;
64use crate::rich::{Format, rich_text};
65use crate::{Tokens, prefs, services};
66
67use crate::{input, shared};
68use input::ChatInput;
69use slash::SlashList;
70use toolbar::ChatToolbar;
71
72pub use attention::{ChatAttentionKind, ChatPanelEvent};
73
74/// Offline runtime injection for shell integration tests only.
75#[cfg(feature = "test-support")]
76pub mod test_support;
77
78pub const OPEN_KEY: &str = "chat.open";
79pub type ContextProvider = Rc<dyn Fn(&App) -> Option<ContextRef>>;
80/// The app's tools for ACP sessions, read when a runtime starts.
81pub type ChatToolsProvider = Rc<dyn Fn(&App) -> Option<Arc<dyn subspace_agent::ChatToolServer>>>;
82
83/// What the shell supplies: the visible board's reference and the tools
84/// ACP sessions receive.
85#[derive(Default)]
86struct Providers {
87    context: Option<ContextProvider>,
88    tools: Option<ChatToolsProvider>,
89}
90const WIDTH_KEY: &str = "chat.width";
91const POLL_INTERVAL: Duration = Duration::from_millis(75);
92const REVEAL_DURATION: Duration = Duration::from_millis(180);
93const DEFAULT_WIDTH: f32 = 420.;
94const DEFAULT_CANVAS_WIDTH: f32 = 380.;
95/// Leave a title/tab lane beside header actions; their measured row overflows.
96const HEADER_ACTION_MAX_SHARE: f32 = 0.75;
97/// The first chat id the panel assigns itself, past the restored range.
98const FIRST_CHAT: ChatId = subspace_agent::MAX_CHATS as ChatId + 1;
99const MIN_WIDTH: f32 = 300.;
100const MAX_WIDTH_FRACTION: f32 = 0.6;
101
102const PENDING_HEIGHT: f32 = 240.;
103const HANDLE_LEFT: f32 = -3.;
104const HANDLE_WIDTH: f32 = 6.;
105const FULL_FRACTION: f32 = 1.;
106const YOLO_WARNING: &str = concat!(
107    "YOLO grants full host access and permits service writes and shell commands without ordinary approval. ",
108    "Enterprise restrictions still apply. Enable for this conversation?"
109);
110/// What a read-only cloud replay says above its disabled input. The SDK
111/// reports the events at load time, so the transcript carries no agent times.
112const REPLAY_BANNER: &str = "Replay of the last cloud agent session; times are from loading";
113
114struct ChatResize;
115
116#[derive(Clone)]
117enum Pending {
118    Approval {
119        id: String,
120        summary: String,
121    },
122    Question {
123        id: String,
124        text: String,
125        choices: Vec<String>,
126    },
127}
128
129/// What a submitted line means. Slash commands never reach the runtime as
130/// text; a skill runs through `RunCommand`.
131#[derive(Debug, PartialEq, Eq)]
132enum InputIntent {
133    AddContext,
134    EnableYolo,
135    DisableYolo,
136    NewChat,
137    CloseChat,
138    Rename(String),
139    OpenSessions,
140    OpenModels,
141    RunSkill { name: String, args: String },
142    UnknownCommand,
143    Message(String),
144}
145
146struct Submission {
147    command: Option<Command>,
148    clear: bool,
149    starts_turn: bool,
150    /// The message joins a turn that is already running, so the turn's timer
151    /// and status phrase keep going instead of restarting.
152    steering: bool,
153    answer_id: Option<String>,
154    /// The message this submission sends, which Retry can send again.
155    last_turn: Option<tabs::LastTurn>,
156}
157
158#[derive(Clone, Copy)]
159enum Preference {
160    Tools,
161    Thinking,
162    AutoContext,
163}
164
165pub struct ChatPanel {
166    engine: ChatEngine,
167    /// The configured ACP agent, which names the engine when it is ACP.
168    acp_agent: subspace_agent::AcpAgent,
169    handle: Option<AgentHandle>,
170    input: Entity<ChatInput>,
171    toolbar: Entity<ChatToolbar>,
172    slash: Entity<SlashList>,
173    /// The open chats, in strip order, and the one shown.
174    tabs: Vec<Tab>,
175    active: usize,
176    /// The next chat id the panel hands to the runtime.
177    next_chat: ChatId,
178    /// The tab whose title is being edited, if any.
179    renaming: Option<ChatId>,
180    rename_input: Entity<InputState>,
181    /// How wide the tab strip was last laid out, so the tabs can share it.
182    strip_width: Entity<f32>,
183    header_toolbar: RefCell<Option<Entity<subspace_dashboard::overflow_toolbar::OverflowToolbar>>>,
184    canvas_toolbar: RefCell<Option<Entity<subspace_dashboard::overflow_toolbar::OverflowToolbar>>>,
185    /// The Sessions tab replaces the transcript and the composer while it is
186    /// selected; the chat tabs keep their state behind it.
187    sessions_open: bool,
188    view: SessionsView,
189    current: Option<ContextRef>,
190    providers: Providers,
191    auto_context: bool,
192    show_tools: bool,
193    show_thinking: bool,
194    models: Vec<ModelChoice>,
195    agents: Vec<Choice>,
196    sessions: Vec<SessionSummary>,
197    commands: Vec<SlashCommand>,
198    /// A failure that belongs to no single chat, such as a startup error.
199    error: Option<String>,
200    errors: error_logging::AcceptedErrors,
201    /// The sign-in that would give chat a working GitHub account.
202    sign_in: Option<SignIn>,
203    /// Failures a reconnect keeps until the new runtime restores their chats.
204    carried: Vec<carry::Carried>,
205    attachment_ingestion_busy: bool,
206    width: f32,
207    canvas_width: f32,
208    canvas_focus: gpui_kit::FocusHandle,
209    reveal: u64,
210    scroll: ScrollHandle,
211    _subscriptions: Vec<Subscription>,
212    /// Follows the shared Sign in with GitHub.
213    _sign_in: Vec<Subscription>,
214    _poller: Task<()>,
215    _shutdown: Subscription,
216}
217
218impl EventEmitter<ChatPanelEvent> for ChatPanel {}
219
220impl ChatPanel {
221    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
222        Self::with_engine(configured_engine(cx), window, cx)
223    }
224
225    fn with_engine(engine: ChatEngine, window: &mut Window, cx: &mut Context<Self>) -> Self {
226        let toolbar = new_toolbar(window, cx);
227        let input = new_input(engine, configured_acp_agent(cx), &toolbar, window, cx);
228        let slash = new_slash(engine, window, cx);
229        let rename_input = cx.new(|cx| InputState::new(window, cx));
230        let session_search =
231            cx.new(|cx| InputState::new(window, cx).placeholder("Search sessions"));
232        let session_rename = cx.new(|cx| InputState::new(window, cx));
233        let subscriptions = vec![
234            cx.subscribe_in(&input, window, Self::on_input_event),
235            cx.subscribe_in(&toolbar, window, Self::on_toolbar_event),
236            cx.subscribe_in(&slash, window, Self::on_slash_event),
237            cx.subscribe_in(&rename_input, window, Self::on_rename_event),
238            cx.subscribe_in(&session_search, window, Self::on_search_event),
239            cx.subscribe_in(&session_rename, window, Self::on_session_rename_event),
240        ];
241        Self {
242            engine,
243            acp_agent: configured_acp_agent(cx),
244            handle: None,
245            input,
246            toolbar,
247            slash,
248            tabs: vec![Tab::new(1)],
249            active: 0,
250            // The runtime numbers the tabs it restores from 1, so the panel's
251            // own ids start past that range and never collide with them.
252            next_chat: FIRST_CHAT,
253            renaming: None,
254            rename_input,
255            strip_width: measure::unmeasured(cx),
256            header_toolbar: RefCell::new(None),
257            canvas_toolbar: RefCell::new(None),
258            sessions_open: false,
259            view: SessionsView::new(session_search, session_rename, measure::unmeasured(cx)),
260            current: None,
261            providers: Providers::default(),
262            auto_context: prefs::get(cx, "chat.auto-context").as_deref() != Some("0"),
263            show_tools: prefs::get(cx, "chat.tools").as_deref() != Some("0"),
264            show_thinking: prefs::get(cx, "chat.thinking").as_deref() == Some("1"),
265            models: Vec::new(),
266            agents: Vec::new(),
267            sessions: Vec::new(),
268            commands: Vec::new(),
269            error: None,
270            errors: Default::default(),
271            sign_in: None,
272            carried: Vec::new(),
273            attachment_ingestion_busy: false,
274            width: panel_width(cx),
275            canvas_width: DEFAULT_CANVAS_WIDTH,
276            canvas_focus: cx.focus_handle(),
277            reveal: 0,
278            scroll: ScrollHandle::new(),
279            _subscriptions: subscriptions,
280            _sign_in: sign_in_subscriptions(cx),
281            _poller: polling_task(cx),
282            _shutdown: shutdown_hook(cx),
283        }
284    }
285
286    #[cfg(test)]
287    fn new_copilot(window: &mut Window, cx: &mut Context<Self>) -> Self {
288        Self::with_engine(ChatEngine::Copilot, window, cx)
289    }
290
291    /// The chat the panel shows. The panel always keeps at least one tab, so
292    /// closing the last one opens an empty chat rather than leaving none.
293    fn tab(&self) -> &Tab {
294        let index = self.active.min(self.tabs.len().saturating_sub(1));
295        &self.tabs[index]
296    }
297
298    fn tab_mut(&mut self) -> &mut Tab {
299        let index = self.active.min(self.tabs.len().saturating_sub(1));
300        &mut self.tabs[index]
301    }
302
303    // qual:api — GPUI lifecycle callback.
304    pub fn on_open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
305        self.reveal = self.reveal.wrapping_add(1);
306        if self.is_disabled() {
307            cx.notify();
308            return;
309        }
310        if self.handle.is_none() {
311            self.start(cx);
312        }
313        self.input.update(cx, |input, cx| input.focus(window, cx));
314        self.sync_toolbar(cx);
315        cx.notify();
316    }
317
318    /// Only stores an already loaded snapshot; no service requests or notifications.
319    // qual:api — shell passes loaded dashboard snapshots, with no UI notification.
320    pub fn set_context(&mut self, context: Option<ContextRef>, _cx: &mut Context<Self>) {
321        if self.current != context {
322            self.current = context;
323        }
324    }
325
326    pub fn set_context_provider(&mut self, provider: ContextProvider) {
327        self.providers.context = Some(provider);
328    }
329
330    /// The app's tools for ACP sessions. A running runtime keeps the ones
331    /// it started with; Reconnect reads them again.
332    pub fn set_chat_tools(&mut self, provider: ChatToolsProvider) {
333        self.providers.tools = Some(provider);
334    }
335
336    pub fn indicator(&self) -> &'static str {
337        activity_label(self.is_busy(), self.needs_attention())
338    }
339
340    /// Whether any chat tab is running a turn.
341    pub fn is_busy(&self) -> bool {
342        self.tabs.iter().any(Tab::is_busy)
343    }
344
345    /// Whether any chat tab waits for an approval or an answer.
346    // qual:api — read by the app shell's status bar.
347    pub fn needs_attention(&self) -> bool {
348        self.tabs.iter().any(Tab::needs_attention)
349    }
350
351    /// Opens or shuts a foldable transcript row of the chat shown.
352    fn toggle_expanded(&mut self, key: &str) {
353        let expanded = &mut self.tab_mut().expanded;
354        if !expanded.remove(key) {
355            expanded.insert(key.to_owned());
356        }
357    }
358
359    /// Push the panel's state into the toolbar and the input after every
360    /// change, so both follow the tab that is shown.
361    pub(crate) fn sync_toolbar(&mut self, cx: &mut Context<Self>) {
362        let model = self.toolbar_model();
363        let read_only = self.tab().read_only;
364        self.toolbar
365            .update(cx, |toolbar, cx| toolbar.set_model(model, cx));
366        self.input
367            .update(cx, |input, cx| input.set_disabled(read_only, cx));
368    }
369
370    /// Publishes the saved sessions, with the tabs that hold them, for the
371    /// dashboards that list them (see [`shared`]).
372    pub(crate) fn publish_sessions(&self, cx: &mut App) {
373        let open: Vec<(String, bool)> = self
374            .tabs
375            .iter()
376            .filter_map(|tab| Some((tab.session.clone()?, tab.is_busy())))
377            .collect();
378        shared::publish(cx, shared::with_tabs(&self.sessions, &open));
379    }
380}
381
382fn configured_acp_agent(cx: &App) -> subspace_agent::AcpAgent {
383    services(cx)
384        .map(|services| services.config.chat.acp.agent)
385        .unwrap_or_default()
386}
387
388fn configured_engine(cx: &App) -> ChatEngine {
389    services(cx)
390        .map(|services| services.config.chat.engine)
391        .unwrap_or_default()
392}
393
394/// The saved panel width, or the default when none was saved.
395fn panel_width(cx: &App) -> f32 {
396    prefs::get(cx, WIDTH_KEY)
397        .and_then(|width| width.parse().ok())
398        .filter(|width: &f32| width.is_finite())
399        .unwrap_or(DEFAULT_WIDTH)
400}
401
402/// Stops the runtime when the application quits.
403fn shutdown_hook(cx: &mut Context<ChatPanel>) -> Subscription {
404    cx.on_app_quit(|chat, _| {
405        let _ = chat
406            .handle
407            .as_ref()
408            .map(|handle| handle.send(Command::Shutdown));
409        async {}
410    })
411}
412
413fn control(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Button {
414    let label = label.into();
415    Button::new(id)
416        .ghost()
417        .xsmall()
418        .accessibility_label(label.clone())
419        .label(label)
420}