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