1use crate::{CommonAnimationExt, DiffStat, GradientFade, HighlightedLabel, Tooltip, prelude::*};
2
3use gpui::{
4 Animation, AnimationExt, AnyView, ClickEvent, Hsla, MouseButton, SharedString,
5 pulsating_between,
6};
7use itertools::Itertools as _;
8use std::{path::PathBuf, sync::Arc, time::Duration};
9
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11pub enum AgentThreadStatus {
12 #[default]
13 Completed,
14 Running,
15 WaitingForConfirmation,
16 Error,
17}
18
19#[derive(Clone)]
20pub struct ThreadItemWorktreeInfo {
21 pub name: SharedString,
22 pub full_path: SharedString,
23 pub highlight_positions: Vec<usize>,
24}
25
26#[derive(IntoElement, RegisterComponent)]
27pub struct ThreadItem {
28 id: ElementId,
29 icon: IconName,
30 icon_color: Option<Color>,
31 icon_visible: bool,
32 custom_icon_from_external_svg: Option<SharedString>,
33 title: SharedString,
34 title_label_color: Option<Color>,
35 title_generating: bool,
36 highlight_positions: Vec<usize>,
37 timestamp: SharedString,
38 notified: bool,
39 status: AgentThreadStatus,
40 selected: bool,
41 focused: bool,
42 hovered: bool,
43 rounded: bool,
44 added: Option<usize>,
45 removed: Option<usize>,
46 project_paths: Option<Arc<[PathBuf]>>,
47 project_name: Option<SharedString>,
48 worktrees: Vec<ThreadItemWorktreeInfo>,
49 pending_worktree_restore: bool,
50 on_cancel_restore: Option<Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>>,
51 on_click: Option<Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>>,
52 on_hover: Box<dyn Fn(&bool, &mut Window, &mut App) + 'static>,
53 action_slot: Option<AnyElement>,
54 tooltip: Option<Box<dyn Fn(&mut Window, &mut App) -> AnyView + 'static>>,
55 base_bg: Option<Hsla>,
56}
57
58impl ThreadItem {
59 pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
60 Self {
61 id: id.into(),
62 icon: IconName::ZedAgent,
63 icon_color: None,
64 icon_visible: true,
65 custom_icon_from_external_svg: None,
66 title: title.into(),
67 title_label_color: None,
68 title_generating: false,
69 highlight_positions: Vec::new(),
70 timestamp: "".into(),
71 notified: false,
72 status: AgentThreadStatus::default(),
73 selected: false,
74 focused: false,
75 hovered: false,
76 rounded: false,
77 added: None,
78 removed: None,
79
80 project_paths: None,
81 project_name: None,
82 worktrees: Vec::new(),
83 pending_worktree_restore: false,
84 on_cancel_restore: None,
85 on_click: None,
86 on_hover: Box::new(|_, _, _| {}),
87 action_slot: None,
88 tooltip: None,
89 base_bg: None,
90 }
91 }
92
93 pub fn timestamp(mut self, timestamp: impl Into<SharedString>) -> Self {
94 self.timestamp = timestamp.into();
95 self
96 }
97
98 pub fn icon(mut self, icon: IconName) -> Self {
99 self.icon = icon;
100 self
101 }
102
103 pub fn icon_color(mut self, color: Color) -> Self {
104 self.icon_color = Some(color);
105 self
106 }
107
108 pub fn icon_visible(mut self, visible: bool) -> Self {
109 self.icon_visible = visible;
110 self
111 }
112
113 pub fn custom_icon_from_external_svg(mut self, svg: impl Into<SharedString>) -> Self {
114 self.custom_icon_from_external_svg = Some(svg.into());
115 self
116 }
117
118 pub fn notified(mut self, notified: bool) -> Self {
119 self.notified = notified;
120 self
121 }
122
123 pub fn status(mut self, status: AgentThreadStatus) -> Self {
124 self.status = status;
125 self
126 }
127
128 pub fn title_generating(mut self, generating: bool) -> Self {
129 self.title_generating = generating;
130 self
131 }
132
133 pub fn title_label_color(mut self, color: Color) -> Self {
134 self.title_label_color = Some(color);
135 self
136 }
137
138 pub fn highlight_positions(mut self, positions: Vec<usize>) -> Self {
139 self.highlight_positions = positions;
140 self
141 }
142
143 pub fn selected(mut self, selected: bool) -> Self {
144 self.selected = selected;
145 self
146 }
147
148 pub fn focused(mut self, focused: bool) -> Self {
149 self.focused = focused;
150 self
151 }
152
153 pub fn added(mut self, added: usize) -> Self {
154 self.added = Some(added);
155 self
156 }
157
158 pub fn removed(mut self, removed: usize) -> Self {
159 self.removed = Some(removed);
160 self
161 }
162
163 pub fn project_paths(mut self, paths: Arc<[PathBuf]>) -> Self {
164 self.project_paths = Some(paths);
165 self
166 }
167
168 pub fn project_name(mut self, name: impl Into<SharedString>) -> Self {
169 self.project_name = Some(name.into());
170 self
171 }
172
173 pub fn worktrees(mut self, worktrees: Vec<ThreadItemWorktreeInfo>) -> Self {
174 self.worktrees = worktrees;
175 self
176 }
177
178 pub fn pending_worktree_restore(mut self, pending: bool) -> Self {
179 self.pending_worktree_restore = pending;
180 self
181 }
182
183 pub fn on_cancel_restore(
184 mut self,
185 handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
186 ) -> Self {
187 self.on_cancel_restore = Some(Box::new(handler));
188 self
189 }
190
191 pub fn hovered(mut self, hovered: bool) -> Self {
192 self.hovered = hovered;
193 self
194 }
195
196 pub fn rounded(mut self, rounded: bool) -> Self {
197 self.rounded = rounded;
198 self
199 }
200
201 pub fn on_click(
202 mut self,
203 handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
204 ) -> Self {
205 self.on_click = Some(Box::new(handler));
206 self
207 }
208
209 pub fn on_hover(mut self, on_hover: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
210 self.on_hover = Box::new(on_hover);
211 self
212 }
213
214 pub fn action_slot(mut self, element: impl IntoElement) -> Self {
215 self.action_slot = Some(element.into_any_element());
216 self
217 }
218
219 pub fn tooltip(mut self, tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self {
220 self.tooltip = Some(Box::new(tooltip));
221 self
222 }
223
224 pub fn base_bg(mut self, color: Hsla) -> Self {
225 self.base_bg = Some(color);
226 self
227 }
228}
229
230impl RenderOnce for ThreadItem {
231 fn render(mut self, _: &mut Window, cx: &mut App) -> impl IntoElement {
232 let color = cx.theme().colors();
233 let sidebar_base_bg = color
234 .title_bar_background
235 .blend(color.panel_background.opacity(0.25));
236
237 let raw_bg = self.base_bg.unwrap_or(sidebar_base_bg);
238 let apparent_bg = color.background.blend(raw_bg);
239
240 let base_bg = if self.selected {
241 apparent_bg.blend(color.element_active)
242 } else {
243 apparent_bg
244 };
245
246 let hover_color = color
247 .element_active
248 .blend(color.element_background.opacity(0.2));
249 let hover_bg = apparent_bg.blend(hover_color);
250
251 let gradient_overlay = GradientFade::new(base_bg, hover_bg, hover_bg)
252 .width(px(64.0))
253 .right(px(-10.0))
254 .gradient_stop(0.75)
255 .group_name("thread-item");
256
257 let dot_separator = || {
258 Label::new("•")
259 .size(LabelSize::Small)
260 .color(Color::Muted)
261 .alpha(0.5)
262 };
263
264 let icon_id = format!("icon-{}", self.id);
265 let icon_visible = self.icon_visible;
266 let icon_container = || {
267 h_flex()
268 .id(icon_id.clone())
269 .size_4()
270 .flex_none()
271 .justify_center()
272 .when(!icon_visible, |this| this.invisible())
273 };
274 let icon_color = self.icon_color.unwrap_or(Color::Muted);
275 let agent_icon = if let Some(custom_svg) = self.custom_icon_from_external_svg {
276 Icon::from_external_svg(custom_svg)
277 .color(icon_color)
278 .size(IconSize::Small)
279 } else {
280 Icon::new(self.icon).color(icon_color).size(IconSize::Small)
281 };
282
283 let (status_icon, icon_tooltip) = if self.status == AgentThreadStatus::Error {
284 (
285 Some(
286 Icon::new(IconName::Close)
287 .size(IconSize::Small)
288 .color(Color::Error),
289 ),
290 Some("Thread has an Error"),
291 )
292 } else if self.status == AgentThreadStatus::WaitingForConfirmation {
293 (
294 Some(
295 Icon::new(IconName::Warning)
296 .size(IconSize::XSmall)
297 .color(Color::Warning),
298 ),
299 Some("Thread is Waiting for Confirmation"),
300 )
301 } else if self.notified {
302 (
303 Some(
304 Icon::new(IconName::Circle)
305 .size(IconSize::Small)
306 .color(Color::Accent),
307 ),
308 Some("Thread's Generation is Complete"),
309 )
310 } else {
311 (None, None)
312 };
313
314 let icon = if self.status == AgentThreadStatus::Running {
315 icon_container()
316 .child(
317 Icon::new(IconName::LoadCircle)
318 .size(IconSize::Small)
319 .color(Color::Muted)
320 .with_rotate_animation(2),
321 )
322 .into_any_element()
323 } else if let Some(status_icon) = status_icon {
324 icon_container()
325 .child(status_icon)
326 .when_some(icon_tooltip, |icon, tooltip| {
327 icon.tooltip(Tooltip::text(tooltip))
328 })
329 .into_any_element()
330 } else {
331 icon_container().child(agent_icon).into_any_element()
332 };
333
334 let title = self.title;
335 let highlight_positions = self.highlight_positions;
336
337 let title_label = if self.title_generating {
338 Label::new(title)
339 .color(Color::Muted)
340 .with_animation(
341 "generating-title",
342 Animation::new(Duration::from_secs(2))
343 .repeat()
344 .with_easing(pulsating_between(0.4, 0.8)),
345 |label, delta| label.alpha(delta),
346 )
347 .into_any_element()
348 } else if highlight_positions.is_empty() {
349 Label::new(title)
350 .when_some(self.title_label_color, |label, color| label.color(color))
351 .into_any_element()
352 } else {
353 HighlightedLabel::new(title, highlight_positions)
354 .when_some(self.title_label_color, |label, color| label.color(color))
355 .into_any_element()
356 };
357
358 let has_diff_stats = self.added.is_some() || self.removed.is_some();
359 let diff_stat_id = self.id.clone();
360 let added_count = self.added.unwrap_or(0);
361 let removed_count = self.removed.unwrap_or(0);
362
363 let project_paths = self.project_paths.as_ref().and_then(|paths| {
364 let paths_str = paths
365 .as_ref()
366 .iter()
367 .filter_map(|p| p.file_name())
368 .filter_map(|name| name.to_str())
369 .join(", ");
370 if paths_str.is_empty() {
371 None
372 } else {
373 Some(paths_str)
374 }
375 });
376
377 let has_project_name = self.project_name.is_some();
378 let has_project_paths = project_paths.is_some();
379 let has_worktree = !self.worktrees.is_empty() || self.pending_worktree_restore;
380 let has_timestamp = !self.timestamp.is_empty();
381 let timestamp = self.timestamp;
382
383 v_flex()
384 .id(self.id.clone())
385 .cursor_pointer()
386 .group("thread-item")
387 .relative()
388 .overflow_hidden()
389 .w_full()
390 .py_1()
391 .px_1p5()
392 .when(self.selected, |s| s.bg(color.element_active))
393 .border_1()
394 .border_color(gpui::transparent_black())
395 .when(self.focused, |s| s.border_color(color.border_focused))
396 .when(self.rounded, |s| s.rounded_sm())
397 .hover(|s| s.bg(hover_color))
398 .on_hover(self.on_hover)
399 .child(
400 h_flex()
401 .min_w_0()
402 .w_full()
403 .gap_2()
404 .justify_between()
405 .child(
406 h_flex()
407 .id("content")
408 .min_w_0()
409 .flex_1()
410 .gap_1p5()
411 .child(icon)
412 .child(title_label)
413 .when_some(self.tooltip, |this, tooltip| this.tooltip(tooltip)),
414 )
415 .child(gradient_overlay)
416 .when(self.hovered, |this| {
417 this.when_some(self.action_slot, |this, slot| {
418 let overlay = GradientFade::new(base_bg, hover_bg, hover_bg)
419 .width(px(64.0))
420 .right(px(6.))
421 .gradient_stop(0.75)
422 .group_name("thread-item");
423
424 this.child(
425 h_flex()
426 .relative()
427 .on_mouse_down(MouseButton::Left, |_, _, cx| {
428 cx.stop_propagation()
429 })
430 .child(overlay)
431 .child(slot),
432 )
433 })
434 }),
435 )
436 .when(
437 has_project_name
438 || has_project_paths
439 || has_worktree
440 || has_diff_stats
441 || has_timestamp,
442 |this| {
443 // Collect all full paths for the shared tooltip.
444 let worktree_tooltip: SharedString = self
445 .worktrees
446 .iter()
447 .map(|wt| wt.full_path.as_ref())
448 .collect::<Vec<_>>()
449 .join("\n")
450 .into();
451
452 let worktree_tooltip_title = if self.worktrees.len() > 1 {
453 "Thread Running in Local Git Worktrees"
454 } else {
455 "Thread Running in a Local Git Worktree"
456 };
457
458 // Deduplicate chips by name — e.g. two paths both named
459 // "olivetti" produce a single chip. Highlight positions
460 // come from the first occurrence.
461 let mut seen_names: Vec<SharedString> = Vec::new();
462 let mut worktree_labels: Vec<AnyElement> = Vec::new();
463
464 for wt in self.worktrees {
465 if seen_names.contains(&wt.name) {
466 continue;
467 }
468
469 let chip_index = seen_names.len();
470 seen_names.push(wt.name.clone());
471
472 let label = if wt.highlight_positions.is_empty() {
473 Label::new(wt.name)
474 .size(LabelSize::Small)
475 .color(Color::Muted)
476 .into_any_element()
477 } else {
478 HighlightedLabel::new(wt.name, wt.highlight_positions)
479 .size(LabelSize::Small)
480 .color(Color::Muted)
481 .into_any_element()
482 };
483 let tooltip_title = worktree_tooltip_title;
484 let tooltip_meta = worktree_tooltip.clone();
485
486 worktree_labels.push(
487 h_flex()
488 .id(format!("{}-worktree-{chip_index}", self.id.clone()))
489 .gap_0p5()
490 .child(
491 Icon::new(IconName::GitWorktree)
492 .size(IconSize::XSmall)
493 .color(Color::Muted),
494 )
495 .child(label)
496 .tooltip(move |_, cx| {
497 Tooltip::with_meta(
498 tooltip_title,
499 None,
500 tooltip_meta.clone(),
501 cx,
502 )
503 })
504 .into_any_element(),
505 );
506 }
507
508 if self.pending_worktree_restore {
509 let on_cancel = self.on_cancel_restore.take();
510 let restore_element = h_flex()
511 .id(format!("{}-worktree-restore", self.id.clone()))
512 .gap_1()
513 .child(
514 Icon::new(IconName::LoadCircle)
515 .size(IconSize::XSmall)
516 .color(Color::Muted)
517 .with_rotate_animation(2),
518 )
519 .child(
520 Label::new("Restoring worktree\u{2026}")
521 .size(LabelSize::Small)
522 .color(Color::Muted),
523 )
524 .when_some(on_cancel, |this, on_cancel| {
525 this.child(
526 IconButton::new(
527 format!("{}-cancel-restore", self.id.clone()),
528 IconName::Close,
529 )
530 .icon_size(IconSize::XSmall)
531 .icon_color(Color::Muted)
532 .tooltip(Tooltip::text("Cancel Restore"))
533 .on_click(
534 move |event, window, cx| {
535 cx.stop_propagation();
536 on_cancel(event, window, cx);
537 },
538 ),
539 )
540 })
541 .tooltip(Tooltip::text("Restoring the Git worktree for this thread"))
542 .into_any_element();
543 worktree_labels.push(restore_element);
544 }
545
546 this.child(
547 h_flex()
548 .min_w_0()
549 .gap_1p5()
550 .child(icon_container()) // Icon Spacing
551 .when_some(self.project_name, |this, name| {
552 this.child(
553 Label::new(name).size(LabelSize::Small).color(Color::Muted),
554 )
555 })
556 .when(
557 has_project_name && (has_project_paths || has_worktree),
558 |this| this.child(dot_separator()),
559 )
560 .when_some(project_paths, |this, paths| {
561 this.child(
562 Label::new(paths)
563 .size(LabelSize::Small)
564 .color(Color::Muted)
565 .into_any_element(),
566 )
567 })
568 .when(has_project_paths && has_worktree, |this| {
569 this.child(dot_separator())
570 })
571 .children(worktree_labels)
572 .when(
573 (has_project_name || has_project_paths || has_worktree)
574 && (has_diff_stats || has_timestamp),
575 |this| this.child(dot_separator()),
576 )
577 .when(has_diff_stats, |this| {
578 this.child(
579 DiffStat::new(diff_stat_id, added_count, removed_count)
580 .tooltip("Unreviewed Changes"),
581 )
582 })
583 .when(has_diff_stats && has_timestamp, |this| {
584 this.child(dot_separator())
585 })
586 .when(has_timestamp, |this| {
587 this.child(
588 Label::new(timestamp.clone())
589 .size(LabelSize::Small)
590 .color(Color::Muted),
591 )
592 }),
593 )
594 },
595 )
596 .when_some(self.on_click, |this, on_click| this.on_click(on_click))
597 }
598}
599
600impl Component for ThreadItem {
601 fn scope() -> ComponentScope {
602 ComponentScope::Agent
603 }
604
605 fn preview(_window: &mut Window, cx: &mut App) -> Option<AnyElement> {
606 let color = cx.theme().colors();
607 let bg = color
608 .title_bar_background
609 .blend(color.panel_background.opacity(0.25));
610
611 let container = || {
612 v_flex()
613 .w_72()
614 .border_1()
615 .border_color(color.border_variant)
616 .bg(bg)
617 };
618
619 let thread_item_examples = vec![
620 single_example(
621 "Default (minutes)",
622 container()
623 .child(
624 ThreadItem::new("ti-1", "Linking to the Agent Panel Depending on Settings")
625 .icon(IconName::AiOpenAi)
626 .timestamp("15m"),
627 )
628 .into_any_element(),
629 ),
630 single_example(
631 "Notified (weeks)",
632 container()
633 .child(
634 ThreadItem::new("ti-2", "Refine thread view scrolling behavior")
635 .timestamp("1w")
636 .notified(true),
637 )
638 .into_any_element(),
639 ),
640 single_example(
641 "Waiting for Confirmation",
642 container()
643 .child(
644 ThreadItem::new("ti-2b", "Execute shell command in terminal")
645 .timestamp("2h")
646 .status(AgentThreadStatus::WaitingForConfirmation),
647 )
648 .into_any_element(),
649 ),
650 single_example(
651 "Error",
652 container()
653 .child(
654 ThreadItem::new("ti-2c", "Failed to connect to language server")
655 .timestamp("5h")
656 .status(AgentThreadStatus::Error),
657 )
658 .into_any_element(),
659 ),
660 single_example(
661 "Running Agent",
662 container()
663 .child(
664 ThreadItem::new("ti-3", "Add line numbers option to FileEditBlock")
665 .icon(IconName::AiClaude)
666 .timestamp("23h")
667 .status(AgentThreadStatus::Running),
668 )
669 .into_any_element(),
670 ),
671 single_example(
672 "In Worktree",
673 container()
674 .child(
675 ThreadItem::new("ti-4", "Add line numbers option to FileEditBlock")
676 .icon(IconName::AiClaude)
677 .timestamp("2w")
678 .worktrees(vec![ThreadItemWorktreeInfo {
679 name: "link-agent-panel".into(),
680 full_path: "link-agent-panel".into(),
681 highlight_positions: Vec::new(),
682 }]),
683 )
684 .into_any_element(),
685 ),
686 single_example(
687 "With Changes (months)",
688 container()
689 .child(
690 ThreadItem::new("ti-5", "Managing user and project settings interactions")
691 .icon(IconName::AiClaude)
692 .timestamp("1mo")
693 .added(10)
694 .removed(3),
695 )
696 .into_any_element(),
697 ),
698 single_example(
699 "Worktree + Changes + Timestamp",
700 container()
701 .child(
702 ThreadItem::new("ti-5b", "Full metadata example")
703 .icon(IconName::AiClaude)
704 .worktrees(vec![ThreadItemWorktreeInfo {
705 name: "my-project".into(),
706 full_path: "my-project".into(),
707 highlight_positions: Vec::new(),
708 }])
709 .added(42)
710 .removed(17)
711 .timestamp("3w"),
712 )
713 .into_any_element(),
714 ),
715 single_example(
716 "Selected Item",
717 container()
718 .child(
719 ThreadItem::new("ti-6", "Refine textarea interaction behavior")
720 .icon(IconName::AiGemini)
721 .timestamp("45m")
722 .selected(true),
723 )
724 .into_any_element(),
725 ),
726 single_example(
727 "Focused Item (Keyboard Selection)",
728 container()
729 .child(
730 ThreadItem::new("ti-7", "Implement keyboard navigation")
731 .icon(IconName::AiClaude)
732 .timestamp("12h")
733 .focused(true),
734 )
735 .into_any_element(),
736 ),
737 single_example(
738 "Selected + Focused",
739 container()
740 .child(
741 ThreadItem::new("ti-8", "Active and keyboard-focused thread")
742 .icon(IconName::AiGemini)
743 .timestamp("2mo")
744 .selected(true)
745 .focused(true),
746 )
747 .into_any_element(),
748 ),
749 single_example(
750 "Hovered with Action Slot",
751 container()
752 .child(
753 ThreadItem::new("ti-9", "Hover to see action button")
754 .icon(IconName::AiClaude)
755 .timestamp("6h")
756 .hovered(true)
757 .action_slot(
758 IconButton::new("delete", IconName::Trash)
759 .icon_size(IconSize::Small)
760 .icon_color(Color::Muted),
761 ),
762 )
763 .into_any_element(),
764 ),
765 single_example(
766 "Search Highlight",
767 container()
768 .child(
769 ThreadItem::new("ti-10", "Implement keyboard navigation")
770 .icon(IconName::AiClaude)
771 .timestamp("4w")
772 .highlight_positions(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
773 )
774 .into_any_element(),
775 ),
776 single_example(
777 "Worktree Search Highlight",
778 container()
779 .child(
780 ThreadItem::new("ti-11", "Search in worktree name")
781 .icon(IconName::AiClaude)
782 .timestamp("3mo")
783 .worktrees(vec![ThreadItemWorktreeInfo {
784 name: "my-project-name".into(),
785 full_path: "my-project-name".into(),
786 highlight_positions: vec![3, 4, 5, 6, 7, 8, 9, 10, 11],
787 }]),
788 )
789 .into_any_element(),
790 ),
791 ];
792
793 Some(
794 example_group(thread_item_examples)
795 .vertical()
796 .into_any_element(),
797 )
798 }
799}