1use crate::inline_prompt_editor::{
2 CodegenStatus, PromptEditor, PromptEditorEvent, TerminalInlineAssistId,
3};
4use crate::terminal_codegen::{CLEAR_INPUT, CodegenEvent, TerminalCodegen};
5use agent::{
6 context::load_context,
7 context_store::ContextStore,
8 thread_store::{TextThreadStore, ThreadStore},
9};
10use agent_settings::AgentSettings;
11use anyhow::{Context as _, Result};
12use client::telemetry::Telemetry;
13use cloud_llm_client::CompletionIntent;
14use collections::{HashMap, VecDeque};
15use editor::{MultiBuffer, actions::SelectAll};
16use fs::Fs;
17use gpui::{App, Entity, Focusable, Global, Subscription, Task, UpdateGlobal, WeakEntity};
18use language::Buffer;
19use language_model::{
20 ConfiguredModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
21 Role, report_assistant_event,
22};
23use project::Project;
24use prompt_store::{PromptBuilder, PromptStore};
25use std::sync::Arc;
26use telemetry_events::{AssistantEventData, AssistantKind, AssistantPhase};
27use terminal_view::TerminalView;
28use ui::prelude::*;
29use util::ResultExt;
30use workspace::{Toast, Workspace, notifications::NotificationId};
31
32pub fn init(
33 fs: Arc<dyn Fs>,
34 prompt_builder: Arc<PromptBuilder>,
35 telemetry: Arc<Telemetry>,
36 cx: &mut App,
37) {
38 cx.set_global(TerminalInlineAssistant::new(fs, prompt_builder, telemetry));
39}
40
41const DEFAULT_CONTEXT_LINES: usize = 50;
42const PROMPT_HISTORY_MAX_LEN: usize = 20;
43
44pub struct TerminalInlineAssistant {
45 next_assist_id: TerminalInlineAssistId,
46 assists: HashMap<TerminalInlineAssistId, TerminalInlineAssist>,
47 prompt_history: VecDeque<String>,
48 telemetry: Option<Arc<Telemetry>>,
49 fs: Arc<dyn Fs>,
50 prompt_builder: Arc<PromptBuilder>,
51}
52
53impl Global for TerminalInlineAssistant {}
54
55impl TerminalInlineAssistant {
56 pub fn new(
57 fs: Arc<dyn Fs>,
58 prompt_builder: Arc<PromptBuilder>,
59 telemetry: Arc<Telemetry>,
60 ) -> Self {
61 Self {
62 next_assist_id: TerminalInlineAssistId::default(),
63 assists: HashMap::default(),
64 prompt_history: VecDeque::default(),
65 telemetry: Some(telemetry),
66 fs,
67 prompt_builder,
68 }
69 }
70
71 pub fn assist(
72 &mut self,
73 terminal_view: &Entity<TerminalView>,
74 workspace: WeakEntity<Workspace>,
75 project: WeakEntity<Project>,
76 prompt_store: Option<Entity<PromptStore>>,
77 thread_store: Option<WeakEntity<ThreadStore>>,
78 text_thread_store: Option<WeakEntity<TextThreadStore>>,
79 initial_prompt: Option<String>,
80 window: &mut Window,
81 cx: &mut App,
82 ) {
83 let terminal = terminal_view.read(cx).terminal().clone();
84 let assist_id = self.next_assist_id.post_inc();
85 let prompt_buffer = cx.new(|cx| {
86 MultiBuffer::singleton(
87 cx.new(|cx| Buffer::local(initial_prompt.unwrap_or_default(), cx)),
88 cx,
89 )
90 });
91 let context_store = cx.new(|_cx| ContextStore::new(project, thread_store.clone()));
92 let codegen = cx.new(|_| TerminalCodegen::new(terminal, self.telemetry.clone()));
93
94 let prompt_editor = cx.new(|cx| {
95 PromptEditor::new_terminal(
96 assist_id,
97 self.prompt_history.clone(),
98 prompt_buffer.clone(),
99 codegen,
100 self.fs.clone(),
101 context_store.clone(),
102 workspace.clone(),
103 thread_store.clone(),
104 text_thread_store.clone(),
105 window,
106 cx,
107 )
108 });
109 let prompt_editor_render = prompt_editor.clone();
110 let block = terminal_view::BlockProperties {
111 height: 4,
112 render: Box::new(move |_| prompt_editor_render.clone().into_any_element()),
113 };
114 terminal_view.update(cx, |terminal_view, cx| {
115 terminal_view.set_block_below_cursor(block, window, cx);
116 });
117
118 let terminal_assistant = TerminalInlineAssist::new(
119 assist_id,
120 terminal_view,
121 prompt_editor,
122 workspace.clone(),
123 context_store,
124 prompt_store,
125 window,
126 cx,
127 );
128
129 self.assists.insert(assist_id, terminal_assistant);
130
131 self.focus_assist(assist_id, window, cx);
132 }
133
134 fn focus_assist(
135 &mut self,
136 assist_id: TerminalInlineAssistId,
137 window: &mut Window,
138 cx: &mut App,
139 ) {
140 let assist = &self.assists[&assist_id];
141 if let Some(prompt_editor) = assist.prompt_editor.as_ref() {
142 prompt_editor.update(cx, |this, cx| {
143 this.editor.update(cx, |editor, cx| {
144 window.focus(&editor.focus_handle(cx));
145 editor.select_all(&SelectAll, window, cx);
146 });
147 });
148 }
149 }
150
151 fn handle_prompt_editor_event(
152 &mut self,
153 prompt_editor: Entity<PromptEditor<TerminalCodegen>>,
154 event: &PromptEditorEvent,
155 window: &mut Window,
156 cx: &mut App,
157 ) {
158 let assist_id = prompt_editor.read(cx).id();
159 match event {
160 PromptEditorEvent::StartRequested => {
161 self.start_assist(assist_id, cx);
162 }
163 PromptEditorEvent::StopRequested => {
164 self.stop_assist(assist_id, cx);
165 }
166 PromptEditorEvent::ConfirmRequested { execute } => {
167 self.finish_assist(assist_id, false, *execute, window, cx);
168 }
169 PromptEditorEvent::CancelRequested => {
170 self.finish_assist(assist_id, true, false, window, cx);
171 }
172 PromptEditorEvent::Resized { height_in_lines } => {
173 self.insert_prompt_editor_into_terminal(assist_id, *height_in_lines, window, cx);
174 }
175 }
176 }
177
178 fn start_assist(&mut self, assist_id: TerminalInlineAssistId, cx: &mut App) {
179 let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
180 assist
181 } else {
182 return;
183 };
184
185 let Some(user_prompt) = assist
186 .prompt_editor
187 .as_ref()
188 .map(|editor| editor.read(cx).prompt(cx))
189 else {
190 return;
191 };
192
193 self.prompt_history.retain(|prompt| *prompt != user_prompt);
194 self.prompt_history.push_back(user_prompt);
195 if self.prompt_history.len() > PROMPT_HISTORY_MAX_LEN {
196 self.prompt_history.pop_front();
197 }
198
199 assist
200 .terminal
201 .update(cx, |terminal, cx| {
202 terminal
203 .terminal()
204 .update(cx, |terminal, _| terminal.input(CLEAR_INPUT.as_bytes()));
205 })
206 .log_err();
207
208 let codegen = assist.codegen.clone();
209 let Some(request_task) = self.request_for_inline_assist(assist_id, cx).log_err() else {
210 return;
211 };
212
213 codegen.update(cx, |codegen, cx| codegen.start(request_task, cx));
214 }
215
216 fn stop_assist(&mut self, assist_id: TerminalInlineAssistId, cx: &mut App) {
217 let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
218 assist
219 } else {
220 return;
221 };
222
223 assist.codegen.update(cx, |codegen, cx| codegen.stop(cx));
224 }
225
226 fn request_for_inline_assist(
227 &self,
228 assist_id: TerminalInlineAssistId,
229 cx: &mut App,
230 ) -> Result<Task<LanguageModelRequest>> {
231 let assist = self.assists.get(&assist_id).context("invalid assist")?;
232
233 let shell = std::env::var("SHELL").ok();
234 let (latest_output, working_directory) = assist
235 .terminal
236 .update(cx, |terminal, cx| {
237 let terminal = terminal.entity().read(cx);
238 let latest_output = terminal.last_n_non_empty_lines(DEFAULT_CONTEXT_LINES);
239 let working_directory = terminal
240 .working_directory()
241 .map(|path| path.to_string_lossy().to_string());
242 (latest_output, working_directory)
243 })
244 .ok()
245 .unwrap_or_default();
246
247 let prompt = self.prompt_builder.generate_terminal_assistant_prompt(
248 &assist
249 .prompt_editor
250 .clone()
251 .context("invalid assist")?
252 .read(cx)
253 .prompt(cx),
254 shell.as_deref(),
255 working_directory.as_deref(),
256 &latest_output,
257 )?;
258
259 let contexts = assist
260 .context_store
261 .read(cx)
262 .context()
263 .cloned()
264 .collect::<Vec<_>>();
265 let context_load_task = assist.workspace.update(cx, |workspace, cx| {
266 let project = workspace.project();
267 load_context(contexts, project, &assist.prompt_store, cx)
268 })?;
269
270 let ConfiguredModel { model, .. } = LanguageModelRegistry::read_global(cx)
271 .inline_assistant_model()
272 .context("No inline assistant model")?;
273
274 let temperature = AgentSettings::temperature_for_model(&model, cx);
275
276 Ok(cx.background_spawn(async move {
277 let mut request_message = LanguageModelRequestMessage {
278 role: Role::User,
279 content: vec![],
280 cache: false,
281 };
282
283 context_load_task
284 .await
285 .loaded_context
286 .add_to_request_message(&mut request_message);
287
288 request_message.content.push(prompt.into());
289
290 LanguageModelRequest {
291 thread_id: None,
292 prompt_id: None,
293 mode: None,
294 intent: Some(CompletionIntent::TerminalInlineAssist),
295 messages: vec![request_message],
296 tools: Vec::new(),
297 tool_choice: None,
298 stop: Vec::new(),
299 temperature,
300 thinking_allowed: false,
301 }
302 }))
303 }
304
305 fn finish_assist(
306 &mut self,
307 assist_id: TerminalInlineAssistId,
308 undo: bool,
309 execute: bool,
310 window: &mut Window,
311 cx: &mut App,
312 ) {
313 self.dismiss_assist(assist_id, window, cx);
314
315 if let Some(assist) = self.assists.remove(&assist_id) {
316 assist
317 .terminal
318 .update(cx, |this, cx| {
319 this.clear_block_below_cursor(cx);
320 this.focus_handle(cx).focus(window);
321 })
322 .log_err();
323
324 if let Some(ConfiguredModel { model, .. }) =
325 LanguageModelRegistry::read_global(cx).inline_assistant_model()
326 {
327 let codegen = assist.codegen.read(cx);
328 let executor = cx.background_executor().clone();
329 report_assistant_event(
330 AssistantEventData {
331 conversation_id: None,
332 kind: AssistantKind::InlineTerminal,
333 message_id: codegen.message_id.clone(),
334 phase: if undo {
335 AssistantPhase::Rejected
336 } else {
337 AssistantPhase::Accepted
338 },
339 model: model.telemetry_id(),
340 model_provider: model.provider_id().to_string(),
341 response_latency: None,
342 error_message: None,
343 language_name: None,
344 },
345 codegen.telemetry.clone(),
346 cx.http_client(),
347 model.api_key(cx),
348 &executor,
349 );
350 }
351
352 assist.codegen.update(cx, |codegen, cx| {
353 if undo {
354 codegen.undo(cx);
355 } else if execute {
356 codegen.complete(cx);
357 }
358 });
359 }
360 }
361
362 fn dismiss_assist(
363 &mut self,
364 assist_id: TerminalInlineAssistId,
365 window: &mut Window,
366 cx: &mut App,
367 ) -> bool {
368 let Some(assist) = self.assists.get_mut(&assist_id) else {
369 return false;
370 };
371 if assist.prompt_editor.is_none() {
372 return false;
373 }
374 assist.prompt_editor = None;
375 assist
376 .terminal
377 .update(cx, |this, cx| {
378 this.clear_block_below_cursor(cx);
379 this.focus_handle(cx).focus(window);
380 })
381 .is_ok()
382 }
383
384 fn insert_prompt_editor_into_terminal(
385 &mut self,
386 assist_id: TerminalInlineAssistId,
387 height: u8,
388 window: &mut Window,
389 cx: &mut App,
390 ) {
391 if let Some(assist) = self.assists.get_mut(&assist_id)
392 && let Some(prompt_editor) = assist.prompt_editor.as_ref().cloned()
393 {
394 assist
395 .terminal
396 .update(cx, |terminal, cx| {
397 terminal.clear_block_below_cursor(cx);
398 let block = terminal_view::BlockProperties {
399 height,
400 render: Box::new(move |_| prompt_editor.clone().into_any_element()),
401 };
402 terminal.set_block_below_cursor(block, window, cx);
403 })
404 .log_err();
405 }
406 }
407}
408
409struct TerminalInlineAssist {
410 terminal: WeakEntity<TerminalView>,
411 prompt_editor: Option<Entity<PromptEditor<TerminalCodegen>>>,
412 codegen: Entity<TerminalCodegen>,
413 workspace: WeakEntity<Workspace>,
414 context_store: Entity<ContextStore>,
415 prompt_store: Option<Entity<PromptStore>>,
416 _subscriptions: Vec<Subscription>,
417}
418
419impl TerminalInlineAssist {
420 pub fn new(
421 assist_id: TerminalInlineAssistId,
422 terminal: &Entity<TerminalView>,
423 prompt_editor: Entity<PromptEditor<TerminalCodegen>>,
424 workspace: WeakEntity<Workspace>,
425 context_store: Entity<ContextStore>,
426 prompt_store: Option<Entity<PromptStore>>,
427 window: &mut Window,
428 cx: &mut App,
429 ) -> Self {
430 let codegen = prompt_editor.read(cx).codegen().clone();
431 Self {
432 terminal: terminal.downgrade(),
433 prompt_editor: Some(prompt_editor.clone()),
434 codegen: codegen.clone(),
435 workspace,
436 context_store,
437 prompt_store,
438 _subscriptions: vec![
439 window.subscribe(&prompt_editor, cx, |prompt_editor, event, window, cx| {
440 TerminalInlineAssistant::update_global(cx, |this, cx| {
441 this.handle_prompt_editor_event(prompt_editor, event, window, cx)
442 })
443 }),
444 window.subscribe(&codegen, cx, move |codegen, event, window, cx| {
445 TerminalInlineAssistant::update_global(cx, |this, cx| match event {
446 CodegenEvent::Finished => {
447 let assist = if let Some(assist) = this.assists.get(&assist_id) {
448 assist
449 } else {
450 return;
451 };
452
453 if let CodegenStatus::Error(error) = &codegen.read(cx).status
454 && assist.prompt_editor.is_none()
455 && let Some(workspace) = assist.workspace.upgrade()
456 {
457 let error = format!("Terminal inline assistant error: {}", error);
458 workspace.update(cx, |workspace, cx| {
459 struct InlineAssistantError;
460
461 let id = NotificationId::composite::<InlineAssistantError>(
462 assist_id.0,
463 );
464
465 workspace.show_toast(Toast::new(id, error), cx);
466 })
467 }
468
469 if assist.prompt_editor.is_none() {
470 this.finish_assist(assist_id, false, false, window, cx);
471 }
472 }
473 })
474 }),
475 ],
476 }
477 }
478}