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