Skip to main content

subspace_chat/agent_chat/
view.rs

1use super::input::CHAT_PANEL_CONTEXT;
2use gpui_kit::{AnyElement, IntoElement};
3
4#[cfg(test)]
5mod extent_tests;
6
7use super::logic::clamped_width;
8use super::sign_in::SignIn;
9use super::{
10    Animation, ChatPanel, ChatResize, Context, Div, DragMoveEvent, EmptyView, FULL_FRACTION,
11    HANDLE_LEFT, HANDLE_WIDTH, REPLAY_BANNER, REVEAL_DURATION, Render, Tokens, Window,
12    YOLO_WARNING, div, ease_out_quint, h_flex, px, v_flex,
13};
14use crate::action::{Intent, action_button};
15use crate::rich;
16use gpui_kit::component::Disableable as _;
17use gpui_kit::prelude::FluentBuilder as _;
18use gpui_kit::{
19    AnimationExt as _, AppContext as _, InteractiveElement as _, ParentElement as _,
20    StatefulInteractiveElement as _, Styled as _, TestSupportExt as _, relative,
21};
22use subspace_lucide::IconName;
23
24/// Chat and a docked Canvas each get half the auxiliary width budget.
25const SHARED_WIDTH_FRACTION: f32 = super::MAX_WIDTH_FRACTION / 2.;
26
27pub(super) fn reconnect_intent(sign_in: bool) -> Intent {
28    if sign_in {
29        Intent::Neutral
30    } else {
31        Intent::Primary
32    }
33}
34
35impl ChatPanel {
36    /// Limit rendered panes against their actual parent row, not the viewport.
37    /// Gallery replaces the board; otherwise reserve its share even beside a
38    /// side dock or rail. Stored widths return unchanged when the row widens.
39    pub(super) fn pane_width_fraction(&self) -> f32 {
40        if !self.canvas_gallery()
41            && super::canvas::shown_canvas(&self.tab().canvases, self.sessions_open).is_some()
42        {
43            SHARED_WIDTH_FRACTION
44        } else {
45            super::MAX_WIDTH_FRACTION
46        }
47    }
48
49    pub(super) fn render_yolo_warning(
50        &self,
51        tokens: &Tokens,
52        cx: &mut Context<Self>,
53    ) -> Option<Div> {
54        (self.capabilities().copilot_controls && self.tab().confirm_yolo).then(|| {
55            v_flex()
56                .p_2()
57                .gap_2()
58                .text_color(tokens.yellow)
59                .child(rich::plain_text("chat-yolo-warning", YOLO_WARNING))
60                .child(
61                    h_flex()
62                        .gap_2()
63                        .child(
64                            action_button(
65                                "chat-yolo-cancel",
66                                Intent::Neutral,
67                                Some(IconName::X),
68                                "Cancel",
69                            )
70                            .on_click(cx.listener(|chat, _, _, cx| {
71                                chat.tab_mut().confirm_yolo = false;
72                                cx.notify();
73                            })),
74                        )
75                        .child(
76                            action_button(
77                                "chat-yolo-confirm",
78                                Intent::Caution,
79                                Some(IconName::ShieldAlert),
80                                "Enable YOLO",
81                            )
82                            .on_click(cx.listener(|chat, _, _, cx| chat.confirm_mode(cx))),
83                        ),
84                )
85        })
86    }
87
88    /// This chat's failure, else a failure that belongs to no chat, with
89    /// Sign in to GitHub when GitHub rejected the chat account's gh token.
90    pub(super) fn render_error(&self, tokens: &Tokens, cx: &mut Context<Self>) -> Option<Div> {
91        let error = self.tab().error.clone().or_else(|| self.error.clone());
92        let signing = self.signing_in(cx);
93        let busy = self.tab().is_busy() || signing;
94        // Only a stopped runtime needs a new one. A chat error, such as a
95        // refused command or a replay's failure, leaves the runtime running,
96        // and restarting it would interrupt every chat.
97        let stopped = self.is_unavailable();
98        let reconnect = stopped && !self.tab().read_only;
99        let sign_in = self.sign_in.is_some() && reconnect;
100        let note = self.sign_in.as_ref().and_then(SignIn::note);
101        let in_app = self.in_app_status(tokens, cx);
102        let reconnect_intent = reconnect_intent(sign_in);
103        error.map(|error| {
104            v_flex()
105                .p_2()
106                .gap_1()
107                .text_color(tokens.red)
108                .child(rich::plain_text("chat-error", &error))
109                .children(
110                    super::engine::error_guidance(self.engine, reconnect).map(|guidance| {
111                        div()
112                            .text_color(tokens.muted)
113                            .child(rich::plain_text("chat-error-guidance", guidance))
114                    }),
115                )
116                .children(note.map(|note| {
117                    div()
118                        .text_color(tokens.yellow)
119                        .child(rich::plain_text("chat-sign-in-note", &note))
120                }))
121                .children(in_app)
122                .when(sign_in, |column| {
123                    column.child(
124                        action_button(
125                            "chat-sign-in",
126                            Intent::Primary,
127                            Some(IconName::LogIn),
128                            "Sign in to GitHub",
129                        )
130                        .disabled(signing)
131                        .on_click(cx.listener(|chat, _, _, cx| chat.sign_in(cx))),
132                    )
133                })
134                .when(reconnect, |column| {
135                    column.child(
136                        action_button(
137                            "chat-reconnect",
138                            reconnect_intent,
139                            Some(IconName::RotateCw),
140                            "Reconnect",
141                        )
142                        .disabled(busy)
143                        .on_click(cx.listener(|chat, _, window, cx| chat.reconnect(window, cx))),
144                    )
145                })
146                .children(self.copy_legacy_error())
147        })
148    }
149
150    /// The `/` list, the context pills and the input with its toolbar.
151    pub(super) fn render_composer(&self, cx: &mut Context<Self>) -> Div {
152        v_flex()
153            .gap_1()
154            .child(self.slash.clone())
155            .child(self.render_context_pills(cx))
156            .child(self.input.clone())
157    }
158
159    /// What a replay tab says above its disabled input, with the way back to
160    /// the task's own page, where it can still be steered.
161    pub(super) fn render_replay_banner(
162        &self,
163        tokens: &Tokens,
164        cx: &mut Context<Self>,
165    ) -> Option<Div> {
166        let tab = self.tab();
167        let url = tab.session_url.clone();
168        tab.read_only.then(|| {
169            v_flex()
170                .p_2()
171                .gap_1()
172                .text_color(tokens.muted)
173                .child(rich::plain_text("chat-replay-banner", REPLAY_BANNER))
174                .children(url.map(|url| {
175                    action_button(
176                        "chat-replay-session",
177                        Intent::Neutral,
178                        Some(IconName::ExternalLink),
179                        if url.as_ref() == "https://github.com/copilot/agents" {
180                            "Open GitHub Agents in browser"
181                        } else {
182                            "Open session in browser"
183                        },
184                    )
185                    .on_click(cx.listener(move |_, _, _, cx| {
186                        crate::links::open(&url, cx);
187                    }))
188                }))
189        })
190    }
191
192    /// The chat below the header, or the session list while the Sessions tab
193    /// is selected.
194    pub(super) fn render_body(&self, tokens: &Tokens, cx: &mut Context<Self>) -> Vec<AnyElement> {
195        if self.is_disabled() {
196            return vec![
197                div()
198                    .id("chat-off")
199                    .test_support()
200                    .p_2()
201                    .text_color(tokens.muted)
202                    .child(rich::plain_text("chat-off-guidance", self.guidance()))
203                    .into_any_element(),
204            ];
205        }
206        if self.sessions_open {
207            return vec![
208                self.render_sessions(tokens, cx).into_any_element(),
209                div()
210                    .children(self.render_notice(tokens))
211                    .into_any_element(),
212                div()
213                    .children(self.render_delete_dialog(cx))
214                    .into_any_element(),
215            ];
216        }
217        let mut body = vec![self.render_transcript(tokens, cx).into_any_element()];
218        // Everything that needs an answer sits directly above the input.
219        body.extend(
220            self.render_pending(tokens, cx)
221                .map(IntoElement::into_any_element),
222        );
223        body.extend(
224            self.render_yolo_warning(tokens, cx)
225                .map(IntoElement::into_any_element),
226        );
227        body.extend(
228            self.render_failure(tokens, cx)
229                .map(IntoElement::into_any_element),
230        );
231        body.extend(
232            self.render_error(tokens, cx)
233                .map(IntoElement::into_any_element),
234        );
235        body.extend(
236            self.render_replay_banner(tokens, cx)
237                .map(IntoElement::into_any_element),
238        );
239        body.push(self.render_composer(cx).into_any_element());
240        body
241    }
242
243    /// One line of feedback under the session list, such as a finished export.
244    fn render_notice(&self, tokens: &Tokens) -> Option<Div> {
245        let notice = self.view.notice.clone().or_else(|| self.error.clone())?;
246        Some(
247            div()
248                .p_2()
249                .text_color(tokens.muted)
250                .child(rich::plain_text("chat-notice", &notice)),
251        )
252    }
253
254    pub(super) fn render_frame(&self, tokens: &Tokens, cx: &mut Context<Self>) -> impl IntoElement {
255        let frame = v_flex().id("agent-chat").when(!self.is_disabled(), |pane| {
256            super::strip::bind_tab_actions(pane, cx)
257        });
258        frame
259            .test_support()
260            .key_context(CHAT_PANEL_CONTEXT)
261            .on_key_down(cx.listener(Self::canvas_key))
262            .on_drop::<gpui_kit::ExternalPaths>(
263                cx.listener(|chat, paths, _, cx| chat.drop_paths(paths, cx)),
264            )
265            .relative()
266            .h_full()
267            .w_full()
268            .min_w_0()
269            .flex_shrink_0()
270            .bg(tokens.surface)
271            .border_l_1()
272            .border_color(tokens.line)
273            .text_size(tokens.row_font)
274            .on_drag_move::<ChatResize>(cx.listener(
275                |chat, event: &DragMoveEvent<ChatResize>, window, cx| {
276                    chat.resize(
277                        f32::from(event.bounds.right() - event.event.position.x),
278                        window,
279                        cx,
280                    );
281                },
282            ))
283            .child(self.render_header(tokens, cx))
284            .children(self.render_body(tokens, cx))
285            .child(
286                div()
287                    .id("chat-resize")
288                    .absolute()
289                    .left(px(HANDLE_LEFT))
290                    .top_0()
291                    .bottom_0()
292                    .w(px(HANDLE_WIDTH))
293                    .cursor_col_resize()
294                    .on_drag(ChatResize, |_, _, _, cx| cx.new(|_| EmptyView)),
295            )
296    }
297}
298
299impl Render for ChatPanel {
300    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
301        let tokens = Tokens::current(cx);
302        let width = clamped_width(self.width, f32::from(window.viewport_size().width));
303        let panel = self.render_frame(&tokens, cx);
304        div()
305            .h_full()
306            .min_w_0()
307            .max_w(relative(self.pane_width_fraction()))
308            .flex_shrink_0()
309            .child(panel)
310            .with_animation(
311                ("chat-reveal", self.reveal),
312                Animation::new(REVEAL_DURATION).with_easing(ease_out_quint()),
313                move |pane, delta| {
314                    pane.w(px(width * delta))
315                        .when(delta < FULL_FRACTION, |pane| pane.overflow_hidden())
316                },
317            )
318    }
319}