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