1use std::{
2 ops::Range,
3 path::{Path, PathBuf},
4 rc::Rc,
5 sync::{
6 Arc,
7 atomic::{AtomicBool, Ordering},
8 },
9 time::Duration,
10};
11
12use acp_thread::{AcpThread, MentionUri, ThreadStatus};
13use agent::{ContextServerRegistry, SharedThread, ThreadStore};
14use agent_client_protocol as acp;
15use agent_servers::AgentServer;
16use collections::HashSet;
17use db::kvp::{Dismissable, KeyValueStore};
18use itertools::Itertools;
19use project::AgentId;
20use serde::{Deserialize, Serialize};
21use settings::{LanguageModelProviderSetting, LanguageModelSelection};
22
23use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt as _};
24use zed_actions::agent::{
25 ConflictContent, OpenClaudeAgentOnboardingModal, ReauthenticateAgent,
26 ResolveConflictedFilesWithAgent, ResolveConflictsWithAgent, ReviewBranchDiff,
27};
28
29use crate::{
30 AddContextServer, AgentDiffPane, ConversationView, CopyThreadToClipboard, CycleStartThreadIn,
31 Follow, InlineAssistant, LoadThreadFromClipboard, NewTextThread, NewThread,
32 OpenActiveThreadAsMarkdown, OpenAgentDiff, OpenHistory, ResetTrialEndUpsell, ResetTrialUpsell,
33 StartThreadIn, ToggleNavigationMenu, ToggleNewThreadMenu, ToggleOptionsMenu,
34 agent_configuration::{AgentConfiguration, AssistantConfigurationEvent},
35 conversation_view::{AcpThreadViewEvent, ThreadView},
36 slash_command::SlashCommandCompletionProvider,
37 text_thread_editor::{AgentPanelDelegate, TextThreadEditor, make_lsp_adapter_delegate},
38 ui::EndTrialUpsell,
39};
40use crate::{
41 Agent, AgentInitialContent, ExternalSourcePrompt, NewExternalAgentThread,
42 NewNativeAgentThreadFromSummary,
43};
44use crate::{
45 DEFAULT_THREAD_TITLE,
46 ui::{AcpOnboardingModal, ClaudeCodeOnboardingModal, HoldForDefault},
47};
48use crate::{
49 ExpandMessageEditor, ThreadHistoryView,
50 text_thread_history::{TextThreadHistory, TextThreadHistoryEvent},
51};
52use crate::{ManageProfiles, ThreadHistoryViewEvent};
53use crate::{ThreadHistory, agent_connection_store::AgentConnectionStore};
54use agent_settings::AgentSettings;
55use ai_onboarding::AgentPanelOnboarding;
56use anyhow::{Context as _, Result, anyhow};
57use assistant_slash_command::SlashCommandWorkingSet;
58use assistant_text_thread::{TextThread, TextThreadEvent, TextThreadSummary};
59use client::UserStore;
60use cloud_api_types::Plan;
61use collections::HashMap;
62use editor::{Anchor, AnchorRangeExt as _, Editor, EditorEvent, MultiBuffer};
63use extension::ExtensionEvents;
64use extension_host::ExtensionStore;
65use fs::Fs;
66use gpui::{
67 Action, Animation, AnimationExt, AnyElement, App, AsyncWindowContext, ClipboardItem, Corner,
68 DismissEvent, Entity, EventEmitter, ExternalPaths, FocusHandle, Focusable, KeyContext, Pixels,
69 Subscription, Task, UpdateGlobal, WeakEntity, prelude::*, pulsating_between,
70};
71use language::LanguageRegistry;
72use language_model::{ConfigurationError, LanguageModelRegistry};
73use project::project_settings::ProjectSettings;
74use project::{Project, ProjectPath, Worktree};
75use prompt_store::{PromptBuilder, PromptStore, UserPromptId};
76use rules_library::{RulesLibrary, open_rules_library};
77use search::{BufferSearchBar, buffer_search};
78use settings::{Settings, update_settings_file};
79use theme::ThemeSettings;
80use ui::{
81 Button, Callout, CommonAnimationExt, ContextMenu, ContextMenuEntry, DocumentationSide,
82 KeyBinding, PopoverMenu, PopoverMenuHandle, Tab, Tooltip, prelude::*, utils::WithRemSize,
83};
84use util::{ResultExt as _, debug_panic};
85use workspace::{
86 CollaboratorId, DraggedSelection, DraggedTab, OpenResult, PathList, SerializedPathList,
87 ToggleWorkspaceSidebar, ToggleZoom, ToolbarItemView, Workspace, WorkspaceId,
88 dock::{DockPosition, Panel, PanelEvent},
89};
90use zed_actions::{
91 DecreaseBufferFontSize, IncreaseBufferFontSize, ResetBufferFontSize,
92 agent::{OpenAcpOnboardingModal, OpenSettings, ResetAgentZoom, ResetOnboarding},
93 assistant::{OpenRulesLibrary, Toggle, ToggleFocus},
94};
95
96const AGENT_PANEL_KEY: &str = "agent_panel";
97const RECENTLY_UPDATED_MENU_LIMIT: usize = 6;
98
99fn read_serialized_panel(
100 workspace_id: workspace::WorkspaceId,
101 kvp: &KeyValueStore,
102) -> Option<SerializedAgentPanel> {
103 let scope = kvp.scoped(AGENT_PANEL_KEY);
104 let key = i64::from(workspace_id).to_string();
105 scope
106 .read(&key)
107 .log_err()
108 .flatten()
109 .and_then(|json| serde_json::from_str::<SerializedAgentPanel>(&json).log_err())
110}
111
112async fn save_serialized_panel(
113 workspace_id: workspace::WorkspaceId,
114 panel: SerializedAgentPanel,
115 kvp: KeyValueStore,
116) -> Result<()> {
117 let scope = kvp.scoped(AGENT_PANEL_KEY);
118 let key = i64::from(workspace_id).to_string();
119 scope.write(key, serde_json::to_string(&panel)?).await?;
120 Ok(())
121}
122
123/// Migration: reads the original single-panel format stored under the
124/// `"agent_panel"` KVP key before per-workspace keying was introduced.
125fn read_legacy_serialized_panel(kvp: &KeyValueStore) -> Option<SerializedAgentPanel> {
126 kvp.read_kvp(AGENT_PANEL_KEY)
127 .log_err()
128 .flatten()
129 .and_then(|json| serde_json::from_str::<SerializedAgentPanel>(&json).log_err())
130}
131
132#[derive(Serialize, Deserialize, Debug)]
133struct SerializedAgentPanel {
134 width: Option<Pixels>,
135 selected_agent: Option<AgentType>,
136 #[serde(default)]
137 last_active_thread: Option<SerializedActiveThread>,
138 #[serde(default)]
139 start_thread_in: Option<StartThreadIn>,
140}
141
142#[derive(Serialize, Deserialize, Debug)]
143struct SerializedActiveThread {
144 session_id: String,
145 agent_type: AgentType,
146 title: Option<String>,
147 work_dirs: Option<SerializedPathList>,
148}
149
150pub fn init(cx: &mut App) {
151 cx.observe_new(
152 |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
153 workspace
154 .register_action(|workspace, action: &NewThread, window, cx| {
155 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
156 panel.update(cx, |panel, cx| panel.new_thread(action, window, cx));
157 workspace.focus_panel::<AgentPanel>(window, cx);
158 }
159 })
160 .register_action(
161 |workspace, action: &NewNativeAgentThreadFromSummary, window, cx| {
162 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
163 panel.update(cx, |panel, cx| {
164 panel.new_native_agent_thread_from_summary(action, window, cx)
165 });
166 workspace.focus_panel::<AgentPanel>(window, cx);
167 }
168 },
169 )
170 .register_action(|workspace, _: &ExpandMessageEditor, window, cx| {
171 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
172 workspace.focus_panel::<AgentPanel>(window, cx);
173 panel.update(cx, |panel, cx| panel.expand_message_editor(window, cx));
174 }
175 })
176 .register_action(|workspace, _: &OpenHistory, window, cx| {
177 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
178 workspace.focus_panel::<AgentPanel>(window, cx);
179 panel.update(cx, |panel, cx| panel.open_history(window, cx));
180 }
181 })
182 .register_action(|workspace, _: &OpenSettings, window, cx| {
183 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
184 workspace.focus_panel::<AgentPanel>(window, cx);
185 panel.update(cx, |panel, cx| panel.open_configuration(window, cx));
186 }
187 })
188 .register_action(|workspace, _: &NewTextThread, window, cx| {
189 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
190 workspace.focus_panel::<AgentPanel>(window, cx);
191 panel.update(cx, |panel, cx| {
192 panel.new_text_thread(window, cx);
193 });
194 }
195 })
196 .register_action(|workspace, action: &NewExternalAgentThread, window, cx| {
197 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
198 workspace.focus_panel::<AgentPanel>(window, cx);
199 panel.update(cx, |panel, cx| {
200 panel.external_thread(
201 action.agent.clone(),
202 None,
203 None,
204 None,
205 None,
206 true,
207 window,
208 cx,
209 )
210 });
211 }
212 })
213 .register_action(|workspace, action: &OpenRulesLibrary, window, cx| {
214 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
215 workspace.focus_panel::<AgentPanel>(window, cx);
216 panel.update(cx, |panel, cx| {
217 panel.deploy_rules_library(action, window, cx)
218 });
219 }
220 })
221 .register_action(|workspace, _: &Follow, window, cx| {
222 workspace.follow(CollaboratorId::Agent, window, cx);
223 })
224 .register_action(|workspace, _: &OpenAgentDiff, window, cx| {
225 let thread = workspace
226 .panel::<AgentPanel>(cx)
227 .and_then(|panel| panel.read(cx).active_conversation_view().cloned())
228 .and_then(|conversation| {
229 conversation
230 .read(cx)
231 .active_thread()
232 .map(|r| r.read(cx).thread.clone())
233 });
234
235 if let Some(thread) = thread {
236 AgentDiffPane::deploy_in_workspace(thread, workspace, window, cx);
237 }
238 })
239 .register_action(|workspace, _: &ToggleNavigationMenu, window, cx| {
240 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
241 workspace.focus_panel::<AgentPanel>(window, cx);
242 panel.update(cx, |panel, cx| {
243 panel.toggle_navigation_menu(&ToggleNavigationMenu, window, cx);
244 });
245 }
246 })
247 .register_action(|workspace, _: &ToggleOptionsMenu, window, cx| {
248 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
249 workspace.focus_panel::<AgentPanel>(window, cx);
250 panel.update(cx, |panel, cx| {
251 panel.toggle_options_menu(&ToggleOptionsMenu, window, cx);
252 });
253 }
254 })
255 .register_action(|workspace, _: &ToggleNewThreadMenu, window, cx| {
256 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
257 workspace.focus_panel::<AgentPanel>(window, cx);
258 panel.update(cx, |panel, cx| {
259 panel.toggle_new_thread_menu(&ToggleNewThreadMenu, window, cx);
260 });
261 }
262 })
263 .register_action(|workspace, _: &OpenAcpOnboardingModal, window, cx| {
264 AcpOnboardingModal::toggle(workspace, window, cx)
265 })
266 .register_action(
267 |workspace, _: &OpenClaudeAgentOnboardingModal, window, cx| {
268 ClaudeCodeOnboardingModal::toggle(workspace, window, cx)
269 },
270 )
271 .register_action(|_workspace, _: &ResetOnboarding, window, cx| {
272 window.dispatch_action(workspace::RestoreBanner.boxed_clone(), cx);
273 window.refresh();
274 })
275 .register_action(|workspace, _: &ResetTrialUpsell, _window, cx| {
276 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
277 panel.update(cx, |panel, _| {
278 panel
279 .on_boarding_upsell_dismissed
280 .store(false, Ordering::Release);
281 });
282 }
283 OnboardingUpsell::set_dismissed(false, cx);
284 })
285 .register_action(|_workspace, _: &ResetTrialEndUpsell, _window, cx| {
286 TrialEndUpsell::set_dismissed(false, cx);
287 })
288 .register_action(|workspace, _: &ResetAgentZoom, window, cx| {
289 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
290 panel.update(cx, |panel, cx| {
291 panel.reset_agent_zoom(window, cx);
292 });
293 }
294 })
295 .register_action(|workspace, _: &CopyThreadToClipboard, window, cx| {
296 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
297 panel.update(cx, |panel, cx| {
298 panel.copy_thread_to_clipboard(window, cx);
299 });
300 }
301 })
302 .register_action(|workspace, _: &LoadThreadFromClipboard, window, cx| {
303 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
304 workspace.focus_panel::<AgentPanel>(window, cx);
305 panel.update(cx, |panel, cx| {
306 panel.load_thread_from_clipboard(window, cx);
307 });
308 }
309 })
310 .register_action(|workspace, action: &ReviewBranchDiff, window, cx| {
311 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
312 return;
313 };
314
315 let mention_uri = MentionUri::GitDiff {
316 base_ref: action.base_ref.to_string(),
317 };
318 let diff_uri = mention_uri.to_uri().to_string();
319
320 let content_blocks = vec![
321 acp::ContentBlock::Text(acp::TextContent::new(
322 "Please review this branch diff carefully. Point out any issues, \
323 potential bugs, or improvement opportunities you find.\n\n"
324 .to_string(),
325 )),
326 acp::ContentBlock::Resource(acp::EmbeddedResource::new(
327 acp::EmbeddedResourceResource::TextResourceContents(
328 acp::TextResourceContents::new(
329 action.diff_text.to_string(),
330 diff_uri,
331 ),
332 ),
333 )),
334 ];
335
336 workspace.focus_panel::<AgentPanel>(window, cx);
337
338 panel.update(cx, |panel, cx| {
339 panel.external_thread(
340 None,
341 None,
342 None,
343 None,
344 Some(AgentInitialContent::ContentBlock {
345 blocks: content_blocks,
346 auto_submit: true,
347 }),
348 true,
349 window,
350 cx,
351 );
352 });
353 })
354 .register_action(
355 |workspace, action: &ResolveConflictsWithAgent, window, cx| {
356 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
357 return;
358 };
359
360 let content_blocks = build_conflict_resolution_prompt(&action.conflicts);
361
362 workspace.focus_panel::<AgentPanel>(window, cx);
363
364 panel.update(cx, |panel, cx| {
365 panel.external_thread(
366 None,
367 None,
368 None,
369 None,
370 Some(AgentInitialContent::ContentBlock {
371 blocks: content_blocks,
372 auto_submit: true,
373 }),
374 true,
375 window,
376 cx,
377 );
378 });
379 },
380 )
381 .register_action(
382 |workspace, action: &ResolveConflictedFilesWithAgent, window, cx| {
383 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
384 return;
385 };
386
387 let content_blocks =
388 build_conflicted_files_resolution_prompt(&action.conflicted_file_paths);
389
390 workspace.focus_panel::<AgentPanel>(window, cx);
391
392 panel.update(cx, |panel, cx| {
393 panel.external_thread(
394 None,
395 None,
396 None,
397 None,
398 Some(AgentInitialContent::ContentBlock {
399 blocks: content_blocks,
400 auto_submit: true,
401 }),
402 true,
403 window,
404 cx,
405 );
406 });
407 },
408 )
409 .register_action(|workspace, action: &StartThreadIn, window, cx| {
410 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
411 panel.update(cx, |panel, cx| {
412 panel.set_start_thread_in(action, window, cx);
413 });
414 }
415 })
416 .register_action(|workspace, _: &CycleStartThreadIn, window, cx| {
417 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
418 panel.update(cx, |panel, cx| {
419 panel.cycle_start_thread_in(window, cx);
420 });
421 }
422 });
423 },
424 )
425 .detach();
426}
427
428fn conflict_resource_block(conflict: &ConflictContent) -> acp::ContentBlock {
429 let mention_uri = MentionUri::MergeConflict {
430 file_path: conflict.file_path.clone(),
431 };
432 acp::ContentBlock::Resource(acp::EmbeddedResource::new(
433 acp::EmbeddedResourceResource::TextResourceContents(acp::TextResourceContents::new(
434 conflict.conflict_text.clone(),
435 mention_uri.to_uri().to_string(),
436 )),
437 ))
438}
439
440fn build_conflict_resolution_prompt(conflicts: &[ConflictContent]) -> Vec<acp::ContentBlock> {
441 if conflicts.is_empty() {
442 return Vec::new();
443 }
444
445 let mut blocks = Vec::new();
446
447 if conflicts.len() == 1 {
448 let conflict = &conflicts[0];
449
450 blocks.push(acp::ContentBlock::Text(acp::TextContent::new(
451 "Please resolve the following merge conflict in ",
452 )));
453 let mention = MentionUri::File {
454 abs_path: PathBuf::from(conflict.file_path.clone()),
455 };
456 blocks.push(acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
457 mention.name(),
458 mention.to_uri(),
459 )));
460
461 blocks.push(acp::ContentBlock::Text(acp::TextContent::new(
462 indoc::formatdoc!(
463 "\nThe conflict is between branch `{ours}` (ours) and `{theirs}` (theirs).
464
465 Analyze both versions carefully and resolve the conflict by editing \
466 the file directly. Choose the resolution that best preserves the intent \
467 of both changes, or combine them if appropriate.
468
469 ",
470 ours = conflict.ours_branch_name,
471 theirs = conflict.theirs_branch_name,
472 ),
473 )));
474 } else {
475 let n = conflicts.len();
476 let unique_files: HashSet<&str> = conflicts.iter().map(|c| c.file_path.as_str()).collect();
477 let ours = &conflicts[0].ours_branch_name;
478 let theirs = &conflicts[0].theirs_branch_name;
479 blocks.push(acp::ContentBlock::Text(acp::TextContent::new(
480 indoc::formatdoc!(
481 "Please resolve all {n} merge conflicts below.
482
483 The conflicts are between branch `{ours}` (ours) and `{theirs}` (theirs).
484
485 For each conflict, analyze both versions carefully and resolve them \
486 by editing the file{suffix} directly. Choose resolutions that best preserve \
487 the intent of both changes, or combine them if appropriate.
488
489 ",
490 suffix = if unique_files.len() > 1 { "s" } else { "" },
491 ),
492 )));
493 }
494
495 for conflict in conflicts {
496 blocks.push(conflict_resource_block(conflict));
497 }
498
499 blocks
500}
501
502fn build_conflicted_files_resolution_prompt(
503 conflicted_file_paths: &[String],
504) -> Vec<acp::ContentBlock> {
505 if conflicted_file_paths.is_empty() {
506 return Vec::new();
507 }
508
509 let instruction = indoc::indoc!(
510 "The following files have unresolved merge conflicts. Please open each \
511 file, find the conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`), \
512 and resolve every conflict by editing the files directly.
513
514 Choose resolutions that best preserve the intent of both changes, \
515 or combine them if appropriate.
516
517 Files with conflicts:
518 ",
519 );
520
521 let mut content = vec![acp::ContentBlock::Text(acp::TextContent::new(instruction))];
522 for path in conflicted_file_paths {
523 let mention = MentionUri::File {
524 abs_path: PathBuf::from(path),
525 };
526 content.push(acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
527 mention.name(),
528 mention.to_uri(),
529 )));
530 content.push(acp::ContentBlock::Text(acp::TextContent::new("\n")));
531 }
532 content
533}
534
535#[derive(Clone, Debug, PartialEq, Eq)]
536enum History {
537 AgentThreads { view: Entity<ThreadHistoryView> },
538 TextThreads,
539}
540
541enum ActiveView {
542 Uninitialized,
543 AgentThread {
544 conversation_view: Entity<ConversationView>,
545 },
546 TextThread {
547 text_thread_editor: Entity<TextThreadEditor>,
548 title_editor: Entity<Editor>,
549 buffer_search_bar: Entity<BufferSearchBar>,
550 _subscriptions: Vec<gpui::Subscription>,
551 },
552 History {
553 history: History,
554 },
555 Configuration,
556}
557
558enum WhichFontSize {
559 AgentFont,
560 BufferFont,
561 None,
562}
563
564// TODO unify this with ExternalAgent
565#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
566pub enum AgentType {
567 #[default]
568 NativeAgent,
569 TextThread,
570 Custom {
571 #[serde(rename = "name")]
572 id: AgentId,
573 },
574}
575
576impl AgentType {
577 pub fn is_native(&self) -> bool {
578 matches!(self, Self::NativeAgent)
579 }
580
581 fn label(&self) -> SharedString {
582 match self {
583 Self::NativeAgent | Self::TextThread => "Zed Agent".into(),
584 Self::Custom { id, .. } => id.0.clone(),
585 }
586 }
587
588 fn icon(&self) -> Option<IconName> {
589 match self {
590 Self::NativeAgent | Self::TextThread => None,
591 Self::Custom { .. } => Some(IconName::Sparkle),
592 }
593 }
594}
595
596impl From<Agent> for AgentType {
597 fn from(value: Agent) -> Self {
598 match value {
599 Agent::Custom { id } => Self::Custom { id },
600 Agent::NativeAgent => Self::NativeAgent,
601 }
602 }
603}
604
605impl StartThreadIn {
606 fn label(&self) -> SharedString {
607 match self {
608 Self::LocalProject => "Current Worktree".into(),
609 Self::NewWorktree => "New Git Worktree".into(),
610 }
611 }
612}
613
614#[derive(Clone, Debug)]
615#[allow(dead_code)]
616pub enum WorktreeCreationStatus {
617 Creating,
618 Error(SharedString),
619}
620
621impl ActiveView {
622 pub fn which_font_size_used(&self) -> WhichFontSize {
623 match self {
624 ActiveView::Uninitialized
625 | ActiveView::AgentThread { .. }
626 | ActiveView::History { .. } => WhichFontSize::AgentFont,
627 ActiveView::TextThread { .. } => WhichFontSize::BufferFont,
628 ActiveView::Configuration => WhichFontSize::None,
629 }
630 }
631
632 pub fn text_thread(
633 text_thread_editor: Entity<TextThreadEditor>,
634 language_registry: Arc<LanguageRegistry>,
635 window: &mut Window,
636 cx: &mut App,
637 ) -> Self {
638 let title = text_thread_editor.read(cx).title(cx).to_string();
639
640 let editor = cx.new(|cx| {
641 let mut editor = Editor::single_line(window, cx);
642 editor.set_text(title, window, cx);
643 editor
644 });
645
646 // This is a workaround for `editor.set_text` emitting a `BufferEdited` event, which would
647 // cause a custom summary to be set. The presence of this custom summary would cause
648 // summarization to not happen.
649 let mut suppress_first_edit = true;
650
651 let subscriptions = vec![
652 window.subscribe(&editor, cx, {
653 {
654 let text_thread_editor = text_thread_editor.clone();
655 move |editor, event, window, cx| match event {
656 EditorEvent::BufferEdited => {
657 if suppress_first_edit {
658 suppress_first_edit = false;
659 return;
660 }
661 let new_summary = editor.read(cx).text(cx);
662
663 text_thread_editor.update(cx, |text_thread_editor, cx| {
664 text_thread_editor
665 .text_thread()
666 .update(cx, |text_thread, cx| {
667 text_thread.set_custom_summary(new_summary, cx);
668 })
669 })
670 }
671 EditorEvent::Blurred => {
672 if editor.read(cx).text(cx).is_empty() {
673 let summary = text_thread_editor
674 .read(cx)
675 .text_thread()
676 .read(cx)
677 .summary()
678 .or_default();
679
680 editor.update(cx, |editor, cx| {
681 editor.set_text(summary, window, cx);
682 });
683 }
684 }
685 _ => {}
686 }
687 }
688 }),
689 window.subscribe(&text_thread_editor.read(cx).text_thread().clone(), cx, {
690 let editor = editor.clone();
691 move |text_thread, event, window, cx| match event {
692 TextThreadEvent::SummaryGenerated => {
693 let summary = text_thread.read(cx).summary().or_default();
694
695 editor.update(cx, |editor, cx| {
696 editor.set_text(summary, window, cx);
697 })
698 }
699 TextThreadEvent::PathChanged { .. } => {}
700 _ => {}
701 }
702 }),
703 ];
704
705 let buffer_search_bar =
706 cx.new(|cx| BufferSearchBar::new(Some(language_registry), window, cx));
707 buffer_search_bar.update(cx, |buffer_search_bar, cx| {
708 buffer_search_bar.set_active_pane_item(Some(&text_thread_editor), window, cx)
709 });
710
711 Self::TextThread {
712 text_thread_editor,
713 title_editor: editor,
714 buffer_search_bar,
715 _subscriptions: subscriptions,
716 }
717 }
718}
719
720pub struct AgentPanel {
721 workspace: WeakEntity<Workspace>,
722 /// Workspace id is used as a database key
723 workspace_id: Option<WorkspaceId>,
724 user_store: Entity<UserStore>,
725 project: Entity<Project>,
726 fs: Arc<dyn Fs>,
727 language_registry: Arc<LanguageRegistry>,
728 text_thread_history: Entity<TextThreadHistory>,
729 thread_store: Entity<ThreadStore>,
730 text_thread_store: Entity<assistant_text_thread::TextThreadStore>,
731 prompt_store: Option<Entity<PromptStore>>,
732 connection_store: Entity<AgentConnectionStore>,
733 context_server_registry: Entity<ContextServerRegistry>,
734 configuration: Option<Entity<AgentConfiguration>>,
735 configuration_subscription: Option<Subscription>,
736 focus_handle: FocusHandle,
737 active_view: ActiveView,
738 previous_view: Option<ActiveView>,
739 background_threads: HashMap<acp::SessionId, Entity<ConversationView>>,
740 new_thread_menu_handle: PopoverMenuHandle<ContextMenu>,
741 start_thread_in_menu_handle: PopoverMenuHandle<ContextMenu>,
742 agent_panel_menu_handle: PopoverMenuHandle<ContextMenu>,
743 agent_navigation_menu_handle: PopoverMenuHandle<ContextMenu>,
744 agent_navigation_menu: Option<Entity<ContextMenu>>,
745 _extension_subscription: Option<Subscription>,
746 width: Option<Pixels>,
747 height: Option<Pixels>,
748 zoomed: bool,
749 pending_serialization: Option<Task<Result<()>>>,
750 onboarding: Entity<AgentPanelOnboarding>,
751 selected_agent_type: AgentType,
752 start_thread_in: StartThreadIn,
753 worktree_creation_status: Option<WorktreeCreationStatus>,
754 _thread_view_subscription: Option<Subscription>,
755 _active_thread_focus_subscription: Option<Subscription>,
756 _worktree_creation_task: Option<Task<()>>,
757 show_trust_workspace_message: bool,
758 last_configuration_error_telemetry: Option<String>,
759 on_boarding_upsell_dismissed: AtomicBool,
760 _active_view_observation: Option<Subscription>,
761}
762
763impl AgentPanel {
764 fn serialize(&mut self, cx: &mut App) {
765 let Some(workspace_id) = self.workspace_id else {
766 return;
767 };
768
769 let width = self.width;
770 let selected_agent_type = self.selected_agent_type.clone();
771 let start_thread_in = Some(self.start_thread_in);
772
773 let last_active_thread = self.active_agent_thread(cx).map(|thread| {
774 let thread = thread.read(cx);
775 let title = thread.title();
776 let work_dirs = thread.work_dirs().cloned();
777 SerializedActiveThread {
778 session_id: thread.session_id().0.to_string(),
779 agent_type: self.selected_agent_type.clone(),
780 title: title.map(|t| t.to_string()),
781 work_dirs: work_dirs.map(|dirs| dirs.serialize()),
782 }
783 });
784
785 let kvp = KeyValueStore::global(cx);
786 self.pending_serialization = Some(cx.background_spawn(async move {
787 save_serialized_panel(
788 workspace_id,
789 SerializedAgentPanel {
790 width,
791 selected_agent: Some(selected_agent_type),
792 last_active_thread,
793 start_thread_in,
794 },
795 kvp,
796 )
797 .await?;
798 anyhow::Ok(())
799 }));
800 }
801
802 pub fn load(
803 workspace: WeakEntity<Workspace>,
804 prompt_builder: Arc<PromptBuilder>,
805 mut cx: AsyncWindowContext,
806 ) -> Task<Result<Entity<Self>>> {
807 let prompt_store = cx.update(|_window, cx| PromptStore::global(cx));
808 let kvp = cx.update(|_window, cx| KeyValueStore::global(cx)).ok();
809 cx.spawn(async move |cx| {
810 let prompt_store = match prompt_store {
811 Ok(prompt_store) => prompt_store.await.ok(),
812 Err(_) => None,
813 };
814 let workspace_id = workspace
815 .read_with(cx, |workspace, _| workspace.database_id())
816 .ok()
817 .flatten();
818
819 let serialized_panel = cx
820 .background_spawn(async move {
821 kvp.and_then(|kvp| {
822 workspace_id
823 .and_then(|id| read_serialized_panel(id, &kvp))
824 .or_else(|| read_legacy_serialized_panel(&kvp))
825 })
826 })
827 .await;
828
829 let slash_commands = Arc::new(SlashCommandWorkingSet::default());
830 let text_thread_store = workspace
831 .update(cx, |workspace, cx| {
832 let project = workspace.project().clone();
833 assistant_text_thread::TextThreadStore::new(
834 project,
835 prompt_builder,
836 slash_commands,
837 cx,
838 )
839 })?
840 .await?;
841
842 let last_active_thread = if let Some(thread_info) = serialized_panel
843 .as_ref()
844 .and_then(|p| p.last_active_thread.as_ref())
845 {
846 if thread_info.agent_type.is_native() {
847 let session_id = acp::SessionId::new(thread_info.session_id.clone());
848 let load_result = cx.update(|_window, cx| {
849 let thread_store = ThreadStore::global(cx);
850 thread_store.update(cx, |store, cx| store.load_thread(session_id, cx))
851 });
852 let thread_exists = if let Ok(task) = load_result {
853 task.await.ok().flatten().is_some()
854 } else {
855 false
856 };
857 if thread_exists {
858 Some(thread_info)
859 } else {
860 log::warn!(
861 "last active thread {} not found in database, skipping restoration",
862 thread_info.session_id
863 );
864 None
865 }
866 } else {
867 Some(thread_info)
868 }
869 } else {
870 None
871 };
872
873 let panel = workspace.update_in(cx, |workspace, window, cx| {
874 let panel =
875 cx.new(|cx| Self::new(workspace, text_thread_store, prompt_store, window, cx));
876
877 if let Some(serialized_panel) = &serialized_panel {
878 panel.update(cx, |panel, cx| {
879 panel.width = serialized_panel.width.map(|w| w.round());
880 if let Some(selected_agent) = serialized_panel.selected_agent.clone() {
881 panel.selected_agent_type = selected_agent;
882 }
883 if let Some(start_thread_in) = serialized_panel.start_thread_in {
884 let is_worktree_flag_enabled =
885 cx.has_flag::<AgentV2FeatureFlag>();
886 let is_valid = match &start_thread_in {
887 StartThreadIn::LocalProject => true,
888 StartThreadIn::NewWorktree => {
889 let project = panel.project.read(cx);
890 is_worktree_flag_enabled && !project.is_via_collab()
891 }
892 };
893 if is_valid {
894 panel.start_thread_in = start_thread_in;
895 } else {
896 log::info!(
897 "deserialized start_thread_in {:?} is no longer valid, falling back to LocalProject",
898 start_thread_in,
899 );
900 }
901 }
902 cx.notify();
903 });
904 }
905
906 if let Some(thread_info) = last_active_thread {
907 let agent_type = thread_info.agent_type.clone();
908 panel.update(cx, |panel, cx| {
909 panel.selected_agent_type = agent_type;
910 if let Some(agent) = panel.selected_agent() {
911 panel.load_agent_thread(
912 agent,
913 thread_info.session_id.clone().into(),
914 thread_info.work_dirs.as_ref().map(|dirs| PathList::deserialize(dirs)),
915 thread_info.title.as_ref().map(|t| t.clone().into()),
916 false,
917 window,
918 cx,
919 );
920 }
921 });
922 }
923 panel
924 })?;
925
926 Ok(panel)
927 })
928 }
929
930 pub(crate) fn new(
931 workspace: &Workspace,
932 text_thread_store: Entity<assistant_text_thread::TextThreadStore>,
933 prompt_store: Option<Entity<PromptStore>>,
934 window: &mut Window,
935 cx: &mut Context<Self>,
936 ) -> Self {
937 let fs = workspace.app_state().fs.clone();
938 let user_store = workspace.app_state().user_store.clone();
939 let project = workspace.project();
940 let language_registry = project.read(cx).languages().clone();
941 let client = workspace.client().clone();
942 let workspace_id = workspace.database_id();
943 let workspace = workspace.weak_handle();
944
945 let context_server_registry =
946 cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
947
948 let thread_store = ThreadStore::global(cx);
949 let text_thread_history =
950 cx.new(|cx| TextThreadHistory::new(text_thread_store.clone(), window, cx));
951
952 cx.subscribe_in(
953 &text_thread_history,
954 window,
955 |this, _, event, window, cx| match event {
956 TextThreadHistoryEvent::Open(thread) => {
957 this.open_saved_text_thread(thread.path.clone(), window, cx)
958 .detach_and_log_err(cx);
959 }
960 },
961 )
962 .detach();
963
964 let active_view = ActiveView::Uninitialized;
965
966 let weak_panel = cx.entity().downgrade();
967
968 window.defer(cx, move |window, cx| {
969 let panel = weak_panel.clone();
970 let agent_navigation_menu =
971 ContextMenu::build_persistent(window, cx, move |mut menu, window, cx| {
972 if let Some(panel) = panel.upgrade() {
973 if let Some(history) = panel
974 .update(cx, |panel, cx| panel.history_for_selected_agent(window, cx))
975 {
976 let view_all_label = match history {
977 History::AgentThreads { .. } => "View All",
978 History::TextThreads => "View All Text Threads",
979 };
980 menu = Self::populate_recently_updated_menu_section(
981 menu, panel, history, cx,
982 );
983 menu = menu.action(view_all_label, Box::new(OpenHistory));
984 }
985 }
986
987 menu = menu
988 .fixed_width(px(320.).into())
989 .keep_open_on_confirm(false)
990 .key_context("NavigationMenu");
991
992 menu
993 });
994 weak_panel
995 .update(cx, |panel, cx| {
996 cx.subscribe_in(
997 &agent_navigation_menu,
998 window,
999 |_, menu, _: &DismissEvent, window, cx| {
1000 menu.update(cx, |menu, _| {
1001 menu.clear_selected();
1002 });
1003 cx.focus_self(window);
1004 },
1005 )
1006 .detach();
1007 panel.agent_navigation_menu = Some(agent_navigation_menu);
1008 })
1009 .ok();
1010 });
1011
1012 let weak_panel = cx.entity().downgrade();
1013 let onboarding = cx.new(|cx| {
1014 AgentPanelOnboarding::new(
1015 user_store.clone(),
1016 client,
1017 move |_window, cx| {
1018 weak_panel
1019 .update(cx, |panel, _| {
1020 panel
1021 .on_boarding_upsell_dismissed
1022 .store(true, Ordering::Release);
1023 })
1024 .ok();
1025 OnboardingUpsell::set_dismissed(true, cx);
1026 },
1027 cx,
1028 )
1029 });
1030
1031 // Subscribe to extension events to sync agent servers when extensions change
1032 let extension_subscription = if let Some(extension_events) = ExtensionEvents::try_global(cx)
1033 {
1034 Some(
1035 cx.subscribe(&extension_events, |this, _source, event, cx| match event {
1036 extension::Event::ExtensionInstalled(_)
1037 | extension::Event::ExtensionUninstalled(_)
1038 | extension::Event::ExtensionsInstalledChanged => {
1039 this.sync_agent_servers_from_extensions(cx);
1040 }
1041 _ => {}
1042 }),
1043 )
1044 } else {
1045 None
1046 };
1047
1048 let connection_store = cx.new(|cx| {
1049 let mut store = AgentConnectionStore::new(project.clone(), cx);
1050 // Register the native agent right away, so that it is available for
1051 // the inline assistant etc.
1052 store.request_connection(
1053 Agent::NativeAgent,
1054 Agent::NativeAgent.server(fs.clone(), thread_store.clone()),
1055 cx,
1056 );
1057 store
1058 });
1059 let mut panel = Self {
1060 workspace_id,
1061 active_view,
1062 workspace,
1063 user_store,
1064 project: project.clone(),
1065 fs: fs.clone(),
1066 language_registry,
1067 text_thread_store,
1068 prompt_store,
1069 connection_store,
1070 configuration: None,
1071 configuration_subscription: None,
1072 focus_handle: cx.focus_handle(),
1073 context_server_registry,
1074 previous_view: None,
1075 background_threads: HashMap::default(),
1076 new_thread_menu_handle: PopoverMenuHandle::default(),
1077 start_thread_in_menu_handle: PopoverMenuHandle::default(),
1078 agent_panel_menu_handle: PopoverMenuHandle::default(),
1079 agent_navigation_menu_handle: PopoverMenuHandle::default(),
1080 agent_navigation_menu: None,
1081 _extension_subscription: extension_subscription,
1082 width: None,
1083 height: None,
1084 zoomed: false,
1085 pending_serialization: None,
1086 onboarding,
1087 text_thread_history,
1088 thread_store,
1089 selected_agent_type: AgentType::default(),
1090 start_thread_in: StartThreadIn::default(),
1091 worktree_creation_status: None,
1092 _thread_view_subscription: None,
1093 _active_thread_focus_subscription: None,
1094 _worktree_creation_task: None,
1095 show_trust_workspace_message: false,
1096 last_configuration_error_telemetry: None,
1097 on_boarding_upsell_dismissed: AtomicBool::new(OnboardingUpsell::dismissed(cx)),
1098 _active_view_observation: None,
1099 };
1100
1101 // Initial sync of agent servers from extensions
1102 panel.sync_agent_servers_from_extensions(cx);
1103 panel
1104 }
1105
1106 pub fn toggle_focus(
1107 workspace: &mut Workspace,
1108 _: &ToggleFocus,
1109 window: &mut Window,
1110 cx: &mut Context<Workspace>,
1111 ) {
1112 if workspace
1113 .panel::<Self>(cx)
1114 .is_some_and(|panel| panel.read(cx).enabled(cx))
1115 {
1116 workspace.toggle_panel_focus::<Self>(window, cx);
1117 }
1118 }
1119
1120 pub fn toggle(
1121 workspace: &mut Workspace,
1122 _: &Toggle,
1123 window: &mut Window,
1124 cx: &mut Context<Workspace>,
1125 ) {
1126 if workspace
1127 .panel::<Self>(cx)
1128 .is_some_and(|panel| panel.read(cx).enabled(cx))
1129 {
1130 if !workspace.toggle_panel_focus::<Self>(window, cx) {
1131 workspace.close_panel::<Self>(window, cx);
1132 }
1133 }
1134 }
1135
1136 pub(crate) fn prompt_store(&self) -> &Option<Entity<PromptStore>> {
1137 &self.prompt_store
1138 }
1139
1140 pub fn thread_store(&self) -> &Entity<ThreadStore> {
1141 &self.thread_store
1142 }
1143
1144 pub fn connection_store(&self) -> &Entity<AgentConnectionStore> {
1145 &self.connection_store
1146 }
1147
1148 pub fn open_thread(
1149 &mut self,
1150 session_id: acp::SessionId,
1151 work_dirs: Option<PathList>,
1152 title: Option<SharedString>,
1153 window: &mut Window,
1154 cx: &mut Context<Self>,
1155 ) {
1156 self.external_thread(
1157 Some(crate::Agent::NativeAgent),
1158 Some(session_id),
1159 work_dirs,
1160 title,
1161 None,
1162 true,
1163 window,
1164 cx,
1165 );
1166 }
1167
1168 pub(crate) fn context_server_registry(&self) -> &Entity<ContextServerRegistry> {
1169 &self.context_server_registry
1170 }
1171
1172 pub fn is_visible(workspace: &Entity<Workspace>, cx: &App) -> bool {
1173 let workspace_read = workspace.read(cx);
1174
1175 workspace_read
1176 .panel::<AgentPanel>(cx)
1177 .map(|panel| {
1178 let panel_id = Entity::entity_id(&panel);
1179
1180 workspace_read.all_docks().iter().any(|dock| {
1181 dock.read(cx)
1182 .visible_panel()
1183 .is_some_and(|visible_panel| visible_panel.panel_id() == panel_id)
1184 })
1185 })
1186 .unwrap_or(false)
1187 }
1188
1189 pub fn new_thread(&mut self, _action: &NewThread, window: &mut Window, cx: &mut Context<Self>) {
1190 self.new_agent_thread(AgentType::NativeAgent, window, cx);
1191 }
1192
1193 fn new_native_agent_thread_from_summary(
1194 &mut self,
1195 action: &NewNativeAgentThreadFromSummary,
1196 window: &mut Window,
1197 cx: &mut Context<Self>,
1198 ) {
1199 let session_id = action.from_session_id.clone();
1200
1201 let Some(history) = self
1202 .connection_store
1203 .read(cx)
1204 .entry(&Agent::NativeAgent)
1205 .and_then(|e| e.read(cx).history().cloned())
1206 else {
1207 debug_panic!("Native agent is not registered");
1208 return;
1209 };
1210
1211 cx.spawn_in(window, async move |this, cx| {
1212 this.update_in(cx, |this, window, cx| {
1213 let thread = history
1214 .read(cx)
1215 .session_for_id(&session_id)
1216 .context("Session not found")?;
1217
1218 this.external_thread(
1219 Some(Agent::NativeAgent),
1220 None,
1221 None,
1222 None,
1223 Some(AgentInitialContent::ThreadSummary {
1224 session_id: thread.session_id,
1225 title: thread.title,
1226 }),
1227 true,
1228 window,
1229 cx,
1230 );
1231 anyhow::Ok(())
1232 })
1233 })
1234 .detach_and_log_err(cx);
1235 }
1236
1237 fn new_text_thread(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1238 telemetry::event!("Agent Thread Started", agent = "zed-text");
1239
1240 let context = self
1241 .text_thread_store
1242 .update(cx, |context_store, cx| context_store.create(cx));
1243 let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx)
1244 .log_err()
1245 .flatten();
1246
1247 let text_thread_editor = cx.new(|cx| {
1248 let mut editor = TextThreadEditor::for_text_thread(
1249 context,
1250 self.fs.clone(),
1251 self.workspace.clone(),
1252 self.project.clone(),
1253 lsp_adapter_delegate,
1254 window,
1255 cx,
1256 );
1257 editor.insert_default_prompt(window, cx);
1258 editor
1259 });
1260
1261 if self.selected_agent_type != AgentType::TextThread {
1262 self.selected_agent_type = AgentType::TextThread;
1263 self.serialize(cx);
1264 }
1265
1266 self.set_active_view(
1267 ActiveView::text_thread(
1268 text_thread_editor.clone(),
1269 self.language_registry.clone(),
1270 window,
1271 cx,
1272 ),
1273 true,
1274 window,
1275 cx,
1276 );
1277 text_thread_editor.focus_handle(cx).focus(window, cx);
1278 }
1279
1280 fn external_thread(
1281 &mut self,
1282 agent_choice: Option<crate::Agent>,
1283 resume_session_id: Option<acp::SessionId>,
1284 work_dirs: Option<PathList>,
1285 title: Option<SharedString>,
1286 initial_content: Option<AgentInitialContent>,
1287 focus: bool,
1288 window: &mut Window,
1289 cx: &mut Context<Self>,
1290 ) {
1291 let workspace = self.workspace.clone();
1292 let project = self.project.clone();
1293 let fs = self.fs.clone();
1294 let is_via_collab = self.project.read(cx).is_via_collab();
1295
1296 const LAST_USED_EXTERNAL_AGENT_KEY: &str = "agent_panel__last_used_external_agent";
1297
1298 #[derive(Serialize, Deserialize)]
1299 struct LastUsedExternalAgent {
1300 agent: crate::Agent,
1301 }
1302
1303 let thread_store = self.thread_store.clone();
1304 let kvp = KeyValueStore::global(cx);
1305
1306 if let Some(agent) = agent_choice {
1307 cx.background_spawn({
1308 let agent = agent.clone();
1309 let kvp = kvp;
1310 async move {
1311 if let Some(serialized) =
1312 serde_json::to_string(&LastUsedExternalAgent { agent }).log_err()
1313 {
1314 kvp.write_kvp(LAST_USED_EXTERNAL_AGENT_KEY.to_string(), serialized)
1315 .await
1316 .log_err();
1317 }
1318 }
1319 })
1320 .detach();
1321
1322 let server = agent.server(fs, thread_store);
1323 self.create_agent_thread(
1324 server,
1325 resume_session_id,
1326 work_dirs,
1327 title,
1328 initial_content,
1329 workspace,
1330 project,
1331 agent,
1332 focus,
1333 window,
1334 cx,
1335 );
1336 } else {
1337 cx.spawn_in(window, async move |this, cx| {
1338 let ext_agent = if is_via_collab {
1339 Agent::NativeAgent
1340 } else {
1341 cx.background_spawn(async move { kvp.read_kvp(LAST_USED_EXTERNAL_AGENT_KEY) })
1342 .await
1343 .log_err()
1344 .flatten()
1345 .and_then(|value| {
1346 serde_json::from_str::<LastUsedExternalAgent>(&value).log_err()
1347 })
1348 .map(|agent| agent.agent)
1349 .unwrap_or(Agent::NativeAgent)
1350 };
1351
1352 let server = ext_agent.server(fs, thread_store);
1353 this.update_in(cx, |agent_panel, window, cx| {
1354 agent_panel.create_agent_thread(
1355 server,
1356 resume_session_id,
1357 work_dirs,
1358 title,
1359 initial_content,
1360 workspace,
1361 project,
1362 ext_agent,
1363 focus,
1364 window,
1365 cx,
1366 );
1367 })?;
1368
1369 anyhow::Ok(())
1370 })
1371 .detach_and_log_err(cx);
1372 }
1373 }
1374
1375 fn deploy_rules_library(
1376 &mut self,
1377 action: &OpenRulesLibrary,
1378 _window: &mut Window,
1379 cx: &mut Context<Self>,
1380 ) {
1381 open_rules_library(
1382 self.language_registry.clone(),
1383 Box::new(PromptLibraryInlineAssist::new(self.workspace.clone())),
1384 Rc::new(|| {
1385 Rc::new(SlashCommandCompletionProvider::new(
1386 Arc::new(SlashCommandWorkingSet::default()),
1387 None,
1388 None,
1389 ))
1390 }),
1391 action
1392 .prompt_to_select
1393 .map(|uuid| UserPromptId(uuid).into()),
1394 cx,
1395 )
1396 .detach_and_log_err(cx);
1397 }
1398
1399 fn expand_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1400 let Some(conversation_view) = self.active_conversation_view() else {
1401 return;
1402 };
1403
1404 let Some(active_thread) = conversation_view.read(cx).active_thread().cloned() else {
1405 return;
1406 };
1407
1408 active_thread.update(cx, |active_thread, cx| {
1409 active_thread.expand_message_editor(&ExpandMessageEditor, window, cx);
1410 active_thread.focus_handle(cx).focus(window, cx);
1411 })
1412 }
1413
1414 fn has_history_for_selected_agent(&self, cx: &App) -> bool {
1415 match &self.selected_agent_type {
1416 AgentType::TextThread | AgentType::NativeAgent => true,
1417 AgentType::Custom { id } => {
1418 let agent = Agent::Custom { id: id.clone() };
1419 self.connection_store
1420 .read(cx)
1421 .entry(&agent)
1422 .map_or(false, |entry| entry.read(cx).history().is_some())
1423 }
1424 }
1425 }
1426
1427 fn history_for_selected_agent(
1428 &self,
1429 window: &mut Window,
1430 cx: &mut Context<Self>,
1431 ) -> Option<History> {
1432 match &self.selected_agent_type {
1433 AgentType::TextThread => Some(History::TextThreads),
1434 AgentType::NativeAgent => {
1435 let history = self
1436 .connection_store
1437 .read(cx)
1438 .entry(&Agent::NativeAgent)?
1439 .read(cx)
1440 .history()?
1441 .clone();
1442
1443 Some(History::AgentThreads {
1444 view: self.create_thread_history_view(Agent::NativeAgent, history, window, cx),
1445 })
1446 }
1447 AgentType::Custom { id, .. } => {
1448 let agent = Agent::Custom { id: id.clone() };
1449 let history = self
1450 .connection_store
1451 .read(cx)
1452 .entry(&agent)?
1453 .read(cx)
1454 .history()?
1455 .clone();
1456 Some(History::AgentThreads {
1457 view: self.create_thread_history_view(agent, history, window, cx),
1458 })
1459 }
1460 }
1461 }
1462
1463 fn create_thread_history_view(
1464 &self,
1465 agent: Agent,
1466 history: Entity<ThreadHistory>,
1467 window: &mut Window,
1468 cx: &mut Context<Self>,
1469 ) -> Entity<ThreadHistoryView> {
1470 let view = cx.new(|cx| ThreadHistoryView::new(history.clone(), window, cx));
1471 cx.subscribe_in(
1472 &view,
1473 window,
1474 move |this, _, event, window, cx| match event {
1475 ThreadHistoryViewEvent::Open(thread) => {
1476 this.load_agent_thread(
1477 agent.clone(),
1478 thread.session_id.clone(),
1479 thread.work_dirs.clone(),
1480 thread.title.clone(),
1481 true,
1482 window,
1483 cx,
1484 );
1485 }
1486 },
1487 )
1488 .detach();
1489 view
1490 }
1491
1492 fn open_history(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1493 let Some(history) = self.history_for_selected_agent(window, cx) else {
1494 return;
1495 };
1496
1497 if let ActiveView::History {
1498 history: active_history,
1499 } = &self.active_view
1500 {
1501 if active_history == &history {
1502 if let Some(previous_view) = self.previous_view.take() {
1503 self.set_active_view(previous_view, true, window, cx);
1504 }
1505 return;
1506 }
1507 }
1508
1509 self.set_active_view(ActiveView::History { history }, true, window, cx);
1510 cx.notify();
1511 }
1512
1513 pub(crate) fn open_saved_text_thread(
1514 &mut self,
1515 path: Arc<Path>,
1516 window: &mut Window,
1517 cx: &mut Context<Self>,
1518 ) -> Task<Result<()>> {
1519 let text_thread_task = self
1520 .text_thread_store
1521 .update(cx, |store, cx| store.open_local(path, cx));
1522 cx.spawn_in(window, async move |this, cx| {
1523 let text_thread = text_thread_task.await?;
1524 this.update_in(cx, |this, window, cx| {
1525 this.open_text_thread(text_thread, window, cx);
1526 })
1527 })
1528 }
1529
1530 pub(crate) fn open_text_thread(
1531 &mut self,
1532 text_thread: Entity<TextThread>,
1533 window: &mut Window,
1534 cx: &mut Context<Self>,
1535 ) {
1536 let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project.clone(), cx)
1537 .log_err()
1538 .flatten();
1539 let editor = cx.new(|cx| {
1540 TextThreadEditor::for_text_thread(
1541 text_thread,
1542 self.fs.clone(),
1543 self.workspace.clone(),
1544 self.project.clone(),
1545 lsp_adapter_delegate,
1546 window,
1547 cx,
1548 )
1549 });
1550
1551 if self.selected_agent_type != AgentType::TextThread {
1552 self.selected_agent_type = AgentType::TextThread;
1553 self.serialize(cx);
1554 }
1555
1556 self.set_active_view(
1557 ActiveView::text_thread(editor, self.language_registry.clone(), window, cx),
1558 true,
1559 window,
1560 cx,
1561 );
1562 }
1563
1564 pub fn go_back(&mut self, _: &workspace::GoBack, window: &mut Window, cx: &mut Context<Self>) {
1565 match self.active_view {
1566 ActiveView::Configuration | ActiveView::History { .. } => {
1567 if let Some(previous_view) = self.previous_view.take() {
1568 self.set_active_view(previous_view, true, window, cx);
1569 }
1570 cx.notify();
1571 }
1572 _ => {}
1573 }
1574 }
1575
1576 pub fn toggle_navigation_menu(
1577 &mut self,
1578 _: &ToggleNavigationMenu,
1579 window: &mut Window,
1580 cx: &mut Context<Self>,
1581 ) {
1582 if !self.has_history_for_selected_agent(cx) {
1583 return;
1584 }
1585 self.agent_navigation_menu_handle.toggle(window, cx);
1586 }
1587
1588 pub fn toggle_options_menu(
1589 &mut self,
1590 _: &ToggleOptionsMenu,
1591 window: &mut Window,
1592 cx: &mut Context<Self>,
1593 ) {
1594 self.agent_panel_menu_handle.toggle(window, cx);
1595 }
1596
1597 pub fn toggle_new_thread_menu(
1598 &mut self,
1599 _: &ToggleNewThreadMenu,
1600 window: &mut Window,
1601 cx: &mut Context<Self>,
1602 ) {
1603 self.new_thread_menu_handle.toggle(window, cx);
1604 }
1605
1606 pub fn increase_font_size(
1607 &mut self,
1608 action: &IncreaseBufferFontSize,
1609 _: &mut Window,
1610 cx: &mut Context<Self>,
1611 ) {
1612 self.handle_font_size_action(action.persist, px(1.0), cx);
1613 }
1614
1615 pub fn decrease_font_size(
1616 &mut self,
1617 action: &DecreaseBufferFontSize,
1618 _: &mut Window,
1619 cx: &mut Context<Self>,
1620 ) {
1621 self.handle_font_size_action(action.persist, px(-1.0), cx);
1622 }
1623
1624 fn handle_font_size_action(&mut self, persist: bool, delta: Pixels, cx: &mut Context<Self>) {
1625 match self.active_view.which_font_size_used() {
1626 WhichFontSize::AgentFont => {
1627 if persist {
1628 update_settings_file(self.fs.clone(), cx, move |settings, cx| {
1629 let agent_ui_font_size =
1630 ThemeSettings::get_global(cx).agent_ui_font_size(cx) + delta;
1631 let agent_buffer_font_size =
1632 ThemeSettings::get_global(cx).agent_buffer_font_size(cx) + delta;
1633
1634 let _ = settings
1635 .theme
1636 .agent_ui_font_size
1637 .insert(f32::from(theme::clamp_font_size(agent_ui_font_size)).into());
1638 let _ = settings.theme.agent_buffer_font_size.insert(
1639 f32::from(theme::clamp_font_size(agent_buffer_font_size)).into(),
1640 );
1641 });
1642 } else {
1643 theme::adjust_agent_ui_font_size(cx, |size| size + delta);
1644 theme::adjust_agent_buffer_font_size(cx, |size| size + delta);
1645 }
1646 }
1647 WhichFontSize::BufferFont => {
1648 // Prompt editor uses the buffer font size, so allow the action to propagate to the
1649 // default handler that changes that font size.
1650 cx.propagate();
1651 }
1652 WhichFontSize::None => {}
1653 }
1654 }
1655
1656 pub fn reset_font_size(
1657 &mut self,
1658 action: &ResetBufferFontSize,
1659 _: &mut Window,
1660 cx: &mut Context<Self>,
1661 ) {
1662 if action.persist {
1663 update_settings_file(self.fs.clone(), cx, move |settings, _| {
1664 settings.theme.agent_ui_font_size = None;
1665 settings.theme.agent_buffer_font_size = None;
1666 });
1667 } else {
1668 theme::reset_agent_ui_font_size(cx);
1669 theme::reset_agent_buffer_font_size(cx);
1670 }
1671 }
1672
1673 pub fn reset_agent_zoom(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1674 theme::reset_agent_ui_font_size(cx);
1675 theme::reset_agent_buffer_font_size(cx);
1676 }
1677
1678 pub fn toggle_zoom(&mut self, _: &ToggleZoom, window: &mut Window, cx: &mut Context<Self>) {
1679 if self.zoomed {
1680 cx.emit(PanelEvent::ZoomOut);
1681 } else {
1682 if !self.focus_handle(cx).contains_focused(window, cx) {
1683 cx.focus_self(window);
1684 }
1685 cx.emit(PanelEvent::ZoomIn);
1686 }
1687 }
1688
1689 pub(crate) fn open_configuration(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1690 let agent_server_store = self.project.read(cx).agent_server_store().clone();
1691 let context_server_store = self.project.read(cx).context_server_store();
1692 let fs = self.fs.clone();
1693
1694 self.set_active_view(ActiveView::Configuration, true, window, cx);
1695 self.configuration = Some(cx.new(|cx| {
1696 AgentConfiguration::new(
1697 fs,
1698 agent_server_store,
1699 context_server_store,
1700 self.context_server_registry.clone(),
1701 self.language_registry.clone(),
1702 self.workspace.clone(),
1703 window,
1704 cx,
1705 )
1706 }));
1707
1708 if let Some(configuration) = self.configuration.as_ref() {
1709 self.configuration_subscription = Some(cx.subscribe_in(
1710 configuration,
1711 window,
1712 Self::handle_agent_configuration_event,
1713 ));
1714
1715 configuration.focus_handle(cx).focus(window, cx);
1716 }
1717 }
1718
1719 pub(crate) fn open_active_thread_as_markdown(
1720 &mut self,
1721 _: &OpenActiveThreadAsMarkdown,
1722 window: &mut Window,
1723 cx: &mut Context<Self>,
1724 ) {
1725 if let Some(workspace) = self.workspace.upgrade()
1726 && let Some(conversation_view) = self.active_conversation_view()
1727 && let Some(active_thread) = conversation_view.read(cx).active_thread().cloned()
1728 {
1729 active_thread.update(cx, |thread, cx| {
1730 thread
1731 .open_thread_as_markdown(workspace, window, cx)
1732 .detach_and_log_err(cx);
1733 });
1734 }
1735 }
1736
1737 fn copy_thread_to_clipboard(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1738 let Some(thread) = self.active_native_agent_thread(cx) else {
1739 Self::show_deferred_toast(&self.workspace, "No active native thread to copy", cx);
1740 return;
1741 };
1742
1743 let workspace = self.workspace.clone();
1744 let load_task = thread.read(cx).to_db(cx);
1745
1746 cx.spawn_in(window, async move |_this, cx| {
1747 let db_thread = load_task.await;
1748 let shared_thread = SharedThread::from_db_thread(&db_thread);
1749 let thread_data = shared_thread.to_bytes()?;
1750 let encoded = base64::Engine::encode(&base64::prelude::BASE64_STANDARD, &thread_data);
1751
1752 cx.update(|_window, cx| {
1753 cx.write_to_clipboard(ClipboardItem::new_string(encoded));
1754 if let Some(workspace) = workspace.upgrade() {
1755 workspace.update(cx, |workspace, cx| {
1756 struct ThreadCopiedToast;
1757 workspace.show_toast(
1758 workspace::Toast::new(
1759 workspace::notifications::NotificationId::unique::<ThreadCopiedToast>(),
1760 "Thread copied to clipboard (base64 encoded)",
1761 )
1762 .autohide(),
1763 cx,
1764 );
1765 });
1766 }
1767 })?;
1768
1769 anyhow::Ok(())
1770 })
1771 .detach_and_log_err(cx);
1772 }
1773
1774 fn show_deferred_toast(
1775 workspace: &WeakEntity<workspace::Workspace>,
1776 message: &'static str,
1777 cx: &mut App,
1778 ) {
1779 let workspace = workspace.clone();
1780 cx.defer(move |cx| {
1781 if let Some(workspace) = workspace.upgrade() {
1782 workspace.update(cx, |workspace, cx| {
1783 struct ClipboardToast;
1784 workspace.show_toast(
1785 workspace::Toast::new(
1786 workspace::notifications::NotificationId::unique::<ClipboardToast>(),
1787 message,
1788 )
1789 .autohide(),
1790 cx,
1791 );
1792 });
1793 }
1794 });
1795 }
1796
1797 fn load_thread_from_clipboard(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1798 let Some(clipboard) = cx.read_from_clipboard() else {
1799 Self::show_deferred_toast(&self.workspace, "No clipboard content available", cx);
1800 return;
1801 };
1802
1803 let Some(encoded) = clipboard.text() else {
1804 Self::show_deferred_toast(&self.workspace, "Clipboard does not contain text", cx);
1805 return;
1806 };
1807
1808 let thread_data = match base64::Engine::decode(&base64::prelude::BASE64_STANDARD, &encoded)
1809 {
1810 Ok(data) => data,
1811 Err(_) => {
1812 Self::show_deferred_toast(
1813 &self.workspace,
1814 "Failed to decode clipboard content (expected base64)",
1815 cx,
1816 );
1817 return;
1818 }
1819 };
1820
1821 let shared_thread = match SharedThread::from_bytes(&thread_data) {
1822 Ok(thread) => thread,
1823 Err(_) => {
1824 Self::show_deferred_toast(
1825 &self.workspace,
1826 "Failed to parse thread data from clipboard",
1827 cx,
1828 );
1829 return;
1830 }
1831 };
1832
1833 let db_thread = shared_thread.to_db_thread();
1834 let session_id = acp::SessionId::new(uuid::Uuid::new_v4().to_string());
1835 let thread_store = self.thread_store.clone();
1836 let title = db_thread.title.clone();
1837 let workspace = self.workspace.clone();
1838
1839 cx.spawn_in(window, async move |this, cx| {
1840 thread_store
1841 .update(&mut cx.clone(), |store, cx| {
1842 store.save_thread(session_id.clone(), db_thread, Default::default(), cx)
1843 })
1844 .await?;
1845
1846 this.update_in(cx, |this, window, cx| {
1847 this.open_thread(session_id, None, Some(title), window, cx);
1848 })?;
1849
1850 this.update_in(cx, |_, _window, cx| {
1851 if let Some(workspace) = workspace.upgrade() {
1852 workspace.update(cx, |workspace, cx| {
1853 struct ThreadLoadedToast;
1854 workspace.show_toast(
1855 workspace::Toast::new(
1856 workspace::notifications::NotificationId::unique::<ThreadLoadedToast>(),
1857 "Thread loaded from clipboard",
1858 )
1859 .autohide(),
1860 cx,
1861 );
1862 });
1863 }
1864 })?;
1865
1866 anyhow::Ok(())
1867 })
1868 .detach_and_log_err(cx);
1869 }
1870
1871 fn handle_agent_configuration_event(
1872 &mut self,
1873 _entity: &Entity<AgentConfiguration>,
1874 event: &AssistantConfigurationEvent,
1875 window: &mut Window,
1876 cx: &mut Context<Self>,
1877 ) {
1878 match event {
1879 AssistantConfigurationEvent::NewThread(provider) => {
1880 if LanguageModelRegistry::read_global(cx)
1881 .default_model()
1882 .is_none_or(|model| model.provider.id() != provider.id())
1883 && let Some(model) = provider.default_model(cx)
1884 {
1885 update_settings_file(self.fs.clone(), cx, move |settings, _| {
1886 let provider = model.provider_id().0.to_string();
1887 let enable_thinking = model.supports_thinking();
1888 let effort = model
1889 .default_effort_level()
1890 .map(|effort| effort.value.to_string());
1891 let model = model.id().0.to_string();
1892 settings
1893 .agent
1894 .get_or_insert_default()
1895 .set_model(LanguageModelSelection {
1896 provider: LanguageModelProviderSetting(provider),
1897 model,
1898 enable_thinking,
1899 effort,
1900 })
1901 });
1902 }
1903
1904 self.new_thread(&NewThread, window, cx);
1905 if let Some((thread, model)) = self
1906 .active_native_agent_thread(cx)
1907 .zip(provider.default_model(cx))
1908 {
1909 thread.update(cx, |thread, cx| {
1910 thread.set_model(model, cx);
1911 });
1912 }
1913 }
1914 }
1915 }
1916
1917 pub fn active_conversation_view(&self) -> Option<&Entity<ConversationView>> {
1918 match &self.active_view {
1919 ActiveView::AgentThread { conversation_view } => Some(conversation_view),
1920 _ => None,
1921 }
1922 }
1923
1924 pub fn active_thread_view(&self, cx: &App) -> Option<Entity<ThreadView>> {
1925 let server_view = self.active_conversation_view()?;
1926 server_view.read(cx).active_thread().cloned()
1927 }
1928
1929 pub fn active_agent_thread(&self, cx: &App) -> Option<Entity<AcpThread>> {
1930 match &self.active_view {
1931 ActiveView::AgentThread {
1932 conversation_view, ..
1933 } => conversation_view
1934 .read(cx)
1935 .active_thread()
1936 .map(|r| r.read(cx).thread.clone()),
1937 _ => None,
1938 }
1939 }
1940
1941 /// Returns the primary thread views for all retained connections: the
1942 pub fn is_background_thread(&self, session_id: &acp::SessionId) -> bool {
1943 self.background_threads.contains_key(session_id)
1944 }
1945
1946 pub fn cancel_thread(&self, session_id: &acp::SessionId, cx: &mut Context<Self>) -> bool {
1947 let conversation_views = self
1948 .active_conversation_view()
1949 .into_iter()
1950 .chain(self.background_threads.values());
1951
1952 for conversation_view in conversation_views {
1953 if let Some(thread_view) = conversation_view.read(cx).thread_view(session_id) {
1954 thread_view.update(cx, |view, cx| view.cancel_generation(cx));
1955 return true;
1956 }
1957 }
1958 false
1959 }
1960
1961 /// active thread plus any background threads that are still running or
1962 /// completed but unseen.
1963 pub fn parent_threads(&self, cx: &App) -> Vec<Entity<ThreadView>> {
1964 let mut views = Vec::new();
1965
1966 if let Some(server_view) = self.active_conversation_view() {
1967 if let Some(thread_view) = server_view.read(cx).root_thread(cx) {
1968 views.push(thread_view);
1969 }
1970 }
1971
1972 for server_view in self.background_threads.values() {
1973 if let Some(thread_view) = server_view.read(cx).root_thread(cx) {
1974 views.push(thread_view);
1975 }
1976 }
1977
1978 views
1979 }
1980
1981 fn retain_running_thread(&mut self, old_view: ActiveView, cx: &mut Context<Self>) {
1982 let ActiveView::AgentThread { conversation_view } = old_view else {
1983 return;
1984 };
1985
1986 let Some(thread_view) = conversation_view.read(cx).root_thread(cx) else {
1987 return;
1988 };
1989
1990 self.background_threads
1991 .insert(thread_view.read(cx).id.clone(), conversation_view);
1992 self.cleanup_background_threads(cx);
1993 }
1994
1995 /// We keep threads that are:
1996 /// - Still running
1997 /// - Do not support reloading the full session
1998 /// - Have had the most recent events (up to 5 idle threads)
1999 fn cleanup_background_threads(&mut self, cx: &App) {
2000 let mut potential_removals = self
2001 .background_threads
2002 .iter()
2003 .filter(|(_id, view)| {
2004 let Some(thread_view) = view.read(cx).root_thread(cx) else {
2005 return true;
2006 };
2007 let thread = thread_view.read(cx).thread.read(cx);
2008 thread.connection().supports_load_session() && thread.status() == ThreadStatus::Idle
2009 })
2010 .collect::<Vec<_>>();
2011
2012 const MAX_IDLE_BACKGROUND_THREADS: usize = 5;
2013
2014 potential_removals.sort_unstable_by_key(|(_, view)| view.read(cx).updated_at(cx));
2015 let n = potential_removals
2016 .len()
2017 .saturating_sub(MAX_IDLE_BACKGROUND_THREADS);
2018 let to_remove = potential_removals
2019 .into_iter()
2020 .map(|(id, _)| id.clone())
2021 .take(n)
2022 .collect::<Vec<_>>();
2023 for id in to_remove {
2024 self.background_threads.remove(&id);
2025 }
2026 }
2027
2028 pub(crate) fn active_native_agent_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
2029 match &self.active_view {
2030 ActiveView::AgentThread {
2031 conversation_view, ..
2032 } => conversation_view.read(cx).as_native_thread(cx),
2033 _ => None,
2034 }
2035 }
2036
2037 pub(crate) fn active_text_thread_editor(&self) -> Option<Entity<TextThreadEditor>> {
2038 match &self.active_view {
2039 ActiveView::TextThread {
2040 text_thread_editor, ..
2041 } => Some(text_thread_editor.clone()),
2042 _ => None,
2043 }
2044 }
2045
2046 fn set_active_view(
2047 &mut self,
2048 new_view: ActiveView,
2049 focus: bool,
2050 window: &mut Window,
2051 cx: &mut Context<Self>,
2052 ) {
2053 let was_in_agent_history = matches!(
2054 self.active_view,
2055 ActiveView::History {
2056 history: History::AgentThreads { .. }
2057 }
2058 );
2059 let current_is_uninitialized = matches!(self.active_view, ActiveView::Uninitialized);
2060 let current_is_history = matches!(self.active_view, ActiveView::History { .. });
2061 let new_is_history = matches!(new_view, ActiveView::History { .. });
2062
2063 let current_is_config = matches!(self.active_view, ActiveView::Configuration);
2064 let new_is_config = matches!(new_view, ActiveView::Configuration);
2065
2066 let current_is_overlay = current_is_history || current_is_config;
2067 let new_is_overlay = new_is_history || new_is_config;
2068
2069 if current_is_uninitialized || (current_is_overlay && !new_is_overlay) {
2070 self.active_view = new_view;
2071 } else if !current_is_overlay && new_is_overlay {
2072 self.previous_view = Some(std::mem::replace(&mut self.active_view, new_view));
2073 } else {
2074 let old_view = std::mem::replace(&mut self.active_view, new_view);
2075 if !new_is_overlay {
2076 if let Some(previous) = self.previous_view.take() {
2077 self.retain_running_thread(previous, cx);
2078 }
2079 }
2080 self.retain_running_thread(old_view, cx);
2081 }
2082
2083 // Subscribe to the active ThreadView's events (e.g. FirstSendRequested)
2084 // so the panel can intercept the first send for worktree creation.
2085 // Re-subscribe whenever the ConnectionView changes, since the inner
2086 // ThreadView may have been replaced (e.g. navigating between threads).
2087 self._active_view_observation = match &self.active_view {
2088 ActiveView::AgentThread { conversation_view } => {
2089 self._thread_view_subscription =
2090 Self::subscribe_to_active_thread_view(conversation_view, window, cx);
2091 let focus_handle = conversation_view.focus_handle(cx);
2092 self._active_thread_focus_subscription =
2093 Some(cx.on_focus_in(&focus_handle, window, |_this, _window, cx| {
2094 cx.emit(AgentPanelEvent::ThreadFocused);
2095 cx.notify();
2096 }));
2097 Some(cx.observe_in(
2098 conversation_view,
2099 window,
2100 |this, server_view, window, cx| {
2101 this._thread_view_subscription =
2102 Self::subscribe_to_active_thread_view(&server_view, window, cx);
2103 cx.emit(AgentPanelEvent::ActiveViewChanged);
2104 this.serialize(cx);
2105 cx.notify();
2106 },
2107 ))
2108 }
2109 _ => {
2110 self._thread_view_subscription = None;
2111 self._active_thread_focus_subscription = None;
2112 None
2113 }
2114 };
2115
2116 if let ActiveView::History { history } = &self.active_view {
2117 if !was_in_agent_history && let History::AgentThreads { view } = history {
2118 view.update(cx, |view, cx| {
2119 view.history()
2120 .update(cx, |history, cx| history.refresh_full_history(cx))
2121 });
2122 }
2123 }
2124
2125 if focus {
2126 self.focus_handle(cx).focus(window, cx);
2127 }
2128 cx.emit(AgentPanelEvent::ActiveViewChanged);
2129 }
2130
2131 fn populate_recently_updated_menu_section(
2132 mut menu: ContextMenu,
2133 panel: Entity<Self>,
2134 history: History,
2135 cx: &mut Context<ContextMenu>,
2136 ) -> ContextMenu {
2137 match history {
2138 History::AgentThreads { view } => {
2139 let entries = view
2140 .read(cx)
2141 .history()
2142 .read(cx)
2143 .sessions()
2144 .iter()
2145 .take(RECENTLY_UPDATED_MENU_LIMIT)
2146 .cloned()
2147 .collect::<Vec<_>>();
2148
2149 if entries.is_empty() {
2150 return menu;
2151 }
2152
2153 menu = menu.header("Recently Updated");
2154
2155 for entry in entries {
2156 let title = entry
2157 .title
2158 .as_ref()
2159 .filter(|title| !title.is_empty())
2160 .cloned()
2161 .unwrap_or_else(|| SharedString::new_static(DEFAULT_THREAD_TITLE));
2162
2163 menu = menu.entry(title, None, {
2164 let panel = panel.downgrade();
2165 let entry = entry.clone();
2166 move |window, cx| {
2167 let entry = entry.clone();
2168 panel
2169 .update(cx, move |this, cx| {
2170 if let Some(agent) = this.selected_agent() {
2171 this.load_agent_thread(
2172 agent,
2173 entry.session_id.clone(),
2174 entry.work_dirs.clone(),
2175 entry.title.clone(),
2176 true,
2177 window,
2178 cx,
2179 );
2180 }
2181 })
2182 .ok();
2183 }
2184 });
2185 }
2186 }
2187 History::TextThreads => {
2188 let entries = panel
2189 .read(cx)
2190 .text_thread_store
2191 .read(cx)
2192 .ordered_text_threads()
2193 .take(RECENTLY_UPDATED_MENU_LIMIT)
2194 .cloned()
2195 .collect::<Vec<_>>();
2196
2197 if entries.is_empty() {
2198 return menu;
2199 }
2200
2201 menu = menu.header("Recent Text Threads");
2202
2203 for entry in entries {
2204 let title = if entry.title.is_empty() {
2205 SharedString::new_static(DEFAULT_THREAD_TITLE)
2206 } else {
2207 entry.title.clone()
2208 };
2209
2210 menu = menu.entry(title, None, {
2211 let panel = panel.downgrade();
2212 let entry = entry.clone();
2213 move |window, cx| {
2214 let path = entry.path.clone();
2215 panel
2216 .update(cx, move |this, cx| {
2217 this.open_saved_text_thread(path.clone(), window, cx)
2218 .detach_and_log_err(cx);
2219 })
2220 .ok();
2221 }
2222 });
2223 }
2224 }
2225 }
2226
2227 menu.separator()
2228 }
2229
2230 fn subscribe_to_active_thread_view(
2231 server_view: &Entity<ConversationView>,
2232 window: &mut Window,
2233 cx: &mut Context<Self>,
2234 ) -> Option<Subscription> {
2235 server_view.read(cx).active_thread().cloned().map(|tv| {
2236 cx.subscribe_in(
2237 &tv,
2238 window,
2239 |this, view, event: &AcpThreadViewEvent, window, cx| match event {
2240 AcpThreadViewEvent::FirstSendRequested { content } => {
2241 this.handle_first_send_requested(view.clone(), content.clone(), window, cx);
2242 }
2243 },
2244 )
2245 })
2246 }
2247
2248 pub fn start_thread_in(&self) -> &StartThreadIn {
2249 &self.start_thread_in
2250 }
2251
2252 fn set_start_thread_in(
2253 &mut self,
2254 action: &StartThreadIn,
2255 window: &mut Window,
2256 cx: &mut Context<Self>,
2257 ) {
2258 if matches!(action, StartThreadIn::NewWorktree) && !cx.has_flag::<AgentV2FeatureFlag>() {
2259 return;
2260 }
2261
2262 let new_target = match *action {
2263 StartThreadIn::LocalProject => StartThreadIn::LocalProject,
2264 StartThreadIn::NewWorktree => {
2265 if !self.project_has_git_repository(cx) {
2266 log::error!(
2267 "set_start_thread_in: cannot use NewWorktree without a git repository"
2268 );
2269 return;
2270 }
2271 if self.project.read(cx).is_via_collab() {
2272 log::error!("set_start_thread_in: cannot use NewWorktree in a collab project");
2273 return;
2274 }
2275 StartThreadIn::NewWorktree
2276 }
2277 };
2278 self.start_thread_in = new_target;
2279 if let Some(thread) = self.active_thread_view(cx) {
2280 thread.update(cx, |thread, cx| thread.focus_handle(cx).focus(window, cx));
2281 }
2282 self.serialize(cx);
2283 cx.notify();
2284 }
2285
2286 fn cycle_start_thread_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2287 let next = match self.start_thread_in {
2288 StartThreadIn::LocalProject => StartThreadIn::NewWorktree,
2289 StartThreadIn::NewWorktree => StartThreadIn::LocalProject,
2290 };
2291 self.set_start_thread_in(&next, window, cx);
2292 }
2293
2294 fn reset_start_thread_in_to_default(&mut self, cx: &mut Context<Self>) {
2295 use settings::{NewThreadLocation, Settings};
2296 let default = AgentSettings::get_global(cx).new_thread_location;
2297 let start_thread_in = match default {
2298 NewThreadLocation::LocalProject => StartThreadIn::LocalProject,
2299 NewThreadLocation::NewWorktree => {
2300 if self.project_has_git_repository(cx) {
2301 StartThreadIn::NewWorktree
2302 } else {
2303 StartThreadIn::LocalProject
2304 }
2305 }
2306 };
2307 if self.start_thread_in != start_thread_in {
2308 self.start_thread_in = start_thread_in;
2309 self.serialize(cx);
2310 cx.notify();
2311 }
2312 }
2313
2314 pub(crate) fn selected_agent(&self) -> Option<Agent> {
2315 match &self.selected_agent_type {
2316 AgentType::NativeAgent => Some(Agent::NativeAgent),
2317 AgentType::Custom { id } => Some(Agent::Custom { id: id.clone() }),
2318 AgentType::TextThread => None,
2319 }
2320 }
2321
2322 fn sync_agent_servers_from_extensions(&mut self, cx: &mut Context<Self>) {
2323 if let Some(extension_store) = ExtensionStore::try_global(cx) {
2324 let (manifests, extensions_dir) = {
2325 let store = extension_store.read(cx);
2326 let installed = store.installed_extensions();
2327 let manifests: Vec<_> = installed
2328 .iter()
2329 .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
2330 .collect();
2331 let extensions_dir = paths::extensions_dir().join("installed");
2332 (manifests, extensions_dir)
2333 };
2334
2335 self.project.update(cx, |project, cx| {
2336 project.agent_server_store().update(cx, |store, cx| {
2337 let manifest_refs: Vec<_> = manifests
2338 .iter()
2339 .map(|(id, manifest)| (id.as_ref(), manifest.as_ref()))
2340 .collect();
2341 store.sync_extension_agents(manifest_refs, extensions_dir, cx);
2342 });
2343 });
2344 }
2345 }
2346
2347 pub fn new_agent_thread_with_external_source_prompt(
2348 &mut self,
2349 external_source_prompt: Option<ExternalSourcePrompt>,
2350 window: &mut Window,
2351 cx: &mut Context<Self>,
2352 ) {
2353 self.external_thread(
2354 None,
2355 None,
2356 None,
2357 None,
2358 external_source_prompt.map(AgentInitialContent::from),
2359 true,
2360 window,
2361 cx,
2362 );
2363 }
2364
2365 pub fn new_agent_thread(
2366 &mut self,
2367 agent: AgentType,
2368 window: &mut Window,
2369 cx: &mut Context<Self>,
2370 ) {
2371 self.reset_start_thread_in_to_default(cx);
2372 self.new_agent_thread_inner(agent, true, window, cx);
2373 }
2374
2375 fn new_agent_thread_inner(
2376 &mut self,
2377 agent: AgentType,
2378 focus: bool,
2379 window: &mut Window,
2380 cx: &mut Context<Self>,
2381 ) {
2382 match agent {
2383 AgentType::TextThread => {
2384 window.dispatch_action(NewTextThread.boxed_clone(), cx);
2385 }
2386 AgentType::NativeAgent => self.external_thread(
2387 Some(crate::Agent::NativeAgent),
2388 None,
2389 None,
2390 None,
2391 None,
2392 focus,
2393 window,
2394 cx,
2395 ),
2396 AgentType::Custom { id } => self.external_thread(
2397 Some(crate::Agent::Custom { id }),
2398 None,
2399 None,
2400 None,
2401 None,
2402 focus,
2403 window,
2404 cx,
2405 ),
2406 }
2407 }
2408
2409 pub fn load_agent_thread(
2410 &mut self,
2411 agent: Agent,
2412 session_id: acp::SessionId,
2413 work_dirs: Option<PathList>,
2414 title: Option<SharedString>,
2415 focus: bool,
2416 window: &mut Window,
2417 cx: &mut Context<Self>,
2418 ) {
2419 if let Some(conversation_view) = self.background_threads.remove(&session_id) {
2420 self.set_active_view(
2421 ActiveView::AgentThread { conversation_view },
2422 focus,
2423 window,
2424 cx,
2425 );
2426 return;
2427 }
2428
2429 if let ActiveView::AgentThread { conversation_view } = &self.active_view {
2430 if conversation_view
2431 .read(cx)
2432 .active_thread()
2433 .map(|t| t.read(cx).id.clone())
2434 == Some(session_id.clone())
2435 {
2436 cx.emit(AgentPanelEvent::ActiveViewChanged);
2437 return;
2438 }
2439 }
2440
2441 if let Some(ActiveView::AgentThread { conversation_view }) = &self.previous_view {
2442 if conversation_view
2443 .read(cx)
2444 .active_thread()
2445 .map(|t| t.read(cx).id.clone())
2446 == Some(session_id.clone())
2447 {
2448 let view = self.previous_view.take().unwrap();
2449 self.set_active_view(view, focus, window, cx);
2450 return;
2451 }
2452 }
2453
2454 self.external_thread(
2455 Some(agent),
2456 Some(session_id),
2457 work_dirs,
2458 title,
2459 None,
2460 focus,
2461 window,
2462 cx,
2463 );
2464 }
2465
2466 pub(crate) fn create_agent_thread(
2467 &mut self,
2468 server: Rc<dyn AgentServer>,
2469 resume_session_id: Option<acp::SessionId>,
2470 work_dirs: Option<PathList>,
2471 title: Option<SharedString>,
2472 initial_content: Option<AgentInitialContent>,
2473 workspace: WeakEntity<Workspace>,
2474 project: Entity<Project>,
2475 ext_agent: Agent,
2476 focus: bool,
2477 window: &mut Window,
2478 cx: &mut Context<Self>,
2479 ) {
2480 let selected_agent = AgentType::from(ext_agent.clone());
2481 if self.selected_agent_type != selected_agent {
2482 self.selected_agent_type = selected_agent;
2483 self.serialize(cx);
2484 }
2485 let thread_store = server
2486 .clone()
2487 .downcast::<agent::NativeAgentServer>()
2488 .is_some()
2489 .then(|| self.thread_store.clone());
2490
2491 let connection_store = self.connection_store.clone();
2492
2493 let conversation_view = cx.new(|cx| {
2494 crate::ConversationView::new(
2495 server,
2496 connection_store,
2497 ext_agent,
2498 resume_session_id,
2499 work_dirs,
2500 title,
2501 initial_content,
2502 workspace.clone(),
2503 project,
2504 thread_store,
2505 self.prompt_store.clone(),
2506 window,
2507 cx,
2508 )
2509 });
2510
2511 cx.observe(&conversation_view, |this, server_view, cx| {
2512 let is_active = this
2513 .active_conversation_view()
2514 .is_some_and(|active| active.entity_id() == server_view.entity_id());
2515 if is_active {
2516 cx.emit(AgentPanelEvent::ActiveViewChanged);
2517 this.serialize(cx);
2518 } else {
2519 cx.emit(AgentPanelEvent::BackgroundThreadChanged);
2520 }
2521 cx.notify();
2522 })
2523 .detach();
2524
2525 self.set_active_view(
2526 ActiveView::AgentThread { conversation_view },
2527 focus,
2528 window,
2529 cx,
2530 );
2531 }
2532
2533 fn active_thread_has_messages(&self, cx: &App) -> bool {
2534 self.active_agent_thread(cx)
2535 .is_some_and(|thread| !thread.read(cx).entries().is_empty())
2536 }
2537
2538 pub fn active_thread_is_draft(&self, cx: &App) -> bool {
2539 self.active_conversation_view().is_some() && !self.active_thread_has_messages(cx)
2540 }
2541
2542 fn handle_first_send_requested(
2543 &mut self,
2544 thread_view: Entity<ThreadView>,
2545 content: Vec<acp::ContentBlock>,
2546 window: &mut Window,
2547 cx: &mut Context<Self>,
2548 ) {
2549 if self.start_thread_in == StartThreadIn::NewWorktree {
2550 self.handle_worktree_creation_requested(content, window, cx);
2551 } else {
2552 cx.defer_in(window, move |_this, window, cx| {
2553 thread_view.update(cx, |thread_view, cx| {
2554 let editor = thread_view.message_editor.clone();
2555 thread_view.send_impl(editor, window, cx);
2556 });
2557 });
2558 }
2559 }
2560
2561 // TODO: The mapping from workspace root paths to git repositories needs a
2562 // unified approach across the codebase: this method, `sidebar::is_root_repo`,
2563 // thread persistence (which PathList is saved to the database), and thread
2564 // querying (which PathList is used to read threads back). All of these need
2565 // to agree on how repos are resolved for a given workspace, especially in
2566 // multi-root and nested-repo configurations.
2567 /// Partitions the project's visible worktrees into git-backed repositories
2568 /// and plain (non-git) paths. Git repos will have worktrees created for
2569 /// them; non-git paths are carried over to the new workspace as-is.
2570 ///
2571 /// When multiple worktrees map to the same repository, the most specific
2572 /// match wins (deepest work directory path), with a deterministic
2573 /// tie-break on entity id. Each repository appears at most once.
2574 fn classify_worktrees(
2575 &self,
2576 cx: &App,
2577 ) -> (Vec<Entity<project::git_store::Repository>>, Vec<PathBuf>) {
2578 let project = &self.project;
2579 let repositories = project.read(cx).repositories(cx).clone();
2580 let mut git_repos: Vec<Entity<project::git_store::Repository>> = Vec::new();
2581 let mut non_git_paths: Vec<PathBuf> = Vec::new();
2582 let mut seen_repo_ids = std::collections::HashSet::new();
2583
2584 for worktree in project.read(cx).visible_worktrees(cx) {
2585 let wt_path = worktree.read(cx).abs_path();
2586
2587 let matching_repo = repositories
2588 .iter()
2589 .filter_map(|(id, repo)| {
2590 let work_dir = repo.read(cx).work_directory_abs_path.clone();
2591 if wt_path.starts_with(work_dir.as_ref())
2592 || work_dir.starts_with(wt_path.as_ref())
2593 {
2594 Some((*id, repo.clone(), work_dir.as_ref().components().count()))
2595 } else {
2596 None
2597 }
2598 })
2599 .max_by(
2600 |(left_id, _left_repo, left_depth), (right_id, _right_repo, right_depth)| {
2601 left_depth
2602 .cmp(right_depth)
2603 .then_with(|| left_id.cmp(right_id))
2604 },
2605 );
2606
2607 if let Some((id, repo, _)) = matching_repo {
2608 if seen_repo_ids.insert(id) {
2609 git_repos.push(repo);
2610 }
2611 } else {
2612 non_git_paths.push(wt_path.to_path_buf());
2613 }
2614 }
2615
2616 (git_repos, non_git_paths)
2617 }
2618
2619 /// Kicks off an async git-worktree creation for each repository. Returns:
2620 ///
2621 /// - `creation_infos`: a vec of `(repo, new_path, receiver)` tuples—the
2622 /// receiver resolves once the git worktree command finishes.
2623 /// - `path_remapping`: `(old_work_dir, new_worktree_path)` pairs used
2624 /// later to remap open editor tabs into the new workspace.
2625 fn start_worktree_creations(
2626 git_repos: &[Entity<project::git_store::Repository>],
2627 branch_name: &str,
2628 worktree_directory_setting: &str,
2629 cx: &mut Context<Self>,
2630 ) -> Result<(
2631 Vec<(
2632 Entity<project::git_store::Repository>,
2633 PathBuf,
2634 futures::channel::oneshot::Receiver<Result<()>>,
2635 )>,
2636 Vec<(PathBuf, PathBuf)>,
2637 )> {
2638 let mut creation_infos = Vec::new();
2639 let mut path_remapping = Vec::new();
2640
2641 for repo in git_repos {
2642 let (work_dir, new_path, receiver) = repo.update(cx, |repo, _cx| {
2643 let new_path =
2644 repo.path_for_new_linked_worktree(branch_name, worktree_directory_setting)?;
2645 let receiver =
2646 repo.create_worktree(branch_name.to_string(), new_path.clone(), None);
2647 let work_dir = repo.work_directory_abs_path.clone();
2648 anyhow::Ok((work_dir, new_path, receiver))
2649 })?;
2650 path_remapping.push((work_dir.to_path_buf(), new_path.clone()));
2651 creation_infos.push((repo.clone(), new_path, receiver));
2652 }
2653
2654 Ok((creation_infos, path_remapping))
2655 }
2656
2657 /// Waits for every in-flight worktree creation to complete. If any
2658 /// creation fails, all successfully-created worktrees are rolled back
2659 /// (removed) so the project isn't left in a half-migrated state.
2660 async fn await_and_rollback_on_failure(
2661 creation_infos: Vec<(
2662 Entity<project::git_store::Repository>,
2663 PathBuf,
2664 futures::channel::oneshot::Receiver<Result<()>>,
2665 )>,
2666 cx: &mut AsyncWindowContext,
2667 ) -> Result<Vec<PathBuf>> {
2668 let mut created_paths: Vec<PathBuf> = Vec::new();
2669 let mut repos_and_paths: Vec<(Entity<project::git_store::Repository>, PathBuf)> =
2670 Vec::new();
2671 let mut first_error: Option<anyhow::Error> = None;
2672
2673 for (repo, new_path, receiver) in creation_infos {
2674 match receiver.await {
2675 Ok(Ok(())) => {
2676 created_paths.push(new_path.clone());
2677 repos_and_paths.push((repo, new_path));
2678 }
2679 Ok(Err(err)) => {
2680 if first_error.is_none() {
2681 first_error = Some(err);
2682 }
2683 }
2684 Err(_canceled) => {
2685 if first_error.is_none() {
2686 first_error = Some(anyhow!("Worktree creation was canceled"));
2687 }
2688 }
2689 }
2690 }
2691
2692 let Some(err) = first_error else {
2693 return Ok(created_paths);
2694 };
2695
2696 // Rollback all successfully created worktrees
2697 let mut rollback_receivers = Vec::new();
2698 for (rollback_repo, rollback_path) in &repos_and_paths {
2699 if let Ok(receiver) = cx.update(|_, cx| {
2700 rollback_repo.update(cx, |repo, _cx| {
2701 repo.remove_worktree(rollback_path.clone(), true)
2702 })
2703 }) {
2704 rollback_receivers.push((rollback_path.clone(), receiver));
2705 }
2706 }
2707 let mut rollback_failures: Vec<String> = Vec::new();
2708 for (path, receiver) in rollback_receivers {
2709 match receiver.await {
2710 Ok(Ok(())) => {}
2711 Ok(Err(rollback_err)) => {
2712 log::error!(
2713 "failed to rollback worktree at {}: {rollback_err}",
2714 path.display()
2715 );
2716 rollback_failures.push(format!("{}: {rollback_err}", path.display()));
2717 }
2718 Err(rollback_err) => {
2719 log::error!(
2720 "failed to rollback worktree at {}: {rollback_err}",
2721 path.display()
2722 );
2723 rollback_failures.push(format!("{}: {rollback_err}", path.display()));
2724 }
2725 }
2726 }
2727 let mut error_message = format!("Failed to create worktree: {err}");
2728 if !rollback_failures.is_empty() {
2729 error_message.push_str("\n\nFailed to clean up: ");
2730 error_message.push_str(&rollback_failures.join(", "));
2731 }
2732 Err(anyhow!(error_message))
2733 }
2734
2735 fn set_worktree_creation_error(
2736 &mut self,
2737 message: SharedString,
2738 window: &mut Window,
2739 cx: &mut Context<Self>,
2740 ) {
2741 self.worktree_creation_status = Some(WorktreeCreationStatus::Error(message));
2742 if matches!(self.active_view, ActiveView::Uninitialized) {
2743 let selected_agent_type = self.selected_agent_type.clone();
2744 self.new_agent_thread(selected_agent_type, window, cx);
2745 }
2746 cx.notify();
2747 }
2748
2749 fn handle_worktree_creation_requested(
2750 &mut self,
2751 content: Vec<acp::ContentBlock>,
2752 window: &mut Window,
2753 cx: &mut Context<Self>,
2754 ) {
2755 if matches!(
2756 self.worktree_creation_status,
2757 Some(WorktreeCreationStatus::Creating)
2758 ) {
2759 return;
2760 }
2761
2762 self.worktree_creation_status = Some(WorktreeCreationStatus::Creating);
2763 cx.notify();
2764
2765 let (git_repos, non_git_paths) = self.classify_worktrees(cx);
2766
2767 if git_repos.is_empty() {
2768 self.set_worktree_creation_error(
2769 "No git repositories found in the project".into(),
2770 window,
2771 cx,
2772 );
2773 return;
2774 }
2775
2776 // Kick off branch listing as early as possible so it can run
2777 // concurrently with the remaining synchronous setup work.
2778 let branch_receivers: Vec<_> = git_repos
2779 .iter()
2780 .map(|repo| repo.update(cx, |repo, _cx| repo.branches()))
2781 .collect();
2782
2783 let worktree_directory_setting = ProjectSettings::get_global(cx)
2784 .git
2785 .worktree_directory
2786 .clone();
2787
2788 let active_file_path = self.workspace.upgrade().and_then(|workspace| {
2789 let workspace = workspace.read(cx);
2790 let active_item = workspace.active_item(cx)?;
2791 let project_path = active_item.project_path(cx)?;
2792 workspace
2793 .project()
2794 .read(cx)
2795 .absolute_path(&project_path, cx)
2796 });
2797
2798 let workspace = self.workspace.clone();
2799 let window_handle = window
2800 .window_handle()
2801 .downcast::<workspace::MultiWorkspace>();
2802
2803 let selected_agent = self.selected_agent();
2804
2805 let task = cx.spawn_in(window, async move |this, cx| {
2806 // Await the branch listings we kicked off earlier.
2807 let mut existing_branches = Vec::new();
2808 for result in futures::future::join_all(branch_receivers).await {
2809 match result {
2810 Ok(Ok(branches)) => {
2811 for branch in branches {
2812 existing_branches.push(branch.name().to_string());
2813 }
2814 }
2815 Ok(Err(err)) => {
2816 Err::<(), _>(err).log_err();
2817 }
2818 Err(_) => {}
2819 }
2820 }
2821
2822 let existing_branch_refs: Vec<&str> =
2823 existing_branches.iter().map(|s| s.as_str()).collect();
2824 let mut rng = rand::rng();
2825 let branch_name =
2826 match crate::branch_names::generate_branch_name(&existing_branch_refs, &mut rng) {
2827 Some(name) => name,
2828 None => {
2829 this.update_in(cx, |this, window, cx| {
2830 this.set_worktree_creation_error(
2831 "Failed to generate a unique branch name".into(),
2832 window,
2833 cx,
2834 );
2835 })?;
2836 return anyhow::Ok(());
2837 }
2838 };
2839
2840 let (creation_infos, path_remapping) = match this.update_in(cx, |_this, _window, cx| {
2841 Self::start_worktree_creations(
2842 &git_repos,
2843 &branch_name,
2844 &worktree_directory_setting,
2845 cx,
2846 )
2847 }) {
2848 Ok(Ok(result)) => result,
2849 Ok(Err(err)) | Err(err) => {
2850 this.update_in(cx, |this, window, cx| {
2851 this.set_worktree_creation_error(
2852 format!("Failed to validate worktree directory: {err}").into(),
2853 window,
2854 cx,
2855 );
2856 })
2857 .log_err();
2858 return anyhow::Ok(());
2859 }
2860 };
2861
2862 let created_paths = match Self::await_and_rollback_on_failure(creation_infos, cx).await
2863 {
2864 Ok(paths) => paths,
2865 Err(err) => {
2866 this.update_in(cx, |this, window, cx| {
2867 this.set_worktree_creation_error(format!("{err}").into(), window, cx);
2868 })?;
2869 return anyhow::Ok(());
2870 }
2871 };
2872
2873 let mut all_paths = created_paths;
2874 let has_non_git = !non_git_paths.is_empty();
2875 all_paths.extend(non_git_paths.iter().cloned());
2876
2877 let app_state = match workspace.upgrade() {
2878 Some(workspace) => cx.update(|_, cx| workspace.read(cx).app_state().clone())?,
2879 None => {
2880 this.update_in(cx, |this, window, cx| {
2881 this.set_worktree_creation_error(
2882 "Workspace no longer available".into(),
2883 window,
2884 cx,
2885 );
2886 })?;
2887 return anyhow::Ok(());
2888 }
2889 };
2890
2891 let this_for_error = this.clone();
2892 if let Err(err) = Self::setup_new_workspace(
2893 this,
2894 all_paths,
2895 app_state,
2896 window_handle,
2897 active_file_path,
2898 path_remapping,
2899 non_git_paths,
2900 has_non_git,
2901 content,
2902 selected_agent,
2903 cx,
2904 )
2905 .await
2906 {
2907 this_for_error
2908 .update_in(cx, |this, window, cx| {
2909 this.set_worktree_creation_error(
2910 format!("Failed to set up workspace: {err}").into(),
2911 window,
2912 cx,
2913 );
2914 })
2915 .log_err();
2916 }
2917 anyhow::Ok(())
2918 });
2919
2920 self._worktree_creation_task = Some(cx.foreground_executor().spawn(async move {
2921 task.await.log_err();
2922 }));
2923 }
2924
2925 async fn setup_new_workspace(
2926 this: WeakEntity<Self>,
2927 all_paths: Vec<PathBuf>,
2928 app_state: Arc<workspace::AppState>,
2929 window_handle: Option<gpui::WindowHandle<workspace::MultiWorkspace>>,
2930 active_file_path: Option<PathBuf>,
2931 path_remapping: Vec<(PathBuf, PathBuf)>,
2932 non_git_paths: Vec<PathBuf>,
2933 has_non_git: bool,
2934 content: Vec<acp::ContentBlock>,
2935 selected_agent: Option<Agent>,
2936 cx: &mut AsyncWindowContext,
2937 ) -> Result<()> {
2938 let OpenResult {
2939 window: new_window_handle,
2940 workspace: new_workspace,
2941 ..
2942 } = cx
2943 .update(|_window, cx| {
2944 Workspace::new_local(all_paths, app_state, window_handle, None, None, false, cx)
2945 })?
2946 .await?;
2947
2948 let panels_task = new_window_handle.update(cx, |_, _, cx| {
2949 new_workspace.update(cx, |workspace, _cx| workspace.take_panels_task())
2950 })?;
2951 if let Some(task) = panels_task {
2952 task.await.log_err();
2953 }
2954
2955 let initial_content = AgentInitialContent::ContentBlock {
2956 blocks: content,
2957 auto_submit: true,
2958 };
2959
2960 new_window_handle.update(cx, |_multi_workspace, window, cx| {
2961 new_workspace.update(cx, |workspace, cx| {
2962 if has_non_git {
2963 let toast_id = workspace::notifications::NotificationId::unique::<AgentPanel>();
2964 workspace.show_toast(
2965 workspace::Toast::new(
2966 toast_id,
2967 "Some project folders are not git repositories. \
2968 They were included as-is without creating a worktree.",
2969 ),
2970 cx,
2971 );
2972 }
2973
2974 // If we had an active buffer, remap its path and reopen it.
2975 let should_zoom_agent_panel = active_file_path.is_none();
2976
2977 let remapped_active_path = active_file_path.and_then(|original_path| {
2978 let best_match = path_remapping
2979 .iter()
2980 .filter_map(|(old_root, new_root)| {
2981 original_path.strip_prefix(old_root).ok().map(|relative| {
2982 (old_root.components().count(), new_root.join(relative))
2983 })
2984 })
2985 .max_by_key(|(depth, _)| *depth);
2986
2987 if let Some((_, remapped_path)) = best_match {
2988 return Some(remapped_path);
2989 }
2990
2991 for non_git in &non_git_paths {
2992 if original_path.starts_with(non_git) {
2993 return Some(original_path);
2994 }
2995 }
2996 None
2997 });
2998
2999 if !should_zoom_agent_panel && remapped_active_path.is_none() {
3000 log::warn!(
3001 "Active file could not be remapped to the new worktree; it will not be reopened"
3002 );
3003 }
3004
3005 if let Some(path) = remapped_active_path {
3006 let open_task = workspace.open_paths(
3007 vec![path],
3008 workspace::OpenOptions::default(),
3009 None,
3010 window,
3011 cx,
3012 );
3013 cx.spawn(async move |_, _| -> anyhow::Result<()> {
3014 for item in open_task.await.into_iter().flatten() {
3015 item?;
3016 }
3017 Ok(())
3018 })
3019 .detach_and_log_err(cx);
3020 }
3021
3022 workspace.focus_panel::<AgentPanel>(window, cx);
3023
3024 // If no active buffer was open, zoom the agent panel
3025 // (equivalent to cmd-esc fullscreen behavior).
3026 // This must happen after focus_panel, which activates
3027 // and opens the panel in the dock.
3028 if should_zoom_agent_panel {
3029 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3030 panel.update(cx, |_panel, cx| {
3031 cx.emit(PanelEvent::ZoomIn);
3032 });
3033 }
3034 }
3035 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3036 panel.update(cx, |panel, cx| {
3037 panel.external_thread(
3038 selected_agent,
3039 None,
3040 None,
3041 None,
3042 Some(initial_content),
3043 true,
3044 window,
3045 cx,
3046 );
3047 });
3048 }
3049 });
3050 })?;
3051
3052 new_window_handle.update(cx, |multi_workspace, _window, cx| {
3053 multi_workspace.activate(new_workspace.clone(), cx);
3054 })?;
3055
3056 this.update_in(cx, |this, window, cx| {
3057 this.worktree_creation_status = None;
3058
3059 if let Some(thread_view) = this.active_thread_view(cx) {
3060 thread_view.update(cx, |thread_view, cx| {
3061 thread_view
3062 .message_editor
3063 .update(cx, |editor, cx| editor.clear(window, cx));
3064 });
3065 }
3066
3067 cx.notify();
3068 })?;
3069
3070 anyhow::Ok(())
3071 }
3072}
3073
3074impl Focusable for AgentPanel {
3075 fn focus_handle(&self, cx: &App) -> FocusHandle {
3076 match &self.active_view {
3077 ActiveView::Uninitialized => self.focus_handle.clone(),
3078 ActiveView::AgentThread {
3079 conversation_view, ..
3080 } => conversation_view.focus_handle(cx),
3081 ActiveView::History { history: kind } => match kind {
3082 History::AgentThreads { view } => view.read(cx).focus_handle(cx),
3083 History::TextThreads => self.text_thread_history.focus_handle(cx),
3084 },
3085 ActiveView::TextThread {
3086 text_thread_editor, ..
3087 } => text_thread_editor.focus_handle(cx),
3088 ActiveView::Configuration => {
3089 if let Some(configuration) = self.configuration.as_ref() {
3090 configuration.focus_handle(cx)
3091 } else {
3092 self.focus_handle.clone()
3093 }
3094 }
3095 }
3096 }
3097}
3098
3099fn agent_panel_dock_position(cx: &App) -> DockPosition {
3100 AgentSettings::get_global(cx).dock.into()
3101}
3102
3103pub enum AgentPanelEvent {
3104 ActiveViewChanged,
3105 ThreadFocused,
3106 BackgroundThreadChanged,
3107}
3108
3109impl EventEmitter<PanelEvent> for AgentPanel {}
3110impl EventEmitter<AgentPanelEvent> for AgentPanel {}
3111
3112impl Panel for AgentPanel {
3113 fn persistent_name() -> &'static str {
3114 "AgentPanel"
3115 }
3116
3117 fn panel_key() -> &'static str {
3118 AGENT_PANEL_KEY
3119 }
3120
3121 fn position(&self, _window: &Window, cx: &App) -> DockPosition {
3122 agent_panel_dock_position(cx)
3123 }
3124
3125 fn position_is_valid(&self, position: DockPosition) -> bool {
3126 position != DockPosition::Bottom
3127 }
3128
3129 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3130 settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
3131 settings
3132 .agent
3133 .get_or_insert_default()
3134 .set_dock(position.into());
3135 });
3136 }
3137
3138 fn size(&self, window: &Window, cx: &App) -> Pixels {
3139 let settings = AgentSettings::get_global(cx);
3140 match self.position(window, cx) {
3141 DockPosition::Left | DockPosition::Right => {
3142 self.width.unwrap_or(settings.default_width)
3143 }
3144 DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
3145 }
3146 }
3147
3148 fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
3149 match self.position(window, cx) {
3150 DockPosition::Left | DockPosition::Right => self.width = size,
3151 DockPosition::Bottom => self.height = size,
3152 }
3153 self.serialize(cx);
3154 cx.notify();
3155 }
3156
3157 fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
3158 if active
3159 && matches!(self.active_view, ActiveView::Uninitialized)
3160 && !matches!(
3161 self.worktree_creation_status,
3162 Some(WorktreeCreationStatus::Creating)
3163 )
3164 {
3165 let selected_agent_type = self.selected_agent_type.clone();
3166 self.new_agent_thread_inner(selected_agent_type, false, window, cx);
3167 }
3168 }
3169
3170 fn remote_id() -> Option<proto::PanelId> {
3171 Some(proto::PanelId::AssistantPanel)
3172 }
3173
3174 fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
3175 (self.enabled(cx) && AgentSettings::get_global(cx).button).then_some(IconName::ZedAssistant)
3176 }
3177
3178 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3179 Some("Agent Panel")
3180 }
3181
3182 fn toggle_action(&self) -> Box<dyn Action> {
3183 Box::new(ToggleFocus)
3184 }
3185
3186 fn activation_priority(&self) -> u32 {
3187 3
3188 }
3189
3190 fn enabled(&self, cx: &App) -> bool {
3191 AgentSettings::get_global(cx).enabled(cx)
3192 }
3193
3194 fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
3195 self.zoomed
3196 }
3197
3198 fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, cx: &mut Context<Self>) {
3199 self.zoomed = zoomed;
3200 cx.notify();
3201 }
3202}
3203
3204impl AgentPanel {
3205 fn render_title_view(&self, _window: &mut Window, cx: &Context<Self>) -> AnyElement {
3206 const LOADING_SUMMARY_PLACEHOLDER: &str = "Loading Summary…";
3207
3208 let content = match &self.active_view {
3209 ActiveView::AgentThread { conversation_view } => {
3210 let server_view_ref = conversation_view.read(cx);
3211 let is_generating_title = server_view_ref.as_native_thread(cx).is_some()
3212 && server_view_ref.root_thread(cx).map_or(false, |tv| {
3213 tv.read(cx).thread.read(cx).has_provisional_title()
3214 });
3215
3216 if let Some(title_editor) = server_view_ref
3217 .root_thread(cx)
3218 .map(|r| r.read(cx).title_editor.clone())
3219 {
3220 if is_generating_title {
3221 Label::new(DEFAULT_THREAD_TITLE)
3222 .color(Color::Muted)
3223 .truncate()
3224 .with_animation(
3225 "generating_title",
3226 Animation::new(Duration::from_secs(2))
3227 .repeat()
3228 .with_easing(pulsating_between(0.4, 0.8)),
3229 |label, delta| label.alpha(delta),
3230 )
3231 .into_any_element()
3232 } else {
3233 div()
3234 .w_full()
3235 .on_action({
3236 let conversation_view = conversation_view.downgrade();
3237 move |_: &menu::Confirm, window, cx| {
3238 if let Some(conversation_view) = conversation_view.upgrade() {
3239 conversation_view.focus_handle(cx).focus(window, cx);
3240 }
3241 }
3242 })
3243 .on_action({
3244 let conversation_view = conversation_view.downgrade();
3245 move |_: &editor::actions::Cancel, window, cx| {
3246 if let Some(conversation_view) = conversation_view.upgrade() {
3247 conversation_view.focus_handle(cx).focus(window, cx);
3248 }
3249 }
3250 })
3251 .child(title_editor)
3252 .into_any_element()
3253 }
3254 } else {
3255 Label::new(conversation_view.read(cx).title(cx))
3256 .color(Color::Muted)
3257 .truncate()
3258 .into_any_element()
3259 }
3260 }
3261 ActiveView::TextThread {
3262 title_editor,
3263 text_thread_editor,
3264 ..
3265 } => {
3266 let summary = text_thread_editor.read(cx).text_thread().read(cx).summary();
3267
3268 match summary {
3269 TextThreadSummary::Pending => Label::new(TextThreadSummary::DEFAULT)
3270 .color(Color::Muted)
3271 .truncate()
3272 .into_any_element(),
3273 TextThreadSummary::Content(summary) => {
3274 if summary.done {
3275 div()
3276 .w_full()
3277 .child(title_editor.clone())
3278 .into_any_element()
3279 } else {
3280 Label::new(LOADING_SUMMARY_PLACEHOLDER)
3281 .truncate()
3282 .color(Color::Muted)
3283 .with_animation(
3284 "generating_title",
3285 Animation::new(Duration::from_secs(2))
3286 .repeat()
3287 .with_easing(pulsating_between(0.4, 0.8)),
3288 |label, delta| label.alpha(delta),
3289 )
3290 .into_any_element()
3291 }
3292 }
3293 TextThreadSummary::Error => h_flex()
3294 .w_full()
3295 .child(title_editor.clone())
3296 .child(
3297 IconButton::new("retry-summary-generation", IconName::RotateCcw)
3298 .icon_size(IconSize::Small)
3299 .on_click({
3300 let text_thread_editor = text_thread_editor.clone();
3301 move |_, _window, cx| {
3302 text_thread_editor.update(cx, |text_thread_editor, cx| {
3303 text_thread_editor.regenerate_summary(cx);
3304 });
3305 }
3306 })
3307 .tooltip(move |_window, cx| {
3308 cx.new(|_| {
3309 Tooltip::new("Failed to generate title")
3310 .meta("Click to try again")
3311 })
3312 .into()
3313 }),
3314 )
3315 .into_any_element(),
3316 }
3317 }
3318 ActiveView::History { history: kind } => {
3319 let title = match kind {
3320 History::AgentThreads { .. } => "History",
3321 History::TextThreads => "Text Thread History",
3322 };
3323 Label::new(title).truncate().into_any_element()
3324 }
3325 ActiveView::Configuration => Label::new("Settings").truncate().into_any_element(),
3326 ActiveView::Uninitialized => Label::new("Agent").truncate().into_any_element(),
3327 };
3328
3329 h_flex()
3330 .key_context("TitleEditor")
3331 .id("TitleEditor")
3332 .flex_grow()
3333 .w_full()
3334 .max_w_full()
3335 .overflow_x_scroll()
3336 .child(content)
3337 .into_any()
3338 }
3339
3340 fn handle_regenerate_thread_title(conversation_view: Entity<ConversationView>, cx: &mut App) {
3341 conversation_view.update(cx, |conversation_view, cx| {
3342 if let Some(thread) = conversation_view.as_native_thread(cx) {
3343 thread.update(cx, |thread, cx| {
3344 thread.generate_title(cx);
3345 });
3346 }
3347 });
3348 }
3349
3350 fn handle_regenerate_text_thread_title(
3351 text_thread_editor: Entity<TextThreadEditor>,
3352 cx: &mut App,
3353 ) {
3354 text_thread_editor.update(cx, |text_thread_editor, cx| {
3355 text_thread_editor.regenerate_summary(cx);
3356 });
3357 }
3358
3359 fn render_panel_options_menu(
3360 &self,
3361 window: &mut Window,
3362 cx: &mut Context<Self>,
3363 ) -> impl IntoElement {
3364 let focus_handle = self.focus_handle(cx);
3365
3366 let full_screen_label = if self.is_zoomed(window, cx) {
3367 "Disable Full Screen"
3368 } else {
3369 "Enable Full Screen"
3370 };
3371
3372 let text_thread_view = match &self.active_view {
3373 ActiveView::TextThread {
3374 text_thread_editor, ..
3375 } => Some(text_thread_editor.clone()),
3376 _ => None,
3377 };
3378 let text_thread_with_messages = match &self.active_view {
3379 ActiveView::TextThread {
3380 text_thread_editor, ..
3381 } => text_thread_editor
3382 .read(cx)
3383 .text_thread()
3384 .read(cx)
3385 .messages(cx)
3386 .any(|message| message.role == language_model::Role::Assistant),
3387 _ => false,
3388 };
3389
3390 let conversation_view = match &self.active_view {
3391 ActiveView::AgentThread { conversation_view } => Some(conversation_view.clone()),
3392 _ => None,
3393 };
3394 let thread_with_messages = match &self.active_view {
3395 ActiveView::AgentThread { conversation_view } => {
3396 conversation_view.read(cx).has_user_submitted_prompt(cx)
3397 }
3398 _ => false,
3399 };
3400 let has_auth_methods = match &self.active_view {
3401 ActiveView::AgentThread { conversation_view } => {
3402 conversation_view.read(cx).has_auth_methods()
3403 }
3404 _ => false,
3405 };
3406
3407 PopoverMenu::new("agent-options-menu")
3408 .trigger_with_tooltip(
3409 IconButton::new("agent-options-menu", IconName::Ellipsis)
3410 .icon_size(IconSize::Small),
3411 {
3412 let focus_handle = focus_handle.clone();
3413 move |_window, cx| {
3414 Tooltip::for_action_in(
3415 "Toggle Agent Menu",
3416 &ToggleOptionsMenu,
3417 &focus_handle,
3418 cx,
3419 )
3420 }
3421 },
3422 )
3423 .anchor(Corner::TopRight)
3424 .with_handle(self.agent_panel_menu_handle.clone())
3425 .menu({
3426 move |window, cx| {
3427 Some(ContextMenu::build(window, cx, |mut menu, _window, _| {
3428 menu = menu.context(focus_handle.clone());
3429
3430 if thread_with_messages | text_thread_with_messages {
3431 menu = menu.header("Current Thread");
3432
3433 if let Some(text_thread_view) = text_thread_view.as_ref() {
3434 menu = menu
3435 .entry("Regenerate Thread Title", None, {
3436 let text_thread_view = text_thread_view.clone();
3437 move |_, cx| {
3438 Self::handle_regenerate_text_thread_title(
3439 text_thread_view.clone(),
3440 cx,
3441 );
3442 }
3443 })
3444 .separator();
3445 }
3446
3447 if let Some(conversation_view) = conversation_view.as_ref() {
3448 menu = menu
3449 .entry("Regenerate Thread Title", None, {
3450 let conversation_view = conversation_view.clone();
3451 move |_, cx| {
3452 Self::handle_regenerate_thread_title(
3453 conversation_view.clone(),
3454 cx,
3455 );
3456 }
3457 })
3458 .separator();
3459 }
3460 }
3461
3462 menu = menu
3463 .header("MCP Servers")
3464 .action(
3465 "View Server Extensions",
3466 Box::new(zed_actions::Extensions {
3467 category_filter: Some(
3468 zed_actions::ExtensionCategoryFilter::ContextServers,
3469 ),
3470 id: None,
3471 }),
3472 )
3473 .action("Add Custom Server…", Box::new(AddContextServer))
3474 .separator()
3475 .action("Rules", Box::new(OpenRulesLibrary::default()))
3476 .action("Profiles", Box::new(ManageProfiles::default()))
3477 .action("Settings", Box::new(OpenSettings))
3478 .separator()
3479 .action("Toggle Threads Sidebar", Box::new(ToggleWorkspaceSidebar))
3480 .action(full_screen_label, Box::new(ToggleZoom));
3481
3482 if has_auth_methods {
3483 menu = menu.action("Reauthenticate", Box::new(ReauthenticateAgent))
3484 }
3485
3486 menu
3487 }))
3488 }
3489 })
3490 }
3491
3492 fn render_recent_entries_menu(
3493 &self,
3494 icon: IconName,
3495 corner: Corner,
3496 cx: &mut Context<Self>,
3497 ) -> impl IntoElement {
3498 let focus_handle = self.focus_handle(cx);
3499
3500 PopoverMenu::new("agent-nav-menu")
3501 .trigger_with_tooltip(
3502 IconButton::new("agent-nav-menu", icon).icon_size(IconSize::Small),
3503 {
3504 move |_window, cx| {
3505 Tooltip::for_action_in(
3506 "Toggle Recently Updated Threads",
3507 &ToggleNavigationMenu,
3508 &focus_handle,
3509 cx,
3510 )
3511 }
3512 },
3513 )
3514 .anchor(corner)
3515 .with_handle(self.agent_navigation_menu_handle.clone())
3516 .menu({
3517 let menu = self.agent_navigation_menu.clone();
3518 move |window, cx| {
3519 telemetry::event!("View Thread History Clicked");
3520
3521 if let Some(menu) = menu.as_ref() {
3522 menu.update(cx, |_, cx| {
3523 cx.defer_in(window, |menu, window, cx| {
3524 menu.rebuild(window, cx);
3525 });
3526 })
3527 }
3528 menu.clone()
3529 }
3530 })
3531 }
3532
3533 fn render_toolbar_back_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3534 let focus_handle = self.focus_handle(cx);
3535
3536 IconButton::new("go-back", IconName::ArrowLeft)
3537 .icon_size(IconSize::Small)
3538 .on_click(cx.listener(|this, _, window, cx| {
3539 this.go_back(&workspace::GoBack, window, cx);
3540 }))
3541 .tooltip({
3542 move |_window, cx| {
3543 Tooltip::for_action_in("Go Back", &workspace::GoBack, &focus_handle, cx)
3544 }
3545 })
3546 }
3547
3548 fn project_has_git_repository(&self, cx: &App) -> bool {
3549 !self.project.read(cx).repositories(cx).is_empty()
3550 }
3551
3552 fn render_start_thread_in_selector(&self, cx: &mut Context<Self>) -> impl IntoElement {
3553 use settings::{NewThreadLocation, Settings};
3554
3555 let focus_handle = self.focus_handle(cx);
3556 let has_git_repo = self.project_has_git_repository(cx);
3557 let is_via_collab = self.project.read(cx).is_via_collab();
3558 let fs = self.fs.clone();
3559
3560 let is_creating = matches!(
3561 self.worktree_creation_status,
3562 Some(WorktreeCreationStatus::Creating)
3563 );
3564
3565 let current_target = self.start_thread_in;
3566 let trigger_label = self.start_thread_in.label();
3567
3568 let new_thread_location = AgentSettings::get_global(cx).new_thread_location;
3569 let is_local_default = new_thread_location == NewThreadLocation::LocalProject;
3570 let is_new_worktree_default = new_thread_location == NewThreadLocation::NewWorktree;
3571
3572 let icon = if self.start_thread_in_menu_handle.is_deployed() {
3573 IconName::ChevronUp
3574 } else {
3575 IconName::ChevronDown
3576 };
3577
3578 let trigger_button = Button::new("thread-target-trigger", trigger_label)
3579 .end_icon(Icon::new(icon).size(IconSize::XSmall).color(Color::Muted))
3580 .disabled(is_creating);
3581
3582 let dock_position = AgentSettings::get_global(cx).dock;
3583 let documentation_side = match dock_position {
3584 settings::DockPosition::Left => DocumentationSide::Right,
3585 settings::DockPosition::Bottom | settings::DockPosition::Right => {
3586 DocumentationSide::Left
3587 }
3588 };
3589
3590 PopoverMenu::new("thread-target-selector")
3591 .trigger_with_tooltip(trigger_button, {
3592 move |_window, cx| {
3593 Tooltip::for_action_in(
3594 "Start Thread In…",
3595 &CycleStartThreadIn,
3596 &focus_handle,
3597 cx,
3598 )
3599 }
3600 })
3601 .menu(move |window, cx| {
3602 let is_local_selected = current_target == StartThreadIn::LocalProject;
3603 let is_new_worktree_selected = current_target == StartThreadIn::NewWorktree;
3604 let fs = fs.clone();
3605
3606 Some(ContextMenu::build(window, cx, move |menu, _window, _cx| {
3607 let new_worktree_disabled = !has_git_repo || is_via_collab;
3608
3609 menu.header("Start Thread In…")
3610 .item(
3611 ContextMenuEntry::new("Current Worktree")
3612 .toggleable(IconPosition::End, is_local_selected)
3613 .documentation_aside(documentation_side, move |_| {
3614 HoldForDefault::new(is_local_default)
3615 .more_content(false)
3616 .into_any_element()
3617 })
3618 .handler({
3619 let fs = fs.clone();
3620 move |window, cx| {
3621 if window.modifiers().secondary() {
3622 update_settings_file(fs.clone(), cx, |settings, _| {
3623 settings
3624 .agent
3625 .get_or_insert_default()
3626 .set_new_thread_location(
3627 NewThreadLocation::LocalProject,
3628 );
3629 });
3630 }
3631 window.dispatch_action(
3632 Box::new(StartThreadIn::LocalProject),
3633 cx,
3634 );
3635 }
3636 }),
3637 )
3638 .item({
3639 let entry = ContextMenuEntry::new("New Git Worktree")
3640 .toggleable(IconPosition::End, is_new_worktree_selected)
3641 .disabled(new_worktree_disabled)
3642 .handler({
3643 let fs = fs.clone();
3644 move |window, cx| {
3645 if window.modifiers().secondary() {
3646 update_settings_file(fs.clone(), cx, |settings, _| {
3647 settings
3648 .agent
3649 .get_or_insert_default()
3650 .set_new_thread_location(
3651 NewThreadLocation::NewWorktree,
3652 );
3653 });
3654 }
3655 window.dispatch_action(
3656 Box::new(StartThreadIn::NewWorktree),
3657 cx,
3658 );
3659 }
3660 });
3661
3662 if new_worktree_disabled {
3663 entry.documentation_aside(documentation_side, move |_| {
3664 let reason = if !has_git_repo {
3665 "No git repository found in this project."
3666 } else {
3667 "Not available for remote/collab projects yet."
3668 };
3669 Label::new(reason)
3670 .color(Color::Muted)
3671 .size(LabelSize::Small)
3672 .into_any_element()
3673 })
3674 } else {
3675 entry.documentation_aside(documentation_side, move |_| {
3676 HoldForDefault::new(is_new_worktree_default)
3677 .more_content(false)
3678 .into_any_element()
3679 })
3680 }
3681 })
3682 }))
3683 })
3684 .with_handle(self.start_thread_in_menu_handle.clone())
3685 .anchor(Corner::TopLeft)
3686 .offset(gpui::Point {
3687 x: px(1.0),
3688 y: px(1.0),
3689 })
3690 }
3691
3692 fn render_toolbar(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3693 let agent_server_store = self.project.read(cx).agent_server_store().clone();
3694 let has_visible_worktrees = self.project.read(cx).visible_worktrees(cx).next().is_some();
3695 let focus_handle = self.focus_handle(cx);
3696
3697 let (selected_agent_custom_icon, selected_agent_label) =
3698 if let AgentType::Custom { id, .. } = &self.selected_agent_type {
3699 let store = agent_server_store.read(cx);
3700 let icon = store.agent_icon(&id);
3701
3702 let label = store
3703 .agent_display_name(&id)
3704 .unwrap_or_else(|| self.selected_agent_type.label());
3705 (icon, label)
3706 } else {
3707 (None, self.selected_agent_type.label())
3708 };
3709
3710 let active_thread = match &self.active_view {
3711 ActiveView::AgentThread { conversation_view } => {
3712 conversation_view.read(cx).as_native_thread(cx)
3713 }
3714 ActiveView::Uninitialized
3715 | ActiveView::TextThread { .. }
3716 | ActiveView::History { .. }
3717 | ActiveView::Configuration => None,
3718 };
3719
3720 let new_thread_menu_builder: Rc<
3721 dyn Fn(&mut Window, &mut App) -> Option<Entity<ContextMenu>>,
3722 > = {
3723 let selected_agent = self.selected_agent_type.clone();
3724 let is_agent_selected = move |agent_type: AgentType| selected_agent == agent_type;
3725
3726 let workspace = self.workspace.clone();
3727 let is_via_collab = workspace
3728 .update(cx, |workspace, cx| {
3729 workspace.project().read(cx).is_via_collab()
3730 })
3731 .unwrap_or_default();
3732
3733 let focus_handle = focus_handle.clone();
3734 let agent_server_store = agent_server_store;
3735
3736 Rc::new(move |window, cx| {
3737 telemetry::event!("New Thread Clicked");
3738
3739 let active_thread = active_thread.clone();
3740 Some(ContextMenu::build(window, cx, |menu, _window, cx| {
3741 menu.context(focus_handle.clone())
3742 .when_some(active_thread, |this, active_thread| {
3743 let thread = active_thread.read(cx);
3744
3745 if !thread.is_empty() {
3746 let session_id = thread.id().clone();
3747 this.item(
3748 ContextMenuEntry::new("New From Summary")
3749 .icon(IconName::ThreadFromSummary)
3750 .icon_color(Color::Muted)
3751 .handler(move |window, cx| {
3752 window.dispatch_action(
3753 Box::new(NewNativeAgentThreadFromSummary {
3754 from_session_id: session_id.clone(),
3755 }),
3756 cx,
3757 );
3758 }),
3759 )
3760 } else {
3761 this
3762 }
3763 })
3764 .item(
3765 ContextMenuEntry::new("Zed Agent")
3766 .when(
3767 is_agent_selected(AgentType::NativeAgent)
3768 | is_agent_selected(AgentType::TextThread),
3769 |this| {
3770 this.action(Box::new(NewExternalAgentThread {
3771 agent: None,
3772 }))
3773 },
3774 )
3775 .icon(IconName::ZedAgent)
3776 .icon_color(Color::Muted)
3777 .handler({
3778 let workspace = workspace.clone();
3779 move |window, cx| {
3780 if let Some(workspace) = workspace.upgrade() {
3781 workspace.update(cx, |workspace, cx| {
3782 if let Some(panel) =
3783 workspace.panel::<AgentPanel>(cx)
3784 {
3785 panel.update(cx, |panel, cx| {
3786 panel.new_agent_thread(
3787 AgentType::NativeAgent,
3788 window,
3789 cx,
3790 );
3791 });
3792 }
3793 });
3794 }
3795 }
3796 }),
3797 )
3798 .item(
3799 ContextMenuEntry::new("Text Thread")
3800 .action(NewTextThread.boxed_clone())
3801 .icon(IconName::TextThread)
3802 .icon_color(Color::Muted)
3803 .handler({
3804 let workspace = workspace.clone();
3805 move |window, cx| {
3806 if let Some(workspace) = workspace.upgrade() {
3807 workspace.update(cx, |workspace, cx| {
3808 if let Some(panel) =
3809 workspace.panel::<AgentPanel>(cx)
3810 {
3811 panel.update(cx, |panel, cx| {
3812 panel.new_agent_thread(
3813 AgentType::TextThread,
3814 window,
3815 cx,
3816 );
3817 });
3818 }
3819 });
3820 }
3821 }
3822 }),
3823 )
3824 .separator()
3825 .header("External Agents")
3826 .map(|mut menu| {
3827 let agent_server_store = agent_server_store.read(cx);
3828 let registry_store = project::AgentRegistryStore::try_global(cx);
3829 let registry_store_ref = registry_store.as_ref().map(|s| s.read(cx));
3830
3831 struct AgentMenuItem {
3832 id: AgentId,
3833 display_name: SharedString,
3834 }
3835
3836 let agent_items = agent_server_store
3837 .external_agents()
3838 .map(|agent_id| {
3839 let display_name = agent_server_store
3840 .agent_display_name(agent_id)
3841 .or_else(|| {
3842 registry_store_ref
3843 .as_ref()
3844 .and_then(|store| store.agent(agent_id))
3845 .map(|a| a.name().clone())
3846 })
3847 .unwrap_or_else(|| agent_id.0.clone());
3848 AgentMenuItem {
3849 id: agent_id.clone(),
3850 display_name,
3851 }
3852 })
3853 .sorted_unstable_by_key(|e| e.display_name.to_lowercase())
3854 .collect::<Vec<_>>();
3855
3856 for item in &agent_items {
3857 let mut entry = ContextMenuEntry::new(item.display_name.clone());
3858
3859 let icon_path =
3860 agent_server_store.agent_icon(&item.id).or_else(|| {
3861 registry_store_ref
3862 .as_ref()
3863 .and_then(|store| store.agent(&item.id))
3864 .and_then(|a| a.icon_path().cloned())
3865 });
3866
3867 if let Some(icon_path) = icon_path {
3868 entry = entry.custom_icon_svg(icon_path);
3869 } else {
3870 entry = entry.icon(IconName::Sparkle);
3871 }
3872
3873 entry = entry
3874 .when(
3875 is_agent_selected(AgentType::Custom {
3876 id: item.id.clone(),
3877 }),
3878 |this| {
3879 this.action(Box::new(NewExternalAgentThread {
3880 agent: None,
3881 }))
3882 },
3883 )
3884 .icon_color(Color::Muted)
3885 .disabled(is_via_collab)
3886 .handler({
3887 let workspace = workspace.clone();
3888 let agent_id = item.id.clone();
3889 move |window, cx| {
3890 if let Some(workspace) = workspace.upgrade() {
3891 workspace.update(cx, |workspace, cx| {
3892 if let Some(panel) =
3893 workspace.panel::<AgentPanel>(cx)
3894 {
3895 panel.update(cx, |panel, cx| {
3896 panel.new_agent_thread(
3897 AgentType::Custom {
3898 id: agent_id.clone(),
3899 },
3900 window,
3901 cx,
3902 );
3903 });
3904 }
3905 });
3906 }
3907 }
3908 });
3909
3910 menu = menu.item(entry);
3911 }
3912
3913 menu
3914 })
3915 .separator()
3916 .item(
3917 ContextMenuEntry::new("Add More Agents")
3918 .icon(IconName::Plus)
3919 .icon_color(Color::Muted)
3920 .handler({
3921 move |window, cx| {
3922 window
3923 .dispatch_action(Box::new(zed_actions::AcpRegistry), cx)
3924 }
3925 }),
3926 )
3927 }))
3928 })
3929 };
3930
3931 let is_thread_loading = self
3932 .active_conversation_view()
3933 .map(|thread| thread.read(cx).is_loading())
3934 .unwrap_or(false);
3935
3936 let has_custom_icon = selected_agent_custom_icon.is_some();
3937 let selected_agent_custom_icon_for_button = selected_agent_custom_icon.clone();
3938 let selected_agent_builtin_icon = self.selected_agent_type.icon();
3939 let selected_agent_label_for_tooltip = selected_agent_label.clone();
3940
3941 let selected_agent = div()
3942 .id("selected_agent_icon")
3943 .when_some(selected_agent_custom_icon, |this, icon_path| {
3944 this.px_1()
3945 .child(Icon::from_external_svg(icon_path).color(Color::Muted))
3946 })
3947 .when(!has_custom_icon, |this| {
3948 this.when_some(self.selected_agent_type.icon(), |this, icon| {
3949 this.px_1().child(Icon::new(icon).color(Color::Muted))
3950 })
3951 })
3952 .tooltip(move |_, cx| {
3953 Tooltip::with_meta(
3954 selected_agent_label_for_tooltip.clone(),
3955 None,
3956 "Selected Agent",
3957 cx,
3958 )
3959 });
3960
3961 let selected_agent = if is_thread_loading {
3962 selected_agent
3963 .with_animation(
3964 "pulsating-icon",
3965 Animation::new(Duration::from_secs(1))
3966 .repeat()
3967 .with_easing(pulsating_between(0.2, 0.6)),
3968 |icon, delta| icon.opacity(delta),
3969 )
3970 .into_any_element()
3971 } else {
3972 selected_agent.into_any_element()
3973 };
3974
3975 let show_history_menu = self.has_history_for_selected_agent(cx);
3976 let has_v2_flag = cx.has_flag::<AgentV2FeatureFlag>();
3977 let is_empty_state = !self.active_thread_has_messages(cx);
3978
3979 let is_in_history_or_config = matches!(
3980 &self.active_view,
3981 ActiveView::History { .. } | ActiveView::Configuration
3982 );
3983
3984 let is_text_thread = matches!(&self.active_view, ActiveView::TextThread { .. });
3985
3986 let use_v2_empty_toolbar =
3987 has_v2_flag && is_empty_state && !is_in_history_or_config && !is_text_thread;
3988
3989 let base_container = h_flex()
3990 .id("agent-panel-toolbar")
3991 .h(Tab::container_height(cx))
3992 .max_w_full()
3993 .flex_none()
3994 .justify_between()
3995 .gap_2()
3996 .bg(cx.theme().colors().tab_bar_background)
3997 .border_b_1()
3998 .border_color(cx.theme().colors().border);
3999
4000 if use_v2_empty_toolbar {
4001 let (chevron_icon, icon_color, label_color) =
4002 if self.new_thread_menu_handle.is_deployed() {
4003 (IconName::ChevronUp, Color::Accent, Color::Accent)
4004 } else {
4005 (IconName::ChevronDown, Color::Muted, Color::Default)
4006 };
4007
4008 let agent_icon = if let Some(icon_path) = selected_agent_custom_icon_for_button {
4009 Icon::from_external_svg(icon_path)
4010 .size(IconSize::Small)
4011 .color(icon_color)
4012 } else {
4013 let icon_name = selected_agent_builtin_icon.unwrap_or(IconName::ZedAgent);
4014 Icon::new(icon_name).size(IconSize::Small).color(icon_color)
4015 };
4016
4017 let agent_selector_button = Button::new("agent-selector-trigger", selected_agent_label)
4018 .start_icon(agent_icon)
4019 .color(label_color)
4020 .end_icon(
4021 Icon::new(chevron_icon)
4022 .color(icon_color)
4023 .size(IconSize::XSmall),
4024 );
4025
4026 let agent_selector_menu = PopoverMenu::new("new_thread_menu")
4027 .trigger_with_tooltip(agent_selector_button, {
4028 move |_window, cx| {
4029 Tooltip::for_action_in(
4030 "New Thread\u{2026}",
4031 &ToggleNewThreadMenu,
4032 &focus_handle,
4033 cx,
4034 )
4035 }
4036 })
4037 .menu({
4038 let builder = new_thread_menu_builder.clone();
4039 move |window, cx| builder(window, cx)
4040 })
4041 .with_handle(self.new_thread_menu_handle.clone())
4042 .anchor(Corner::TopLeft)
4043 .offset(gpui::Point {
4044 x: px(1.0),
4045 y: px(1.0),
4046 });
4047
4048 base_container
4049 .child(
4050 h_flex()
4051 .size_full()
4052 .gap(DynamicSpacing::Base04.rems(cx))
4053 .pl(DynamicSpacing::Base04.rems(cx))
4054 .child(agent_selector_menu)
4055 .when(
4056 has_visible_worktrees && self.project_has_git_repository(cx),
4057 |this| this.child(self.render_start_thread_in_selector(cx)),
4058 ),
4059 )
4060 .child(
4061 h_flex()
4062 .h_full()
4063 .flex_none()
4064 .gap_1()
4065 .pl_1()
4066 .pr_1()
4067 .when(show_history_menu && !has_v2_flag, |this| {
4068 this.child(self.render_recent_entries_menu(
4069 IconName::MenuAltTemp,
4070 Corner::TopRight,
4071 cx,
4072 ))
4073 })
4074 .child(self.render_panel_options_menu(window, cx)),
4075 )
4076 .into_any_element()
4077 } else {
4078 let new_thread_menu = PopoverMenu::new("new_thread_menu")
4079 .trigger_with_tooltip(
4080 IconButton::new("new_thread_menu_btn", IconName::Plus)
4081 .icon_size(IconSize::Small),
4082 {
4083 move |_window, cx| {
4084 Tooltip::for_action_in(
4085 "New Thread\u{2026}",
4086 &ToggleNewThreadMenu,
4087 &focus_handle,
4088 cx,
4089 )
4090 }
4091 },
4092 )
4093 .anchor(Corner::TopRight)
4094 .with_handle(self.new_thread_menu_handle.clone())
4095 .menu(move |window, cx| new_thread_menu_builder(window, cx));
4096
4097 base_container
4098 .child(
4099 h_flex()
4100 .size_full()
4101 .gap(DynamicSpacing::Base04.rems(cx))
4102 .pl(DynamicSpacing::Base04.rems(cx))
4103 .child(match &self.active_view {
4104 ActiveView::History { .. } | ActiveView::Configuration => {
4105 self.render_toolbar_back_button(cx).into_any_element()
4106 }
4107 _ => selected_agent.into_any_element(),
4108 })
4109 .child(self.render_title_view(window, cx)),
4110 )
4111 .child(
4112 h_flex()
4113 .h_full()
4114 .flex_none()
4115 .gap_1()
4116 .pl_1()
4117 .pr_1()
4118 .child(new_thread_menu)
4119 .when(show_history_menu && !has_v2_flag, |this| {
4120 this.child(self.render_recent_entries_menu(
4121 IconName::MenuAltTemp,
4122 Corner::TopRight,
4123 cx,
4124 ))
4125 })
4126 .child(self.render_panel_options_menu(window, cx)),
4127 )
4128 .into_any_element()
4129 }
4130 }
4131
4132 fn render_worktree_creation_status(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4133 let status = self.worktree_creation_status.as_ref()?;
4134 match status {
4135 WorktreeCreationStatus::Creating => Some(
4136 h_flex()
4137 .absolute()
4138 .bottom_12()
4139 .w_full()
4140 .p_2()
4141 .gap_1()
4142 .justify_center()
4143 .bg(cx.theme().colors().editor_background)
4144 .child(
4145 Icon::new(IconName::LoadCircle)
4146 .size(IconSize::Small)
4147 .color(Color::Muted)
4148 .with_rotate_animation(3),
4149 )
4150 .child(
4151 Label::new("Creating Worktree…")
4152 .color(Color::Muted)
4153 .size(LabelSize::Small),
4154 )
4155 .into_any_element(),
4156 ),
4157 WorktreeCreationStatus::Error(message) => Some(
4158 Callout::new()
4159 .icon(IconName::Warning)
4160 .severity(Severity::Warning)
4161 .title(message.clone())
4162 .into_any_element(),
4163 ),
4164 }
4165 }
4166
4167 fn should_render_trial_end_upsell(&self, cx: &mut Context<Self>) -> bool {
4168 if TrialEndUpsell::dismissed(cx) {
4169 return false;
4170 }
4171
4172 match &self.active_view {
4173 ActiveView::TextThread { .. } => {
4174 if LanguageModelRegistry::global(cx)
4175 .read(cx)
4176 .default_model()
4177 .is_some_and(|model| {
4178 model.provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
4179 })
4180 {
4181 return false;
4182 }
4183 }
4184 ActiveView::Uninitialized
4185 | ActiveView::AgentThread { .. }
4186 | ActiveView::History { .. }
4187 | ActiveView::Configuration => return false,
4188 }
4189
4190 let plan = self.user_store.read(cx).plan();
4191 let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
4192
4193 plan.is_some_and(|plan| plan == Plan::ZedFree) && has_previous_trial
4194 }
4195
4196 fn should_render_onboarding(&self, cx: &mut Context<Self>) -> bool {
4197 if self.on_boarding_upsell_dismissed.load(Ordering::Acquire) {
4198 return false;
4199 }
4200
4201 let user_store = self.user_store.read(cx);
4202
4203 if user_store.plan().is_some_and(|plan| plan == Plan::ZedPro)
4204 && user_store
4205 .subscription_period()
4206 .and_then(|period| period.0.checked_add_days(chrono::Days::new(1)))
4207 .is_some_and(|date| date < chrono::Utc::now())
4208 {
4209 OnboardingUpsell::set_dismissed(true, cx);
4210 self.on_boarding_upsell_dismissed
4211 .store(true, Ordering::Release);
4212 return false;
4213 }
4214
4215 let has_configured_non_zed_providers = LanguageModelRegistry::read_global(cx)
4216 .visible_providers()
4217 .iter()
4218 .any(|provider| {
4219 provider.is_authenticated(cx)
4220 && provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
4221 });
4222
4223 match &self.active_view {
4224 ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {
4225 false
4226 }
4227 ActiveView::AgentThread {
4228 conversation_view, ..
4229 } if conversation_view.read(cx).as_native_thread(cx).is_none() => false,
4230 ActiveView::AgentThread { conversation_view } => {
4231 let history_is_empty = conversation_view
4232 .read(cx)
4233 .history()
4234 .is_none_or(|h| h.read(cx).is_empty());
4235 history_is_empty || !has_configured_non_zed_providers
4236 }
4237 ActiveView::TextThread { .. } => {
4238 let history_is_empty = self.text_thread_history.read(cx).is_empty();
4239 history_is_empty || !has_configured_non_zed_providers
4240 }
4241 }
4242 }
4243
4244 fn render_onboarding(
4245 &self,
4246 _window: &mut Window,
4247 cx: &mut Context<Self>,
4248 ) -> Option<impl IntoElement> {
4249 if !self.should_render_onboarding(cx) {
4250 return None;
4251 }
4252
4253 let text_thread_view = matches!(&self.active_view, ActiveView::TextThread { .. });
4254
4255 Some(
4256 div()
4257 .when(text_thread_view, |this| {
4258 this.bg(cx.theme().colors().editor_background)
4259 })
4260 .child(self.onboarding.clone()),
4261 )
4262 }
4263
4264 fn render_trial_end_upsell(
4265 &self,
4266 _window: &mut Window,
4267 cx: &mut Context<Self>,
4268 ) -> Option<impl IntoElement> {
4269 if !self.should_render_trial_end_upsell(cx) {
4270 return None;
4271 }
4272
4273 Some(
4274 v_flex()
4275 .absolute()
4276 .inset_0()
4277 .size_full()
4278 .bg(cx.theme().colors().panel_background)
4279 .opacity(0.85)
4280 .block_mouse_except_scroll()
4281 .child(EndTrialUpsell::new(Arc::new({
4282 let this = cx.entity();
4283 move |_, cx| {
4284 this.update(cx, |_this, cx| {
4285 TrialEndUpsell::set_dismissed(true, cx);
4286 cx.notify();
4287 });
4288 }
4289 }))),
4290 )
4291 }
4292
4293 fn emit_configuration_error_telemetry_if_needed(
4294 &mut self,
4295 configuration_error: Option<&ConfigurationError>,
4296 ) {
4297 let error_kind = configuration_error.map(|err| match err {
4298 ConfigurationError::NoProvider => "no_provider",
4299 ConfigurationError::ModelNotFound => "model_not_found",
4300 ConfigurationError::ProviderNotAuthenticated(_) => "provider_not_authenticated",
4301 });
4302
4303 let error_kind_string = error_kind.map(String::from);
4304
4305 if self.last_configuration_error_telemetry == error_kind_string {
4306 return;
4307 }
4308
4309 self.last_configuration_error_telemetry = error_kind_string;
4310
4311 if let Some(kind) = error_kind {
4312 let message = configuration_error
4313 .map(|err| err.to_string())
4314 .unwrap_or_default();
4315
4316 telemetry::event!("Agent Panel Error Shown", kind = kind, message = message,);
4317 }
4318 }
4319
4320 fn render_configuration_error(
4321 &self,
4322 border_bottom: bool,
4323 configuration_error: &ConfigurationError,
4324 focus_handle: &FocusHandle,
4325 cx: &mut App,
4326 ) -> impl IntoElement {
4327 let zed_provider_configured = AgentSettings::get_global(cx)
4328 .default_model
4329 .as_ref()
4330 .is_some_and(|selection| selection.provider.0.as_str() == "zed.dev");
4331
4332 let callout = if zed_provider_configured {
4333 Callout::new()
4334 .icon(IconName::Warning)
4335 .severity(Severity::Warning)
4336 .when(border_bottom, |this| {
4337 this.border_position(ui::BorderPosition::Bottom)
4338 })
4339 .title("Sign in to continue using Zed as your LLM provider.")
4340 .actions_slot(
4341 Button::new("sign_in", "Sign In")
4342 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
4343 .label_size(LabelSize::Small)
4344 .on_click({
4345 let workspace = self.workspace.clone();
4346 move |_, _, cx| {
4347 let Ok(client) =
4348 workspace.update(cx, |workspace, _| workspace.client().clone())
4349 else {
4350 return;
4351 };
4352
4353 cx.spawn(async move |cx| {
4354 client.sign_in_with_optional_connect(true, cx).await
4355 })
4356 .detach_and_log_err(cx);
4357 }
4358 }),
4359 )
4360 } else {
4361 Callout::new()
4362 .icon(IconName::Warning)
4363 .severity(Severity::Warning)
4364 .when(border_bottom, |this| {
4365 this.border_position(ui::BorderPosition::Bottom)
4366 })
4367 .title(configuration_error.to_string())
4368 .actions_slot(
4369 Button::new("settings", "Configure")
4370 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
4371 .label_size(LabelSize::Small)
4372 .key_binding(
4373 KeyBinding::for_action_in(&OpenSettings, focus_handle, cx)
4374 .map(|kb| kb.size(rems_from_px(12.))),
4375 )
4376 .on_click(|_event, window, cx| {
4377 window.dispatch_action(OpenSettings.boxed_clone(), cx)
4378 }),
4379 )
4380 };
4381
4382 match configuration_error {
4383 ConfigurationError::ModelNotFound
4384 | ConfigurationError::ProviderNotAuthenticated(_)
4385 | ConfigurationError::NoProvider => callout.into_any_element(),
4386 }
4387 }
4388
4389 fn render_text_thread(
4390 &self,
4391 text_thread_editor: &Entity<TextThreadEditor>,
4392 buffer_search_bar: &Entity<BufferSearchBar>,
4393 window: &mut Window,
4394 cx: &mut Context<Self>,
4395 ) -> Div {
4396 let mut registrar = buffer_search::DivRegistrar::new(
4397 |this, _, _cx| match &this.active_view {
4398 ActiveView::TextThread {
4399 buffer_search_bar, ..
4400 } => Some(buffer_search_bar.clone()),
4401 _ => None,
4402 },
4403 cx,
4404 );
4405 BufferSearchBar::register(&mut registrar);
4406 registrar
4407 .into_div()
4408 .size_full()
4409 .relative()
4410 .map(|parent| {
4411 buffer_search_bar.update(cx, |buffer_search_bar, cx| {
4412 if buffer_search_bar.is_dismissed() {
4413 return parent;
4414 }
4415 parent.child(
4416 div()
4417 .p(DynamicSpacing::Base08.rems(cx))
4418 .border_b_1()
4419 .border_color(cx.theme().colors().border_variant)
4420 .bg(cx.theme().colors().editor_background)
4421 .child(buffer_search_bar.render(window, cx)),
4422 )
4423 })
4424 })
4425 .child(text_thread_editor.clone())
4426 .child(self.render_drag_target(cx))
4427 }
4428
4429 fn render_drag_target(&self, cx: &Context<Self>) -> Div {
4430 let is_local = self.project.read(cx).is_local();
4431 div()
4432 .invisible()
4433 .absolute()
4434 .top_0()
4435 .right_0()
4436 .bottom_0()
4437 .left_0()
4438 .bg(cx.theme().colors().drop_target_background)
4439 .drag_over::<DraggedTab>(|this, _, _, _| this.visible())
4440 .drag_over::<DraggedSelection>(|this, _, _, _| this.visible())
4441 .when(is_local, |this| {
4442 this.drag_over::<ExternalPaths>(|this, _, _, _| this.visible())
4443 })
4444 .on_drop(cx.listener(move |this, tab: &DraggedTab, window, cx| {
4445 let item = tab.pane.read(cx).item_for_index(tab.ix);
4446 let project_paths = item
4447 .and_then(|item| item.project_path(cx))
4448 .into_iter()
4449 .collect::<Vec<_>>();
4450 this.handle_drop(project_paths, vec![], window, cx);
4451 }))
4452 .on_drop(
4453 cx.listener(move |this, selection: &DraggedSelection, window, cx| {
4454 let project_paths = selection
4455 .items()
4456 .filter_map(|item| this.project.read(cx).path_for_entry(item.entry_id, cx))
4457 .collect::<Vec<_>>();
4458 this.handle_drop(project_paths, vec![], window, cx);
4459 }),
4460 )
4461 .on_drop(cx.listener(move |this, paths: &ExternalPaths, window, cx| {
4462 let tasks = paths
4463 .paths()
4464 .iter()
4465 .map(|path| {
4466 Workspace::project_path_for_path(this.project.clone(), path, false, cx)
4467 })
4468 .collect::<Vec<_>>();
4469 cx.spawn_in(window, async move |this, cx| {
4470 let mut paths = vec![];
4471 let mut added_worktrees = vec![];
4472 let opened_paths = futures::future::join_all(tasks).await;
4473 for entry in opened_paths {
4474 if let Some((worktree, project_path)) = entry.log_err() {
4475 added_worktrees.push(worktree);
4476 paths.push(project_path);
4477 }
4478 }
4479 this.update_in(cx, |this, window, cx| {
4480 this.handle_drop(paths, added_worktrees, window, cx);
4481 })
4482 .ok();
4483 })
4484 .detach();
4485 }))
4486 }
4487
4488 fn handle_drop(
4489 &mut self,
4490 paths: Vec<ProjectPath>,
4491 added_worktrees: Vec<Entity<Worktree>>,
4492 window: &mut Window,
4493 cx: &mut Context<Self>,
4494 ) {
4495 match &self.active_view {
4496 ActiveView::AgentThread { conversation_view } => {
4497 conversation_view.update(cx, |conversation_view, cx| {
4498 conversation_view.insert_dragged_files(paths, added_worktrees, window, cx);
4499 });
4500 }
4501 ActiveView::TextThread {
4502 text_thread_editor, ..
4503 } => {
4504 text_thread_editor.update(cx, |text_thread_editor, cx| {
4505 TextThreadEditor::insert_dragged_files(
4506 text_thread_editor,
4507 paths,
4508 added_worktrees,
4509 window,
4510 cx,
4511 );
4512 });
4513 }
4514 ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {}
4515 }
4516 }
4517
4518 fn render_workspace_trust_message(&self, cx: &Context<Self>) -> Option<impl IntoElement> {
4519 if !self.show_trust_workspace_message {
4520 return None;
4521 }
4522
4523 let description = "To protect your system, third-party code—like MCP servers—won't run until you mark this workspace as safe.";
4524
4525 Some(
4526 Callout::new()
4527 .icon(IconName::Warning)
4528 .severity(Severity::Warning)
4529 .border_position(ui::BorderPosition::Bottom)
4530 .title("You're in Restricted Mode")
4531 .description(description)
4532 .actions_slot(
4533 Button::new("open-trust-modal", "Configure Project Trust")
4534 .label_size(LabelSize::Small)
4535 .style(ButtonStyle::Outlined)
4536 .on_click({
4537 cx.listener(move |this, _, window, cx| {
4538 this.workspace
4539 .update(cx, |workspace, cx| {
4540 workspace
4541 .show_worktree_trust_security_modal(true, window, cx)
4542 })
4543 .log_err();
4544 })
4545 }),
4546 ),
4547 )
4548 }
4549
4550 fn key_context(&self) -> KeyContext {
4551 let mut key_context = KeyContext::new_with_defaults();
4552 key_context.add("AgentPanel");
4553 match &self.active_view {
4554 ActiveView::AgentThread { .. } => key_context.add("acp_thread"),
4555 ActiveView::TextThread { .. } => key_context.add("text_thread"),
4556 ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {}
4557 }
4558 key_context
4559 }
4560}
4561
4562impl Render for AgentPanel {
4563 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4564 // WARNING: Changes to this element hierarchy can have
4565 // non-obvious implications to the layout of children.
4566 //
4567 // If you need to change it, please confirm:
4568 // - The message editor expands (cmd-option-esc) correctly
4569 // - When expanded, the buttons at the bottom of the panel are displayed correctly
4570 // - Font size works as expected and can be changed with cmd-+/cmd-
4571 // - Scrolling in all views works as expected
4572 // - Files can be dropped into the panel
4573 let content = v_flex()
4574 .relative()
4575 .size_full()
4576 .justify_between()
4577 .key_context(self.key_context())
4578 .on_action(cx.listener(|this, action: &NewThread, window, cx| {
4579 this.new_thread(action, window, cx);
4580 }))
4581 .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
4582 this.open_history(window, cx);
4583 }))
4584 .on_action(cx.listener(|this, _: &OpenSettings, window, cx| {
4585 this.open_configuration(window, cx);
4586 }))
4587 .on_action(cx.listener(Self::open_active_thread_as_markdown))
4588 .on_action(cx.listener(Self::deploy_rules_library))
4589 .on_action(cx.listener(Self::go_back))
4590 .on_action(cx.listener(Self::toggle_navigation_menu))
4591 .on_action(cx.listener(Self::toggle_options_menu))
4592 .on_action(cx.listener(Self::increase_font_size))
4593 .on_action(cx.listener(Self::decrease_font_size))
4594 .on_action(cx.listener(Self::reset_font_size))
4595 .on_action(cx.listener(Self::toggle_zoom))
4596 .on_action(cx.listener(|this, _: &ReauthenticateAgent, window, cx| {
4597 if let Some(conversation_view) = this.active_conversation_view() {
4598 conversation_view.update(cx, |conversation_view, cx| {
4599 conversation_view.reauthenticate(window, cx)
4600 })
4601 }
4602 }))
4603 .child(self.render_toolbar(window, cx))
4604 .children(self.render_workspace_trust_message(cx))
4605 .children(self.render_onboarding(window, cx))
4606 .map(|parent| {
4607 // Emit configuration error telemetry before entering the match to avoid borrow conflicts
4608 if matches!(&self.active_view, ActiveView::TextThread { .. }) {
4609 let model_registry = LanguageModelRegistry::read_global(cx);
4610 let configuration_error =
4611 model_registry.configuration_error(model_registry.default_model(), cx);
4612 self.emit_configuration_error_telemetry_if_needed(configuration_error.as_ref());
4613 }
4614
4615 match &self.active_view {
4616 ActiveView::Uninitialized => parent,
4617 ActiveView::AgentThread {
4618 conversation_view, ..
4619 } => parent
4620 .child(conversation_view.clone())
4621 .child(self.render_drag_target(cx)),
4622 ActiveView::History { history: kind } => match kind {
4623 History::AgentThreads { view } => parent.child(view.clone()),
4624 History::TextThreads => parent.child(self.text_thread_history.clone()),
4625 },
4626 ActiveView::TextThread {
4627 text_thread_editor,
4628 buffer_search_bar,
4629 ..
4630 } => {
4631 let model_registry = LanguageModelRegistry::read_global(cx);
4632 let configuration_error =
4633 model_registry.configuration_error(model_registry.default_model(), cx);
4634
4635 parent
4636 .map(|this| {
4637 if !self.should_render_onboarding(cx)
4638 && let Some(err) = configuration_error.as_ref()
4639 {
4640 this.child(self.render_configuration_error(
4641 true,
4642 err,
4643 &self.focus_handle(cx),
4644 cx,
4645 ))
4646 } else {
4647 this
4648 }
4649 })
4650 .child(self.render_text_thread(
4651 text_thread_editor,
4652 buffer_search_bar,
4653 window,
4654 cx,
4655 ))
4656 }
4657 ActiveView::Configuration => parent.children(self.configuration.clone()),
4658 }
4659 })
4660 .children(self.render_worktree_creation_status(cx))
4661 .children(self.render_trial_end_upsell(window, cx));
4662
4663 match self.active_view.which_font_size_used() {
4664 WhichFontSize::AgentFont => {
4665 WithRemSize::new(ThemeSettings::get_global(cx).agent_ui_font_size(cx))
4666 .size_full()
4667 .child(content)
4668 .into_any()
4669 }
4670 _ => content.into_any(),
4671 }
4672 }
4673}
4674
4675struct PromptLibraryInlineAssist {
4676 workspace: WeakEntity<Workspace>,
4677}
4678
4679impl PromptLibraryInlineAssist {
4680 pub fn new(workspace: WeakEntity<Workspace>) -> Self {
4681 Self { workspace }
4682 }
4683}
4684
4685impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
4686 fn assist(
4687 &self,
4688 prompt_editor: &Entity<Editor>,
4689 initial_prompt: Option<String>,
4690 window: &mut Window,
4691 cx: &mut Context<RulesLibrary>,
4692 ) {
4693 InlineAssistant::update_global(cx, |assistant, cx| {
4694 let Some(workspace) = self.workspace.upgrade() else {
4695 return;
4696 };
4697 let Some(panel) = workspace.read(cx).panel::<AgentPanel>(cx) else {
4698 return;
4699 };
4700 let history = panel
4701 .read(cx)
4702 .connection_store()
4703 .read(cx)
4704 .entry(&crate::Agent::NativeAgent)
4705 .and_then(|s| s.read(cx).history())
4706 .map(|h| h.downgrade());
4707 let project = workspace.read(cx).project().downgrade();
4708 let panel = panel.read(cx);
4709 let thread_store = panel.thread_store().clone();
4710 assistant.assist(
4711 prompt_editor,
4712 self.workspace.clone(),
4713 project,
4714 thread_store,
4715 None,
4716 history,
4717 initial_prompt,
4718 window,
4719 cx,
4720 );
4721 })
4722 }
4723
4724 fn focus_agent_panel(
4725 &self,
4726 workspace: &mut Workspace,
4727 window: &mut Window,
4728 cx: &mut Context<Workspace>,
4729 ) -> bool {
4730 workspace.focus_panel::<AgentPanel>(window, cx).is_some()
4731 }
4732}
4733
4734pub struct ConcreteAssistantPanelDelegate;
4735
4736impl AgentPanelDelegate for ConcreteAssistantPanelDelegate {
4737 fn active_text_thread_editor(
4738 &self,
4739 workspace: &mut Workspace,
4740 _window: &mut Window,
4741 cx: &mut Context<Workspace>,
4742 ) -> Option<Entity<TextThreadEditor>> {
4743 let panel = workspace.panel::<AgentPanel>(cx)?;
4744 panel.read(cx).active_text_thread_editor()
4745 }
4746
4747 fn open_local_text_thread(
4748 &self,
4749 workspace: &mut Workspace,
4750 path: Arc<Path>,
4751 window: &mut Window,
4752 cx: &mut Context<Workspace>,
4753 ) -> Task<Result<()>> {
4754 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
4755 return Task::ready(Err(anyhow!("Agent panel not found")));
4756 };
4757
4758 panel.update(cx, |panel, cx| {
4759 panel.open_saved_text_thread(path, window, cx)
4760 })
4761 }
4762
4763 fn open_remote_text_thread(
4764 &self,
4765 _workspace: &mut Workspace,
4766 _text_thread_id: assistant_text_thread::TextThreadId,
4767 _window: &mut Window,
4768 _cx: &mut Context<Workspace>,
4769 ) -> Task<Result<Entity<TextThreadEditor>>> {
4770 Task::ready(Err(anyhow!("opening remote context not implemented")))
4771 }
4772
4773 fn quote_selection(
4774 &self,
4775 workspace: &mut Workspace,
4776 selection_ranges: Vec<Range<Anchor>>,
4777 buffer: Entity<MultiBuffer>,
4778 window: &mut Window,
4779 cx: &mut Context<Workspace>,
4780 ) {
4781 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
4782 return;
4783 };
4784
4785 if !panel.focus_handle(cx).contains_focused(window, cx) {
4786 workspace.toggle_panel_focus::<AgentPanel>(window, cx);
4787 }
4788
4789 panel.update(cx, |_, cx| {
4790 // Wait to create a new context until the workspace is no longer
4791 // being updated.
4792 cx.defer_in(window, move |panel, window, cx| {
4793 if let Some(conversation_view) = panel.active_conversation_view() {
4794 conversation_view.update(cx, |conversation_view, cx| {
4795 conversation_view.insert_selections(window, cx);
4796 });
4797 } else if let Some(text_thread_editor) = panel.active_text_thread_editor() {
4798 let snapshot = buffer.read(cx).snapshot(cx);
4799 let selection_ranges = selection_ranges
4800 .into_iter()
4801 .map(|range| range.to_point(&snapshot))
4802 .collect::<Vec<_>>();
4803
4804 text_thread_editor.update(cx, |text_thread_editor, cx| {
4805 text_thread_editor.quote_ranges(selection_ranges, snapshot, window, cx)
4806 });
4807 }
4808 });
4809 });
4810 }
4811
4812 fn quote_terminal_text(
4813 &self,
4814 workspace: &mut Workspace,
4815 text: String,
4816 window: &mut Window,
4817 cx: &mut Context<Workspace>,
4818 ) {
4819 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
4820 return;
4821 };
4822
4823 if !panel.focus_handle(cx).contains_focused(window, cx) {
4824 workspace.toggle_panel_focus::<AgentPanel>(window, cx);
4825 }
4826
4827 panel.update(cx, |_, cx| {
4828 // Wait to create a new context until the workspace is no longer
4829 // being updated.
4830 cx.defer_in(window, move |panel, window, cx| {
4831 if let Some(conversation_view) = panel.active_conversation_view() {
4832 conversation_view.update(cx, |conversation_view, cx| {
4833 conversation_view.insert_terminal_text(text, window, cx);
4834 });
4835 } else if let Some(text_thread_editor) = panel.active_text_thread_editor() {
4836 text_thread_editor.update(cx, |text_thread_editor, cx| {
4837 text_thread_editor.quote_terminal_text(text, window, cx)
4838 });
4839 }
4840 });
4841 });
4842 }
4843}
4844
4845struct OnboardingUpsell;
4846
4847impl Dismissable for OnboardingUpsell {
4848 const KEY: &'static str = "dismissed-trial-upsell";
4849}
4850
4851struct TrialEndUpsell;
4852
4853impl Dismissable for TrialEndUpsell {
4854 const KEY: &'static str = "dismissed-trial-end-upsell";
4855}
4856
4857/// Test-only helper methods
4858#[cfg(any(test, feature = "test-support"))]
4859impl AgentPanel {
4860 pub fn test_new(
4861 workspace: &Workspace,
4862 text_thread_store: Entity<assistant_text_thread::TextThreadStore>,
4863 window: &mut Window,
4864 cx: &mut Context<Self>,
4865 ) -> Self {
4866 Self::new(workspace, text_thread_store, None, window, cx)
4867 }
4868
4869 /// Opens an external thread using an arbitrary AgentServer.
4870 ///
4871 /// This is a test-only helper that allows visual tests and integration tests
4872 /// to inject a stub server without modifying production code paths.
4873 /// Not compiled into production builds.
4874 pub fn open_external_thread_with_server(
4875 &mut self,
4876 server: Rc<dyn AgentServer>,
4877 window: &mut Window,
4878 cx: &mut Context<Self>,
4879 ) {
4880 let workspace = self.workspace.clone();
4881 let project = self.project.clone();
4882
4883 let ext_agent = Agent::Custom {
4884 id: server.agent_id(),
4885 };
4886
4887 self.create_agent_thread(
4888 server, None, None, None, None, workspace, project, ext_agent, true, window, cx,
4889 );
4890 }
4891
4892 /// Returns the currently active thread view, if any.
4893 ///
4894 /// This is a test-only accessor that exposes the private `active_thread_view()`
4895 /// method for test assertions. Not compiled into production builds.
4896 pub fn active_thread_view_for_tests(&self) -> Option<&Entity<ConversationView>> {
4897 self.active_conversation_view()
4898 }
4899
4900 /// Sets the start_thread_in value directly, bypassing validation.
4901 ///
4902 /// This is a test-only helper for visual tests that need to show specific
4903 /// start_thread_in states without requiring a real git repository.
4904 pub fn set_start_thread_in_for_tests(&mut self, target: StartThreadIn, cx: &mut Context<Self>) {
4905 self.start_thread_in = target;
4906 cx.notify();
4907 }
4908
4909 /// Returns the current worktree creation status.
4910 ///
4911 /// This is a test-only helper for visual tests.
4912 pub fn worktree_creation_status_for_tests(&self) -> Option<&WorktreeCreationStatus> {
4913 self.worktree_creation_status.as_ref()
4914 }
4915
4916 /// Sets the worktree creation status directly.
4917 ///
4918 /// This is a test-only helper for visual tests that need to show the
4919 /// "Creating worktree…" spinner or error banners.
4920 pub fn set_worktree_creation_status_for_tests(
4921 &mut self,
4922 status: Option<WorktreeCreationStatus>,
4923 cx: &mut Context<Self>,
4924 ) {
4925 self.worktree_creation_status = status;
4926 cx.notify();
4927 }
4928
4929 /// Opens the history view.
4930 ///
4931 /// This is a test-only helper that exposes the private `open_history()`
4932 /// method for visual tests.
4933 pub fn open_history_for_tests(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4934 self.open_history(window, cx);
4935 }
4936
4937 /// Opens the start_thread_in selector popover menu.
4938 ///
4939 /// This is a test-only helper for visual tests.
4940 pub fn open_start_thread_in_menu_for_tests(
4941 &mut self,
4942 window: &mut Window,
4943 cx: &mut Context<Self>,
4944 ) {
4945 self.start_thread_in_menu_handle.show(window, cx);
4946 }
4947
4948 /// Dismisses the start_thread_in dropdown menu.
4949 ///
4950 /// This is a test-only helper for visual tests.
4951 pub fn close_start_thread_in_menu_for_tests(&mut self, cx: &mut Context<Self>) {
4952 self.start_thread_in_menu_handle.hide(cx);
4953 }
4954}
4955
4956#[cfg(test)]
4957mod tests {
4958 use super::*;
4959 use crate::conversation_view::tests::{StubAgentServer, init_test};
4960 use crate::test_support::{
4961 active_session_id, open_thread_with_connection, open_thread_with_custom_connection,
4962 send_message,
4963 };
4964 use acp_thread::{StubAgentConnection, ThreadStatus};
4965 use agent_servers::CODEX_ID;
4966 use assistant_text_thread::TextThreadStore;
4967 use feature_flags::FeatureFlagAppExt;
4968 use fs::FakeFs;
4969 use gpui::{TestAppContext, VisualTestContext};
4970 use project::Project;
4971 use serde_json::json;
4972 use std::time::Instant;
4973 use workspace::MultiWorkspace;
4974
4975 #[gpui::test]
4976 async fn test_active_thread_serialize_and_load_round_trip(cx: &mut TestAppContext) {
4977 init_test(cx);
4978 cx.update(|cx| {
4979 cx.update_flags(true, vec!["agent-v2".to_string()]);
4980 agent::ThreadStore::init_global(cx);
4981 language_model::LanguageModelRegistry::test(cx);
4982 });
4983
4984 // --- Create a MultiWorkspace window with two workspaces ---
4985 let fs = FakeFs::new(cx.executor());
4986 let project_a = Project::test(fs.clone(), [], cx).await;
4987 let project_b = Project::test(fs, [], cx).await;
4988
4989 let multi_workspace =
4990 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
4991
4992 let workspace_a = multi_workspace
4993 .read_with(cx, |multi_workspace, _cx| {
4994 multi_workspace.workspace().clone()
4995 })
4996 .unwrap();
4997
4998 let workspace_b = multi_workspace
4999 .update(cx, |multi_workspace, window, cx| {
5000 multi_workspace.test_add_workspace(project_b.clone(), window, cx)
5001 })
5002 .unwrap();
5003
5004 workspace_a.update(cx, |workspace, _cx| {
5005 workspace.set_random_database_id();
5006 });
5007 workspace_b.update(cx, |workspace, _cx| {
5008 workspace.set_random_database_id();
5009 });
5010
5011 let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5012
5013 // --- Set up workspace A: width=300, with an active thread ---
5014 let panel_a = workspace_a.update_in(cx, |workspace, window, cx| {
5015 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project_a.clone(), cx));
5016 cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
5017 });
5018
5019 panel_a.update(cx, |panel, _cx| {
5020 panel.width = Some(px(300.0));
5021 });
5022
5023 panel_a.update_in(cx, |panel, window, cx| {
5024 panel.open_external_thread_with_server(
5025 Rc::new(StubAgentServer::default_response()),
5026 window,
5027 cx,
5028 );
5029 });
5030
5031 cx.run_until_parked();
5032
5033 panel_a.read_with(cx, |panel, cx| {
5034 assert!(
5035 panel.active_agent_thread(cx).is_some(),
5036 "workspace A should have an active thread after connection"
5037 );
5038 });
5039
5040 let agent_type_a = panel_a.read_with(cx, |panel, _cx| panel.selected_agent_type.clone());
5041
5042 // --- Set up workspace B: ClaudeCode, width=400, no active thread ---
5043 let panel_b = workspace_b.update_in(cx, |workspace, window, cx| {
5044 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project_b.clone(), cx));
5045 cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
5046 });
5047
5048 panel_b.update(cx, |panel, _cx| {
5049 panel.width = Some(px(400.0));
5050 panel.selected_agent_type = AgentType::Custom {
5051 id: "claude-acp".into(),
5052 };
5053 });
5054
5055 // --- Serialize both panels ---
5056 panel_a.update(cx, |panel, cx| panel.serialize(cx));
5057 panel_b.update(cx, |panel, cx| panel.serialize(cx));
5058 cx.run_until_parked();
5059
5060 // --- Load fresh panels for each workspace and verify independent state ---
5061 let prompt_builder = Arc::new(prompt_store::PromptBuilder::new(None).unwrap());
5062
5063 let async_cx = cx.update(|window, cx| window.to_async(cx));
5064 let loaded_a = AgentPanel::load(workspace_a.downgrade(), prompt_builder.clone(), async_cx)
5065 .await
5066 .expect("panel A load should succeed");
5067 cx.run_until_parked();
5068
5069 let async_cx = cx.update(|window, cx| window.to_async(cx));
5070 let loaded_b = AgentPanel::load(workspace_b.downgrade(), prompt_builder.clone(), async_cx)
5071 .await
5072 .expect("panel B load should succeed");
5073 cx.run_until_parked();
5074
5075 // Workspace A should restore its thread, width, and agent type
5076 loaded_a.read_with(cx, |panel, _cx| {
5077 assert_eq!(
5078 panel.width,
5079 Some(px(300.0)),
5080 "workspace A width should be restored"
5081 );
5082 assert_eq!(
5083 panel.selected_agent_type, agent_type_a,
5084 "workspace A agent type should be restored"
5085 );
5086 assert!(
5087 panel.active_conversation_view().is_some(),
5088 "workspace A should have its active thread restored"
5089 );
5090 });
5091
5092 // Workspace B should restore its own width and agent type, with no thread
5093 loaded_b.read_with(cx, |panel, _cx| {
5094 assert_eq!(
5095 panel.width,
5096 Some(px(400.0)),
5097 "workspace B width should be restored"
5098 );
5099 assert_eq!(
5100 panel.selected_agent_type,
5101 AgentType::Custom {
5102 id: "claude-acp".into()
5103 },
5104 "workspace B agent type should be restored"
5105 );
5106 assert!(
5107 panel.active_conversation_view().is_none(),
5108 "workspace B should have no active thread"
5109 );
5110 });
5111 }
5112
5113 // Simple regression test
5114 #[gpui::test]
5115 async fn test_new_text_thread_action_handler(cx: &mut TestAppContext) {
5116 init_test(cx);
5117
5118 let fs = FakeFs::new(cx.executor());
5119
5120 cx.update(|cx| {
5121 cx.update_flags(true, vec!["agent-v2".to_string()]);
5122 agent::ThreadStore::init_global(cx);
5123 language_model::LanguageModelRegistry::test(cx);
5124 let slash_command_registry =
5125 assistant_slash_command::SlashCommandRegistry::default_global(cx);
5126 slash_command_registry
5127 .register_command(assistant_slash_commands::DefaultSlashCommand, false);
5128 <dyn fs::Fs>::set_global(fs.clone(), cx);
5129 });
5130
5131 let project = Project::test(fs.clone(), [], cx).await;
5132
5133 let multi_workspace =
5134 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5135
5136 let workspace_a = multi_workspace
5137 .read_with(cx, |multi_workspace, _cx| {
5138 multi_workspace.workspace().clone()
5139 })
5140 .unwrap();
5141
5142 let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5143
5144 workspace_a.update_in(cx, |workspace, window, cx| {
5145 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5146 let panel =
5147 cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
5148 workspace.add_panel(panel, window, cx);
5149 });
5150
5151 cx.run_until_parked();
5152
5153 workspace_a.update_in(cx, |_, window, cx| {
5154 window.dispatch_action(NewTextThread.boxed_clone(), cx);
5155 });
5156
5157 cx.run_until_parked();
5158 }
5159
5160 /// Extracts the text from a Text content block, panicking if it's not Text.
5161 fn expect_text_block(block: &acp::ContentBlock) -> &str {
5162 match block {
5163 acp::ContentBlock::Text(t) => t.text.as_str(),
5164 other => panic!("expected Text block, got {:?}", other),
5165 }
5166 }
5167
5168 /// Extracts the (text_content, uri) from a Resource content block, panicking
5169 /// if it's not a TextResourceContents resource.
5170 fn expect_resource_block(block: &acp::ContentBlock) -> (&str, &str) {
5171 match block {
5172 acp::ContentBlock::Resource(r) => match &r.resource {
5173 acp::EmbeddedResourceResource::TextResourceContents(t) => {
5174 (t.text.as_str(), t.uri.as_str())
5175 }
5176 other => panic!("expected TextResourceContents, got {:?}", other),
5177 },
5178 other => panic!("expected Resource block, got {:?}", other),
5179 }
5180 }
5181
5182 #[test]
5183 fn test_build_conflict_resolution_prompt_single_conflict() {
5184 let conflicts = vec![ConflictContent {
5185 file_path: "src/main.rs".to_string(),
5186 conflict_text: "<<<<<<< HEAD\nlet x = 1;\n=======\nlet x = 2;\n>>>>>>> feature"
5187 .to_string(),
5188 ours_branch_name: "HEAD".to_string(),
5189 theirs_branch_name: "feature".to_string(),
5190 }];
5191
5192 let blocks = build_conflict_resolution_prompt(&conflicts);
5193 // 2 Text blocks + 1 ResourceLink + 1 Resource for the conflict
5194 assert_eq!(
5195 blocks.len(),
5196 4,
5197 "expected 2 text + 1 resource link + 1 resource block"
5198 );
5199
5200 let intro_text = expect_text_block(&blocks[0]);
5201 assert!(
5202 intro_text.contains("Please resolve the following merge conflict in"),
5203 "prompt should include single-conflict intro text"
5204 );
5205
5206 match &blocks[1] {
5207 acp::ContentBlock::ResourceLink(link) => {
5208 assert!(
5209 link.uri.contains("file://"),
5210 "resource link URI should use file scheme"
5211 );
5212 assert!(
5213 link.uri.contains("main.rs"),
5214 "resource link URI should reference file path"
5215 );
5216 }
5217 other => panic!("expected ResourceLink block, got {:?}", other),
5218 }
5219
5220 let body_text = expect_text_block(&blocks[2]);
5221 assert!(
5222 body_text.contains("`HEAD` (ours)"),
5223 "prompt should mention ours branch"
5224 );
5225 assert!(
5226 body_text.contains("`feature` (theirs)"),
5227 "prompt should mention theirs branch"
5228 );
5229 assert!(
5230 body_text.contains("editing the file directly"),
5231 "prompt should instruct the agent to edit the file"
5232 );
5233
5234 let (resource_text, resource_uri) = expect_resource_block(&blocks[3]);
5235 assert!(
5236 resource_text.contains("<<<<<<< HEAD"),
5237 "resource should contain the conflict text"
5238 );
5239 assert!(
5240 resource_uri.contains("merge-conflict"),
5241 "resource URI should use the merge-conflict scheme"
5242 );
5243 assert!(
5244 resource_uri.contains("main.rs"),
5245 "resource URI should reference the file path"
5246 );
5247 }
5248
5249 #[test]
5250 fn test_build_conflict_resolution_prompt_multiple_conflicts_same_file() {
5251 let conflicts = vec![
5252 ConflictContent {
5253 file_path: "src/lib.rs".to_string(),
5254 conflict_text: "<<<<<<< main\nfn a() {}\n=======\nfn a_v2() {}\n>>>>>>> dev"
5255 .to_string(),
5256 ours_branch_name: "main".to_string(),
5257 theirs_branch_name: "dev".to_string(),
5258 },
5259 ConflictContent {
5260 file_path: "src/lib.rs".to_string(),
5261 conflict_text: "<<<<<<< main\nfn b() {}\n=======\nfn b_v2() {}\n>>>>>>> dev"
5262 .to_string(),
5263 ours_branch_name: "main".to_string(),
5264 theirs_branch_name: "dev".to_string(),
5265 },
5266 ];
5267
5268 let blocks = build_conflict_resolution_prompt(&conflicts);
5269 // 1 Text instruction + 2 Resource blocks
5270 assert_eq!(blocks.len(), 3, "expected 1 text + 2 resource blocks");
5271
5272 let text = expect_text_block(&blocks[0]);
5273 assert!(
5274 text.contains("all 2 merge conflicts"),
5275 "prompt should mention the total count"
5276 );
5277 assert!(
5278 text.contains("`main` (ours)"),
5279 "prompt should mention ours branch"
5280 );
5281 assert!(
5282 text.contains("`dev` (theirs)"),
5283 "prompt should mention theirs branch"
5284 );
5285 // Single file, so "file" not "files"
5286 assert!(
5287 text.contains("file directly"),
5288 "single file should use singular 'file'"
5289 );
5290
5291 let (resource_a, _) = expect_resource_block(&blocks[1]);
5292 let (resource_b, _) = expect_resource_block(&blocks[2]);
5293 assert!(
5294 resource_a.contains("fn a()"),
5295 "first resource should contain first conflict"
5296 );
5297 assert!(
5298 resource_b.contains("fn b()"),
5299 "second resource should contain second conflict"
5300 );
5301 }
5302
5303 #[test]
5304 fn test_build_conflict_resolution_prompt_multiple_conflicts_different_files() {
5305 let conflicts = vec![
5306 ConflictContent {
5307 file_path: "src/a.rs".to_string(),
5308 conflict_text: "<<<<<<< main\nA\n=======\nB\n>>>>>>> dev".to_string(),
5309 ours_branch_name: "main".to_string(),
5310 theirs_branch_name: "dev".to_string(),
5311 },
5312 ConflictContent {
5313 file_path: "src/b.rs".to_string(),
5314 conflict_text: "<<<<<<< main\nC\n=======\nD\n>>>>>>> dev".to_string(),
5315 ours_branch_name: "main".to_string(),
5316 theirs_branch_name: "dev".to_string(),
5317 },
5318 ];
5319
5320 let blocks = build_conflict_resolution_prompt(&conflicts);
5321 // 1 Text instruction + 2 Resource blocks
5322 assert_eq!(blocks.len(), 3, "expected 1 text + 2 resource blocks");
5323
5324 let text = expect_text_block(&blocks[0]);
5325 assert!(
5326 text.contains("files directly"),
5327 "multiple files should use plural 'files'"
5328 );
5329
5330 let (_, uri_a) = expect_resource_block(&blocks[1]);
5331 let (_, uri_b) = expect_resource_block(&blocks[2]);
5332 assert!(
5333 uri_a.contains("a.rs"),
5334 "first resource URI should reference a.rs"
5335 );
5336 assert!(
5337 uri_b.contains("b.rs"),
5338 "second resource URI should reference b.rs"
5339 );
5340 }
5341
5342 #[test]
5343 fn test_build_conflicted_files_resolution_prompt_file_paths_only() {
5344 let file_paths = vec![
5345 "src/main.rs".to_string(),
5346 "src/lib.rs".to_string(),
5347 "tests/integration.rs".to_string(),
5348 ];
5349
5350 let blocks = build_conflicted_files_resolution_prompt(&file_paths);
5351 // 1 instruction Text block + (ResourceLink + newline Text) per file
5352 assert_eq!(
5353 blocks.len(),
5354 1 + (file_paths.len() * 2),
5355 "expected instruction text plus resource links and separators"
5356 );
5357
5358 let text = expect_text_block(&blocks[0]);
5359 assert!(
5360 text.contains("unresolved merge conflicts"),
5361 "prompt should describe the task"
5362 );
5363 assert!(
5364 text.contains("conflict markers"),
5365 "prompt should mention conflict markers"
5366 );
5367
5368 for (index, path) in file_paths.iter().enumerate() {
5369 let link_index = 1 + (index * 2);
5370 let newline_index = link_index + 1;
5371
5372 match &blocks[link_index] {
5373 acp::ContentBlock::ResourceLink(link) => {
5374 assert!(
5375 link.uri.contains("file://"),
5376 "resource link URI should use file scheme"
5377 );
5378 assert!(
5379 link.uri.contains(path),
5380 "resource link URI should reference file path: {path}"
5381 );
5382 }
5383 other => panic!(
5384 "expected ResourceLink block at index {}, got {:?}",
5385 link_index, other
5386 ),
5387 }
5388
5389 let separator = expect_text_block(&blocks[newline_index]);
5390 assert_eq!(
5391 separator, "\n",
5392 "expected newline separator after each file"
5393 );
5394 }
5395 }
5396
5397 #[test]
5398 fn test_build_conflict_resolution_prompt_empty_conflicts() {
5399 let blocks = build_conflict_resolution_prompt(&[]);
5400 assert!(
5401 blocks.is_empty(),
5402 "empty conflicts should produce no blocks, got {} blocks",
5403 blocks.len()
5404 );
5405 }
5406
5407 #[test]
5408 fn test_build_conflicted_files_resolution_prompt_empty_paths() {
5409 let blocks = build_conflicted_files_resolution_prompt(&[]);
5410 assert!(
5411 blocks.is_empty(),
5412 "empty paths should produce no blocks, got {} blocks",
5413 blocks.len()
5414 );
5415 }
5416
5417 #[test]
5418 fn test_conflict_resource_block_structure() {
5419 let conflict = ConflictContent {
5420 file_path: "src/utils.rs".to_string(),
5421 conflict_text: "<<<<<<< HEAD\nold code\n=======\nnew code\n>>>>>>> branch".to_string(),
5422 ours_branch_name: "HEAD".to_string(),
5423 theirs_branch_name: "branch".to_string(),
5424 };
5425
5426 let block = conflict_resource_block(&conflict);
5427 let (text, uri) = expect_resource_block(&block);
5428
5429 assert_eq!(
5430 text, conflict.conflict_text,
5431 "resource text should be the raw conflict"
5432 );
5433 assert!(
5434 uri.starts_with("zed:///agent/merge-conflict"),
5435 "URI should use the zed merge-conflict scheme, got: {uri}"
5436 );
5437 assert!(uri.contains("utils.rs"), "URI should encode the file path");
5438 }
5439
5440 fn open_generating_thread_with_loadable_connection(
5441 panel: &Entity<AgentPanel>,
5442 connection: &StubAgentConnection,
5443 cx: &mut VisualTestContext,
5444 ) -> acp::SessionId {
5445 open_thread_with_custom_connection(panel, connection.clone(), cx);
5446 let session_id = active_session_id(panel, cx);
5447 send_message(panel, cx);
5448 cx.update(|_, cx| {
5449 connection.send_update(
5450 session_id.clone(),
5451 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("done".into())),
5452 cx,
5453 );
5454 });
5455 cx.run_until_parked();
5456 session_id
5457 }
5458
5459 fn open_idle_thread_with_non_loadable_connection(
5460 panel: &Entity<AgentPanel>,
5461 connection: &StubAgentConnection,
5462 cx: &mut VisualTestContext,
5463 ) -> acp::SessionId {
5464 open_thread_with_custom_connection(panel, connection.clone(), cx);
5465 let session_id = active_session_id(panel, cx);
5466
5467 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5468 acp::ContentChunk::new("done".into()),
5469 )]);
5470 send_message(panel, cx);
5471
5472 session_id
5473 }
5474
5475 async fn setup_panel(cx: &mut TestAppContext) -> (Entity<AgentPanel>, VisualTestContext) {
5476 init_test(cx);
5477 cx.update(|cx| {
5478 cx.update_flags(true, vec!["agent-v2".to_string()]);
5479 agent::ThreadStore::init_global(cx);
5480 language_model::LanguageModelRegistry::test(cx);
5481 });
5482
5483 let fs = FakeFs::new(cx.executor());
5484 let project = Project::test(fs.clone(), [], cx).await;
5485
5486 let multi_workspace =
5487 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5488
5489 let workspace = multi_workspace
5490 .read_with(cx, |mw, _cx| mw.workspace().clone())
5491 .unwrap();
5492
5493 let mut cx = VisualTestContext::from_window(multi_workspace.into(), cx);
5494
5495 let panel = workspace.update_in(&mut cx, |workspace, window, cx| {
5496 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5497 cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
5498 });
5499
5500 (panel, cx)
5501 }
5502
5503 #[gpui::test]
5504 async fn test_running_thread_retained_when_navigating_away(cx: &mut TestAppContext) {
5505 let (panel, mut cx) = setup_panel(cx).await;
5506
5507 let connection_a = StubAgentConnection::new();
5508 open_thread_with_connection(&panel, connection_a.clone(), &mut cx);
5509 send_message(&panel, &mut cx);
5510
5511 let session_id_a = active_session_id(&panel, &cx);
5512
5513 // Send a chunk to keep thread A generating (don't end the turn).
5514 cx.update(|_, cx| {
5515 connection_a.send_update(
5516 session_id_a.clone(),
5517 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("chunk".into())),
5518 cx,
5519 );
5520 });
5521 cx.run_until_parked();
5522
5523 // Verify thread A is generating.
5524 panel.read_with(&cx, |panel, cx| {
5525 let thread = panel.active_agent_thread(cx).unwrap();
5526 assert_eq!(thread.read(cx).status(), ThreadStatus::Generating);
5527 assert!(panel.background_threads.is_empty());
5528 });
5529
5530 // Open a new thread B — thread A should be retained in background.
5531 let connection_b = StubAgentConnection::new();
5532 open_thread_with_connection(&panel, connection_b, &mut cx);
5533
5534 panel.read_with(&cx, |panel, _cx| {
5535 assert_eq!(
5536 panel.background_threads.len(),
5537 1,
5538 "Running thread A should be retained in background_views"
5539 );
5540 assert!(
5541 panel.background_threads.contains_key(&session_id_a),
5542 "Background view should be keyed by thread A's session ID"
5543 );
5544 });
5545 }
5546
5547 #[gpui::test]
5548 async fn test_idle_non_loadable_thread_retained_when_navigating_away(cx: &mut TestAppContext) {
5549 let (panel, mut cx) = setup_panel(cx).await;
5550
5551 let connection_a = StubAgentConnection::new();
5552 connection_a.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5553 acp::ContentChunk::new("Response".into()),
5554 )]);
5555 open_thread_with_connection(&panel, connection_a, &mut cx);
5556 send_message(&panel, &mut cx);
5557
5558 let weak_view_a = panel.read_with(&cx, |panel, _cx| {
5559 panel.active_conversation_view().unwrap().downgrade()
5560 });
5561 let session_id_a = active_session_id(&panel, &cx);
5562
5563 // Thread A should be idle (auto-completed via set_next_prompt_updates).
5564 panel.read_with(&cx, |panel, cx| {
5565 let thread = panel.active_agent_thread(cx).unwrap();
5566 assert_eq!(thread.read(cx).status(), ThreadStatus::Idle);
5567 });
5568
5569 // Open a new thread B — thread A should be retained because it is not loadable.
5570 let connection_b = StubAgentConnection::new();
5571 open_thread_with_connection(&panel, connection_b, &mut cx);
5572
5573 panel.read_with(&cx, |panel, _cx| {
5574 assert_eq!(
5575 panel.background_threads.len(),
5576 1,
5577 "Idle non-loadable thread A should be retained in background_views"
5578 );
5579 assert!(
5580 panel.background_threads.contains_key(&session_id_a),
5581 "Background view should be keyed by thread A's session ID"
5582 );
5583 });
5584
5585 assert!(
5586 weak_view_a.upgrade().is_some(),
5587 "Idle non-loadable ConnectionView should still be retained"
5588 );
5589 }
5590
5591 #[gpui::test]
5592 async fn test_background_thread_promoted_via_load(cx: &mut TestAppContext) {
5593 let (panel, mut cx) = setup_panel(cx).await;
5594
5595 let connection_a = StubAgentConnection::new();
5596 open_thread_with_connection(&panel, connection_a.clone(), &mut cx);
5597 send_message(&panel, &mut cx);
5598
5599 let session_id_a = active_session_id(&panel, &cx);
5600
5601 // Keep thread A generating.
5602 cx.update(|_, cx| {
5603 connection_a.send_update(
5604 session_id_a.clone(),
5605 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("chunk".into())),
5606 cx,
5607 );
5608 });
5609 cx.run_until_parked();
5610
5611 // Open thread B — thread A goes to background.
5612 let connection_b = StubAgentConnection::new();
5613 open_thread_with_connection(&panel, connection_b, &mut cx);
5614
5615 let session_id_b = active_session_id(&panel, &cx);
5616
5617 panel.read_with(&cx, |panel, _cx| {
5618 assert_eq!(panel.background_threads.len(), 1);
5619 assert!(panel.background_threads.contains_key(&session_id_a));
5620 });
5621
5622 // Load thread A back via load_agent_thread — should promote from background.
5623 panel.update_in(&mut cx, |panel, window, cx| {
5624 panel.load_agent_thread(
5625 panel.selected_agent().expect("selected agent must be set"),
5626 session_id_a.clone(),
5627 None,
5628 None,
5629 true,
5630 window,
5631 cx,
5632 );
5633 });
5634
5635 // Thread A should now be the active view, promoted from background.
5636 let active_session = active_session_id(&panel, &cx);
5637 assert_eq!(
5638 active_session, session_id_a,
5639 "Thread A should be the active thread after promotion"
5640 );
5641
5642 panel.read_with(&cx, |panel, _cx| {
5643 assert!(
5644 !panel.background_threads.contains_key(&session_id_a),
5645 "Promoted thread A should no longer be in background_views"
5646 );
5647 assert!(
5648 panel.background_threads.contains_key(&session_id_b),
5649 "Thread B (idle, non-loadable) should remain retained in background_views"
5650 );
5651 });
5652 }
5653
5654 #[gpui::test]
5655 async fn test_cleanup_background_threads_keeps_five_most_recent_idle_loadable_threads(
5656 cx: &mut TestAppContext,
5657 ) {
5658 let (panel, mut cx) = setup_panel(cx).await;
5659 let connection = StubAgentConnection::new()
5660 .with_supports_load_session(true)
5661 .with_agent_id("loadable-stub".into())
5662 .with_telemetry_id("loadable-stub".into());
5663 let mut session_ids = Vec::new();
5664
5665 for _ in 0..7 {
5666 session_ids.push(open_generating_thread_with_loadable_connection(
5667 &panel,
5668 &connection,
5669 &mut cx,
5670 ));
5671 }
5672
5673 let base_time = Instant::now();
5674
5675 for session_id in session_ids.iter().take(6) {
5676 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5677 }
5678 cx.run_until_parked();
5679
5680 panel.update(&mut cx, |panel, cx| {
5681 for (index, session_id) in session_ids.iter().take(6).enumerate() {
5682 let conversation_view = panel
5683 .background_threads
5684 .get(session_id)
5685 .expect("background thread should exist")
5686 .clone();
5687 conversation_view.update(cx, |view, cx| {
5688 view.set_updated_at(base_time + Duration::from_secs(index as u64), cx);
5689 });
5690 }
5691 panel.cleanup_background_threads(cx);
5692 });
5693
5694 panel.read_with(&cx, |panel, _cx| {
5695 assert_eq!(
5696 panel.background_threads.len(),
5697 5,
5698 "cleanup should keep at most five idle loadable background threads"
5699 );
5700 assert!(
5701 !panel.background_threads.contains_key(&session_ids[0]),
5702 "oldest idle loadable background thread should be removed"
5703 );
5704 for session_id in &session_ids[1..6] {
5705 assert!(
5706 panel.background_threads.contains_key(session_id),
5707 "more recent idle loadable background threads should be retained"
5708 );
5709 }
5710 assert!(
5711 !panel.background_threads.contains_key(&session_ids[6]),
5712 "the active thread should not also be stored as a background thread"
5713 );
5714 });
5715 }
5716
5717 #[gpui::test]
5718 async fn test_cleanup_background_threads_preserves_idle_non_loadable_threads(
5719 cx: &mut TestAppContext,
5720 ) {
5721 let (panel, mut cx) = setup_panel(cx).await;
5722
5723 let non_loadable_connection = StubAgentConnection::new();
5724 let non_loadable_session_id = open_idle_thread_with_non_loadable_connection(
5725 &panel,
5726 &non_loadable_connection,
5727 &mut cx,
5728 );
5729
5730 let loadable_connection = StubAgentConnection::new()
5731 .with_supports_load_session(true)
5732 .with_agent_id("loadable-stub".into())
5733 .with_telemetry_id("loadable-stub".into());
5734 let mut loadable_session_ids = Vec::new();
5735
5736 for _ in 0..7 {
5737 loadable_session_ids.push(open_generating_thread_with_loadable_connection(
5738 &panel,
5739 &loadable_connection,
5740 &mut cx,
5741 ));
5742 }
5743
5744 let base_time = Instant::now();
5745
5746 for session_id in loadable_session_ids.iter().take(6) {
5747 loadable_connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5748 }
5749 cx.run_until_parked();
5750
5751 panel.update(&mut cx, |panel, cx| {
5752 for (index, session_id) in loadable_session_ids.iter().take(6).enumerate() {
5753 let conversation_view = panel
5754 .background_threads
5755 .get(session_id)
5756 .expect("background thread should exist")
5757 .clone();
5758 conversation_view.update(cx, |view, cx| {
5759 view.set_updated_at(base_time + Duration::from_secs(index as u64), cx);
5760 });
5761 }
5762 panel.cleanup_background_threads(cx);
5763 });
5764
5765 panel.read_with(&cx, |panel, _cx| {
5766 assert_eq!(
5767 panel.background_threads.len(),
5768 6,
5769 "cleanup should keep the non-loadable idle thread in addition to five loadable ones"
5770 );
5771 assert!(
5772 panel
5773 .background_threads
5774 .contains_key(&non_loadable_session_id),
5775 "idle non-loadable background threads should not be cleanup candidates"
5776 );
5777 assert!(
5778 !panel
5779 .background_threads
5780 .contains_key(&loadable_session_ids[0]),
5781 "oldest idle loadable background thread should still be removed"
5782 );
5783 for session_id in &loadable_session_ids[1..6] {
5784 assert!(
5785 panel.background_threads.contains_key(session_id),
5786 "more recent idle loadable background threads should be retained"
5787 );
5788 }
5789 assert!(
5790 !panel
5791 .background_threads
5792 .contains_key(&loadable_session_ids[6]),
5793 "the active loadable thread should not also be stored as a background thread"
5794 );
5795 });
5796 }
5797
5798 #[gpui::test]
5799 async fn test_thread_target_local_project(cx: &mut TestAppContext) {
5800 init_test(cx);
5801 cx.update(|cx| {
5802 cx.update_flags(true, vec!["agent-v2".to_string()]);
5803 agent::ThreadStore::init_global(cx);
5804 language_model::LanguageModelRegistry::test(cx);
5805 });
5806
5807 let fs = FakeFs::new(cx.executor());
5808 fs.insert_tree(
5809 "/project",
5810 json!({
5811 ".git": {},
5812 "src": {
5813 "main.rs": "fn main() {}"
5814 }
5815 }),
5816 )
5817 .await;
5818 fs.set_branch_name(Path::new("/project/.git"), Some("main"));
5819
5820 let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
5821
5822 let multi_workspace =
5823 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5824
5825 let workspace = multi_workspace
5826 .read_with(cx, |multi_workspace, _cx| {
5827 multi_workspace.workspace().clone()
5828 })
5829 .unwrap();
5830
5831 workspace.update(cx, |workspace, _cx| {
5832 workspace.set_random_database_id();
5833 });
5834
5835 let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5836
5837 // Wait for the project to discover the git repository.
5838 cx.run_until_parked();
5839
5840 let panel = workspace.update_in(cx, |workspace, window, cx| {
5841 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5842 let panel =
5843 cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
5844 workspace.add_panel(panel.clone(), window, cx);
5845 panel
5846 });
5847
5848 cx.run_until_parked();
5849
5850 // Default thread target should be LocalProject.
5851 panel.read_with(cx, |panel, _cx| {
5852 assert_eq!(
5853 *panel.start_thread_in(),
5854 StartThreadIn::LocalProject,
5855 "default thread target should be LocalProject"
5856 );
5857 });
5858
5859 // Start a new thread with the default LocalProject target.
5860 // Use StubAgentServer so the thread connects immediately in tests.
5861 panel.update_in(cx, |panel, window, cx| {
5862 panel.open_external_thread_with_server(
5863 Rc::new(StubAgentServer::default_response()),
5864 window,
5865 cx,
5866 );
5867 });
5868
5869 cx.run_until_parked();
5870
5871 // MultiWorkspace should still have exactly one workspace (no worktree created).
5872 multi_workspace
5873 .read_with(cx, |multi_workspace, _cx| {
5874 assert_eq!(
5875 multi_workspace.workspaces().len(),
5876 1,
5877 "LocalProject should not create a new workspace"
5878 );
5879 })
5880 .unwrap();
5881
5882 // The thread should be active in the panel.
5883 panel.read_with(cx, |panel, cx| {
5884 assert!(
5885 panel.active_agent_thread(cx).is_some(),
5886 "a thread should be running in the current workspace"
5887 );
5888 });
5889
5890 // The thread target should still be LocalProject (unchanged).
5891 panel.read_with(cx, |panel, _cx| {
5892 assert_eq!(
5893 *panel.start_thread_in(),
5894 StartThreadIn::LocalProject,
5895 "thread target should remain LocalProject"
5896 );
5897 });
5898
5899 // No worktree creation status should be set.
5900 panel.read_with(cx, |panel, _cx| {
5901 assert!(
5902 panel.worktree_creation_status.is_none(),
5903 "no worktree creation should have occurred"
5904 );
5905 });
5906 }
5907
5908 #[gpui::test]
5909 async fn test_thread_target_serialization_round_trip(cx: &mut TestAppContext) {
5910 init_test(cx);
5911 cx.update(|cx| {
5912 cx.update_flags(true, vec!["agent-v2".to_string()]);
5913 agent::ThreadStore::init_global(cx);
5914 language_model::LanguageModelRegistry::test(cx);
5915 });
5916
5917 let fs = FakeFs::new(cx.executor());
5918 fs.insert_tree(
5919 "/project",
5920 json!({
5921 ".git": {},
5922 "src": {
5923 "main.rs": "fn main() {}"
5924 }
5925 }),
5926 )
5927 .await;
5928 fs.set_branch_name(Path::new("/project/.git"), Some("main"));
5929
5930 let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
5931
5932 let multi_workspace =
5933 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5934
5935 let workspace = multi_workspace
5936 .read_with(cx, |multi_workspace, _cx| {
5937 multi_workspace.workspace().clone()
5938 })
5939 .unwrap();
5940
5941 workspace.update(cx, |workspace, _cx| {
5942 workspace.set_random_database_id();
5943 });
5944
5945 let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5946
5947 // Wait for the project to discover the git repository.
5948 cx.run_until_parked();
5949
5950 let panel = workspace.update_in(cx, |workspace, window, cx| {
5951 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5952 let panel =
5953 cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
5954 workspace.add_panel(panel.clone(), window, cx);
5955 panel
5956 });
5957
5958 cx.run_until_parked();
5959
5960 // Default should be LocalProject.
5961 panel.read_with(cx, |panel, _cx| {
5962 assert_eq!(*panel.start_thread_in(), StartThreadIn::LocalProject);
5963 });
5964
5965 // Change thread target to NewWorktree.
5966 panel.update_in(cx, |panel, window, cx| {
5967 panel.set_start_thread_in(&StartThreadIn::NewWorktree, window, cx);
5968 });
5969
5970 panel.read_with(cx, |panel, _cx| {
5971 assert_eq!(
5972 *panel.start_thread_in(),
5973 StartThreadIn::NewWorktree,
5974 "thread target should be NewWorktree after set_thread_target"
5975 );
5976 });
5977
5978 // Let serialization complete.
5979 cx.run_until_parked();
5980
5981 // Load a fresh panel from the serialized data.
5982 let prompt_builder = Arc::new(prompt_store::PromptBuilder::new(None).unwrap());
5983 let async_cx = cx.update(|window, cx| window.to_async(cx));
5984 let loaded_panel =
5985 AgentPanel::load(workspace.downgrade(), prompt_builder.clone(), async_cx)
5986 .await
5987 .expect("panel load should succeed");
5988 cx.run_until_parked();
5989
5990 loaded_panel.read_with(cx, |panel, _cx| {
5991 assert_eq!(
5992 *panel.start_thread_in(),
5993 StartThreadIn::NewWorktree,
5994 "thread target should survive serialization round-trip"
5995 );
5996 });
5997 }
5998
5999 #[gpui::test]
6000 async fn test_set_active_blocked_during_worktree_creation(cx: &mut TestAppContext) {
6001 init_test(cx);
6002
6003 let fs = FakeFs::new(cx.executor());
6004 cx.update(|cx| {
6005 cx.update_flags(true, vec!["agent-v2".to_string()]);
6006 agent::ThreadStore::init_global(cx);
6007 language_model::LanguageModelRegistry::test(cx);
6008 <dyn fs::Fs>::set_global(fs.clone(), cx);
6009 });
6010
6011 fs.insert_tree(
6012 "/project",
6013 json!({
6014 ".git": {},
6015 "src": {
6016 "main.rs": "fn main() {}"
6017 }
6018 }),
6019 )
6020 .await;
6021
6022 let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
6023
6024 let multi_workspace =
6025 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6026
6027 let workspace = multi_workspace
6028 .read_with(cx, |multi_workspace, _cx| {
6029 multi_workspace.workspace().clone()
6030 })
6031 .unwrap();
6032
6033 let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
6034
6035 let panel = workspace.update_in(cx, |workspace, window, cx| {
6036 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
6037 let panel =
6038 cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
6039 workspace.add_panel(panel.clone(), window, cx);
6040 panel
6041 });
6042
6043 cx.run_until_parked();
6044
6045 // Simulate worktree creation in progress and reset to Uninitialized
6046 panel.update_in(cx, |panel, window, cx| {
6047 panel.worktree_creation_status = Some(WorktreeCreationStatus::Creating);
6048 panel.active_view = ActiveView::Uninitialized;
6049 Panel::set_active(panel, true, window, cx);
6050 assert!(
6051 matches!(panel.active_view, ActiveView::Uninitialized),
6052 "set_active should not create a thread while worktree is being created"
6053 );
6054 });
6055
6056 // Clear the creation status and use open_external_thread_with_server
6057 // (which bypasses new_agent_thread) to verify the panel can transition
6058 // out of Uninitialized. We can't call set_active directly because
6059 // new_agent_thread requires full agent server infrastructure.
6060 panel.update_in(cx, |panel, window, cx| {
6061 panel.worktree_creation_status = None;
6062 panel.active_view = ActiveView::Uninitialized;
6063 panel.open_external_thread_with_server(
6064 Rc::new(StubAgentServer::default_response()),
6065 window,
6066 cx,
6067 );
6068 });
6069
6070 cx.run_until_parked();
6071
6072 panel.read_with(cx, |panel, _cx| {
6073 assert!(
6074 !matches!(panel.active_view, ActiveView::Uninitialized),
6075 "panel should transition out of Uninitialized once worktree creation is cleared"
6076 );
6077 });
6078 }
6079
6080 #[test]
6081 fn test_deserialize_agent_type_variants() {
6082 assert_eq!(
6083 serde_json::from_str::<AgentType>(r#""NativeAgent""#).unwrap(),
6084 AgentType::NativeAgent,
6085 );
6086 assert_eq!(
6087 serde_json::from_str::<AgentType>(r#""TextThread""#).unwrap(),
6088 AgentType::TextThread,
6089 );
6090 assert_eq!(
6091 serde_json::from_str::<AgentType>(r#"{"Custom":{"name":"my-agent"}}"#).unwrap(),
6092 AgentType::Custom {
6093 id: "my-agent".into(),
6094 },
6095 );
6096 }
6097
6098 #[gpui::test]
6099 async fn test_worktree_creation_preserves_selected_agent(cx: &mut TestAppContext) {
6100 init_test(cx);
6101
6102 let app_state = cx.update(|cx| {
6103 cx.update_flags(true, vec!["agent-v2".to_string()]);
6104 agent::ThreadStore::init_global(cx);
6105 language_model::LanguageModelRegistry::test(cx);
6106
6107 let app_state = workspace::AppState::test(cx);
6108 workspace::init(app_state.clone(), cx);
6109 app_state
6110 });
6111
6112 let fs = app_state.fs.as_fake();
6113 fs.insert_tree(
6114 "/project",
6115 json!({
6116 ".git": {},
6117 "src": {
6118 "main.rs": "fn main() {}"
6119 }
6120 }),
6121 )
6122 .await;
6123 fs.set_branch_name(Path::new("/project/.git"), Some("main"));
6124
6125 let project = Project::test(app_state.fs.clone(), [Path::new("/project")], cx).await;
6126
6127 let multi_workspace =
6128 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6129
6130 let workspace = multi_workspace
6131 .read_with(cx, |multi_workspace, _cx| {
6132 multi_workspace.workspace().clone()
6133 })
6134 .unwrap();
6135
6136 workspace.update(cx, |workspace, _cx| {
6137 workspace.set_random_database_id();
6138 });
6139
6140 // Register a callback so new workspaces also get an AgentPanel.
6141 cx.update(|cx| {
6142 cx.observe_new(
6143 |workspace: &mut Workspace,
6144 window: Option<&mut Window>,
6145 cx: &mut Context<Workspace>| {
6146 if let Some(window) = window {
6147 let project = workspace.project().clone();
6148 let text_thread_store =
6149 cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
6150 let panel = cx.new(|cx| {
6151 AgentPanel::new(workspace, text_thread_store, None, window, cx)
6152 });
6153 workspace.add_panel(panel, window, cx);
6154 }
6155 },
6156 )
6157 .detach();
6158 });
6159
6160 let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
6161
6162 // Wait for the project to discover the git repository.
6163 cx.run_until_parked();
6164
6165 let panel = workspace.update_in(cx, |workspace, window, cx| {
6166 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
6167 let panel =
6168 cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
6169 workspace.add_panel(panel.clone(), window, cx);
6170 panel
6171 });
6172
6173 cx.run_until_parked();
6174
6175 // Open a thread (needed so there's an active thread view).
6176 panel.update_in(cx, |panel, window, cx| {
6177 panel.open_external_thread_with_server(
6178 Rc::new(StubAgentServer::default_response()),
6179 window,
6180 cx,
6181 );
6182 });
6183
6184 cx.run_until_parked();
6185
6186 // Set the selected agent to Codex (a custom agent) and start_thread_in
6187 // to NewWorktree. We do this AFTER opening the thread because
6188 // open_external_thread_with_server overrides selected_agent_type.
6189 panel.update_in(cx, |panel, window, cx| {
6190 panel.selected_agent_type = AgentType::Custom {
6191 id: CODEX_ID.into(),
6192 };
6193 panel.set_start_thread_in(&StartThreadIn::NewWorktree, window, cx);
6194 });
6195
6196 // Verify the panel has the Codex agent selected.
6197 panel.read_with(cx, |panel, _cx| {
6198 assert_eq!(
6199 panel.selected_agent_type,
6200 AgentType::Custom {
6201 id: CODEX_ID.into()
6202 },
6203 );
6204 });
6205
6206 // Directly call handle_worktree_creation_requested, which is what
6207 // handle_first_send_requested does when start_thread_in == NewWorktree.
6208 let content = vec![acp::ContentBlock::Text(acp::TextContent::new(
6209 "Hello from test",
6210 ))];
6211 panel.update_in(cx, |panel, window, cx| {
6212 panel.handle_worktree_creation_requested(content, window, cx);
6213 });
6214
6215 // Let the async worktree creation + workspace setup complete.
6216 cx.run_until_parked();
6217
6218 // Find the new workspace's AgentPanel and verify it used the Codex agent.
6219 let found_codex = multi_workspace
6220 .read_with(cx, |multi_workspace, cx| {
6221 // There should be more than one workspace now (the original + the new worktree).
6222 assert!(
6223 multi_workspace.workspaces().len() > 1,
6224 "expected a new workspace to have been created, found {}",
6225 multi_workspace.workspaces().len(),
6226 );
6227
6228 // Check the newest workspace's panel for the correct agent.
6229 let new_workspace = multi_workspace
6230 .workspaces()
6231 .iter()
6232 .find(|ws| ws.entity_id() != workspace.entity_id())
6233 .expect("should find the new workspace");
6234 let new_panel = new_workspace
6235 .read(cx)
6236 .panel::<AgentPanel>(cx)
6237 .expect("new workspace should have an AgentPanel");
6238
6239 new_panel.read(cx).selected_agent_type.clone()
6240 })
6241 .unwrap();
6242
6243 assert_eq!(
6244 found_codex,
6245 AgentType::Custom {
6246 id: CODEX_ID.into()
6247 },
6248 "the new worktree workspace should use the same agent (Codex) that was selected in the original panel",
6249 );
6250 }
6251
6252 /// Regression test: NewThread must produce a connected thread even when
6253 /// the PromptStore fails to initialize (e.g. LMDB permission error).
6254 /// Before the fix, `NativeAgentServer::connect` propagated the
6255 /// PromptStore error with `?`, which put every new ConversationView
6256 /// into LoadError and made it impossible to start any native-agent
6257 /// thread.
6258 #[gpui::test]
6259 async fn test_new_thread_with_prompt_store_error(cx: &mut TestAppContext) {
6260 let (panel, mut cx) = setup_panel(cx).await;
6261
6262 // NativeAgentServer::connect needs a global Fs.
6263 let fs = FakeFs::new(cx.executor());
6264 cx.update(|_, cx| {
6265 <dyn fs::Fs>::set_global(fs.clone(), cx);
6266 });
6267 cx.run_until_parked();
6268
6269 // Dispatch NewThread, which goes through the real NativeAgentServer
6270 // path. In tests the PromptStore LMDB open fails with
6271 // "Permission denied"; the fix (.log_err() instead of ?) lets
6272 // the connection succeed anyway.
6273 panel.update_in(&mut cx, |panel, window, cx| {
6274 panel.new_thread(&NewThread, window, cx);
6275 });
6276 cx.run_until_parked();
6277
6278 panel.read_with(&cx, |panel, cx| {
6279 assert!(
6280 panel.active_conversation_view().is_some(),
6281 "panel should have a conversation view after NewThread"
6282 );
6283 assert!(
6284 panel.active_agent_thread(cx).is_some(),
6285 "panel should have an active, connected agent thread"
6286 );
6287 });
6288 }
6289}