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