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