terminal_inline_assistant.rs

   1use crate::{AssistantPanel, AssistantPanelEvent, DEFAULT_CONTEXT_LINES};
   2use anyhow::{Context as _, Result};
   3use assistant_context_editor::{humanize_token_count, RequestType};
   4use assistant_settings::AssistantSettings;
   5use client::telemetry::Telemetry;
   6use collections::{HashMap, VecDeque};
   7use editor::{
   8    actions::{MoveDown, MoveUp, SelectAll},
   9    Editor, EditorElement, EditorEvent, EditorMode, EditorStyle, MultiBuffer,
  10};
  11use fs::Fs;
  12use futures::{channel::mpsc, SinkExt, StreamExt};
  13use gpui::{
  14    App, Context, Entity, EventEmitter, FocusHandle, Focusable, Global, Subscription, Task,
  15    TextStyle, UpdateGlobal, WeakEntity,
  16};
  17use language::Buffer;
  18use language_model::{
  19    report_assistant_event, LanguageModelRegistry, LanguageModelRequest,
  20    LanguageModelRequestMessage, Role,
  21};
  22use language_model_selector::inline_language_model_selector;
  23use prompt_store::PromptBuilder;
  24use settings::{update_settings_file, Settings};
  25use std::{
  26    cmp,
  27    sync::Arc,
  28    time::{Duration, Instant},
  29};
  30use telemetry_events::{AssistantEvent, AssistantKind, AssistantPhase};
  31use terminal::Terminal;
  32use terminal_view::TerminalView;
  33use theme::ThemeSettings;
  34use ui::{prelude::*, text_for_action, IconButtonShape, Tooltip};
  35use util::ResultExt;
  36use workspace::{notifications::NotificationId, Toast, Workspace};
  37
  38pub fn init(
  39    fs: Arc<dyn Fs>,
  40    prompt_builder: Arc<PromptBuilder>,
  41    telemetry: Arc<Telemetry>,
  42    cx: &mut App,
  43) {
  44    cx.set_global(TerminalInlineAssistant::new(fs, prompt_builder, telemetry));
  45}
  46
  47const PROMPT_HISTORY_MAX_LEN: usize = 20;
  48
  49#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
  50struct TerminalInlineAssistId(usize);
  51
  52impl TerminalInlineAssistId {
  53    fn post_inc(&mut self) -> TerminalInlineAssistId {
  54        let id = *self;
  55        self.0 += 1;
  56        id
  57    }
  58}
  59
  60pub struct TerminalInlineAssistant {
  61    next_assist_id: TerminalInlineAssistId,
  62    assists: HashMap<TerminalInlineAssistId, TerminalInlineAssist>,
  63    prompt_history: VecDeque<String>,
  64    telemetry: Option<Arc<Telemetry>>,
  65    fs: Arc<dyn Fs>,
  66    prompt_builder: Arc<PromptBuilder>,
  67}
  68
  69impl Global for TerminalInlineAssistant {}
  70
  71impl TerminalInlineAssistant {
  72    pub fn new(
  73        fs: Arc<dyn Fs>,
  74        prompt_builder: Arc<PromptBuilder>,
  75        telemetry: Arc<Telemetry>,
  76    ) -> Self {
  77        Self {
  78            next_assist_id: TerminalInlineAssistId::default(),
  79            assists: HashMap::default(),
  80            prompt_history: VecDeque::default(),
  81            telemetry: Some(telemetry),
  82            fs,
  83            prompt_builder,
  84        }
  85    }
  86
  87    pub fn assist(
  88        &mut self,
  89        terminal_view: &Entity<TerminalView>,
  90        workspace: Option<WeakEntity<Workspace>>,
  91        assistant_panel: Option<&Entity<AssistantPanel>>,
  92        initial_prompt: Option<String>,
  93        window: &mut Window,
  94        cx: &mut App,
  95    ) {
  96        let terminal = terminal_view.read(cx).terminal().clone();
  97        let assist_id = self.next_assist_id.post_inc();
  98        let prompt_buffer = cx.new(|cx| Buffer::local(initial_prompt.unwrap_or_default(), cx));
  99        let prompt_buffer = cx.new(|cx| MultiBuffer::singleton(prompt_buffer, cx));
 100        let codegen = cx.new(|_| Codegen::new(terminal, self.telemetry.clone()));
 101
 102        let prompt_editor = cx.new(|cx| {
 103            PromptEditor::new(
 104                assist_id,
 105                self.prompt_history.clone(),
 106                prompt_buffer.clone(),
 107                codegen,
 108                assistant_panel,
 109                workspace.clone(),
 110                self.fs.clone(),
 111                window,
 112                cx,
 113            )
 114        });
 115        let prompt_editor_render = prompt_editor.clone();
 116        let block = terminal_view::BlockProperties {
 117            height: 2,
 118            render: Box::new(move |_| prompt_editor_render.clone().into_any_element()),
 119        };
 120        terminal_view.update(cx, |terminal_view, cx| {
 121            terminal_view.set_block_below_cursor(block, window, cx);
 122        });
 123
 124        let terminal_assistant = TerminalInlineAssist::new(
 125            assist_id,
 126            terminal_view,
 127            assistant_panel.is_some(),
 128            prompt_editor,
 129            workspace.clone(),
 130            window,
 131            cx,
 132        );
 133
 134        self.assists.insert(assist_id, terminal_assistant);
 135
 136        self.focus_assist(assist_id, window, cx);
 137    }
 138
 139    fn focus_assist(
 140        &mut self,
 141        assist_id: TerminalInlineAssistId,
 142        window: &mut Window,
 143        cx: &mut App,
 144    ) {
 145        let assist = &self.assists[&assist_id];
 146        if let Some(prompt_editor) = assist.prompt_editor.as_ref() {
 147            prompt_editor.update(cx, |this, cx| {
 148                this.editor.update(cx, |editor, cx| {
 149                    window.focus(&editor.focus_handle(cx));
 150                    editor.select_all(&SelectAll, window, cx);
 151                });
 152            });
 153        }
 154    }
 155
 156    fn handle_prompt_editor_event(
 157        &mut self,
 158        prompt_editor: Entity<PromptEditor>,
 159        event: &PromptEditorEvent,
 160        window: &mut Window,
 161        cx: &mut App,
 162    ) {
 163        let assist_id = prompt_editor.read(cx).id;
 164        match event {
 165            PromptEditorEvent::StartRequested => {
 166                self.start_assist(assist_id, cx);
 167            }
 168            PromptEditorEvent::StopRequested => {
 169                self.stop_assist(assist_id, cx);
 170            }
 171            PromptEditorEvent::ConfirmRequested { execute } => {
 172                self.finish_assist(assist_id, false, *execute, window, cx);
 173            }
 174            PromptEditorEvent::CancelRequested => {
 175                self.finish_assist(assist_id, true, false, window, cx);
 176            }
 177            PromptEditorEvent::DismissRequested => {
 178                self.dismiss_assist(assist_id, window, cx);
 179            }
 180            PromptEditorEvent::Resized { height_in_lines } => {
 181                self.insert_prompt_editor_into_terminal(assist_id, *height_in_lines, window, cx);
 182            }
 183        }
 184    }
 185
 186    fn start_assist(&mut self, assist_id: TerminalInlineAssistId, cx: &mut App) {
 187        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
 188            assist
 189        } else {
 190            return;
 191        };
 192
 193        let Some(user_prompt) = assist
 194            .prompt_editor
 195            .as_ref()
 196            .map(|editor| editor.read(cx).prompt(cx))
 197        else {
 198            return;
 199        };
 200
 201        self.prompt_history.retain(|prompt| *prompt != user_prompt);
 202        self.prompt_history.push_back(user_prompt.clone());
 203        if self.prompt_history.len() > PROMPT_HISTORY_MAX_LEN {
 204            self.prompt_history.pop_front();
 205        }
 206
 207        assist
 208            .terminal
 209            .update(cx, |terminal, cx| {
 210                terminal
 211                    .terminal()
 212                    .update(cx, |terminal, _| terminal.input(CLEAR_INPUT.to_string()));
 213            })
 214            .log_err();
 215
 216        let codegen = assist.codegen.clone();
 217        let Some(request) = self.request_for_inline_assist(assist_id, cx).log_err() else {
 218            return;
 219        };
 220
 221        codegen.update(cx, |codegen, cx| codegen.start(request, cx));
 222    }
 223
 224    fn stop_assist(&mut self, assist_id: TerminalInlineAssistId, cx: &mut App) {
 225        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
 226            assist
 227        } else {
 228            return;
 229        };
 230
 231        assist.codegen.update(cx, |codegen, cx| codegen.stop(cx));
 232    }
 233
 234    fn request_for_inline_assist(
 235        &self,
 236        assist_id: TerminalInlineAssistId,
 237        cx: &mut App,
 238    ) -> Result<LanguageModelRequest> {
 239        let assist = self.assists.get(&assist_id).context("invalid assist")?;
 240
 241        let shell = std::env::var("SHELL").ok();
 242        let (latest_output, working_directory) = assist
 243            .terminal
 244            .update(cx, |terminal, cx| {
 245                let terminal = terminal.entity().read(cx);
 246                let latest_output = terminal.last_n_non_empty_lines(DEFAULT_CONTEXT_LINES);
 247                let working_directory = terminal
 248                    .working_directory()
 249                    .map(|path| path.to_string_lossy().to_string());
 250                (latest_output, working_directory)
 251            })
 252            .ok()
 253            .unwrap_or_default();
 254
 255        let context_request = if assist.include_context {
 256            assist.workspace.as_ref().and_then(|workspace| {
 257                let workspace = workspace.upgrade()?.read(cx);
 258                let assistant_panel = workspace.panel::<AssistantPanel>(cx)?;
 259                Some(
 260                    assistant_panel
 261                        .read(cx)
 262                        .active_context(cx)?
 263                        .read(cx)
 264                        .to_completion_request(RequestType::Chat, cx),
 265                )
 266            })
 267        } else {
 268            None
 269        };
 270
 271        let prompt = self.prompt_builder.generate_terminal_assistant_prompt(
 272            &assist
 273                .prompt_editor
 274                .clone()
 275                .context("invalid assist")?
 276                .read(cx)
 277                .prompt(cx),
 278            shell.as_deref(),
 279            working_directory.as_deref(),
 280            &latest_output,
 281        )?;
 282
 283        let mut messages = Vec::new();
 284        if let Some(context_request) = context_request {
 285            messages = context_request.messages;
 286        }
 287
 288        messages.push(LanguageModelRequestMessage {
 289            role: Role::User,
 290            content: vec![prompt.into()],
 291            cache: false,
 292        });
 293
 294        Ok(LanguageModelRequest {
 295            messages,
 296            tools: Vec::new(),
 297            stop: Vec::new(),
 298            temperature: None,
 299        })
 300    }
 301
 302    fn finish_assist(
 303        &mut self,
 304        assist_id: TerminalInlineAssistId,
 305        undo: bool,
 306        execute: bool,
 307        window: &mut Window,
 308        cx: &mut App,
 309    ) {
 310        self.dismiss_assist(assist_id, window, cx);
 311
 312        if let Some(assist) = self.assists.remove(&assist_id) {
 313            assist
 314                .terminal
 315                .update(cx, |this, cx| {
 316                    this.clear_block_below_cursor(cx);
 317                    this.focus_handle(cx).focus(window);
 318                })
 319                .log_err();
 320
 321            if let Some(model) = LanguageModelRegistry::read_global(cx).active_model() {
 322                let codegen = assist.codegen.read(cx);
 323                let executor = cx.background_executor().clone();
 324                report_assistant_event(
 325                    AssistantEvent {
 326                        conversation_id: None,
 327                        kind: AssistantKind::InlineTerminal,
 328                        message_id: codegen.message_id.clone(),
 329                        phase: if undo {
 330                            AssistantPhase::Rejected
 331                        } else {
 332                            AssistantPhase::Accepted
 333                        },
 334                        model: model.telemetry_id(),
 335                        model_provider: model.provider_id().to_string(),
 336                        response_latency: None,
 337                        error_message: None,
 338                        language_name: None,
 339                    },
 340                    codegen.telemetry.clone(),
 341                    cx.http_client(),
 342                    model.api_key(cx),
 343                    &executor,
 344                );
 345            }
 346
 347            assist.codegen.update(cx, |codegen, cx| {
 348                if undo {
 349                    codegen.undo(cx);
 350                } else if execute {
 351                    codegen.complete(cx);
 352                }
 353            });
 354        }
 355    }
 356
 357    fn dismiss_assist(
 358        &mut self,
 359        assist_id: TerminalInlineAssistId,
 360        window: &mut Window,
 361        cx: &mut App,
 362    ) -> bool {
 363        let Some(assist) = self.assists.get_mut(&assist_id) else {
 364            return false;
 365        };
 366        if assist.prompt_editor.is_none() {
 367            return false;
 368        }
 369        assist.prompt_editor = None;
 370        assist
 371            .terminal
 372            .update(cx, |this, cx| {
 373                this.clear_block_below_cursor(cx);
 374                this.focus_handle(cx).focus(window);
 375            })
 376            .is_ok()
 377    }
 378
 379    fn insert_prompt_editor_into_terminal(
 380        &mut self,
 381        assist_id: TerminalInlineAssistId,
 382        height: u8,
 383        window: &mut Window,
 384        cx: &mut App,
 385    ) {
 386        if let Some(assist) = self.assists.get_mut(&assist_id) {
 387            if let Some(prompt_editor) = assist.prompt_editor.as_ref().cloned() {
 388                assist
 389                    .terminal
 390                    .update(cx, |terminal, cx| {
 391                        terminal.clear_block_below_cursor(cx);
 392                        let block = terminal_view::BlockProperties {
 393                            height,
 394                            render: Box::new(move |_| prompt_editor.clone().into_any_element()),
 395                        };
 396                        terminal.set_block_below_cursor(block, window, cx);
 397                    })
 398                    .log_err();
 399            }
 400        }
 401    }
 402}
 403
 404struct TerminalInlineAssist {
 405    terminal: WeakEntity<TerminalView>,
 406    prompt_editor: Option<Entity<PromptEditor>>,
 407    codegen: Entity<Codegen>,
 408    workspace: Option<WeakEntity<Workspace>>,
 409    include_context: bool,
 410    _subscriptions: Vec<Subscription>,
 411}
 412
 413impl TerminalInlineAssist {
 414    pub fn new(
 415        assist_id: TerminalInlineAssistId,
 416        terminal: &Entity<TerminalView>,
 417        include_context: bool,
 418        prompt_editor: Entity<PromptEditor>,
 419        workspace: Option<WeakEntity<Workspace>>,
 420        window: &mut Window,
 421        cx: &mut App,
 422    ) -> Self {
 423        let codegen = prompt_editor.read(cx).codegen.clone();
 424        Self {
 425            terminal: terminal.downgrade(),
 426            prompt_editor: Some(prompt_editor.clone()),
 427            codegen: codegen.clone(),
 428            workspace: workspace.clone(),
 429            include_context,
 430            _subscriptions: vec![
 431                window.subscribe(&prompt_editor, cx, |prompt_editor, event, window, cx| {
 432                    TerminalInlineAssistant::update_global(cx, |this, cx| {
 433                        this.handle_prompt_editor_event(prompt_editor, event, window, cx)
 434                    })
 435                }),
 436                window.subscribe(&codegen, cx, move |codegen, event, window, cx| {
 437                    TerminalInlineAssistant::update_global(cx, |this, cx| match event {
 438                        CodegenEvent::Finished => {
 439                            let assist = if let Some(assist) = this.assists.get(&assist_id) {
 440                                assist
 441                            } else {
 442                                return;
 443                            };
 444
 445                            if let CodegenStatus::Error(error) = &codegen.read(cx).status {
 446                                if assist.prompt_editor.is_none() {
 447                                    if let Some(workspace) = assist
 448                                        .workspace
 449                                        .as_ref()
 450                                        .and_then(|workspace| workspace.upgrade())
 451                                    {
 452                                        let error =
 453                                            format!("Terminal inline assistant error: {}", error);
 454                                        workspace.update(cx, |workspace, cx| {
 455                                            struct InlineAssistantError;
 456
 457                                            let id =
 458                                                NotificationId::composite::<InlineAssistantError>(
 459                                                    assist_id.0,
 460                                                );
 461
 462                                            workspace.show_toast(Toast::new(id, error), cx);
 463                                        })
 464                                    }
 465                                }
 466                            }
 467
 468                            if assist.prompt_editor.is_none() {
 469                                this.finish_assist(assist_id, false, false, window, cx);
 470                            }
 471                        }
 472                    })
 473                }),
 474            ],
 475        }
 476    }
 477}
 478
 479enum PromptEditorEvent {
 480    StartRequested,
 481    StopRequested,
 482    ConfirmRequested { execute: bool },
 483    CancelRequested,
 484    DismissRequested,
 485    Resized { height_in_lines: u8 },
 486}
 487
 488struct PromptEditor {
 489    id: TerminalInlineAssistId,
 490    fs: Arc<dyn Fs>,
 491    height_in_lines: u8,
 492    editor: Entity<Editor>,
 493    edited_since_done: bool,
 494    prompt_history: VecDeque<String>,
 495    prompt_history_ix: Option<usize>,
 496    pending_prompt: String,
 497    codegen: Entity<Codegen>,
 498    _codegen_subscription: Subscription,
 499    editor_subscriptions: Vec<Subscription>,
 500    pending_token_count: Task<Result<()>>,
 501    token_count: Option<usize>,
 502    _token_count_subscriptions: Vec<Subscription>,
 503    workspace: Option<WeakEntity<Workspace>>,
 504}
 505
 506impl EventEmitter<PromptEditorEvent> for PromptEditor {}
 507
 508impl Render for PromptEditor {
 509    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 510        let status = &self.codegen.read(cx).status;
 511        let buttons = match status {
 512            CodegenStatus::Idle => {
 513                vec![
 514                    IconButton::new("cancel", IconName::Close)
 515                        .icon_color(Color::Muted)
 516                        .shape(IconButtonShape::Square)
 517                        .tooltip(|window, cx| {
 518                            Tooltip::for_action("Cancel Assist", &menu::Cancel, window, cx)
 519                        })
 520                        .on_click(
 521                            cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::CancelRequested)),
 522                        ),
 523                    IconButton::new("start", IconName::SparkleAlt)
 524                        .icon_color(Color::Muted)
 525                        .shape(IconButtonShape::Square)
 526                        .tooltip(|window, cx| {
 527                            Tooltip::for_action("Generate", &menu::Confirm, window, cx)
 528                        })
 529                        .on_click(
 530                            cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::StartRequested)),
 531                        ),
 532                ]
 533            }
 534            CodegenStatus::Pending => {
 535                vec![
 536                    IconButton::new("cancel", IconName::Close)
 537                        .icon_color(Color::Muted)
 538                        .shape(IconButtonShape::Square)
 539                        .tooltip(Tooltip::text("Cancel Assist"))
 540                        .on_click(
 541                            cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::CancelRequested)),
 542                        ),
 543                    IconButton::new("stop", IconName::Stop)
 544                        .icon_color(Color::Error)
 545                        .shape(IconButtonShape::Square)
 546                        .tooltip(|window, cx| {
 547                            Tooltip::with_meta(
 548                                "Interrupt Generation",
 549                                Some(&menu::Cancel),
 550                                "Changes won't be discarded",
 551                                window,
 552                                cx,
 553                            )
 554                        })
 555                        .on_click(
 556                            cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::StopRequested)),
 557                        ),
 558                ]
 559            }
 560            CodegenStatus::Error(_) | CodegenStatus::Done => {
 561                let cancel = IconButton::new("cancel", IconName::Close)
 562                    .icon_color(Color::Muted)
 563                    .shape(IconButtonShape::Square)
 564                    .tooltip(|window, cx| {
 565                        Tooltip::for_action("Cancel Assist", &menu::Cancel, window, cx)
 566                    })
 567                    .on_click(
 568                        cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::CancelRequested)),
 569                    );
 570
 571                let has_error = matches!(status, CodegenStatus::Error(_));
 572                if has_error || self.edited_since_done {
 573                    vec![
 574                        cancel,
 575                        IconButton::new("restart", IconName::RotateCw)
 576                            .icon_color(Color::Info)
 577                            .shape(IconButtonShape::Square)
 578                            .tooltip(|window, cx| {
 579                                Tooltip::with_meta(
 580                                    "Restart Generation",
 581                                    Some(&menu::Confirm),
 582                                    "Changes will be discarded",
 583                                    window,
 584                                    cx,
 585                                )
 586                            })
 587                            .on_click(cx.listener(|_, _, _, cx| {
 588                                cx.emit(PromptEditorEvent::StartRequested);
 589                            })),
 590                    ]
 591                } else {
 592                    vec![
 593                        cancel,
 594                        IconButton::new("accept", IconName::Check)
 595                            .icon_color(Color::Info)
 596                            .shape(IconButtonShape::Square)
 597                            .tooltip(|window, cx| {
 598                                Tooltip::for_action(
 599                                    "Accept Generated Command",
 600                                    &menu::Confirm,
 601                                    window,
 602                                    cx,
 603                                )
 604                            })
 605                            .on_click(cx.listener(|_, _, _, cx| {
 606                                cx.emit(PromptEditorEvent::ConfirmRequested { execute: false });
 607                            })),
 608                        IconButton::new("confirm", IconName::Play)
 609                            .icon_color(Color::Info)
 610                            .shape(IconButtonShape::Square)
 611                            .tooltip(|window, cx| {
 612                                Tooltip::for_action(
 613                                    "Execute Generated Command",
 614                                    &menu::SecondaryConfirm,
 615                                    window,
 616                                    cx,
 617                                )
 618                            })
 619                            .on_click(cx.listener(|_, _, _, cx| {
 620                                cx.emit(PromptEditorEvent::ConfirmRequested { execute: true });
 621                            })),
 622                    ]
 623                }
 624            }
 625        };
 626
 627        h_flex()
 628            .bg(cx.theme().colors().editor_background)
 629            .border_y_1()
 630            .border_color(cx.theme().status().info_border)
 631            .py_2()
 632            .h_full()
 633            .w_full()
 634            .on_action(cx.listener(Self::confirm))
 635            .on_action(cx.listener(Self::secondary_confirm))
 636            .on_action(cx.listener(Self::cancel))
 637            .on_action(cx.listener(Self::move_up))
 638            .on_action(cx.listener(Self::move_down))
 639            .child(
 640                h_flex()
 641                    .w_12()
 642                    .justify_center()
 643                    .gap_2()
 644                    .child(inline_language_model_selector({
 645                        let fs = self.fs.clone();
 646                        move |model, cx| {
 647                            update_settings_file::<AssistantSettings>(
 648                                fs.clone(),
 649                                cx,
 650                                move |settings, _| settings.set_model(model.clone()),
 651                            );
 652                        }
 653                    }))
 654                    .children(
 655                        if let CodegenStatus::Error(error) = &self.codegen.read(cx).status {
 656                            let error_message = SharedString::from(error.to_string());
 657                            Some(
 658                                div()
 659                                    .id("error")
 660                                    .tooltip(Tooltip::text(error_message))
 661                                    .child(
 662                                        Icon::new(IconName::XCircle)
 663                                            .size(IconSize::Small)
 664                                            .color(Color::Error),
 665                                    ),
 666                            )
 667                        } else {
 668                            None
 669                        },
 670                    ),
 671            )
 672            .child(div().flex_1().child(self.render_prompt_editor(cx)))
 673            .child(
 674                h_flex()
 675                    .gap_1()
 676                    .pr_4()
 677                    .children(self.render_token_count(cx))
 678                    .children(buttons),
 679            )
 680    }
 681}
 682
 683impl Focusable for PromptEditor {
 684    fn focus_handle(&self, cx: &App) -> FocusHandle {
 685        self.editor.focus_handle(cx)
 686    }
 687}
 688
 689impl PromptEditor {
 690    const MAX_LINES: u8 = 8;
 691
 692    #[allow(clippy::too_many_arguments)]
 693    fn new(
 694        id: TerminalInlineAssistId,
 695        prompt_history: VecDeque<String>,
 696        prompt_buffer: Entity<MultiBuffer>,
 697        codegen: Entity<Codegen>,
 698        assistant_panel: Option<&Entity<AssistantPanel>>,
 699        workspace: Option<WeakEntity<Workspace>>,
 700        fs: Arc<dyn Fs>,
 701        window: &mut Window,
 702        cx: &mut Context<Self>,
 703    ) -> Self {
 704        let prompt_editor = cx.new(|cx| {
 705            let mut editor = Editor::new(
 706                EditorMode::AutoHeight {
 707                    max_lines: Self::MAX_LINES as usize,
 708                },
 709                prompt_buffer,
 710                None,
 711                false,
 712                window,
 713                cx,
 714            );
 715            editor.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
 716            editor.set_placeholder_text(Self::placeholder_text(window, cx), cx);
 717            editor
 718        });
 719
 720        let mut token_count_subscriptions = Vec::new();
 721        if let Some(assistant_panel) = assistant_panel {
 722            token_count_subscriptions.push(cx.subscribe_in(
 723                assistant_panel,
 724                window,
 725                Self::handle_assistant_panel_event,
 726            ));
 727        }
 728
 729        let mut this = Self {
 730            id,
 731            fs,
 732            height_in_lines: 1,
 733            editor: prompt_editor,
 734            edited_since_done: false,
 735            prompt_history,
 736            prompt_history_ix: None,
 737            pending_prompt: String::new(),
 738            _codegen_subscription: cx.observe_in(&codegen, window, Self::handle_codegen_changed),
 739            editor_subscriptions: Vec::new(),
 740            codegen,
 741            pending_token_count: Task::ready(Ok(())),
 742            token_count: None,
 743            _token_count_subscriptions: token_count_subscriptions,
 744            workspace,
 745        };
 746        this.count_lines(cx);
 747        this.count_tokens(cx);
 748        this.subscribe_to_editor(cx);
 749        this
 750    }
 751
 752    fn placeholder_text(window: &Window, cx: &App) -> String {
 753        let context_keybinding = text_for_action(&zed_actions::assistant::ToggleFocus, window, cx)
 754            .map(|keybinding| format!("{keybinding} for context"))
 755            .unwrap_or_default();
 756
 757        format!("Generate…{context_keybinding} • ↓↑ for history")
 758    }
 759
 760    fn subscribe_to_editor(&mut self, cx: &mut Context<Self>) {
 761        self.editor_subscriptions.clear();
 762        self.editor_subscriptions
 763            .push(cx.observe(&self.editor, Self::handle_prompt_editor_changed));
 764        self.editor_subscriptions
 765            .push(cx.subscribe(&self.editor, Self::handle_prompt_editor_events));
 766    }
 767
 768    fn prompt(&self, cx: &App) -> String {
 769        self.editor.read(cx).text(cx)
 770    }
 771
 772    fn count_lines(&mut self, cx: &mut Context<Self>) {
 773        let height_in_lines = cmp::max(
 774            2, // Make the editor at least two lines tall, to account for padding and buttons.
 775            cmp::min(
 776                self.editor
 777                    .update(cx, |editor, cx| editor.max_point(cx).row().0 + 1),
 778                Self::MAX_LINES as u32,
 779            ),
 780        ) as u8;
 781
 782        if height_in_lines != self.height_in_lines {
 783            self.height_in_lines = height_in_lines;
 784            cx.emit(PromptEditorEvent::Resized { height_in_lines });
 785        }
 786    }
 787
 788    fn handle_assistant_panel_event(
 789        &mut self,
 790        _: &Entity<AssistantPanel>,
 791        event: &AssistantPanelEvent,
 792        _: &mut Window,
 793        cx: &mut Context<Self>,
 794    ) {
 795        let AssistantPanelEvent::ContextEdited { .. } = event;
 796        self.count_tokens(cx);
 797    }
 798
 799    fn count_tokens(&mut self, cx: &mut Context<Self>) {
 800        let assist_id = self.id;
 801        let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
 802            return;
 803        };
 804        self.pending_token_count = cx.spawn(|this, mut cx| async move {
 805            cx.background_executor().timer(Duration::from_secs(1)).await;
 806            let request =
 807                cx.update_global(|inline_assistant: &mut TerminalInlineAssistant, cx| {
 808                    inline_assistant.request_for_inline_assist(assist_id, cx)
 809                })??;
 810
 811            let token_count = cx.update(|cx| model.count_tokens(request, cx))?.await?;
 812            this.update(&mut cx, |this, cx| {
 813                this.token_count = Some(token_count);
 814                cx.notify();
 815            })
 816        })
 817    }
 818
 819    fn handle_prompt_editor_changed(&mut self, _: Entity<Editor>, cx: &mut Context<Self>) {
 820        self.count_lines(cx);
 821    }
 822
 823    fn handle_prompt_editor_events(
 824        &mut self,
 825        _: Entity<Editor>,
 826        event: &EditorEvent,
 827        cx: &mut Context<Self>,
 828    ) {
 829        match event {
 830            EditorEvent::Edited { .. } => {
 831                let prompt = self.editor.read(cx).text(cx);
 832                if self
 833                    .prompt_history_ix
 834                    .map_or(true, |ix| self.prompt_history[ix] != prompt)
 835                {
 836                    self.prompt_history_ix.take();
 837                    self.pending_prompt = prompt;
 838                }
 839
 840                self.edited_since_done = true;
 841                cx.notify();
 842            }
 843            EditorEvent::BufferEdited => {
 844                self.count_tokens(cx);
 845            }
 846            _ => {}
 847        }
 848    }
 849
 850    fn handle_codegen_changed(
 851        &mut self,
 852        _: Entity<Codegen>,
 853        _: &mut Window,
 854        cx: &mut Context<Self>,
 855    ) {
 856        match &self.codegen.read(cx).status {
 857            CodegenStatus::Idle => {
 858                self.editor
 859                    .update(cx, |editor, _| editor.set_read_only(false));
 860            }
 861            CodegenStatus::Pending => {
 862                self.editor
 863                    .update(cx, |editor, _| editor.set_read_only(true));
 864            }
 865            CodegenStatus::Done | CodegenStatus::Error(_) => {
 866                self.edited_since_done = false;
 867                self.editor
 868                    .update(cx, |editor, _| editor.set_read_only(false));
 869            }
 870        }
 871    }
 872
 873    fn cancel(&mut self, _: &editor::actions::Cancel, _: &mut Window, cx: &mut Context<Self>) {
 874        match &self.codegen.read(cx).status {
 875            CodegenStatus::Idle | CodegenStatus::Done | CodegenStatus::Error(_) => {
 876                cx.emit(PromptEditorEvent::CancelRequested);
 877            }
 878            CodegenStatus::Pending => {
 879                cx.emit(PromptEditorEvent::StopRequested);
 880            }
 881        }
 882    }
 883
 884    fn confirm(&mut self, _: &menu::Confirm, _: &mut Window, cx: &mut Context<Self>) {
 885        match &self.codegen.read(cx).status {
 886            CodegenStatus::Idle => {
 887                if !self.editor.read(cx).text(cx).trim().is_empty() {
 888                    cx.emit(PromptEditorEvent::StartRequested);
 889                }
 890            }
 891            CodegenStatus::Pending => {
 892                cx.emit(PromptEditorEvent::DismissRequested);
 893            }
 894            CodegenStatus::Done => {
 895                if self.edited_since_done {
 896                    cx.emit(PromptEditorEvent::StartRequested);
 897                } else {
 898                    cx.emit(PromptEditorEvent::ConfirmRequested { execute: false });
 899                }
 900            }
 901            CodegenStatus::Error(_) => {
 902                cx.emit(PromptEditorEvent::StartRequested);
 903            }
 904        }
 905    }
 906
 907    fn secondary_confirm(
 908        &mut self,
 909        _: &menu::SecondaryConfirm,
 910        _: &mut Window,
 911        cx: &mut Context<Self>,
 912    ) {
 913        if matches!(self.codegen.read(cx).status, CodegenStatus::Done) {
 914            cx.emit(PromptEditorEvent::ConfirmRequested { execute: true });
 915        }
 916    }
 917
 918    fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 919        if let Some(ix) = self.prompt_history_ix {
 920            if ix > 0 {
 921                self.prompt_history_ix = Some(ix - 1);
 922                let prompt = self.prompt_history[ix - 1].as_str();
 923                self.editor.update(cx, |editor, cx| {
 924                    editor.set_text(prompt, window, cx);
 925                    editor.move_to_beginning(&Default::default(), window, cx);
 926                });
 927            }
 928        } else if !self.prompt_history.is_empty() {
 929            self.prompt_history_ix = Some(self.prompt_history.len() - 1);
 930            let prompt = self.prompt_history[self.prompt_history.len() - 1].as_str();
 931            self.editor.update(cx, |editor, cx| {
 932                editor.set_text(prompt, window, cx);
 933                editor.move_to_beginning(&Default::default(), window, cx);
 934            });
 935        }
 936    }
 937
 938    fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 939        if let Some(ix) = self.prompt_history_ix {
 940            if ix < self.prompt_history.len() - 1 {
 941                self.prompt_history_ix = Some(ix + 1);
 942                let prompt = self.prompt_history[ix + 1].as_str();
 943                self.editor.update(cx, |editor, cx| {
 944                    editor.set_text(prompt, window, cx);
 945                    editor.move_to_end(&Default::default(), window, cx)
 946                });
 947            } else {
 948                self.prompt_history_ix = None;
 949                let prompt = self.pending_prompt.as_str();
 950                self.editor.update(cx, |editor, cx| {
 951                    editor.set_text(prompt, window, cx);
 952                    editor.move_to_end(&Default::default(), window, cx)
 953                });
 954            }
 955        }
 956    }
 957
 958    fn render_token_count(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
 959        let model = LanguageModelRegistry::read_global(cx).active_model()?;
 960        let token_count = self.token_count?;
 961        let max_token_count = model.max_token_count();
 962
 963        let remaining_tokens = max_token_count as isize - token_count as isize;
 964        let token_count_color = if remaining_tokens <= 0 {
 965            Color::Error
 966        } else if token_count as f32 / max_token_count as f32 >= 0.8 {
 967            Color::Warning
 968        } else {
 969            Color::Muted
 970        };
 971
 972        let mut token_count = h_flex()
 973            .id("token_count")
 974            .gap_0p5()
 975            .child(
 976                Label::new(humanize_token_count(token_count))
 977                    .size(LabelSize::Small)
 978                    .color(token_count_color),
 979            )
 980            .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
 981            .child(
 982                Label::new(humanize_token_count(max_token_count))
 983                    .size(LabelSize::Small)
 984                    .color(Color::Muted),
 985            );
 986        if let Some(workspace) = self.workspace.clone() {
 987            token_count = token_count
 988                .tooltip(|window, cx| {
 989                    Tooltip::with_meta(
 990                        "Tokens Used by Inline Assistant",
 991                        None,
 992                        "Click to Open Assistant Panel",
 993                        window,
 994                        cx,
 995                    )
 996                })
 997                .cursor_pointer()
 998                .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation())
 999                .on_click(move |_, window, cx| {
1000                    cx.stop_propagation();
1001                    workspace
1002                        .update(cx, |workspace, cx| {
1003                            workspace.focus_panel::<AssistantPanel>(window, cx)
1004                        })
1005                        .ok();
1006                });
1007        } else {
1008            token_count = token_count
1009                .cursor_default()
1010                .tooltip(Tooltip::text("Tokens Used by Inline Assistant"));
1011        }
1012
1013        Some(token_count)
1014    }
1015
1016    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
1017        let settings = ThemeSettings::get_global(cx);
1018        let text_style = TextStyle {
1019            color: if self.editor.read(cx).read_only(cx) {
1020                cx.theme().colors().text_disabled
1021            } else {
1022                cx.theme().colors().text
1023            },
1024            font_family: settings.buffer_font.family.clone(),
1025            font_fallbacks: settings.buffer_font.fallbacks.clone(),
1026            font_size: settings.buffer_font_size(cx).into(),
1027            font_weight: settings.buffer_font.weight,
1028            line_height: relative(settings.buffer_line_height.value()),
1029            ..Default::default()
1030        };
1031        EditorElement::new(
1032            &self.editor,
1033            EditorStyle {
1034                background: cx.theme().colors().editor_background,
1035                local_player: cx.theme().players().local(),
1036                text: text_style,
1037                ..Default::default()
1038            },
1039        )
1040    }
1041}
1042
1043#[derive(Debug)]
1044pub enum CodegenEvent {
1045    Finished,
1046}
1047
1048impl EventEmitter<CodegenEvent> for Codegen {}
1049
1050#[cfg(not(target_os = "windows"))]
1051const CLEAR_INPUT: &str = "\x15";
1052#[cfg(target_os = "windows")]
1053const CLEAR_INPUT: &str = "\x03";
1054const CARRIAGE_RETURN: &str = "\x0d";
1055
1056struct TerminalTransaction {
1057    terminal: Entity<Terminal>,
1058}
1059
1060impl TerminalTransaction {
1061    pub fn start(terminal: Entity<Terminal>) -> Self {
1062        Self { terminal }
1063    }
1064
1065    pub fn push(&mut self, hunk: String, cx: &mut App) {
1066        // Ensure that the assistant cannot accidentally execute commands that are streamed into the terminal
1067        let input = Self::sanitize_input(hunk);
1068        self.terminal
1069            .update(cx, |terminal, _| terminal.input(input));
1070    }
1071
1072    pub fn undo(&self, cx: &mut App) {
1073        self.terminal
1074            .update(cx, |terminal, _| terminal.input(CLEAR_INPUT.to_string()));
1075    }
1076
1077    pub fn complete(&self, cx: &mut App) {
1078        self.terminal.update(cx, |terminal, _| {
1079            terminal.input(CARRIAGE_RETURN.to_string())
1080        });
1081    }
1082
1083    fn sanitize_input(input: String) -> String {
1084        input.replace(['\r', '\n'], "")
1085    }
1086}
1087
1088pub struct Codegen {
1089    status: CodegenStatus,
1090    telemetry: Option<Arc<Telemetry>>,
1091    terminal: Entity<Terminal>,
1092    generation: Task<()>,
1093    message_id: Option<String>,
1094    transaction: Option<TerminalTransaction>,
1095}
1096
1097impl Codegen {
1098    pub fn new(terminal: Entity<Terminal>, telemetry: Option<Arc<Telemetry>>) -> Self {
1099        Self {
1100            terminal,
1101            telemetry,
1102            status: CodegenStatus::Idle,
1103            generation: Task::ready(()),
1104            message_id: None,
1105            transaction: None,
1106        }
1107    }
1108
1109    pub fn start(&mut self, prompt: LanguageModelRequest, cx: &mut Context<Self>) {
1110        let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
1111            return;
1112        };
1113
1114        let model_api_key = model.api_key(cx);
1115        let http_client = cx.http_client();
1116        let telemetry = self.telemetry.clone();
1117        self.status = CodegenStatus::Pending;
1118        self.transaction = Some(TerminalTransaction::start(self.terminal.clone()));
1119        self.generation = cx.spawn(|this, mut cx| async move {
1120            let model_telemetry_id = model.telemetry_id();
1121            let model_provider_id = model.provider_id();
1122            let response = model.stream_completion_text(prompt, &cx).await;
1123            let generate = async {
1124                let message_id = response
1125                    .as_ref()
1126                    .ok()
1127                    .and_then(|response| response.message_id.clone());
1128
1129                let (mut hunks_tx, mut hunks_rx) = mpsc::channel(1);
1130
1131                let task = cx.background_spawn({
1132                    let message_id = message_id.clone();
1133                    let executor = cx.background_executor().clone();
1134                    async move {
1135                        let mut response_latency = None;
1136                        let request_start = Instant::now();
1137                        let task = async {
1138                            let mut chunks = response?.stream;
1139                            while let Some(chunk) = chunks.next().await {
1140                                if response_latency.is_none() {
1141                                    response_latency = Some(request_start.elapsed());
1142                                }
1143                                let chunk = chunk?;
1144                                hunks_tx.send(chunk).await?;
1145                            }
1146
1147                            anyhow::Ok(())
1148                        };
1149
1150                        let result = task.await;
1151
1152                        let error_message = result.as_ref().err().map(|error| error.to_string());
1153                        report_assistant_event(
1154                            AssistantEvent {
1155                                conversation_id: None,
1156                                kind: AssistantKind::InlineTerminal,
1157                                message_id,
1158                                phase: AssistantPhase::Response,
1159                                model: model_telemetry_id,
1160                                model_provider: model_provider_id.to_string(),
1161                                response_latency,
1162                                error_message,
1163                                language_name: None,
1164                            },
1165                            telemetry,
1166                            http_client,
1167                            model_api_key,
1168                            &executor,
1169                        );
1170
1171                        result?;
1172                        anyhow::Ok(())
1173                    }
1174                });
1175
1176                this.update(&mut cx, |this, _| {
1177                    this.message_id = message_id;
1178                })?;
1179
1180                while let Some(hunk) = hunks_rx.next().await {
1181                    this.update(&mut cx, |this, cx| {
1182                        if let Some(transaction) = &mut this.transaction {
1183                            transaction.push(hunk, cx);
1184                            cx.notify();
1185                        }
1186                    })?;
1187                }
1188
1189                task.await?;
1190                anyhow::Ok(())
1191            };
1192
1193            let result = generate.await;
1194
1195            this.update(&mut cx, |this, cx| {
1196                if let Err(error) = result {
1197                    this.status = CodegenStatus::Error(error);
1198                } else {
1199                    this.status = CodegenStatus::Done;
1200                }
1201                cx.emit(CodegenEvent::Finished);
1202                cx.notify();
1203            })
1204            .ok();
1205        });
1206        cx.notify();
1207    }
1208
1209    pub fn stop(&mut self, cx: &mut Context<Self>) {
1210        self.status = CodegenStatus::Done;
1211        self.generation = Task::ready(());
1212        cx.emit(CodegenEvent::Finished);
1213        cx.notify();
1214    }
1215
1216    pub fn complete(&mut self, cx: &mut Context<Self>) {
1217        if let Some(transaction) = self.transaction.take() {
1218            transaction.complete(cx);
1219        }
1220    }
1221
1222    pub fn undo(&mut self, cx: &mut Context<Self>) {
1223        if let Some(transaction) = self.transaction.take() {
1224            transaction.undo(cx);
1225        }
1226    }
1227}
1228
1229enum CodegenStatus {
1230    Idle,
1231    Pending,
1232    Done,
1233    Error(anyhow::Error),
1234}