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 branch name: all typewriter names are taken"
2832 .into(),
2833 window,
2834 cx,
2835 );
2836 })?;
2837 return anyhow::Ok(());
2838 }
2839 };
2840
2841 let (creation_infos, path_remapping) = match this.update_in(cx, |_this, _window, cx| {
2842 Self::start_worktree_creations(
2843 &git_repos,
2844 &branch_name,
2845 &worktree_directory_setting,
2846 cx,
2847 )
2848 }) {
2849 Ok(Ok(result)) => result,
2850 Ok(Err(err)) | Err(err) => {
2851 this.update_in(cx, |this, window, cx| {
2852 this.set_worktree_creation_error(
2853 format!("Failed to validate worktree directory: {err}").into(),
2854 window,
2855 cx,
2856 );
2857 })
2858 .log_err();
2859 return anyhow::Ok(());
2860 }
2861 };
2862
2863 let created_paths = match Self::await_and_rollback_on_failure(creation_infos, cx).await
2864 {
2865 Ok(paths) => paths,
2866 Err(err) => {
2867 this.update_in(cx, |this, window, cx| {
2868 this.set_worktree_creation_error(format!("{err}").into(), window, cx);
2869 })?;
2870 return anyhow::Ok(());
2871 }
2872 };
2873
2874 let mut all_paths = created_paths;
2875 let has_non_git = !non_git_paths.is_empty();
2876 all_paths.extend(non_git_paths.iter().cloned());
2877
2878 let app_state = match workspace.upgrade() {
2879 Some(workspace) => cx.update(|_, cx| workspace.read(cx).app_state().clone())?,
2880 None => {
2881 this.update_in(cx, |this, window, cx| {
2882 this.set_worktree_creation_error(
2883 "Workspace no longer available".into(),
2884 window,
2885 cx,
2886 );
2887 })?;
2888 return anyhow::Ok(());
2889 }
2890 };
2891
2892 let this_for_error = this.clone();
2893 if let Err(err) = Self::setup_new_workspace(
2894 this,
2895 all_paths,
2896 app_state,
2897 window_handle,
2898 active_file_path,
2899 path_remapping,
2900 non_git_paths,
2901 has_non_git,
2902 content,
2903 selected_agent,
2904 cx,
2905 )
2906 .await
2907 {
2908 this_for_error
2909 .update_in(cx, |this, window, cx| {
2910 this.set_worktree_creation_error(
2911 format!("Failed to set up workspace: {err}").into(),
2912 window,
2913 cx,
2914 );
2915 })
2916 .log_err();
2917 }
2918 anyhow::Ok(())
2919 });
2920
2921 self._worktree_creation_task = Some(cx.foreground_executor().spawn(async move {
2922 task.await.log_err();
2923 }));
2924 }
2925
2926 async fn setup_new_workspace(
2927 this: WeakEntity<Self>,
2928 all_paths: Vec<PathBuf>,
2929 app_state: Arc<workspace::AppState>,
2930 window_handle: Option<gpui::WindowHandle<workspace::MultiWorkspace>>,
2931 active_file_path: Option<PathBuf>,
2932 path_remapping: Vec<(PathBuf, PathBuf)>,
2933 non_git_paths: Vec<PathBuf>,
2934 has_non_git: bool,
2935 content: Vec<acp::ContentBlock>,
2936 selected_agent: Option<Agent>,
2937 cx: &mut AsyncWindowContext,
2938 ) -> Result<()> {
2939 let OpenResult {
2940 window: new_window_handle,
2941 workspace: new_workspace,
2942 ..
2943 } = cx
2944 .update(|_window, cx| {
2945 Workspace::new_local(all_paths, app_state, window_handle, None, None, false, cx)
2946 })?
2947 .await?;
2948
2949 let panels_task = new_window_handle.update(cx, |_, _, cx| {
2950 new_workspace.update(cx, |workspace, _cx| workspace.take_panels_task())
2951 })?;
2952 if let Some(task) = panels_task {
2953 task.await.log_err();
2954 }
2955
2956 let initial_content = AgentInitialContent::ContentBlock {
2957 blocks: content,
2958 auto_submit: true,
2959 };
2960
2961 new_window_handle.update(cx, |_multi_workspace, window, cx| {
2962 new_workspace.update(cx, |workspace, cx| {
2963 if has_non_git {
2964 let toast_id = workspace::notifications::NotificationId::unique::<AgentPanel>();
2965 workspace.show_toast(
2966 workspace::Toast::new(
2967 toast_id,
2968 "Some project folders are not git repositories. \
2969 They were included as-is without creating a worktree.",
2970 ),
2971 cx,
2972 );
2973 }
2974
2975 // If we had an active buffer, remap its path and reopen it.
2976 let should_zoom_agent_panel = active_file_path.is_none();
2977
2978 let remapped_active_path = active_file_path.and_then(|original_path| {
2979 let best_match = path_remapping
2980 .iter()
2981 .filter_map(|(old_root, new_root)| {
2982 original_path.strip_prefix(old_root).ok().map(|relative| {
2983 (old_root.components().count(), new_root.join(relative))
2984 })
2985 })
2986 .max_by_key(|(depth, _)| *depth);
2987
2988 if let Some((_, remapped_path)) = best_match {
2989 return Some(remapped_path);
2990 }
2991
2992 for non_git in &non_git_paths {
2993 if original_path.starts_with(non_git) {
2994 return Some(original_path);
2995 }
2996 }
2997 None
2998 });
2999
3000 if !should_zoom_agent_panel && remapped_active_path.is_none() {
3001 log::warn!(
3002 "Active file could not be remapped to the new worktree; it will not be reopened"
3003 );
3004 }
3005
3006 if let Some(path) = remapped_active_path {
3007 let open_task = workspace.open_paths(
3008 vec![path],
3009 workspace::OpenOptions::default(),
3010 None,
3011 window,
3012 cx,
3013 );
3014 cx.spawn(async move |_, _| -> anyhow::Result<()> {
3015 for item in open_task.await.into_iter().flatten() {
3016 item?;
3017 }
3018 Ok(())
3019 })
3020 .detach_and_log_err(cx);
3021 }
3022
3023 workspace.focus_panel::<AgentPanel>(window, cx);
3024
3025 // If no active buffer was open, zoom the agent panel
3026 // (equivalent to cmd-esc fullscreen behavior).
3027 // This must happen after focus_panel, which activates
3028 // and opens the panel in the dock.
3029 if should_zoom_agent_panel {
3030 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3031 panel.update(cx, |_panel, cx| {
3032 cx.emit(PanelEvent::ZoomIn);
3033 });
3034 }
3035 }
3036 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3037 panel.update(cx, |panel, cx| {
3038 panel.external_thread(
3039 selected_agent,
3040 None,
3041 None,
3042 None,
3043 Some(initial_content),
3044 true,
3045 window,
3046 cx,
3047 );
3048 });
3049 }
3050 });
3051 })?;
3052
3053 new_window_handle.update(cx, |multi_workspace, _window, cx| {
3054 multi_workspace.activate(new_workspace.clone(), cx);
3055 })?;
3056
3057 this.update_in(cx, |this, window, cx| {
3058 this.worktree_creation_status = None;
3059
3060 if let Some(thread_view) = this.active_thread_view(cx) {
3061 thread_view.update(cx, |thread_view, cx| {
3062 thread_view
3063 .message_editor
3064 .update(cx, |editor, cx| editor.clear(window, cx));
3065 });
3066 }
3067
3068 cx.notify();
3069 })?;
3070
3071 anyhow::Ok(())
3072 }
3073}
3074
3075impl Focusable for AgentPanel {
3076 fn focus_handle(&self, cx: &App) -> FocusHandle {
3077 match &self.active_view {
3078 ActiveView::Uninitialized => self.focus_handle.clone(),
3079 ActiveView::AgentThread {
3080 conversation_view, ..
3081 } => conversation_view.focus_handle(cx),
3082 ActiveView::History { history: kind } => match kind {
3083 History::AgentThreads { view } => view.read(cx).focus_handle(cx),
3084 History::TextThreads => self.text_thread_history.focus_handle(cx),
3085 },
3086 ActiveView::TextThread {
3087 text_thread_editor, ..
3088 } => text_thread_editor.focus_handle(cx),
3089 ActiveView::Configuration => {
3090 if let Some(configuration) = self.configuration.as_ref() {
3091 configuration.focus_handle(cx)
3092 } else {
3093 self.focus_handle.clone()
3094 }
3095 }
3096 }
3097 }
3098}
3099
3100fn agent_panel_dock_position(cx: &App) -> DockPosition {
3101 AgentSettings::get_global(cx).dock.into()
3102}
3103
3104pub enum AgentPanelEvent {
3105 ActiveViewChanged,
3106 ThreadFocused,
3107 BackgroundThreadChanged,
3108}
3109
3110impl EventEmitter<PanelEvent> for AgentPanel {}
3111impl EventEmitter<AgentPanelEvent> for AgentPanel {}
3112
3113impl Panel for AgentPanel {
3114 fn persistent_name() -> &'static str {
3115 "AgentPanel"
3116 }
3117
3118 fn panel_key() -> &'static str {
3119 AGENT_PANEL_KEY
3120 }
3121
3122 fn position(&self, _window: &Window, cx: &App) -> DockPosition {
3123 agent_panel_dock_position(cx)
3124 }
3125
3126 fn position_is_valid(&self, position: DockPosition) -> bool {
3127 position != DockPosition::Bottom
3128 }
3129
3130 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3131 settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
3132 settings
3133 .agent
3134 .get_or_insert_default()
3135 .set_dock(position.into());
3136 });
3137 }
3138
3139 fn size(&self, window: &Window, cx: &App) -> Pixels {
3140 let settings = AgentSettings::get_global(cx);
3141 match self.position(window, cx) {
3142 DockPosition::Left | DockPosition::Right => {
3143 self.width.unwrap_or(settings.default_width)
3144 }
3145 DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
3146 }
3147 }
3148
3149 fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
3150 match self.position(window, cx) {
3151 DockPosition::Left | DockPosition::Right => self.width = size,
3152 DockPosition::Bottom => self.height = size,
3153 }
3154 self.serialize(cx);
3155 cx.notify();
3156 }
3157
3158 fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
3159 if active
3160 && matches!(self.active_view, ActiveView::Uninitialized)
3161 && !matches!(
3162 self.worktree_creation_status,
3163 Some(WorktreeCreationStatus::Creating)
3164 )
3165 {
3166 let selected_agent_type = self.selected_agent_type.clone();
3167 self.new_agent_thread_inner(selected_agent_type, false, window, cx);
3168 }
3169 }
3170
3171 fn remote_id() -> Option<proto::PanelId> {
3172 Some(proto::PanelId::AssistantPanel)
3173 }
3174
3175 fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
3176 (self.enabled(cx) && AgentSettings::get_global(cx).button).then_some(IconName::ZedAssistant)
3177 }
3178
3179 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3180 Some("Agent Panel")
3181 }
3182
3183 fn toggle_action(&self) -> Box<dyn Action> {
3184 Box::new(ToggleFocus)
3185 }
3186
3187 fn activation_priority(&self) -> u32 {
3188 3
3189 }
3190
3191 fn enabled(&self, cx: &App) -> bool {
3192 AgentSettings::get_global(cx).enabled(cx)
3193 }
3194
3195 fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
3196 self.zoomed
3197 }
3198
3199 fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, cx: &mut Context<Self>) {
3200 self.zoomed = zoomed;
3201 cx.notify();
3202 }
3203}
3204
3205impl AgentPanel {
3206 fn render_title_view(&self, _window: &mut Window, cx: &Context<Self>) -> AnyElement {
3207 const LOADING_SUMMARY_PLACEHOLDER: &str = "Loading Summary…";
3208
3209 let content = match &self.active_view {
3210 ActiveView::AgentThread { conversation_view } => {
3211 let server_view_ref = conversation_view.read(cx);
3212 let is_generating_title = server_view_ref.as_native_thread(cx).is_some()
3213 && server_view_ref.root_thread(cx).map_or(false, |tv| {
3214 tv.read(cx).thread.read(cx).has_provisional_title()
3215 });
3216
3217 if let Some(title_editor) = server_view_ref
3218 .root_thread(cx)
3219 .map(|r| r.read(cx).title_editor.clone())
3220 {
3221 if is_generating_title {
3222 Label::new(DEFAULT_THREAD_TITLE)
3223 .color(Color::Muted)
3224 .truncate()
3225 .with_animation(
3226 "generating_title",
3227 Animation::new(Duration::from_secs(2))
3228 .repeat()
3229 .with_easing(pulsating_between(0.4, 0.8)),
3230 |label, delta| label.alpha(delta),
3231 )
3232 .into_any_element()
3233 } else {
3234 div()
3235 .w_full()
3236 .on_action({
3237 let conversation_view = conversation_view.downgrade();
3238 move |_: &menu::Confirm, window, cx| {
3239 if let Some(conversation_view) = conversation_view.upgrade() {
3240 conversation_view.focus_handle(cx).focus(window, cx);
3241 }
3242 }
3243 })
3244 .on_action({
3245 let conversation_view = conversation_view.downgrade();
3246 move |_: &editor::actions::Cancel, window, cx| {
3247 if let Some(conversation_view) = conversation_view.upgrade() {
3248 conversation_view.focus_handle(cx).focus(window, cx);
3249 }
3250 }
3251 })
3252 .child(title_editor)
3253 .into_any_element()
3254 }
3255 } else {
3256 Label::new(conversation_view.read(cx).title(cx))
3257 .color(Color::Muted)
3258 .truncate()
3259 .into_any_element()
3260 }
3261 }
3262 ActiveView::TextThread {
3263 title_editor,
3264 text_thread_editor,
3265 ..
3266 } => {
3267 let summary = text_thread_editor.read(cx).text_thread().read(cx).summary();
3268
3269 match summary {
3270 TextThreadSummary::Pending => Label::new(TextThreadSummary::DEFAULT)
3271 .color(Color::Muted)
3272 .truncate()
3273 .into_any_element(),
3274 TextThreadSummary::Content(summary) => {
3275 if summary.done {
3276 div()
3277 .w_full()
3278 .child(title_editor.clone())
3279 .into_any_element()
3280 } else {
3281 Label::new(LOADING_SUMMARY_PLACEHOLDER)
3282 .truncate()
3283 .color(Color::Muted)
3284 .with_animation(
3285 "generating_title",
3286 Animation::new(Duration::from_secs(2))
3287 .repeat()
3288 .with_easing(pulsating_between(0.4, 0.8)),
3289 |label, delta| label.alpha(delta),
3290 )
3291 .into_any_element()
3292 }
3293 }
3294 TextThreadSummary::Error => h_flex()
3295 .w_full()
3296 .child(title_editor.clone())
3297 .child(
3298 IconButton::new("retry-summary-generation", IconName::RotateCcw)
3299 .icon_size(IconSize::Small)
3300 .on_click({
3301 let text_thread_editor = text_thread_editor.clone();
3302 move |_, _window, cx| {
3303 text_thread_editor.update(cx, |text_thread_editor, cx| {
3304 text_thread_editor.regenerate_summary(cx);
3305 });
3306 }
3307 })
3308 .tooltip(move |_window, cx| {
3309 cx.new(|_| {
3310 Tooltip::new("Failed to generate title")
3311 .meta("Click to try again")
3312 })
3313 .into()
3314 }),
3315 )
3316 .into_any_element(),
3317 }
3318 }
3319 ActiveView::History { history: kind } => {
3320 let title = match kind {
3321 History::AgentThreads { .. } => "History",
3322 History::TextThreads => "Text Thread History",
3323 };
3324 Label::new(title).truncate().into_any_element()
3325 }
3326 ActiveView::Configuration => Label::new("Settings").truncate().into_any_element(),
3327 ActiveView::Uninitialized => Label::new("Agent").truncate().into_any_element(),
3328 };
3329
3330 h_flex()
3331 .key_context("TitleEditor")
3332 .id("TitleEditor")
3333 .flex_grow()
3334 .w_full()
3335 .max_w_full()
3336 .overflow_x_scroll()
3337 .child(content)
3338 .into_any()
3339 }
3340
3341 fn handle_regenerate_thread_title(conversation_view: Entity<ConversationView>, cx: &mut App) {
3342 conversation_view.update(cx, |conversation_view, cx| {
3343 if let Some(thread) = conversation_view.as_native_thread(cx) {
3344 thread.update(cx, |thread, cx| {
3345 thread.generate_title(cx);
3346 });
3347 }
3348 });
3349 }
3350
3351 fn handle_regenerate_text_thread_title(
3352 text_thread_editor: Entity<TextThreadEditor>,
3353 cx: &mut App,
3354 ) {
3355 text_thread_editor.update(cx, |text_thread_editor, cx| {
3356 text_thread_editor.regenerate_summary(cx);
3357 });
3358 }
3359
3360 fn render_panel_options_menu(
3361 &self,
3362 window: &mut Window,
3363 cx: &mut Context<Self>,
3364 ) -> impl IntoElement {
3365 let focus_handle = self.focus_handle(cx);
3366
3367 let full_screen_label = if self.is_zoomed(window, cx) {
3368 "Disable Full Screen"
3369 } else {
3370 "Enable Full Screen"
3371 };
3372
3373 let text_thread_view = match &self.active_view {
3374 ActiveView::TextThread {
3375 text_thread_editor, ..
3376 } => Some(text_thread_editor.clone()),
3377 _ => None,
3378 };
3379 let text_thread_with_messages = match &self.active_view {
3380 ActiveView::TextThread {
3381 text_thread_editor, ..
3382 } => text_thread_editor
3383 .read(cx)
3384 .text_thread()
3385 .read(cx)
3386 .messages(cx)
3387 .any(|message| message.role == language_model::Role::Assistant),
3388 _ => false,
3389 };
3390
3391 let conversation_view = match &self.active_view {
3392 ActiveView::AgentThread { conversation_view } => Some(conversation_view.clone()),
3393 _ => None,
3394 };
3395 let thread_with_messages = match &self.active_view {
3396 ActiveView::AgentThread { conversation_view } => {
3397 conversation_view.read(cx).has_user_submitted_prompt(cx)
3398 }
3399 _ => false,
3400 };
3401 let has_auth_methods = match &self.active_view {
3402 ActiveView::AgentThread { conversation_view } => {
3403 conversation_view.read(cx).has_auth_methods()
3404 }
3405 _ => false,
3406 };
3407
3408 PopoverMenu::new("agent-options-menu")
3409 .trigger_with_tooltip(
3410 IconButton::new("agent-options-menu", IconName::Ellipsis)
3411 .icon_size(IconSize::Small),
3412 {
3413 let focus_handle = focus_handle.clone();
3414 move |_window, cx| {
3415 Tooltip::for_action_in(
3416 "Toggle Agent Menu",
3417 &ToggleOptionsMenu,
3418 &focus_handle,
3419 cx,
3420 )
3421 }
3422 },
3423 )
3424 .anchor(Corner::TopRight)
3425 .with_handle(self.agent_panel_menu_handle.clone())
3426 .menu({
3427 move |window, cx| {
3428 Some(ContextMenu::build(window, cx, |mut menu, _window, _| {
3429 menu = menu.context(focus_handle.clone());
3430
3431 if thread_with_messages | text_thread_with_messages {
3432 menu = menu.header("Current Thread");
3433
3434 if let Some(text_thread_view) = text_thread_view.as_ref() {
3435 menu = menu
3436 .entry("Regenerate Thread Title", None, {
3437 let text_thread_view = text_thread_view.clone();
3438 move |_, cx| {
3439 Self::handle_regenerate_text_thread_title(
3440 text_thread_view.clone(),
3441 cx,
3442 );
3443 }
3444 })
3445 .separator();
3446 }
3447
3448 if let Some(conversation_view) = conversation_view.as_ref() {
3449 menu = menu
3450 .entry("Regenerate Thread Title", None, {
3451 let conversation_view = conversation_view.clone();
3452 move |_, cx| {
3453 Self::handle_regenerate_thread_title(
3454 conversation_view.clone(),
3455 cx,
3456 );
3457 }
3458 })
3459 .separator();
3460 }
3461 }
3462
3463 menu = menu
3464 .header("MCP Servers")
3465 .action(
3466 "View Server Extensions",
3467 Box::new(zed_actions::Extensions {
3468 category_filter: Some(
3469 zed_actions::ExtensionCategoryFilter::ContextServers,
3470 ),
3471 id: None,
3472 }),
3473 )
3474 .action("Add Custom Server…", Box::new(AddContextServer))
3475 .separator()
3476 .action("Rules", Box::new(OpenRulesLibrary::default()))
3477 .action("Profiles", Box::new(ManageProfiles::default()))
3478 .action("Settings", Box::new(OpenSettings))
3479 .separator()
3480 .action("Toggle Threads Sidebar", Box::new(ToggleWorkspaceSidebar))
3481 .action(full_screen_label, Box::new(ToggleZoom));
3482
3483 if has_auth_methods {
3484 menu = menu.action("Reauthenticate", Box::new(ReauthenticateAgent))
3485 }
3486
3487 menu
3488 }))
3489 }
3490 })
3491 }
3492
3493 fn render_recent_entries_menu(
3494 &self,
3495 icon: IconName,
3496 corner: Corner,
3497 cx: &mut Context<Self>,
3498 ) -> impl IntoElement {
3499 let focus_handle = self.focus_handle(cx);
3500
3501 PopoverMenu::new("agent-nav-menu")
3502 .trigger_with_tooltip(
3503 IconButton::new("agent-nav-menu", icon).icon_size(IconSize::Small),
3504 {
3505 move |_window, cx| {
3506 Tooltip::for_action_in(
3507 "Toggle Recently Updated Threads",
3508 &ToggleNavigationMenu,
3509 &focus_handle,
3510 cx,
3511 )
3512 }
3513 },
3514 )
3515 .anchor(corner)
3516 .with_handle(self.agent_navigation_menu_handle.clone())
3517 .menu({
3518 let menu = self.agent_navigation_menu.clone();
3519 move |window, cx| {
3520 telemetry::event!("View Thread History Clicked");
3521
3522 if let Some(menu) = menu.as_ref() {
3523 menu.update(cx, |_, cx| {
3524 cx.defer_in(window, |menu, window, cx| {
3525 menu.rebuild(window, cx);
3526 });
3527 })
3528 }
3529 menu.clone()
3530 }
3531 })
3532 }
3533
3534 fn render_toolbar_back_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3535 let focus_handle = self.focus_handle(cx);
3536
3537 IconButton::new("go-back", IconName::ArrowLeft)
3538 .icon_size(IconSize::Small)
3539 .on_click(cx.listener(|this, _, window, cx| {
3540 this.go_back(&workspace::GoBack, window, cx);
3541 }))
3542 .tooltip({
3543 move |_window, cx| {
3544 Tooltip::for_action_in("Go Back", &workspace::GoBack, &focus_handle, cx)
3545 }
3546 })
3547 }
3548
3549 fn project_has_git_repository(&self, cx: &App) -> bool {
3550 !self.project.read(cx).repositories(cx).is_empty()
3551 }
3552
3553 fn render_start_thread_in_selector(&self, cx: &mut Context<Self>) -> impl IntoElement {
3554 use settings::{NewThreadLocation, Settings};
3555
3556 let focus_handle = self.focus_handle(cx);
3557 let has_git_repo = self.project_has_git_repository(cx);
3558 let is_via_collab = self.project.read(cx).is_via_collab();
3559 let fs = self.fs.clone();
3560
3561 let is_creating = matches!(
3562 self.worktree_creation_status,
3563 Some(WorktreeCreationStatus::Creating)
3564 );
3565
3566 let current_target = self.start_thread_in;
3567 let trigger_label = self.start_thread_in.label();
3568
3569 let new_thread_location = AgentSettings::get_global(cx).new_thread_location;
3570 let is_local_default = new_thread_location == NewThreadLocation::LocalProject;
3571 let is_new_worktree_default = new_thread_location == NewThreadLocation::NewWorktree;
3572
3573 let icon = if self.start_thread_in_menu_handle.is_deployed() {
3574 IconName::ChevronUp
3575 } else {
3576 IconName::ChevronDown
3577 };
3578
3579 let trigger_button = Button::new("thread-target-trigger", trigger_label)
3580 .end_icon(Icon::new(icon).size(IconSize::XSmall).color(Color::Muted))
3581 .disabled(is_creating);
3582
3583 let dock_position = AgentSettings::get_global(cx).dock;
3584 let documentation_side = match dock_position {
3585 settings::DockPosition::Left => DocumentationSide::Right,
3586 settings::DockPosition::Bottom | settings::DockPosition::Right => {
3587 DocumentationSide::Left
3588 }
3589 };
3590
3591 PopoverMenu::new("thread-target-selector")
3592 .trigger_with_tooltip(trigger_button, {
3593 move |_window, cx| {
3594 Tooltip::for_action_in(
3595 "Start Thread In…",
3596 &CycleStartThreadIn,
3597 &focus_handle,
3598 cx,
3599 )
3600 }
3601 })
3602 .menu(move |window, cx| {
3603 let is_local_selected = current_target == StartThreadIn::LocalProject;
3604 let is_new_worktree_selected = current_target == StartThreadIn::NewWorktree;
3605 let fs = fs.clone();
3606
3607 Some(ContextMenu::build(window, cx, move |menu, _window, _cx| {
3608 let new_worktree_disabled = !has_git_repo || is_via_collab;
3609
3610 menu.header("Start Thread In…")
3611 .item(
3612 ContextMenuEntry::new("Current Worktree")
3613 .toggleable(IconPosition::End, is_local_selected)
3614 .documentation_aside(documentation_side, move |_| {
3615 HoldForDefault::new(is_local_default)
3616 .more_content(false)
3617 .into_any_element()
3618 })
3619 .handler({
3620 let fs = fs.clone();
3621 move |window, cx| {
3622 if window.modifiers().secondary() {
3623 update_settings_file(fs.clone(), cx, |settings, _| {
3624 settings
3625 .agent
3626 .get_or_insert_default()
3627 .set_new_thread_location(
3628 NewThreadLocation::LocalProject,
3629 );
3630 });
3631 }
3632 window.dispatch_action(
3633 Box::new(StartThreadIn::LocalProject),
3634 cx,
3635 );
3636 }
3637 }),
3638 )
3639 .item({
3640 let entry = ContextMenuEntry::new("New Git Worktree")
3641 .toggleable(IconPosition::End, is_new_worktree_selected)
3642 .disabled(new_worktree_disabled)
3643 .handler({
3644 let fs = fs.clone();
3645 move |window, cx| {
3646 if window.modifiers().secondary() {
3647 update_settings_file(fs.clone(), cx, |settings, _| {
3648 settings
3649 .agent
3650 .get_or_insert_default()
3651 .set_new_thread_location(
3652 NewThreadLocation::NewWorktree,
3653 );
3654 });
3655 }
3656 window.dispatch_action(
3657 Box::new(StartThreadIn::NewWorktree),
3658 cx,
3659 );
3660 }
3661 });
3662
3663 if new_worktree_disabled {
3664 entry.documentation_aside(documentation_side, move |_| {
3665 let reason = if !has_git_repo {
3666 "No git repository found in this project."
3667 } else {
3668 "Not available for remote/collab projects yet."
3669 };
3670 Label::new(reason)
3671 .color(Color::Muted)
3672 .size(LabelSize::Small)
3673 .into_any_element()
3674 })
3675 } else {
3676 entry.documentation_aside(documentation_side, move |_| {
3677 HoldForDefault::new(is_new_worktree_default)
3678 .more_content(false)
3679 .into_any_element()
3680 })
3681 }
3682 })
3683 }))
3684 })
3685 .with_handle(self.start_thread_in_menu_handle.clone())
3686 .anchor(Corner::TopLeft)
3687 .offset(gpui::Point {
3688 x: px(1.0),
3689 y: px(1.0),
3690 })
3691 }
3692
3693 fn render_toolbar(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3694 let agent_server_store = self.project.read(cx).agent_server_store().clone();
3695 let has_visible_worktrees = self.project.read(cx).visible_worktrees(cx).next().is_some();
3696 let focus_handle = self.focus_handle(cx);
3697
3698 let (selected_agent_custom_icon, selected_agent_label) =
3699 if let AgentType::Custom { id, .. } = &self.selected_agent_type {
3700 let store = agent_server_store.read(cx);
3701 let icon = store.agent_icon(&id);
3702
3703 let label = store
3704 .agent_display_name(&id)
3705 .unwrap_or_else(|| self.selected_agent_type.label());
3706 (icon, label)
3707 } else {
3708 (None, self.selected_agent_type.label())
3709 };
3710
3711 let active_thread = match &self.active_view {
3712 ActiveView::AgentThread { conversation_view } => {
3713 conversation_view.read(cx).as_native_thread(cx)
3714 }
3715 ActiveView::Uninitialized
3716 | ActiveView::TextThread { .. }
3717 | ActiveView::History { .. }
3718 | ActiveView::Configuration => None,
3719 };
3720
3721 let new_thread_menu_builder: Rc<
3722 dyn Fn(&mut Window, &mut App) -> Option<Entity<ContextMenu>>,
3723 > = {
3724 let selected_agent = self.selected_agent_type.clone();
3725 let is_agent_selected = move |agent_type: AgentType| selected_agent == agent_type;
3726
3727 let workspace = self.workspace.clone();
3728 let is_via_collab = workspace
3729 .update(cx, |workspace, cx| {
3730 workspace.project().read(cx).is_via_collab()
3731 })
3732 .unwrap_or_default();
3733
3734 let focus_handle = focus_handle.clone();
3735 let agent_server_store = agent_server_store;
3736
3737 Rc::new(move |window, cx| {
3738 telemetry::event!("New Thread Clicked");
3739
3740 let active_thread = active_thread.clone();
3741 Some(ContextMenu::build(window, cx, |menu, _window, cx| {
3742 menu.context(focus_handle.clone())
3743 .when_some(active_thread, |this, active_thread| {
3744 let thread = active_thread.read(cx);
3745
3746 if !thread.is_empty() {
3747 let session_id = thread.id().clone();
3748 this.item(
3749 ContextMenuEntry::new("New From Summary")
3750 .icon(IconName::ThreadFromSummary)
3751 .icon_color(Color::Muted)
3752 .handler(move |window, cx| {
3753 window.dispatch_action(
3754 Box::new(NewNativeAgentThreadFromSummary {
3755 from_session_id: session_id.clone(),
3756 }),
3757 cx,
3758 );
3759 }),
3760 )
3761 } else {
3762 this
3763 }
3764 })
3765 .item(
3766 ContextMenuEntry::new("Zed Agent")
3767 .when(
3768 is_agent_selected(AgentType::NativeAgent)
3769 | is_agent_selected(AgentType::TextThread),
3770 |this| {
3771 this.action(Box::new(NewExternalAgentThread {
3772 agent: None,
3773 }))
3774 },
3775 )
3776 .icon(IconName::ZedAgent)
3777 .icon_color(Color::Muted)
3778 .handler({
3779 let workspace = workspace.clone();
3780 move |window, cx| {
3781 if let Some(workspace) = workspace.upgrade() {
3782 workspace.update(cx, |workspace, cx| {
3783 if let Some(panel) =
3784 workspace.panel::<AgentPanel>(cx)
3785 {
3786 panel.update(cx, |panel, cx| {
3787 panel.new_agent_thread(
3788 AgentType::NativeAgent,
3789 window,
3790 cx,
3791 );
3792 });
3793 }
3794 });
3795 }
3796 }
3797 }),
3798 )
3799 .item(
3800 ContextMenuEntry::new("Text Thread")
3801 .action(NewTextThread.boxed_clone())
3802 .icon(IconName::TextThread)
3803 .icon_color(Color::Muted)
3804 .handler({
3805 let workspace = workspace.clone();
3806 move |window, cx| {
3807 if let Some(workspace) = workspace.upgrade() {
3808 workspace.update(cx, |workspace, cx| {
3809 if let Some(panel) =
3810 workspace.panel::<AgentPanel>(cx)
3811 {
3812 panel.update(cx, |panel, cx| {
3813 panel.new_agent_thread(
3814 AgentType::TextThread,
3815 window,
3816 cx,
3817 );
3818 });
3819 }
3820 });
3821 }
3822 }
3823 }),
3824 )
3825 .separator()
3826 .header("External Agents")
3827 .map(|mut menu| {
3828 let agent_server_store = agent_server_store.read(cx);
3829 let registry_store = project::AgentRegistryStore::try_global(cx);
3830 let registry_store_ref = registry_store.as_ref().map(|s| s.read(cx));
3831
3832 struct AgentMenuItem {
3833 id: AgentId,
3834 display_name: SharedString,
3835 }
3836
3837 let agent_items = agent_server_store
3838 .external_agents()
3839 .map(|agent_id| {
3840 let display_name = agent_server_store
3841 .agent_display_name(agent_id)
3842 .or_else(|| {
3843 registry_store_ref
3844 .as_ref()
3845 .and_then(|store| store.agent(agent_id))
3846 .map(|a| a.name().clone())
3847 })
3848 .unwrap_or_else(|| agent_id.0.clone());
3849 AgentMenuItem {
3850 id: agent_id.clone(),
3851 display_name,
3852 }
3853 })
3854 .sorted_unstable_by_key(|e| e.display_name.to_lowercase())
3855 .collect::<Vec<_>>();
3856
3857 for item in &agent_items {
3858 let mut entry = ContextMenuEntry::new(item.display_name.clone());
3859
3860 let icon_path =
3861 agent_server_store.agent_icon(&item.id).or_else(|| {
3862 registry_store_ref
3863 .as_ref()
3864 .and_then(|store| store.agent(&item.id))
3865 .and_then(|a| a.icon_path().cloned())
3866 });
3867
3868 if let Some(icon_path) = icon_path {
3869 entry = entry.custom_icon_svg(icon_path);
3870 } else {
3871 entry = entry.icon(IconName::Sparkle);
3872 }
3873
3874 entry = entry
3875 .when(
3876 is_agent_selected(AgentType::Custom {
3877 id: item.id.clone(),
3878 }),
3879 |this| {
3880 this.action(Box::new(NewExternalAgentThread {
3881 agent: None,
3882 }))
3883 },
3884 )
3885 .icon_color(Color::Muted)
3886 .disabled(is_via_collab)
3887 .handler({
3888 let workspace = workspace.clone();
3889 let agent_id = item.id.clone();
3890 move |window, cx| {
3891 if let Some(workspace) = workspace.upgrade() {
3892 workspace.update(cx, |workspace, cx| {
3893 if let Some(panel) =
3894 workspace.panel::<AgentPanel>(cx)
3895 {
3896 panel.update(cx, |panel, cx| {
3897 panel.new_agent_thread(
3898 AgentType::Custom {
3899 id: agent_id.clone(),
3900 },
3901 window,
3902 cx,
3903 );
3904 });
3905 }
3906 });
3907 }
3908 }
3909 });
3910
3911 menu = menu.item(entry);
3912 }
3913
3914 menu
3915 })
3916 .separator()
3917 .item(
3918 ContextMenuEntry::new("Add More Agents")
3919 .icon(IconName::Plus)
3920 .icon_color(Color::Muted)
3921 .handler({
3922 move |window, cx| {
3923 window
3924 .dispatch_action(Box::new(zed_actions::AcpRegistry), cx)
3925 }
3926 }),
3927 )
3928 }))
3929 })
3930 };
3931
3932 let is_thread_loading = self
3933 .active_conversation_view()
3934 .map(|thread| thread.read(cx).is_loading())
3935 .unwrap_or(false);
3936
3937 let has_custom_icon = selected_agent_custom_icon.is_some();
3938 let selected_agent_custom_icon_for_button = selected_agent_custom_icon.clone();
3939 let selected_agent_builtin_icon = self.selected_agent_type.icon();
3940 let selected_agent_label_for_tooltip = selected_agent_label.clone();
3941
3942 let selected_agent = div()
3943 .id("selected_agent_icon")
3944 .when_some(selected_agent_custom_icon, |this, icon_path| {
3945 this.px_1()
3946 .child(Icon::from_external_svg(icon_path).color(Color::Muted))
3947 })
3948 .when(!has_custom_icon, |this| {
3949 this.when_some(self.selected_agent_type.icon(), |this, icon| {
3950 this.px_1().child(Icon::new(icon).color(Color::Muted))
3951 })
3952 })
3953 .tooltip(move |_, cx| {
3954 Tooltip::with_meta(
3955 selected_agent_label_for_tooltip.clone(),
3956 None,
3957 "Selected Agent",
3958 cx,
3959 )
3960 });
3961
3962 let selected_agent = if is_thread_loading {
3963 selected_agent
3964 .with_animation(
3965 "pulsating-icon",
3966 Animation::new(Duration::from_secs(1))
3967 .repeat()
3968 .with_easing(pulsating_between(0.2, 0.6)),
3969 |icon, delta| icon.opacity(delta),
3970 )
3971 .into_any_element()
3972 } else {
3973 selected_agent.into_any_element()
3974 };
3975
3976 let show_history_menu = self.has_history_for_selected_agent(cx);
3977 let has_v2_flag = cx.has_flag::<AgentV2FeatureFlag>();
3978 let is_empty_state = !self.active_thread_has_messages(cx);
3979
3980 let is_in_history_or_config = matches!(
3981 &self.active_view,
3982 ActiveView::History { .. } | ActiveView::Configuration
3983 );
3984
3985 let is_text_thread = matches!(&self.active_view, ActiveView::TextThread { .. });
3986
3987 let use_v2_empty_toolbar =
3988 has_v2_flag && is_empty_state && !is_in_history_or_config && !is_text_thread;
3989
3990 let base_container = h_flex()
3991 .id("agent-panel-toolbar")
3992 .h(Tab::container_height(cx))
3993 .max_w_full()
3994 .flex_none()
3995 .justify_between()
3996 .gap_2()
3997 .bg(cx.theme().colors().tab_bar_background)
3998 .border_b_1()
3999 .border_color(cx.theme().colors().border);
4000
4001 if use_v2_empty_toolbar {
4002 let (chevron_icon, icon_color, label_color) =
4003 if self.new_thread_menu_handle.is_deployed() {
4004 (IconName::ChevronUp, Color::Accent, Color::Accent)
4005 } else {
4006 (IconName::ChevronDown, Color::Muted, Color::Default)
4007 };
4008
4009 let agent_icon = if let Some(icon_path) = selected_agent_custom_icon_for_button {
4010 Icon::from_external_svg(icon_path)
4011 .size(IconSize::Small)
4012 .color(icon_color)
4013 } else {
4014 let icon_name = selected_agent_builtin_icon.unwrap_or(IconName::ZedAgent);
4015 Icon::new(icon_name).size(IconSize::Small).color(icon_color)
4016 };
4017
4018 let agent_selector_button = Button::new("agent-selector-trigger", selected_agent_label)
4019 .start_icon(agent_icon)
4020 .color(label_color)
4021 .end_icon(
4022 Icon::new(chevron_icon)
4023 .color(icon_color)
4024 .size(IconSize::XSmall),
4025 );
4026
4027 let agent_selector_menu = PopoverMenu::new("new_thread_menu")
4028 .trigger_with_tooltip(agent_selector_button, {
4029 move |_window, cx| {
4030 Tooltip::for_action_in(
4031 "New Thread\u{2026}",
4032 &ToggleNewThreadMenu,
4033 &focus_handle,
4034 cx,
4035 )
4036 }
4037 })
4038 .menu({
4039 let builder = new_thread_menu_builder.clone();
4040 move |window, cx| builder(window, cx)
4041 })
4042 .with_handle(self.new_thread_menu_handle.clone())
4043 .anchor(Corner::TopLeft)
4044 .offset(gpui::Point {
4045 x: px(1.0),
4046 y: px(1.0),
4047 });
4048
4049 base_container
4050 .child(
4051 h_flex()
4052 .size_full()
4053 .gap(DynamicSpacing::Base04.rems(cx))
4054 .pl(DynamicSpacing::Base04.rems(cx))
4055 .child(agent_selector_menu)
4056 .when(
4057 has_visible_worktrees && self.project_has_git_repository(cx),
4058 |this| this.child(self.render_start_thread_in_selector(cx)),
4059 ),
4060 )
4061 .child(
4062 h_flex()
4063 .h_full()
4064 .flex_none()
4065 .gap_1()
4066 .pl_1()
4067 .pr_1()
4068 .when(show_history_menu && !has_v2_flag, |this| {
4069 this.child(self.render_recent_entries_menu(
4070 IconName::MenuAltTemp,
4071 Corner::TopRight,
4072 cx,
4073 ))
4074 })
4075 .child(self.render_panel_options_menu(window, cx)),
4076 )
4077 .into_any_element()
4078 } else {
4079 let new_thread_menu = PopoverMenu::new("new_thread_menu")
4080 .trigger_with_tooltip(
4081 IconButton::new("new_thread_menu_btn", IconName::Plus)
4082 .icon_size(IconSize::Small),
4083 {
4084 move |_window, cx| {
4085 Tooltip::for_action_in(
4086 "New Thread\u{2026}",
4087 &ToggleNewThreadMenu,
4088 &focus_handle,
4089 cx,
4090 )
4091 }
4092 },
4093 )
4094 .anchor(Corner::TopRight)
4095 .with_handle(self.new_thread_menu_handle.clone())
4096 .menu(move |window, cx| new_thread_menu_builder(window, cx));
4097
4098 base_container
4099 .child(
4100 h_flex()
4101 .size_full()
4102 .gap(DynamicSpacing::Base04.rems(cx))
4103 .pl(DynamicSpacing::Base04.rems(cx))
4104 .child(match &self.active_view {
4105 ActiveView::History { .. } | ActiveView::Configuration => {
4106 self.render_toolbar_back_button(cx).into_any_element()
4107 }
4108 _ => selected_agent.into_any_element(),
4109 })
4110 .child(self.render_title_view(window, cx)),
4111 )
4112 .child(
4113 h_flex()
4114 .h_full()
4115 .flex_none()
4116 .gap_1()
4117 .pl_1()
4118 .pr_1()
4119 .child(new_thread_menu)
4120 .when(show_history_menu && !has_v2_flag, |this| {
4121 this.child(self.render_recent_entries_menu(
4122 IconName::MenuAltTemp,
4123 Corner::TopRight,
4124 cx,
4125 ))
4126 })
4127 .child(self.render_panel_options_menu(window, cx)),
4128 )
4129 .into_any_element()
4130 }
4131 }
4132
4133 fn render_worktree_creation_status(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4134 let status = self.worktree_creation_status.as_ref()?;
4135 match status {
4136 WorktreeCreationStatus::Creating => Some(
4137 h_flex()
4138 .absolute()
4139 .bottom_12()
4140 .w_full()
4141 .p_2()
4142 .gap_1()
4143 .justify_center()
4144 .bg(cx.theme().colors().editor_background)
4145 .child(
4146 Icon::new(IconName::LoadCircle)
4147 .size(IconSize::Small)
4148 .color(Color::Muted)
4149 .with_rotate_animation(3),
4150 )
4151 .child(
4152 Label::new("Creating Worktree…")
4153 .color(Color::Muted)
4154 .size(LabelSize::Small),
4155 )
4156 .into_any_element(),
4157 ),
4158 WorktreeCreationStatus::Error(message) => Some(
4159 Callout::new()
4160 .icon(IconName::Warning)
4161 .severity(Severity::Warning)
4162 .title(message.clone())
4163 .into_any_element(),
4164 ),
4165 }
4166 }
4167
4168 fn should_render_trial_end_upsell(&self, cx: &mut Context<Self>) -> bool {
4169 if TrialEndUpsell::dismissed(cx) {
4170 return false;
4171 }
4172
4173 match &self.active_view {
4174 ActiveView::TextThread { .. } => {
4175 if LanguageModelRegistry::global(cx)
4176 .read(cx)
4177 .default_model()
4178 .is_some_and(|model| {
4179 model.provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
4180 })
4181 {
4182 return false;
4183 }
4184 }
4185 ActiveView::Uninitialized
4186 | ActiveView::AgentThread { .. }
4187 | ActiveView::History { .. }
4188 | ActiveView::Configuration => return false,
4189 }
4190
4191 let plan = self.user_store.read(cx).plan();
4192 let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
4193
4194 plan.is_some_and(|plan| plan == Plan::ZedFree) && has_previous_trial
4195 }
4196
4197 fn should_render_onboarding(&self, cx: &mut Context<Self>) -> bool {
4198 if self.on_boarding_upsell_dismissed.load(Ordering::Acquire) {
4199 return false;
4200 }
4201
4202 let user_store = self.user_store.read(cx);
4203
4204 if user_store.plan().is_some_and(|plan| plan == Plan::ZedPro)
4205 && user_store
4206 .subscription_period()
4207 .and_then(|period| period.0.checked_add_days(chrono::Days::new(1)))
4208 .is_some_and(|date| date < chrono::Utc::now())
4209 {
4210 OnboardingUpsell::set_dismissed(true, cx);
4211 self.on_boarding_upsell_dismissed
4212 .store(true, Ordering::Release);
4213 return false;
4214 }
4215
4216 let has_configured_non_zed_providers = LanguageModelRegistry::read_global(cx)
4217 .visible_providers()
4218 .iter()
4219 .any(|provider| {
4220 provider.is_authenticated(cx)
4221 && provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
4222 });
4223
4224 match &self.active_view {
4225 ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {
4226 false
4227 }
4228 ActiveView::AgentThread {
4229 conversation_view, ..
4230 } if conversation_view.read(cx).as_native_thread(cx).is_none() => false,
4231 ActiveView::AgentThread { conversation_view } => {
4232 let history_is_empty = conversation_view
4233 .read(cx)
4234 .history()
4235 .is_none_or(|h| h.read(cx).is_empty());
4236 history_is_empty || !has_configured_non_zed_providers
4237 }
4238 ActiveView::TextThread { .. } => {
4239 let history_is_empty = self.text_thread_history.read(cx).is_empty();
4240 history_is_empty || !has_configured_non_zed_providers
4241 }
4242 }
4243 }
4244
4245 fn render_onboarding(
4246 &self,
4247 _window: &mut Window,
4248 cx: &mut Context<Self>,
4249 ) -> Option<impl IntoElement> {
4250 if !self.should_render_onboarding(cx) {
4251 return None;
4252 }
4253
4254 let text_thread_view = matches!(&self.active_view, ActiveView::TextThread { .. });
4255
4256 Some(
4257 div()
4258 .when(text_thread_view, |this| {
4259 this.bg(cx.theme().colors().editor_background)
4260 })
4261 .child(self.onboarding.clone()),
4262 )
4263 }
4264
4265 fn render_trial_end_upsell(
4266 &self,
4267 _window: &mut Window,
4268 cx: &mut Context<Self>,
4269 ) -> Option<impl IntoElement> {
4270 if !self.should_render_trial_end_upsell(cx) {
4271 return None;
4272 }
4273
4274 Some(
4275 v_flex()
4276 .absolute()
4277 .inset_0()
4278 .size_full()
4279 .bg(cx.theme().colors().panel_background)
4280 .opacity(0.85)
4281 .block_mouse_except_scroll()
4282 .child(EndTrialUpsell::new(Arc::new({
4283 let this = cx.entity();
4284 move |_, cx| {
4285 this.update(cx, |_this, cx| {
4286 TrialEndUpsell::set_dismissed(true, cx);
4287 cx.notify();
4288 });
4289 }
4290 }))),
4291 )
4292 }
4293
4294 fn emit_configuration_error_telemetry_if_needed(
4295 &mut self,
4296 configuration_error: Option<&ConfigurationError>,
4297 ) {
4298 let error_kind = configuration_error.map(|err| match err {
4299 ConfigurationError::NoProvider => "no_provider",
4300 ConfigurationError::ModelNotFound => "model_not_found",
4301 ConfigurationError::ProviderNotAuthenticated(_) => "provider_not_authenticated",
4302 });
4303
4304 let error_kind_string = error_kind.map(String::from);
4305
4306 if self.last_configuration_error_telemetry == error_kind_string {
4307 return;
4308 }
4309
4310 self.last_configuration_error_telemetry = error_kind_string;
4311
4312 if let Some(kind) = error_kind {
4313 let message = configuration_error
4314 .map(|err| err.to_string())
4315 .unwrap_or_default();
4316
4317 telemetry::event!("Agent Panel Error Shown", kind = kind, message = message,);
4318 }
4319 }
4320
4321 fn render_configuration_error(
4322 &self,
4323 border_bottom: bool,
4324 configuration_error: &ConfigurationError,
4325 focus_handle: &FocusHandle,
4326 cx: &mut App,
4327 ) -> impl IntoElement {
4328 let zed_provider_configured = AgentSettings::get_global(cx)
4329 .default_model
4330 .as_ref()
4331 .is_some_and(|selection| selection.provider.0.as_str() == "zed.dev");
4332
4333 let callout = if zed_provider_configured {
4334 Callout::new()
4335 .icon(IconName::Warning)
4336 .severity(Severity::Warning)
4337 .when(border_bottom, |this| {
4338 this.border_position(ui::BorderPosition::Bottom)
4339 })
4340 .title("Sign in to continue using Zed as your LLM provider.")
4341 .actions_slot(
4342 Button::new("sign_in", "Sign In")
4343 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
4344 .label_size(LabelSize::Small)
4345 .on_click({
4346 let workspace = self.workspace.clone();
4347 move |_, _, cx| {
4348 let Ok(client) =
4349 workspace.update(cx, |workspace, _| workspace.client().clone())
4350 else {
4351 return;
4352 };
4353
4354 cx.spawn(async move |cx| {
4355 client.sign_in_with_optional_connect(true, cx).await
4356 })
4357 .detach_and_log_err(cx);
4358 }
4359 }),
4360 )
4361 } else {
4362 Callout::new()
4363 .icon(IconName::Warning)
4364 .severity(Severity::Warning)
4365 .when(border_bottom, |this| {
4366 this.border_position(ui::BorderPosition::Bottom)
4367 })
4368 .title(configuration_error.to_string())
4369 .actions_slot(
4370 Button::new("settings", "Configure")
4371 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
4372 .label_size(LabelSize::Small)
4373 .key_binding(
4374 KeyBinding::for_action_in(&OpenSettings, focus_handle, cx)
4375 .map(|kb| kb.size(rems_from_px(12.))),
4376 )
4377 .on_click(|_event, window, cx| {
4378 window.dispatch_action(OpenSettings.boxed_clone(), cx)
4379 }),
4380 )
4381 };
4382
4383 match configuration_error {
4384 ConfigurationError::ModelNotFound
4385 | ConfigurationError::ProviderNotAuthenticated(_)
4386 | ConfigurationError::NoProvider => callout.into_any_element(),
4387 }
4388 }
4389
4390 fn render_text_thread(
4391 &self,
4392 text_thread_editor: &Entity<TextThreadEditor>,
4393 buffer_search_bar: &Entity<BufferSearchBar>,
4394 window: &mut Window,
4395 cx: &mut Context<Self>,
4396 ) -> Div {
4397 let mut registrar = buffer_search::DivRegistrar::new(
4398 |this, _, _cx| match &this.active_view {
4399 ActiveView::TextThread {
4400 buffer_search_bar, ..
4401 } => Some(buffer_search_bar.clone()),
4402 _ => None,
4403 },
4404 cx,
4405 );
4406 BufferSearchBar::register(&mut registrar);
4407 registrar
4408 .into_div()
4409 .size_full()
4410 .relative()
4411 .map(|parent| {
4412 buffer_search_bar.update(cx, |buffer_search_bar, cx| {
4413 if buffer_search_bar.is_dismissed() {
4414 return parent;
4415 }
4416 parent.child(
4417 div()
4418 .p(DynamicSpacing::Base08.rems(cx))
4419 .border_b_1()
4420 .border_color(cx.theme().colors().border_variant)
4421 .bg(cx.theme().colors().editor_background)
4422 .child(buffer_search_bar.render(window, cx)),
4423 )
4424 })
4425 })
4426 .child(text_thread_editor.clone())
4427 .child(self.render_drag_target(cx))
4428 }
4429
4430 fn render_drag_target(&self, cx: &Context<Self>) -> Div {
4431 let is_local = self.project.read(cx).is_local();
4432 div()
4433 .invisible()
4434 .absolute()
4435 .top_0()
4436 .right_0()
4437 .bottom_0()
4438 .left_0()
4439 .bg(cx.theme().colors().drop_target_background)
4440 .drag_over::<DraggedTab>(|this, _, _, _| this.visible())
4441 .drag_over::<DraggedSelection>(|this, _, _, _| this.visible())
4442 .when(is_local, |this| {
4443 this.drag_over::<ExternalPaths>(|this, _, _, _| this.visible())
4444 })
4445 .on_drop(cx.listener(move |this, tab: &DraggedTab, window, cx| {
4446 let item = tab.pane.read(cx).item_for_index(tab.ix);
4447 let project_paths = item
4448 .and_then(|item| item.project_path(cx))
4449 .into_iter()
4450 .collect::<Vec<_>>();
4451 this.handle_drop(project_paths, vec![], window, cx);
4452 }))
4453 .on_drop(
4454 cx.listener(move |this, selection: &DraggedSelection, window, cx| {
4455 let project_paths = selection
4456 .items()
4457 .filter_map(|item| this.project.read(cx).path_for_entry(item.entry_id, cx))
4458 .collect::<Vec<_>>();
4459 this.handle_drop(project_paths, vec![], window, cx);
4460 }),
4461 )
4462 .on_drop(cx.listener(move |this, paths: &ExternalPaths, window, cx| {
4463 let tasks = paths
4464 .paths()
4465 .iter()
4466 .map(|path| {
4467 Workspace::project_path_for_path(this.project.clone(), path, false, cx)
4468 })
4469 .collect::<Vec<_>>();
4470 cx.spawn_in(window, async move |this, cx| {
4471 let mut paths = vec![];
4472 let mut added_worktrees = vec![];
4473 let opened_paths = futures::future::join_all(tasks).await;
4474 for entry in opened_paths {
4475 if let Some((worktree, project_path)) = entry.log_err() {
4476 added_worktrees.push(worktree);
4477 paths.push(project_path);
4478 }
4479 }
4480 this.update_in(cx, |this, window, cx| {
4481 this.handle_drop(paths, added_worktrees, window, cx);
4482 })
4483 .ok();
4484 })
4485 .detach();
4486 }))
4487 }
4488
4489 fn handle_drop(
4490 &mut self,
4491 paths: Vec<ProjectPath>,
4492 added_worktrees: Vec<Entity<Worktree>>,
4493 window: &mut Window,
4494 cx: &mut Context<Self>,
4495 ) {
4496 match &self.active_view {
4497 ActiveView::AgentThread { conversation_view } => {
4498 conversation_view.update(cx, |conversation_view, cx| {
4499 conversation_view.insert_dragged_files(paths, added_worktrees, window, cx);
4500 });
4501 }
4502 ActiveView::TextThread {
4503 text_thread_editor, ..
4504 } => {
4505 text_thread_editor.update(cx, |text_thread_editor, cx| {
4506 TextThreadEditor::insert_dragged_files(
4507 text_thread_editor,
4508 paths,
4509 added_worktrees,
4510 window,
4511 cx,
4512 );
4513 });
4514 }
4515 ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {}
4516 }
4517 }
4518
4519 fn render_workspace_trust_message(&self, cx: &Context<Self>) -> Option<impl IntoElement> {
4520 if !self.show_trust_workspace_message {
4521 return None;
4522 }
4523
4524 let description = "To protect your system, third-party code—like MCP servers—won't run until you mark this workspace as safe.";
4525
4526 Some(
4527 Callout::new()
4528 .icon(IconName::Warning)
4529 .severity(Severity::Warning)
4530 .border_position(ui::BorderPosition::Bottom)
4531 .title("You're in Restricted Mode")
4532 .description(description)
4533 .actions_slot(
4534 Button::new("open-trust-modal", "Configure Project Trust")
4535 .label_size(LabelSize::Small)
4536 .style(ButtonStyle::Outlined)
4537 .on_click({
4538 cx.listener(move |this, _, window, cx| {
4539 this.workspace
4540 .update(cx, |workspace, cx| {
4541 workspace
4542 .show_worktree_trust_security_modal(true, window, cx)
4543 })
4544 .log_err();
4545 })
4546 }),
4547 ),
4548 )
4549 }
4550
4551 fn key_context(&self) -> KeyContext {
4552 let mut key_context = KeyContext::new_with_defaults();
4553 key_context.add("AgentPanel");
4554 match &self.active_view {
4555 ActiveView::AgentThread { .. } => key_context.add("acp_thread"),
4556 ActiveView::TextThread { .. } => key_context.add("text_thread"),
4557 ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {}
4558 }
4559 key_context
4560 }
4561}
4562
4563impl Render for AgentPanel {
4564 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4565 // WARNING: Changes to this element hierarchy can have
4566 // non-obvious implications to the layout of children.
4567 //
4568 // If you need to change it, please confirm:
4569 // - The message editor expands (cmd-option-esc) correctly
4570 // - When expanded, the buttons at the bottom of the panel are displayed correctly
4571 // - Font size works as expected and can be changed with cmd-+/cmd-
4572 // - Scrolling in all views works as expected
4573 // - Files can be dropped into the panel
4574 let content = v_flex()
4575 .relative()
4576 .size_full()
4577 .justify_between()
4578 .key_context(self.key_context())
4579 .on_action(cx.listener(|this, action: &NewThread, window, cx| {
4580 this.new_thread(action, window, cx);
4581 }))
4582 .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
4583 this.open_history(window, cx);
4584 }))
4585 .on_action(cx.listener(|this, _: &OpenSettings, window, cx| {
4586 this.open_configuration(window, cx);
4587 }))
4588 .on_action(cx.listener(Self::open_active_thread_as_markdown))
4589 .on_action(cx.listener(Self::deploy_rules_library))
4590 .on_action(cx.listener(Self::go_back))
4591 .on_action(cx.listener(Self::toggle_navigation_menu))
4592 .on_action(cx.listener(Self::toggle_options_menu))
4593 .on_action(cx.listener(Self::increase_font_size))
4594 .on_action(cx.listener(Self::decrease_font_size))
4595 .on_action(cx.listener(Self::reset_font_size))
4596 .on_action(cx.listener(Self::toggle_zoom))
4597 .on_action(cx.listener(|this, _: &ReauthenticateAgent, window, cx| {
4598 if let Some(conversation_view) = this.active_conversation_view() {
4599 conversation_view.update(cx, |conversation_view, cx| {
4600 conversation_view.reauthenticate(window, cx)
4601 })
4602 }
4603 }))
4604 .child(self.render_toolbar(window, cx))
4605 .children(self.render_workspace_trust_message(cx))
4606 .children(self.render_onboarding(window, cx))
4607 .map(|parent| {
4608 // Emit configuration error telemetry before entering the match to avoid borrow conflicts
4609 if matches!(&self.active_view, ActiveView::TextThread { .. }) {
4610 let model_registry = LanguageModelRegistry::read_global(cx);
4611 let configuration_error =
4612 model_registry.configuration_error(model_registry.default_model(), cx);
4613 self.emit_configuration_error_telemetry_if_needed(configuration_error.as_ref());
4614 }
4615
4616 match &self.active_view {
4617 ActiveView::Uninitialized => parent,
4618 ActiveView::AgentThread {
4619 conversation_view, ..
4620 } => parent
4621 .child(conversation_view.clone())
4622 .child(self.render_drag_target(cx)),
4623 ActiveView::History { history: kind } => match kind {
4624 History::AgentThreads { view } => parent.child(view.clone()),
4625 History::TextThreads => parent.child(self.text_thread_history.clone()),
4626 },
4627 ActiveView::TextThread {
4628 text_thread_editor,
4629 buffer_search_bar,
4630 ..
4631 } => {
4632 let model_registry = LanguageModelRegistry::read_global(cx);
4633 let configuration_error =
4634 model_registry.configuration_error(model_registry.default_model(), cx);
4635
4636 parent
4637 .map(|this| {
4638 if !self.should_render_onboarding(cx)
4639 && let Some(err) = configuration_error.as_ref()
4640 {
4641 this.child(self.render_configuration_error(
4642 true,
4643 err,
4644 &self.focus_handle(cx),
4645 cx,
4646 ))
4647 } else {
4648 this
4649 }
4650 })
4651 .child(self.render_text_thread(
4652 text_thread_editor,
4653 buffer_search_bar,
4654 window,
4655 cx,
4656 ))
4657 }
4658 ActiveView::Configuration => parent.children(self.configuration.clone()),
4659 }
4660 })
4661 .children(self.render_worktree_creation_status(cx))
4662 .children(self.render_trial_end_upsell(window, cx));
4663
4664 match self.active_view.which_font_size_used() {
4665 WhichFontSize::AgentFont => {
4666 WithRemSize::new(ThemeSettings::get_global(cx).agent_ui_font_size(cx))
4667 .size_full()
4668 .child(content)
4669 .into_any()
4670 }
4671 _ => content.into_any(),
4672 }
4673 }
4674}
4675
4676struct PromptLibraryInlineAssist {
4677 workspace: WeakEntity<Workspace>,
4678}
4679
4680impl PromptLibraryInlineAssist {
4681 pub fn new(workspace: WeakEntity<Workspace>) -> Self {
4682 Self { workspace }
4683 }
4684}
4685
4686impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
4687 fn assist(
4688 &self,
4689 prompt_editor: &Entity<Editor>,
4690 initial_prompt: Option<String>,
4691 window: &mut Window,
4692 cx: &mut Context<RulesLibrary>,
4693 ) {
4694 InlineAssistant::update_global(cx, |assistant, cx| {
4695 let Some(workspace) = self.workspace.upgrade() else {
4696 return;
4697 };
4698 let Some(panel) = workspace.read(cx).panel::<AgentPanel>(cx) else {
4699 return;
4700 };
4701 let history = panel
4702 .read(cx)
4703 .connection_store()
4704 .read(cx)
4705 .entry(&crate::Agent::NativeAgent)
4706 .and_then(|s| s.read(cx).history())
4707 .map(|h| h.downgrade());
4708 let project = workspace.read(cx).project().downgrade();
4709 let panel = panel.read(cx);
4710 let thread_store = panel.thread_store().clone();
4711 assistant.assist(
4712 prompt_editor,
4713 self.workspace.clone(),
4714 project,
4715 thread_store,
4716 None,
4717 history,
4718 initial_prompt,
4719 window,
4720 cx,
4721 );
4722 })
4723 }
4724
4725 fn focus_agent_panel(
4726 &self,
4727 workspace: &mut Workspace,
4728 window: &mut Window,
4729 cx: &mut Context<Workspace>,
4730 ) -> bool {
4731 workspace.focus_panel::<AgentPanel>(window, cx).is_some()
4732 }
4733}
4734
4735pub struct ConcreteAssistantPanelDelegate;
4736
4737impl AgentPanelDelegate for ConcreteAssistantPanelDelegate {
4738 fn active_text_thread_editor(
4739 &self,
4740 workspace: &mut Workspace,
4741 _window: &mut Window,
4742 cx: &mut Context<Workspace>,
4743 ) -> Option<Entity<TextThreadEditor>> {
4744 let panel = workspace.panel::<AgentPanel>(cx)?;
4745 panel.read(cx).active_text_thread_editor()
4746 }
4747
4748 fn open_local_text_thread(
4749 &self,
4750 workspace: &mut Workspace,
4751 path: Arc<Path>,
4752 window: &mut Window,
4753 cx: &mut Context<Workspace>,
4754 ) -> Task<Result<()>> {
4755 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
4756 return Task::ready(Err(anyhow!("Agent panel not found")));
4757 };
4758
4759 panel.update(cx, |panel, cx| {
4760 panel.open_saved_text_thread(path, window, cx)
4761 })
4762 }
4763
4764 fn open_remote_text_thread(
4765 &self,
4766 _workspace: &mut Workspace,
4767 _text_thread_id: assistant_text_thread::TextThreadId,
4768 _window: &mut Window,
4769 _cx: &mut Context<Workspace>,
4770 ) -> Task<Result<Entity<TextThreadEditor>>> {
4771 Task::ready(Err(anyhow!("opening remote context not implemented")))
4772 }
4773
4774 fn quote_selection(
4775 &self,
4776 workspace: &mut Workspace,
4777 selection_ranges: Vec<Range<Anchor>>,
4778 buffer: Entity<MultiBuffer>,
4779 window: &mut Window,
4780 cx: &mut Context<Workspace>,
4781 ) {
4782 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
4783 return;
4784 };
4785
4786 if !panel.focus_handle(cx).contains_focused(window, cx) {
4787 workspace.toggle_panel_focus::<AgentPanel>(window, cx);
4788 }
4789
4790 panel.update(cx, |_, cx| {
4791 // Wait to create a new context until the workspace is no longer
4792 // being updated.
4793 cx.defer_in(window, move |panel, window, cx| {
4794 if let Some(conversation_view) = panel.active_conversation_view() {
4795 conversation_view.update(cx, |conversation_view, cx| {
4796 conversation_view.insert_selections(window, cx);
4797 });
4798 } else if let Some(text_thread_editor) = panel.active_text_thread_editor() {
4799 let snapshot = buffer.read(cx).snapshot(cx);
4800 let selection_ranges = selection_ranges
4801 .into_iter()
4802 .map(|range| range.to_point(&snapshot))
4803 .collect::<Vec<_>>();
4804
4805 text_thread_editor.update(cx, |text_thread_editor, cx| {
4806 text_thread_editor.quote_ranges(selection_ranges, snapshot, window, cx)
4807 });
4808 }
4809 });
4810 });
4811 }
4812
4813 fn quote_terminal_text(
4814 &self,
4815 workspace: &mut Workspace,
4816 text: String,
4817 window: &mut Window,
4818 cx: &mut Context<Workspace>,
4819 ) {
4820 let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
4821 return;
4822 };
4823
4824 if !panel.focus_handle(cx).contains_focused(window, cx) {
4825 workspace.toggle_panel_focus::<AgentPanel>(window, cx);
4826 }
4827
4828 panel.update(cx, |_, cx| {
4829 // Wait to create a new context until the workspace is no longer
4830 // being updated.
4831 cx.defer_in(window, move |panel, window, cx| {
4832 if let Some(conversation_view) = panel.active_conversation_view() {
4833 conversation_view.update(cx, |conversation_view, cx| {
4834 conversation_view.insert_terminal_text(text, window, cx);
4835 });
4836 } else if let Some(text_thread_editor) = panel.active_text_thread_editor() {
4837 text_thread_editor.update(cx, |text_thread_editor, cx| {
4838 text_thread_editor.quote_terminal_text(text, window, cx)
4839 });
4840 }
4841 });
4842 });
4843 }
4844}
4845
4846struct OnboardingUpsell;
4847
4848impl Dismissable for OnboardingUpsell {
4849 const KEY: &'static str = "dismissed-trial-upsell";
4850}
4851
4852struct TrialEndUpsell;
4853
4854impl Dismissable for TrialEndUpsell {
4855 const KEY: &'static str = "dismissed-trial-end-upsell";
4856}
4857
4858/// Test-only helper methods
4859#[cfg(any(test, feature = "test-support"))]
4860impl AgentPanel {
4861 pub fn test_new(
4862 workspace: &Workspace,
4863 text_thread_store: Entity<assistant_text_thread::TextThreadStore>,
4864 window: &mut Window,
4865 cx: &mut Context<Self>,
4866 ) -> Self {
4867 Self::new(workspace, text_thread_store, None, window, cx)
4868 }
4869
4870 /// Opens an external thread using an arbitrary AgentServer.
4871 ///
4872 /// This is a test-only helper that allows visual tests and integration tests
4873 /// to inject a stub server without modifying production code paths.
4874 /// Not compiled into production builds.
4875 pub fn open_external_thread_with_server(
4876 &mut self,
4877 server: Rc<dyn AgentServer>,
4878 window: &mut Window,
4879 cx: &mut Context<Self>,
4880 ) {
4881 let workspace = self.workspace.clone();
4882 let project = self.project.clone();
4883
4884 let ext_agent = Agent::Custom {
4885 id: server.agent_id(),
4886 };
4887
4888 self.create_agent_thread(
4889 server, None, None, None, None, workspace, project, ext_agent, true, window, cx,
4890 );
4891 }
4892
4893 /// Returns the currently active thread view, if any.
4894 ///
4895 /// This is a test-only accessor that exposes the private `active_thread_view()`
4896 /// method for test assertions. Not compiled into production builds.
4897 pub fn active_thread_view_for_tests(&self) -> Option<&Entity<ConversationView>> {
4898 self.active_conversation_view()
4899 }
4900
4901 /// Sets the start_thread_in value directly, bypassing validation.
4902 ///
4903 /// This is a test-only helper for visual tests that need to show specific
4904 /// start_thread_in states without requiring a real git repository.
4905 pub fn set_start_thread_in_for_tests(&mut self, target: StartThreadIn, cx: &mut Context<Self>) {
4906 self.start_thread_in = target;
4907 cx.notify();
4908 }
4909
4910 /// Returns the current worktree creation status.
4911 ///
4912 /// This is a test-only helper for visual tests.
4913 pub fn worktree_creation_status_for_tests(&self) -> Option<&WorktreeCreationStatus> {
4914 self.worktree_creation_status.as_ref()
4915 }
4916
4917 /// Sets the worktree creation status directly.
4918 ///
4919 /// This is a test-only helper for visual tests that need to show the
4920 /// "Creating worktree…" spinner or error banners.
4921 pub fn set_worktree_creation_status_for_tests(
4922 &mut self,
4923 status: Option<WorktreeCreationStatus>,
4924 cx: &mut Context<Self>,
4925 ) {
4926 self.worktree_creation_status = status;
4927 cx.notify();
4928 }
4929
4930 /// Opens the history view.
4931 ///
4932 /// This is a test-only helper that exposes the private `open_history()`
4933 /// method for visual tests.
4934 pub fn open_history_for_tests(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4935 self.open_history(window, cx);
4936 }
4937
4938 /// Opens the start_thread_in selector popover menu.
4939 ///
4940 /// This is a test-only helper for visual tests.
4941 pub fn open_start_thread_in_menu_for_tests(
4942 &mut self,
4943 window: &mut Window,
4944 cx: &mut Context<Self>,
4945 ) {
4946 self.start_thread_in_menu_handle.show(window, cx);
4947 }
4948
4949 /// Dismisses the start_thread_in dropdown menu.
4950 ///
4951 /// This is a test-only helper for visual tests.
4952 pub fn close_start_thread_in_menu_for_tests(&mut self, cx: &mut Context<Self>) {
4953 self.start_thread_in_menu_handle.hide(cx);
4954 }
4955}
4956
4957#[cfg(test)]
4958mod tests {
4959 use super::*;
4960 use crate::conversation_view::tests::{StubAgentServer, init_test};
4961 use crate::test_support::{
4962 active_session_id, open_thread_with_connection, open_thread_with_custom_connection,
4963 send_message,
4964 };
4965 use acp_thread::{StubAgentConnection, ThreadStatus};
4966 use agent_servers::CODEX_ID;
4967 use assistant_text_thread::TextThreadStore;
4968 use feature_flags::FeatureFlagAppExt;
4969 use fs::FakeFs;
4970 use gpui::{TestAppContext, VisualTestContext};
4971 use project::Project;
4972 use serde_json::json;
4973 use std::time::Instant;
4974 use workspace::MultiWorkspace;
4975
4976 #[gpui::test]
4977 async fn test_active_thread_serialize_and_load_round_trip(cx: &mut TestAppContext) {
4978 init_test(cx);
4979 cx.update(|cx| {
4980 cx.update_flags(true, vec!["agent-v2".to_string()]);
4981 agent::ThreadStore::init_global(cx);
4982 language_model::LanguageModelRegistry::test(cx);
4983 });
4984
4985 // --- Create a MultiWorkspace window with two workspaces ---
4986 let fs = FakeFs::new(cx.executor());
4987 let project_a = Project::test(fs.clone(), [], cx).await;
4988 let project_b = Project::test(fs, [], cx).await;
4989
4990 let multi_workspace =
4991 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
4992
4993 let workspace_a = multi_workspace
4994 .read_with(cx, |multi_workspace, _cx| {
4995 multi_workspace.workspace().clone()
4996 })
4997 .unwrap();
4998
4999 let workspace_b = multi_workspace
5000 .update(cx, |multi_workspace, window, cx| {
5001 multi_workspace.test_add_workspace(project_b.clone(), window, cx)
5002 })
5003 .unwrap();
5004
5005 workspace_a.update(cx, |workspace, _cx| {
5006 workspace.set_random_database_id();
5007 });
5008 workspace_b.update(cx, |workspace, _cx| {
5009 workspace.set_random_database_id();
5010 });
5011
5012 let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5013
5014 // --- Set up workspace A: width=300, with an active thread ---
5015 let panel_a = workspace_a.update_in(cx, |workspace, window, cx| {
5016 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project_a.clone(), cx));
5017 cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
5018 });
5019
5020 panel_a.update(cx, |panel, _cx| {
5021 panel.width = Some(px(300.0));
5022 });
5023
5024 panel_a.update_in(cx, |panel, window, cx| {
5025 panel.open_external_thread_with_server(
5026 Rc::new(StubAgentServer::default_response()),
5027 window,
5028 cx,
5029 );
5030 });
5031
5032 cx.run_until_parked();
5033
5034 panel_a.read_with(cx, |panel, cx| {
5035 assert!(
5036 panel.active_agent_thread(cx).is_some(),
5037 "workspace A should have an active thread after connection"
5038 );
5039 });
5040
5041 let agent_type_a = panel_a.read_with(cx, |panel, _cx| panel.selected_agent_type.clone());
5042
5043 // --- Set up workspace B: ClaudeCode, width=400, no active thread ---
5044 let panel_b = workspace_b.update_in(cx, |workspace, window, cx| {
5045 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project_b.clone(), cx));
5046 cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
5047 });
5048
5049 panel_b.update(cx, |panel, _cx| {
5050 panel.width = Some(px(400.0));
5051 panel.selected_agent_type = AgentType::Custom {
5052 id: "claude-acp".into(),
5053 };
5054 });
5055
5056 // --- Serialize both panels ---
5057 panel_a.update(cx, |panel, cx| panel.serialize(cx));
5058 panel_b.update(cx, |panel, cx| panel.serialize(cx));
5059 cx.run_until_parked();
5060
5061 // --- Load fresh panels for each workspace and verify independent state ---
5062 let prompt_builder = Arc::new(prompt_store::PromptBuilder::new(None).unwrap());
5063
5064 let async_cx = cx.update(|window, cx| window.to_async(cx));
5065 let loaded_a = AgentPanel::load(workspace_a.downgrade(), prompt_builder.clone(), async_cx)
5066 .await
5067 .expect("panel A load should succeed");
5068 cx.run_until_parked();
5069
5070 let async_cx = cx.update(|window, cx| window.to_async(cx));
5071 let loaded_b = AgentPanel::load(workspace_b.downgrade(), prompt_builder.clone(), async_cx)
5072 .await
5073 .expect("panel B load should succeed");
5074 cx.run_until_parked();
5075
5076 // Workspace A should restore its thread, width, and agent type
5077 loaded_a.read_with(cx, |panel, _cx| {
5078 assert_eq!(
5079 panel.width,
5080 Some(px(300.0)),
5081 "workspace A width should be restored"
5082 );
5083 assert_eq!(
5084 panel.selected_agent_type, agent_type_a,
5085 "workspace A agent type should be restored"
5086 );
5087 assert!(
5088 panel.active_conversation_view().is_some(),
5089 "workspace A should have its active thread restored"
5090 );
5091 });
5092
5093 // Workspace B should restore its own width and agent type, with no thread
5094 loaded_b.read_with(cx, |panel, _cx| {
5095 assert_eq!(
5096 panel.width,
5097 Some(px(400.0)),
5098 "workspace B width should be restored"
5099 );
5100 assert_eq!(
5101 panel.selected_agent_type,
5102 AgentType::Custom {
5103 id: "claude-acp".into()
5104 },
5105 "workspace B agent type should be restored"
5106 );
5107 assert!(
5108 panel.active_conversation_view().is_none(),
5109 "workspace B should have no active thread"
5110 );
5111 });
5112 }
5113
5114 // Simple regression test
5115 #[gpui::test]
5116 async fn test_new_text_thread_action_handler(cx: &mut TestAppContext) {
5117 init_test(cx);
5118
5119 let fs = FakeFs::new(cx.executor());
5120
5121 cx.update(|cx| {
5122 cx.update_flags(true, vec!["agent-v2".to_string()]);
5123 agent::ThreadStore::init_global(cx);
5124 language_model::LanguageModelRegistry::test(cx);
5125 let slash_command_registry =
5126 assistant_slash_command::SlashCommandRegistry::default_global(cx);
5127 slash_command_registry
5128 .register_command(assistant_slash_commands::DefaultSlashCommand, false);
5129 <dyn fs::Fs>::set_global(fs.clone(), cx);
5130 });
5131
5132 let project = Project::test(fs.clone(), [], cx).await;
5133
5134 let multi_workspace =
5135 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5136
5137 let workspace_a = multi_workspace
5138 .read_with(cx, |multi_workspace, _cx| {
5139 multi_workspace.workspace().clone()
5140 })
5141 .unwrap();
5142
5143 let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5144
5145 workspace_a.update_in(cx, |workspace, window, cx| {
5146 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5147 let panel =
5148 cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
5149 workspace.add_panel(panel, window, cx);
5150 });
5151
5152 cx.run_until_parked();
5153
5154 workspace_a.update_in(cx, |_, window, cx| {
5155 window.dispatch_action(NewTextThread.boxed_clone(), cx);
5156 });
5157
5158 cx.run_until_parked();
5159 }
5160
5161 /// Extracts the text from a Text content block, panicking if it's not Text.
5162 fn expect_text_block(block: &acp::ContentBlock) -> &str {
5163 match block {
5164 acp::ContentBlock::Text(t) => t.text.as_str(),
5165 other => panic!("expected Text block, got {:?}", other),
5166 }
5167 }
5168
5169 /// Extracts the (text_content, uri) from a Resource content block, panicking
5170 /// if it's not a TextResourceContents resource.
5171 fn expect_resource_block(block: &acp::ContentBlock) -> (&str, &str) {
5172 match block {
5173 acp::ContentBlock::Resource(r) => match &r.resource {
5174 acp::EmbeddedResourceResource::TextResourceContents(t) => {
5175 (t.text.as_str(), t.uri.as_str())
5176 }
5177 other => panic!("expected TextResourceContents, got {:?}", other),
5178 },
5179 other => panic!("expected Resource block, got {:?}", other),
5180 }
5181 }
5182
5183 #[test]
5184 fn test_build_conflict_resolution_prompt_single_conflict() {
5185 let conflicts = vec![ConflictContent {
5186 file_path: "src/main.rs".to_string(),
5187 conflict_text: "<<<<<<< HEAD\nlet x = 1;\n=======\nlet x = 2;\n>>>>>>> feature"
5188 .to_string(),
5189 ours_branch_name: "HEAD".to_string(),
5190 theirs_branch_name: "feature".to_string(),
5191 }];
5192
5193 let blocks = build_conflict_resolution_prompt(&conflicts);
5194 // 2 Text blocks + 1 ResourceLink + 1 Resource for the conflict
5195 assert_eq!(
5196 blocks.len(),
5197 4,
5198 "expected 2 text + 1 resource link + 1 resource block"
5199 );
5200
5201 let intro_text = expect_text_block(&blocks[0]);
5202 assert!(
5203 intro_text.contains("Please resolve the following merge conflict in"),
5204 "prompt should include single-conflict intro text"
5205 );
5206
5207 match &blocks[1] {
5208 acp::ContentBlock::ResourceLink(link) => {
5209 assert!(
5210 link.uri.contains("file://"),
5211 "resource link URI should use file scheme"
5212 );
5213 assert!(
5214 link.uri.contains("main.rs"),
5215 "resource link URI should reference file path"
5216 );
5217 }
5218 other => panic!("expected ResourceLink block, got {:?}", other),
5219 }
5220
5221 let body_text = expect_text_block(&blocks[2]);
5222 assert!(
5223 body_text.contains("`HEAD` (ours)"),
5224 "prompt should mention ours branch"
5225 );
5226 assert!(
5227 body_text.contains("`feature` (theirs)"),
5228 "prompt should mention theirs branch"
5229 );
5230 assert!(
5231 body_text.contains("editing the file directly"),
5232 "prompt should instruct the agent to edit the file"
5233 );
5234
5235 let (resource_text, resource_uri) = expect_resource_block(&blocks[3]);
5236 assert!(
5237 resource_text.contains("<<<<<<< HEAD"),
5238 "resource should contain the conflict text"
5239 );
5240 assert!(
5241 resource_uri.contains("merge-conflict"),
5242 "resource URI should use the merge-conflict scheme"
5243 );
5244 assert!(
5245 resource_uri.contains("main.rs"),
5246 "resource URI should reference the file path"
5247 );
5248 }
5249
5250 #[test]
5251 fn test_build_conflict_resolution_prompt_multiple_conflicts_same_file() {
5252 let conflicts = vec![
5253 ConflictContent {
5254 file_path: "src/lib.rs".to_string(),
5255 conflict_text: "<<<<<<< main\nfn a() {}\n=======\nfn a_v2() {}\n>>>>>>> dev"
5256 .to_string(),
5257 ours_branch_name: "main".to_string(),
5258 theirs_branch_name: "dev".to_string(),
5259 },
5260 ConflictContent {
5261 file_path: "src/lib.rs".to_string(),
5262 conflict_text: "<<<<<<< main\nfn b() {}\n=======\nfn b_v2() {}\n>>>>>>> dev"
5263 .to_string(),
5264 ours_branch_name: "main".to_string(),
5265 theirs_branch_name: "dev".to_string(),
5266 },
5267 ];
5268
5269 let blocks = build_conflict_resolution_prompt(&conflicts);
5270 // 1 Text instruction + 2 Resource blocks
5271 assert_eq!(blocks.len(), 3, "expected 1 text + 2 resource blocks");
5272
5273 let text = expect_text_block(&blocks[0]);
5274 assert!(
5275 text.contains("all 2 merge conflicts"),
5276 "prompt should mention the total count"
5277 );
5278 assert!(
5279 text.contains("`main` (ours)"),
5280 "prompt should mention ours branch"
5281 );
5282 assert!(
5283 text.contains("`dev` (theirs)"),
5284 "prompt should mention theirs branch"
5285 );
5286 // Single file, so "file" not "files"
5287 assert!(
5288 text.contains("file directly"),
5289 "single file should use singular 'file'"
5290 );
5291
5292 let (resource_a, _) = expect_resource_block(&blocks[1]);
5293 let (resource_b, _) = expect_resource_block(&blocks[2]);
5294 assert!(
5295 resource_a.contains("fn a()"),
5296 "first resource should contain first conflict"
5297 );
5298 assert!(
5299 resource_b.contains("fn b()"),
5300 "second resource should contain second conflict"
5301 );
5302 }
5303
5304 #[test]
5305 fn test_build_conflict_resolution_prompt_multiple_conflicts_different_files() {
5306 let conflicts = vec![
5307 ConflictContent {
5308 file_path: "src/a.rs".to_string(),
5309 conflict_text: "<<<<<<< main\nA\n=======\nB\n>>>>>>> dev".to_string(),
5310 ours_branch_name: "main".to_string(),
5311 theirs_branch_name: "dev".to_string(),
5312 },
5313 ConflictContent {
5314 file_path: "src/b.rs".to_string(),
5315 conflict_text: "<<<<<<< main\nC\n=======\nD\n>>>>>>> dev".to_string(),
5316 ours_branch_name: "main".to_string(),
5317 theirs_branch_name: "dev".to_string(),
5318 },
5319 ];
5320
5321 let blocks = build_conflict_resolution_prompt(&conflicts);
5322 // 1 Text instruction + 2 Resource blocks
5323 assert_eq!(blocks.len(), 3, "expected 1 text + 2 resource blocks");
5324
5325 let text = expect_text_block(&blocks[0]);
5326 assert!(
5327 text.contains("files directly"),
5328 "multiple files should use plural 'files'"
5329 );
5330
5331 let (_, uri_a) = expect_resource_block(&blocks[1]);
5332 let (_, uri_b) = expect_resource_block(&blocks[2]);
5333 assert!(
5334 uri_a.contains("a.rs"),
5335 "first resource URI should reference a.rs"
5336 );
5337 assert!(
5338 uri_b.contains("b.rs"),
5339 "second resource URI should reference b.rs"
5340 );
5341 }
5342
5343 #[test]
5344 fn test_build_conflicted_files_resolution_prompt_file_paths_only() {
5345 let file_paths = vec![
5346 "src/main.rs".to_string(),
5347 "src/lib.rs".to_string(),
5348 "tests/integration.rs".to_string(),
5349 ];
5350
5351 let blocks = build_conflicted_files_resolution_prompt(&file_paths);
5352 // 1 instruction Text block + (ResourceLink + newline Text) per file
5353 assert_eq!(
5354 blocks.len(),
5355 1 + (file_paths.len() * 2),
5356 "expected instruction text plus resource links and separators"
5357 );
5358
5359 let text = expect_text_block(&blocks[0]);
5360 assert!(
5361 text.contains("unresolved merge conflicts"),
5362 "prompt should describe the task"
5363 );
5364 assert!(
5365 text.contains("conflict markers"),
5366 "prompt should mention conflict markers"
5367 );
5368
5369 for (index, path) in file_paths.iter().enumerate() {
5370 let link_index = 1 + (index * 2);
5371 let newline_index = link_index + 1;
5372
5373 match &blocks[link_index] {
5374 acp::ContentBlock::ResourceLink(link) => {
5375 assert!(
5376 link.uri.contains("file://"),
5377 "resource link URI should use file scheme"
5378 );
5379 assert!(
5380 link.uri.contains(path),
5381 "resource link URI should reference file path: {path}"
5382 );
5383 }
5384 other => panic!(
5385 "expected ResourceLink block at index {}, got {:?}",
5386 link_index, other
5387 ),
5388 }
5389
5390 let separator = expect_text_block(&blocks[newline_index]);
5391 assert_eq!(
5392 separator, "\n",
5393 "expected newline separator after each file"
5394 );
5395 }
5396 }
5397
5398 #[test]
5399 fn test_build_conflict_resolution_prompt_empty_conflicts() {
5400 let blocks = build_conflict_resolution_prompt(&[]);
5401 assert!(
5402 blocks.is_empty(),
5403 "empty conflicts should produce no blocks, got {} blocks",
5404 blocks.len()
5405 );
5406 }
5407
5408 #[test]
5409 fn test_build_conflicted_files_resolution_prompt_empty_paths() {
5410 let blocks = build_conflicted_files_resolution_prompt(&[]);
5411 assert!(
5412 blocks.is_empty(),
5413 "empty paths should produce no blocks, got {} blocks",
5414 blocks.len()
5415 );
5416 }
5417
5418 #[test]
5419 fn test_conflict_resource_block_structure() {
5420 let conflict = ConflictContent {
5421 file_path: "src/utils.rs".to_string(),
5422 conflict_text: "<<<<<<< HEAD\nold code\n=======\nnew code\n>>>>>>> branch".to_string(),
5423 ours_branch_name: "HEAD".to_string(),
5424 theirs_branch_name: "branch".to_string(),
5425 };
5426
5427 let block = conflict_resource_block(&conflict);
5428 let (text, uri) = expect_resource_block(&block);
5429
5430 assert_eq!(
5431 text, conflict.conflict_text,
5432 "resource text should be the raw conflict"
5433 );
5434 assert!(
5435 uri.starts_with("zed:///agent/merge-conflict"),
5436 "URI should use the zed merge-conflict scheme, got: {uri}"
5437 );
5438 assert!(uri.contains("utils.rs"), "URI should encode the file path");
5439 }
5440
5441 fn open_generating_thread_with_loadable_connection(
5442 panel: &Entity<AgentPanel>,
5443 connection: &StubAgentConnection,
5444 cx: &mut VisualTestContext,
5445 ) -> acp::SessionId {
5446 open_thread_with_custom_connection(panel, connection.clone(), cx);
5447 let session_id = active_session_id(panel, cx);
5448 send_message(panel, cx);
5449 cx.update(|_, cx| {
5450 connection.send_update(
5451 session_id.clone(),
5452 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("done".into())),
5453 cx,
5454 );
5455 });
5456 cx.run_until_parked();
5457 session_id
5458 }
5459
5460 fn open_idle_thread_with_non_loadable_connection(
5461 panel: &Entity<AgentPanel>,
5462 connection: &StubAgentConnection,
5463 cx: &mut VisualTestContext,
5464 ) -> acp::SessionId {
5465 open_thread_with_custom_connection(panel, connection.clone(), cx);
5466 let session_id = active_session_id(panel, cx);
5467
5468 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5469 acp::ContentChunk::new("done".into()),
5470 )]);
5471 send_message(panel, cx);
5472
5473 session_id
5474 }
5475
5476 async fn setup_panel(cx: &mut TestAppContext) -> (Entity<AgentPanel>, VisualTestContext) {
5477 init_test(cx);
5478 cx.update(|cx| {
5479 cx.update_flags(true, vec!["agent-v2".to_string()]);
5480 agent::ThreadStore::init_global(cx);
5481 language_model::LanguageModelRegistry::test(cx);
5482 });
5483
5484 let fs = FakeFs::new(cx.executor());
5485 let project = Project::test(fs.clone(), [], cx).await;
5486
5487 let multi_workspace =
5488 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5489
5490 let workspace = multi_workspace
5491 .read_with(cx, |mw, _cx| mw.workspace().clone())
5492 .unwrap();
5493
5494 let mut cx = VisualTestContext::from_window(multi_workspace.into(), cx);
5495
5496 let panel = workspace.update_in(&mut cx, |workspace, window, cx| {
5497 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5498 cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
5499 });
5500
5501 (panel, cx)
5502 }
5503
5504 #[gpui::test]
5505 async fn test_running_thread_retained_when_navigating_away(cx: &mut TestAppContext) {
5506 let (panel, mut cx) = setup_panel(cx).await;
5507
5508 let connection_a = StubAgentConnection::new();
5509 open_thread_with_connection(&panel, connection_a.clone(), &mut cx);
5510 send_message(&panel, &mut cx);
5511
5512 let session_id_a = active_session_id(&panel, &cx);
5513
5514 // Send a chunk to keep thread A generating (don't end the turn).
5515 cx.update(|_, cx| {
5516 connection_a.send_update(
5517 session_id_a.clone(),
5518 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("chunk".into())),
5519 cx,
5520 );
5521 });
5522 cx.run_until_parked();
5523
5524 // Verify thread A is generating.
5525 panel.read_with(&cx, |panel, cx| {
5526 let thread = panel.active_agent_thread(cx).unwrap();
5527 assert_eq!(thread.read(cx).status(), ThreadStatus::Generating);
5528 assert!(panel.background_threads.is_empty());
5529 });
5530
5531 // Open a new thread B — thread A should be retained in background.
5532 let connection_b = StubAgentConnection::new();
5533 open_thread_with_connection(&panel, connection_b, &mut cx);
5534
5535 panel.read_with(&cx, |panel, _cx| {
5536 assert_eq!(
5537 panel.background_threads.len(),
5538 1,
5539 "Running thread A should be retained in background_views"
5540 );
5541 assert!(
5542 panel.background_threads.contains_key(&session_id_a),
5543 "Background view should be keyed by thread A's session ID"
5544 );
5545 });
5546 }
5547
5548 #[gpui::test]
5549 async fn test_idle_non_loadable_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 connection_a.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5554 acp::ContentChunk::new("Response".into()),
5555 )]);
5556 open_thread_with_connection(&panel, connection_a, &mut cx);
5557 send_message(&panel, &mut cx);
5558
5559 let weak_view_a = panel.read_with(&cx, |panel, _cx| {
5560 panel.active_conversation_view().unwrap().downgrade()
5561 });
5562 let session_id_a = active_session_id(&panel, &cx);
5563
5564 // Thread A should be idle (auto-completed via set_next_prompt_updates).
5565 panel.read_with(&cx, |panel, cx| {
5566 let thread = panel.active_agent_thread(cx).unwrap();
5567 assert_eq!(thread.read(cx).status(), ThreadStatus::Idle);
5568 });
5569
5570 // Open a new thread B — thread A should be retained because it is not loadable.
5571 let connection_b = StubAgentConnection::new();
5572 open_thread_with_connection(&panel, connection_b, &mut cx);
5573
5574 panel.read_with(&cx, |panel, _cx| {
5575 assert_eq!(
5576 panel.background_threads.len(),
5577 1,
5578 "Idle non-loadable thread A should be retained in background_views"
5579 );
5580 assert!(
5581 panel.background_threads.contains_key(&session_id_a),
5582 "Background view should be keyed by thread A's session ID"
5583 );
5584 });
5585
5586 assert!(
5587 weak_view_a.upgrade().is_some(),
5588 "Idle non-loadable ConnectionView should still be retained"
5589 );
5590 }
5591
5592 #[gpui::test]
5593 async fn test_background_thread_promoted_via_load(cx: &mut TestAppContext) {
5594 let (panel, mut cx) = setup_panel(cx).await;
5595
5596 let connection_a = StubAgentConnection::new();
5597 open_thread_with_connection(&panel, connection_a.clone(), &mut cx);
5598 send_message(&panel, &mut cx);
5599
5600 let session_id_a = active_session_id(&panel, &cx);
5601
5602 // Keep thread A generating.
5603 cx.update(|_, cx| {
5604 connection_a.send_update(
5605 session_id_a.clone(),
5606 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("chunk".into())),
5607 cx,
5608 );
5609 });
5610 cx.run_until_parked();
5611
5612 // Open thread B — thread A goes to background.
5613 let connection_b = StubAgentConnection::new();
5614 open_thread_with_connection(&panel, connection_b, &mut cx);
5615
5616 let session_id_b = active_session_id(&panel, &cx);
5617
5618 panel.read_with(&cx, |panel, _cx| {
5619 assert_eq!(panel.background_threads.len(), 1);
5620 assert!(panel.background_threads.contains_key(&session_id_a));
5621 });
5622
5623 // Load thread A back via load_agent_thread — should promote from background.
5624 panel.update_in(&mut cx, |panel, window, cx| {
5625 panel.load_agent_thread(
5626 panel.selected_agent().expect("selected agent must be set"),
5627 session_id_a.clone(),
5628 None,
5629 None,
5630 true,
5631 window,
5632 cx,
5633 );
5634 });
5635
5636 // Thread A should now be the active view, promoted from background.
5637 let active_session = active_session_id(&panel, &cx);
5638 assert_eq!(
5639 active_session, session_id_a,
5640 "Thread A should be the active thread after promotion"
5641 );
5642
5643 panel.read_with(&cx, |panel, _cx| {
5644 assert!(
5645 !panel.background_threads.contains_key(&session_id_a),
5646 "Promoted thread A should no longer be in background_views"
5647 );
5648 assert!(
5649 panel.background_threads.contains_key(&session_id_b),
5650 "Thread B (idle, non-loadable) should remain retained in background_views"
5651 );
5652 });
5653 }
5654
5655 #[gpui::test]
5656 async fn test_cleanup_background_threads_keeps_five_most_recent_idle_loadable_threads(
5657 cx: &mut TestAppContext,
5658 ) {
5659 let (panel, mut cx) = setup_panel(cx).await;
5660 let connection = StubAgentConnection::new()
5661 .with_supports_load_session(true)
5662 .with_agent_id("loadable-stub".into())
5663 .with_telemetry_id("loadable-stub".into());
5664 let mut session_ids = Vec::new();
5665
5666 for _ in 0..7 {
5667 session_ids.push(open_generating_thread_with_loadable_connection(
5668 &panel,
5669 &connection,
5670 &mut cx,
5671 ));
5672 }
5673
5674 let base_time = Instant::now();
5675
5676 for session_id in session_ids.iter().take(6) {
5677 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5678 }
5679 cx.run_until_parked();
5680
5681 panel.update(&mut cx, |panel, cx| {
5682 for (index, session_id) in session_ids.iter().take(6).enumerate() {
5683 let conversation_view = panel
5684 .background_threads
5685 .get(session_id)
5686 .expect("background thread should exist")
5687 .clone();
5688 conversation_view.update(cx, |view, cx| {
5689 view.set_updated_at(base_time + Duration::from_secs(index as u64), cx);
5690 });
5691 }
5692 panel.cleanup_background_threads(cx);
5693 });
5694
5695 panel.read_with(&cx, |panel, _cx| {
5696 assert_eq!(
5697 panel.background_threads.len(),
5698 5,
5699 "cleanup should keep at most five idle loadable background threads"
5700 );
5701 assert!(
5702 !panel.background_threads.contains_key(&session_ids[0]),
5703 "oldest idle loadable background thread should be removed"
5704 );
5705 for session_id in &session_ids[1..6] {
5706 assert!(
5707 panel.background_threads.contains_key(session_id),
5708 "more recent idle loadable background threads should be retained"
5709 );
5710 }
5711 assert!(
5712 !panel.background_threads.contains_key(&session_ids[6]),
5713 "the active thread should not also be stored as a background thread"
5714 );
5715 });
5716 }
5717
5718 #[gpui::test]
5719 async fn test_cleanup_background_threads_preserves_idle_non_loadable_threads(
5720 cx: &mut TestAppContext,
5721 ) {
5722 let (panel, mut cx) = setup_panel(cx).await;
5723
5724 let non_loadable_connection = StubAgentConnection::new();
5725 let non_loadable_session_id = open_idle_thread_with_non_loadable_connection(
5726 &panel,
5727 &non_loadable_connection,
5728 &mut cx,
5729 );
5730
5731 let loadable_connection = StubAgentConnection::new()
5732 .with_supports_load_session(true)
5733 .with_agent_id("loadable-stub".into())
5734 .with_telemetry_id("loadable-stub".into());
5735 let mut loadable_session_ids = Vec::new();
5736
5737 for _ in 0..7 {
5738 loadable_session_ids.push(open_generating_thread_with_loadable_connection(
5739 &panel,
5740 &loadable_connection,
5741 &mut cx,
5742 ));
5743 }
5744
5745 let base_time = Instant::now();
5746
5747 for session_id in loadable_session_ids.iter().take(6) {
5748 loadable_connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5749 }
5750 cx.run_until_parked();
5751
5752 panel.update(&mut cx, |panel, cx| {
5753 for (index, session_id) in loadable_session_ids.iter().take(6).enumerate() {
5754 let conversation_view = panel
5755 .background_threads
5756 .get(session_id)
5757 .expect("background thread should exist")
5758 .clone();
5759 conversation_view.update(cx, |view, cx| {
5760 view.set_updated_at(base_time + Duration::from_secs(index as u64), cx);
5761 });
5762 }
5763 panel.cleanup_background_threads(cx);
5764 });
5765
5766 panel.read_with(&cx, |panel, _cx| {
5767 assert_eq!(
5768 panel.background_threads.len(),
5769 6,
5770 "cleanup should keep the non-loadable idle thread in addition to five loadable ones"
5771 );
5772 assert!(
5773 panel
5774 .background_threads
5775 .contains_key(&non_loadable_session_id),
5776 "idle non-loadable background threads should not be cleanup candidates"
5777 );
5778 assert!(
5779 !panel
5780 .background_threads
5781 .contains_key(&loadable_session_ids[0]),
5782 "oldest idle loadable background thread should still be removed"
5783 );
5784 for session_id in &loadable_session_ids[1..6] {
5785 assert!(
5786 panel.background_threads.contains_key(session_id),
5787 "more recent idle loadable background threads should be retained"
5788 );
5789 }
5790 assert!(
5791 !panel
5792 .background_threads
5793 .contains_key(&loadable_session_ids[6]),
5794 "the active loadable thread should not also be stored as a background thread"
5795 );
5796 });
5797 }
5798
5799 #[gpui::test]
5800 async fn test_thread_target_local_project(cx: &mut TestAppContext) {
5801 init_test(cx);
5802 cx.update(|cx| {
5803 cx.update_flags(true, vec!["agent-v2".to_string()]);
5804 agent::ThreadStore::init_global(cx);
5805 language_model::LanguageModelRegistry::test(cx);
5806 });
5807
5808 let fs = FakeFs::new(cx.executor());
5809 fs.insert_tree(
5810 "/project",
5811 json!({
5812 ".git": {},
5813 "src": {
5814 "main.rs": "fn main() {}"
5815 }
5816 }),
5817 )
5818 .await;
5819 fs.set_branch_name(Path::new("/project/.git"), Some("main"));
5820
5821 let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
5822
5823 let multi_workspace =
5824 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5825
5826 let workspace = multi_workspace
5827 .read_with(cx, |multi_workspace, _cx| {
5828 multi_workspace.workspace().clone()
5829 })
5830 .unwrap();
5831
5832 workspace.update(cx, |workspace, _cx| {
5833 workspace.set_random_database_id();
5834 });
5835
5836 let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5837
5838 // Wait for the project to discover the git repository.
5839 cx.run_until_parked();
5840
5841 let panel = workspace.update_in(cx, |workspace, window, cx| {
5842 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5843 let panel =
5844 cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
5845 workspace.add_panel(panel.clone(), window, cx);
5846 panel
5847 });
5848
5849 cx.run_until_parked();
5850
5851 // Default thread target should be LocalProject.
5852 panel.read_with(cx, |panel, _cx| {
5853 assert_eq!(
5854 *panel.start_thread_in(),
5855 StartThreadIn::LocalProject,
5856 "default thread target should be LocalProject"
5857 );
5858 });
5859
5860 // Start a new thread with the default LocalProject target.
5861 // Use StubAgentServer so the thread connects immediately in tests.
5862 panel.update_in(cx, |panel, window, cx| {
5863 panel.open_external_thread_with_server(
5864 Rc::new(StubAgentServer::default_response()),
5865 window,
5866 cx,
5867 );
5868 });
5869
5870 cx.run_until_parked();
5871
5872 // MultiWorkspace should still have exactly one workspace (no worktree created).
5873 multi_workspace
5874 .read_with(cx, |multi_workspace, _cx| {
5875 assert_eq!(
5876 multi_workspace.workspaces().len(),
5877 1,
5878 "LocalProject should not create a new workspace"
5879 );
5880 })
5881 .unwrap();
5882
5883 // The thread should be active in the panel.
5884 panel.read_with(cx, |panel, cx| {
5885 assert!(
5886 panel.active_agent_thread(cx).is_some(),
5887 "a thread should be running in the current workspace"
5888 );
5889 });
5890
5891 // The thread target should still be LocalProject (unchanged).
5892 panel.read_with(cx, |panel, _cx| {
5893 assert_eq!(
5894 *panel.start_thread_in(),
5895 StartThreadIn::LocalProject,
5896 "thread target should remain LocalProject"
5897 );
5898 });
5899
5900 // No worktree creation status should be set.
5901 panel.read_with(cx, |panel, _cx| {
5902 assert!(
5903 panel.worktree_creation_status.is_none(),
5904 "no worktree creation should have occurred"
5905 );
5906 });
5907 }
5908
5909 #[gpui::test]
5910 async fn test_thread_target_serialization_round_trip(cx: &mut TestAppContext) {
5911 init_test(cx);
5912 cx.update(|cx| {
5913 cx.update_flags(true, vec!["agent-v2".to_string()]);
5914 agent::ThreadStore::init_global(cx);
5915 language_model::LanguageModelRegistry::test(cx);
5916 });
5917
5918 let fs = FakeFs::new(cx.executor());
5919 fs.insert_tree(
5920 "/project",
5921 json!({
5922 ".git": {},
5923 "src": {
5924 "main.rs": "fn main() {}"
5925 }
5926 }),
5927 )
5928 .await;
5929 fs.set_branch_name(Path::new("/project/.git"), Some("main"));
5930
5931 let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
5932
5933 let multi_workspace =
5934 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5935
5936 let workspace = multi_workspace
5937 .read_with(cx, |multi_workspace, _cx| {
5938 multi_workspace.workspace().clone()
5939 })
5940 .unwrap();
5941
5942 workspace.update(cx, |workspace, _cx| {
5943 workspace.set_random_database_id();
5944 });
5945
5946 let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5947
5948 // Wait for the project to discover the git repository.
5949 cx.run_until_parked();
5950
5951 let panel = workspace.update_in(cx, |workspace, window, cx| {
5952 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5953 let panel =
5954 cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
5955 workspace.add_panel(panel.clone(), window, cx);
5956 panel
5957 });
5958
5959 cx.run_until_parked();
5960
5961 // Default should be LocalProject.
5962 panel.read_with(cx, |panel, _cx| {
5963 assert_eq!(*panel.start_thread_in(), StartThreadIn::LocalProject);
5964 });
5965
5966 // Change thread target to NewWorktree.
5967 panel.update_in(cx, |panel, window, cx| {
5968 panel.set_start_thread_in(&StartThreadIn::NewWorktree, window, cx);
5969 });
5970
5971 panel.read_with(cx, |panel, _cx| {
5972 assert_eq!(
5973 *panel.start_thread_in(),
5974 StartThreadIn::NewWorktree,
5975 "thread target should be NewWorktree after set_thread_target"
5976 );
5977 });
5978
5979 // Let serialization complete.
5980 cx.run_until_parked();
5981
5982 // Load a fresh panel from the serialized data.
5983 let prompt_builder = Arc::new(prompt_store::PromptBuilder::new(None).unwrap());
5984 let async_cx = cx.update(|window, cx| window.to_async(cx));
5985 let loaded_panel =
5986 AgentPanel::load(workspace.downgrade(), prompt_builder.clone(), async_cx)
5987 .await
5988 .expect("panel load should succeed");
5989 cx.run_until_parked();
5990
5991 loaded_panel.read_with(cx, |panel, _cx| {
5992 assert_eq!(
5993 *panel.start_thread_in(),
5994 StartThreadIn::NewWorktree,
5995 "thread target should survive serialization round-trip"
5996 );
5997 });
5998 }
5999
6000 #[gpui::test]
6001 async fn test_set_active_blocked_during_worktree_creation(cx: &mut TestAppContext) {
6002 init_test(cx);
6003
6004 let fs = FakeFs::new(cx.executor());
6005 cx.update(|cx| {
6006 cx.update_flags(true, vec!["agent-v2".to_string()]);
6007 agent::ThreadStore::init_global(cx);
6008 language_model::LanguageModelRegistry::test(cx);
6009 <dyn fs::Fs>::set_global(fs.clone(), cx);
6010 });
6011
6012 fs.insert_tree(
6013 "/project",
6014 json!({
6015 ".git": {},
6016 "src": {
6017 "main.rs": "fn main() {}"
6018 }
6019 }),
6020 )
6021 .await;
6022
6023 let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
6024
6025 let multi_workspace =
6026 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6027
6028 let workspace = multi_workspace
6029 .read_with(cx, |multi_workspace, _cx| {
6030 multi_workspace.workspace().clone()
6031 })
6032 .unwrap();
6033
6034 let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
6035
6036 let panel = workspace.update_in(cx, |workspace, window, cx| {
6037 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
6038 let panel =
6039 cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
6040 workspace.add_panel(panel.clone(), window, cx);
6041 panel
6042 });
6043
6044 cx.run_until_parked();
6045
6046 // Simulate worktree creation in progress and reset to Uninitialized
6047 panel.update_in(cx, |panel, window, cx| {
6048 panel.worktree_creation_status = Some(WorktreeCreationStatus::Creating);
6049 panel.active_view = ActiveView::Uninitialized;
6050 Panel::set_active(panel, true, window, cx);
6051 assert!(
6052 matches!(panel.active_view, ActiveView::Uninitialized),
6053 "set_active should not create a thread while worktree is being created"
6054 );
6055 });
6056
6057 // Clear the creation status and use open_external_thread_with_server
6058 // (which bypasses new_agent_thread) to verify the panel can transition
6059 // out of Uninitialized. We can't call set_active directly because
6060 // new_agent_thread requires full agent server infrastructure.
6061 panel.update_in(cx, |panel, window, cx| {
6062 panel.worktree_creation_status = None;
6063 panel.active_view = ActiveView::Uninitialized;
6064 panel.open_external_thread_with_server(
6065 Rc::new(StubAgentServer::default_response()),
6066 window,
6067 cx,
6068 );
6069 });
6070
6071 cx.run_until_parked();
6072
6073 panel.read_with(cx, |panel, _cx| {
6074 assert!(
6075 !matches!(panel.active_view, ActiveView::Uninitialized),
6076 "panel should transition out of Uninitialized once worktree creation is cleared"
6077 );
6078 });
6079 }
6080
6081 #[test]
6082 fn test_deserialize_agent_type_variants() {
6083 assert_eq!(
6084 serde_json::from_str::<AgentType>(r#""NativeAgent""#).unwrap(),
6085 AgentType::NativeAgent,
6086 );
6087 assert_eq!(
6088 serde_json::from_str::<AgentType>(r#""TextThread""#).unwrap(),
6089 AgentType::TextThread,
6090 );
6091 assert_eq!(
6092 serde_json::from_str::<AgentType>(r#"{"Custom":{"name":"my-agent"}}"#).unwrap(),
6093 AgentType::Custom {
6094 id: "my-agent".into(),
6095 },
6096 );
6097 }
6098
6099 #[gpui::test]
6100 async fn test_worktree_creation_preserves_selected_agent(cx: &mut TestAppContext) {
6101 init_test(cx);
6102
6103 let app_state = cx.update(|cx| {
6104 cx.update_flags(true, vec!["agent-v2".to_string()]);
6105 agent::ThreadStore::init_global(cx);
6106 language_model::LanguageModelRegistry::test(cx);
6107
6108 let app_state = workspace::AppState::test(cx);
6109 workspace::init(app_state.clone(), cx);
6110 app_state
6111 });
6112
6113 let fs = app_state.fs.as_fake();
6114 fs.insert_tree(
6115 "/project",
6116 json!({
6117 ".git": {},
6118 "src": {
6119 "main.rs": "fn main() {}"
6120 }
6121 }),
6122 )
6123 .await;
6124 fs.set_branch_name(Path::new("/project/.git"), Some("main"));
6125
6126 let project = Project::test(app_state.fs.clone(), [Path::new("/project")], cx).await;
6127
6128 let multi_workspace =
6129 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6130
6131 let workspace = multi_workspace
6132 .read_with(cx, |multi_workspace, _cx| {
6133 multi_workspace.workspace().clone()
6134 })
6135 .unwrap();
6136
6137 workspace.update(cx, |workspace, _cx| {
6138 workspace.set_random_database_id();
6139 });
6140
6141 // Register a callback so new workspaces also get an AgentPanel.
6142 cx.update(|cx| {
6143 cx.observe_new(
6144 |workspace: &mut Workspace,
6145 window: Option<&mut Window>,
6146 cx: &mut Context<Workspace>| {
6147 if let Some(window) = window {
6148 let project = workspace.project().clone();
6149 let text_thread_store =
6150 cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
6151 let panel = cx.new(|cx| {
6152 AgentPanel::new(workspace, text_thread_store, None, window, cx)
6153 });
6154 workspace.add_panel(panel, window, cx);
6155 }
6156 },
6157 )
6158 .detach();
6159 });
6160
6161 let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
6162
6163 // Wait for the project to discover the git repository.
6164 cx.run_until_parked();
6165
6166 let panel = workspace.update_in(cx, |workspace, window, cx| {
6167 let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
6168 let panel =
6169 cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
6170 workspace.add_panel(panel.clone(), window, cx);
6171 panel
6172 });
6173
6174 cx.run_until_parked();
6175
6176 // Open a thread (needed so there's an active thread view).
6177 panel.update_in(cx, |panel, window, cx| {
6178 panel.open_external_thread_with_server(
6179 Rc::new(StubAgentServer::default_response()),
6180 window,
6181 cx,
6182 );
6183 });
6184
6185 cx.run_until_parked();
6186
6187 // Set the selected agent to Codex (a custom agent) and start_thread_in
6188 // to NewWorktree. We do this AFTER opening the thread because
6189 // open_external_thread_with_server overrides selected_agent_type.
6190 panel.update_in(cx, |panel, window, cx| {
6191 panel.selected_agent_type = AgentType::Custom {
6192 id: CODEX_ID.into(),
6193 };
6194 panel.set_start_thread_in(&StartThreadIn::NewWorktree, window, cx);
6195 });
6196
6197 // Verify the panel has the Codex agent selected.
6198 panel.read_with(cx, |panel, _cx| {
6199 assert_eq!(
6200 panel.selected_agent_type,
6201 AgentType::Custom {
6202 id: CODEX_ID.into()
6203 },
6204 );
6205 });
6206
6207 // Directly call handle_worktree_creation_requested, which is what
6208 // handle_first_send_requested does when start_thread_in == NewWorktree.
6209 let content = vec![acp::ContentBlock::Text(acp::TextContent::new(
6210 "Hello from test",
6211 ))];
6212 panel.update_in(cx, |panel, window, cx| {
6213 panel.handle_worktree_creation_requested(content, window, cx);
6214 });
6215
6216 // Let the async worktree creation + workspace setup complete.
6217 cx.run_until_parked();
6218
6219 // Find the new workspace's AgentPanel and verify it used the Codex agent.
6220 let found_codex = multi_workspace
6221 .read_with(cx, |multi_workspace, cx| {
6222 // There should be more than one workspace now (the original + the new worktree).
6223 assert!(
6224 multi_workspace.workspaces().len() > 1,
6225 "expected a new workspace to have been created, found {}",
6226 multi_workspace.workspaces().len(),
6227 );
6228
6229 // Check the newest workspace's panel for the correct agent.
6230 let new_workspace = multi_workspace
6231 .workspaces()
6232 .iter()
6233 .find(|ws| ws.entity_id() != workspace.entity_id())
6234 .expect("should find the new workspace");
6235 let new_panel = new_workspace
6236 .read(cx)
6237 .panel::<AgentPanel>(cx)
6238 .expect("new workspace should have an AgentPanel");
6239
6240 new_panel.read(cx).selected_agent_type.clone()
6241 })
6242 .unwrap();
6243
6244 assert_eq!(
6245 found_codex,
6246 AgentType::Custom {
6247 id: CODEX_ID.into()
6248 },
6249 "the new worktree workspace should use the same agent (Codex) that was selected in the original panel",
6250 );
6251 }
6252}