Skip to repository content951 lines · 36.1 KB · rust
tenant.openagents/omega
No repository description is available.
OpenAgents Git authority 2026-07-28T02:54:42.220Z Public web read
NIP-34 coordinate
30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omegaMaintainersHidden in public view
References2 branches · 1 tag
Read-only clone
git clone https://openagents.com/git/tenant.openagents/omega.gitBrowse files
entry_view_state.rs
1use std::{ops::Range, sync::Arc};
2
3use acp_thread::{AcpThread, AgentThreadEntry, AssistantMessageChunk};
4use agent::ThreadStore;
5use agent_client_protocol::schema::v1 as acp;
6use agent_settings::AgentSettings;
7use collections::{HashMap, HashSet};
8use editor::{
9 Editor, EditorEvent, EditorMode, MinimapVisibility, RestoreOnlyUnstagedDiffHunkDelegate,
10 SizingBehavior,
11};
12use gpui::{
13 AnyEntity, App, AppContext as _, Entity, EntityId, EventEmitter, FocusHandle, Focusable,
14 ScrollHandle, TextStyleRefinement, WeakEntity, Window,
15};
16use language::language_settings::SoftWrap;
17use project::{AgentId, Project, project_settings::DiagnosticSeverity};
18use rope::Point;
19use settings::{Settings as _, ThinkingBlockDisplay};
20use terminal_view::TerminalView;
21use theme_settings::ThemeSettings;
22use ui::{Context, TextSize};
23use workspace::Workspace;
24
25use crate::message_editor::{MessageEditor, MessageEditorEvent, SharedSessionCapabilities};
26
27/// Maps an entry index through the removal of `removed` (a contiguous range of
28/// entries), returning `None` if the index referred to a removed entry.
29fn reindex_after_removal(index: usize, removed: &Range<usize>) -> Option<usize> {
30 if index < removed.start {
31 Some(index)
32 } else if index < removed.end {
33 None
34 } else {
35 Some(index - removed.len())
36 }
37}
38
39pub struct EntryViewState {
40 workspace: WeakEntity<Workspace>,
41 project: WeakEntity<Project>,
42 thread_store: Option<Entity<ThreadStore>>,
43 entries: Vec<Entry>,
44 session_capabilities: SharedSessionCapabilities,
45 agent_id: AgentId,
46 expanded_thinking_blocks: HashSet<(usize, usize)>,
47 auto_expanded_thinking_block: Option<(usize, usize)>,
48 user_toggled_thinking_blocks: HashSet<(usize, usize)>,
49 expanded_compactions: HashSet<usize>,
50 expanded_tool_calls: HashSet<acp::ToolCallId>,
51}
52
53impl EntryViewState {
54 pub fn new(
55 workspace: WeakEntity<Workspace>,
56 project: WeakEntity<Project>,
57 thread_store: Option<Entity<ThreadStore>>,
58 session_capabilities: SharedSessionCapabilities,
59 agent_id: AgentId,
60 ) -> Self {
61 Self {
62 workspace,
63 project,
64 thread_store,
65 entries: Vec::new(),
66 session_capabilities,
67 agent_id,
68 expanded_thinking_blocks: HashSet::default(),
69 auto_expanded_thinking_block: None,
70 user_toggled_thinking_blocks: HashSet::default(),
71 expanded_compactions: HashSet::default(),
72 expanded_tool_calls: HashSet::default(),
73 }
74 }
75
76 pub(crate) fn is_tool_call_expanded(&self, tool_call_id: &acp::ToolCallId) -> bool {
77 self.expanded_tool_calls.contains(tool_call_id)
78 }
79
80 pub(crate) fn expand_tool_call(&mut self, tool_call_id: acp::ToolCallId) {
81 self.expanded_tool_calls.insert(tool_call_id);
82 }
83
84 pub(crate) fn collapse_tool_call(&mut self, tool_call_id: &acp::ToolCallId) {
85 self.expanded_tool_calls.remove(tool_call_id);
86 }
87
88 pub(crate) fn toggle_tool_call_expansion(&mut self, tool_call_id: &acp::ToolCallId) {
89 if !self.expanded_tool_calls.remove(tool_call_id) {
90 self.expanded_tool_calls.insert(tool_call_id.clone());
91 }
92 }
93
94 pub(crate) fn is_compaction_expanded(&self, entry_ix: usize) -> bool {
95 self.expanded_compactions.contains(&entry_ix)
96 }
97
98 pub(crate) fn collapse_compaction(&mut self, entry_ix: usize) {
99 self.expanded_compactions.remove(&entry_ix);
100 }
101
102 pub(crate) fn toggle_compaction_expansion(&mut self, entry_ix: usize) {
103 if !self.expanded_compactions.remove(&entry_ix) {
104 self.expanded_compactions.insert(entry_ix);
105 }
106 }
107
108 pub(crate) fn clear_auto_expand_tracking(&mut self) {
109 self.auto_expanded_thinking_block = None;
110 }
111
112 pub(crate) fn is_auto_expanded_thinking_block(&self, key: (usize, usize)) -> bool {
113 self.auto_expanded_thinking_block == Some(key)
114 }
115
116 pub(crate) fn auto_expand_streaming_thought(&mut self, thread: &AcpThread, cx: &App) -> bool {
117 let thinking_display = AgentSettings::get_global(cx).thinking_display;
118
119 if !matches!(
120 thinking_display,
121 ThinkingBlockDisplay::Auto | ThinkingBlockDisplay::Preview
122 ) {
123 return false;
124 }
125
126 let last_ix = thread.entries().len().saturating_sub(1);
127 let key = match thread.entries().get(last_ix) {
128 Some(AgentThreadEntry::AssistantMessage(message)) => match message.chunks.last() {
129 Some(AssistantMessageChunk::Thought { .. }) => {
130 Some((last_ix, message.chunks.len() - 1))
131 }
132 _ => None,
133 },
134 _ => None,
135 };
136
137 if let Some(key) = key {
138 if self.auto_expanded_thinking_block != Some(key) {
139 self.auto_expanded_thinking_block = Some(key);
140 self.expanded_thinking_blocks.insert(key);
141 return true;
142 }
143 } else if self.auto_expanded_thinking_block.is_some() {
144 if thinking_display == ThinkingBlockDisplay::Auto
145 && let Some(key) = self.auto_expanded_thinking_block
146 && !self.user_toggled_thinking_blocks.contains(&key)
147 {
148 self.expanded_thinking_blocks.remove(&key);
149 }
150 self.auto_expanded_thinking_block = None;
151 return true;
152 }
153
154 false
155 }
156
157 pub(crate) fn toggle_thinking_block_expansion(&mut self, key: (usize, usize), cx: &App) {
158 match AgentSettings::get_global(cx).thinking_display {
159 ThinkingBlockDisplay::Auto => {
160 let is_open = self.expanded_thinking_blocks.contains(&key)
161 || self.user_toggled_thinking_blocks.contains(&key);
162
163 if is_open {
164 self.expanded_thinking_blocks.remove(&key);
165 self.user_toggled_thinking_blocks.remove(&key);
166 } else {
167 self.expanded_thinking_blocks.insert(key);
168 self.user_toggled_thinking_blocks.insert(key);
169 }
170 }
171 ThinkingBlockDisplay::Preview => {
172 let is_user_expanded = self.user_toggled_thinking_blocks.contains(&key);
173 let is_in_expanded_set = self.expanded_thinking_blocks.contains(&key);
174
175 if is_user_expanded {
176 self.user_toggled_thinking_blocks.remove(&key);
177 self.expanded_thinking_blocks.remove(&key);
178 } else if is_in_expanded_set {
179 self.user_toggled_thinking_blocks.insert(key);
180 } else {
181 self.expanded_thinking_blocks.insert(key);
182 self.user_toggled_thinking_blocks.insert(key);
183 }
184 }
185 ThinkingBlockDisplay::AlwaysExpanded => {
186 if self.user_toggled_thinking_blocks.contains(&key) {
187 self.user_toggled_thinking_blocks.remove(&key);
188 } else {
189 self.user_toggled_thinking_blocks.insert(key);
190 }
191 }
192 ThinkingBlockDisplay::AlwaysCollapsed => {
193 if self.user_toggled_thinking_blocks.contains(&key) {
194 self.user_toggled_thinking_blocks.remove(&key);
195 self.expanded_thinking_blocks.remove(&key);
196 } else {
197 self.expanded_thinking_blocks.insert(key);
198 self.user_toggled_thinking_blocks.insert(key);
199 }
200 }
201 }
202 }
203
204 pub(crate) fn thinking_block_state(&self, key: (usize, usize), cx: &App) -> (bool, bool) {
205 let is_user_toggled = self.user_toggled_thinking_blocks.contains(&key);
206 let is_in_expanded_set = self.expanded_thinking_blocks.contains(&key);
207
208 match AgentSettings::get_global(cx).thinking_display {
209 ThinkingBlockDisplay::Auto => {
210 let is_open = is_user_toggled || is_in_expanded_set;
211 (is_open, false)
212 }
213 ThinkingBlockDisplay::Preview => {
214 let is_open = is_user_toggled || is_in_expanded_set;
215 let is_constrained = is_in_expanded_set && !is_user_toggled;
216 (is_open, is_constrained)
217 }
218 ThinkingBlockDisplay::AlwaysExpanded => (!is_user_toggled, false),
219 ThinkingBlockDisplay::AlwaysCollapsed => (is_user_toggled, false),
220 }
221 }
222
223 pub fn entry(&self, index: usize) -> Option<&Entry> {
224 self.entries.get(index)
225 }
226
227 pub fn sync_entry(
228 &mut self,
229 index: usize,
230 thread: &Entity<AcpThread>,
231 window: &mut Window,
232 cx: &mut Context<Self>,
233 ) {
234 let Some(thread_entry) = thread.read(cx).entries().get(index) else {
235 return;
236 };
237
238 match thread_entry {
239 AgentThreadEntry::UserMessage(message) => {
240 let can_rewind = thread.read(cx).supports_truncate(cx);
241 let has_client_id = message.client_id.is_some();
242 let is_subagent = thread.read(cx).parent_session_id().is_some();
243 let chunks = message.chunks.clone();
244 if let Some(Entry::UserMessage(editor)) = self.entries.get_mut(index) {
245 if !editor.focus_handle(cx).is_focused(window) {
246 // Only update if we are not editing.
247 // If we are, cancelling the edit will set the message to the newest content.
248 editor.update(cx, |editor, cx| {
249 editor.set_message(chunks, window, cx);
250 });
251 }
252 } else {
253 let message_editor = cx.new(|cx| {
254 let mut editor = MessageEditor::new(
255 self.workspace.clone(),
256 self.project.clone(),
257 self.thread_store.clone(),
258 self.session_capabilities.clone(),
259 self.agent_id.clone(),
260 "Edit message - @ to include context",
261 editor::EditorMode::AutoHeight {
262 min_lines: 1,
263 max_lines: None,
264 },
265 window,
266 cx,
267 );
268 if !can_rewind || !has_client_id || is_subagent {
269 editor.set_read_only(true, cx);
270 }
271 editor.set_message(chunks, window, cx);
272 editor
273 });
274 cx.subscribe(&message_editor, move |_, editor, event, cx| {
275 cx.emit(EntryViewEvent {
276 entry_index: index,
277 view_event: ViewEvent::MessageEditorEvent(editor, event.clone()),
278 })
279 })
280 .detach();
281 self.set_entry(index, Entry::UserMessage(message_editor));
282 }
283 }
284 AgentThreadEntry::ToolCall(tool_call) => {
285 let id = tool_call.id.clone();
286 let terminals = tool_call.terminals().cloned().collect::<Vec<_>>();
287 let diffs = tool_call.diffs().cloned().collect::<Vec<_>>();
288
289 let views = if let Some(Entry::ToolCall(tool_call)) = self.entries.get_mut(index) {
290 &mut tool_call.content
291 } else {
292 self.set_entry(
293 index,
294 Entry::ToolCall(ToolCallEntry {
295 content: HashMap::default(),
296 focus_handle: cx.focus_handle(),
297 }),
298 );
299 let Some(Entry::ToolCall(tool_call)) = self.entries.get_mut(index) else {
300 unreachable!()
301 };
302 &mut tool_call.content
303 };
304
305 let is_tool_call_completed =
306 matches!(tool_call.status, acp_thread::ToolCallStatus::Completed);
307
308 for terminal in terminals {
309 match views.entry(terminal.entity_id()) {
310 collections::hash_map::Entry::Vacant(entry) => {
311 let element = create_terminal(
312 self.workspace.clone(),
313 self.project.clone(),
314 terminal.clone(),
315 window,
316 cx,
317 )
318 .into_any();
319 cx.emit(EntryViewEvent {
320 entry_index: index,
321 view_event: ViewEvent::NewTerminal(id.clone()),
322 });
323 entry.insert(element);
324 }
325 collections::hash_map::Entry::Occupied(_entry) => {
326 if is_tool_call_completed && terminal.read(cx).output().is_none() {
327 cx.emit(EntryViewEvent {
328 entry_index: index,
329 view_event: ViewEvent::TerminalMovedToBackground(id.clone()),
330 });
331 }
332 }
333 }
334 }
335
336 for diff in diffs {
337 views.entry(diff.entity_id()).or_insert_with(|| {
338 let editor = create_editor_diff(diff.clone(), window, cx);
339 cx.subscribe(&editor, {
340 let diff = diff.clone();
341 let entry_index = index;
342 move |_this, _editor, event: &EditorEvent, cx| {
343 if let EditorEvent::OpenExcerptsRequested {
344 selections_by_buffer,
345 split,
346 } = event
347 {
348 let multibuffer = diff.read(cx).multibuffer();
349 if let Some((buffer_id, (ranges, _))) =
350 selections_by_buffer.iter().next()
351 {
352 if let Some(buffer) =
353 multibuffer.read(cx).buffer(*buffer_id)
354 {
355 if let Some(range) = ranges.first() {
356 let point =
357 buffer.read(cx).offset_to_point(range.start.0);
358 if let Some(path) = diff.read(cx).file_path(cx) {
359 cx.emit(EntryViewEvent {
360 entry_index,
361 view_event: ViewEvent::OpenDiffLocation {
362 path,
363 position: point,
364 split: *split,
365 },
366 });
367 }
368 }
369 }
370 }
371 }
372 }
373 })
374 .detach();
375 cx.emit(EntryViewEvent {
376 entry_index: index,
377 view_event: ViewEvent::NewDiff(id.clone()),
378 });
379 editor.into_any()
380 });
381 }
382 }
383 AgentThreadEntry::Elicitation(_) => {
384 if !matches!(self.entries.get(index), Some(Entry::Elicitation { .. })) {
385 self.set_entry(
386 index,
387 Entry::Elicitation {
388 focus_handle: cx.focus_handle(),
389 },
390 );
391 }
392 }
393 AgentThreadEntry::AssistantMessage(message) => {
394 let entry = if let Some(Entry::AssistantMessage(entry)) =
395 self.entries.get_mut(index)
396 {
397 entry
398 } else {
399 self.set_entry(
400 index,
401 Entry::AssistantMessage(AssistantMessageEntry {
402 scroll_handles_by_chunk_index: HashMap::default(),
403 focus_handle: cx.focus_handle(),
404 }),
405 );
406 let Some(Entry::AssistantMessage(entry)) = self.entries.get_mut(index) else {
407 unreachable!()
408 };
409 entry
410 };
411 entry.sync(message);
412 }
413 AgentThreadEntry::CompletedPlan(_) => {
414 if !matches!(self.entries.get(index), Some(Entry::CompletedPlan)) {
415 self.set_entry(index, Entry::CompletedPlan);
416 }
417 }
418 AgentThreadEntry::ContextCompaction(_) => {
419 if !matches!(self.entries.get(index), Some(Entry::ContextCompaction)) {
420 self.set_entry(index, Entry::ContextCompaction);
421 }
422 }
423 // OMEGA-DELTA-0045. A host-authored note has no editor, no tool
424 // content and no focusable body — it is a rendered line of text.
425 AgentThreadEntry::SystemNote(_) => {
426 if !matches!(self.entries.get(index), Some(Entry::SystemNote)) {
427 self.set_entry(index, Entry::SystemNote);
428 }
429 }
430 };
431 }
432
433 fn set_entry(&mut self, index: usize, entry: Entry) {
434 if index == self.entries.len() {
435 self.entries.push(entry);
436 } else {
437 self.entries[index] = entry;
438 }
439 }
440
441 pub fn remove(&mut self, range: Range<usize>) {
442 self.entries.drain(range.clone());
443
444 self.expanded_compactions = self
445 .expanded_compactions
446 .iter()
447 .filter_map(|&entry_ix| reindex_after_removal(entry_ix, &range))
448 .collect();
449 self.expanded_thinking_blocks = self
450 .expanded_thinking_blocks
451 .iter()
452 .filter_map(|&(entry_ix, chunk_ix)| {
453 reindex_after_removal(entry_ix, &range).map(|entry_ix| (entry_ix, chunk_ix))
454 })
455 .collect();
456 self.user_toggled_thinking_blocks = self
457 .user_toggled_thinking_blocks
458 .iter()
459 .filter_map(|&(entry_ix, chunk_ix)| {
460 reindex_after_removal(entry_ix, &range).map(|entry_ix| (entry_ix, chunk_ix))
461 })
462 .collect();
463 self.auto_expanded_thinking_block =
464 self.auto_expanded_thinking_block
465 .and_then(|(entry_ix, chunk_ix)| {
466 reindex_after_removal(entry_ix, &range).map(|entry_ix| (entry_ix, chunk_ix))
467 });
468 }
469
470 pub fn agent_ui_font_size_changed(&mut self, cx: &mut App) {
471 for entry in self.entries.iter() {
472 match entry {
473 Entry::UserMessage { .. }
474 | Entry::AssistantMessage { .. }
475 | Entry::Elicitation { .. }
476 | Entry::CompletedPlan
477 | Entry::ContextCompaction
478 | Entry::SystemNote => {}
479 Entry::ToolCall(ToolCallEntry { content, .. }) => {
480 for view in content.values() {
481 if let Ok(diff_editor) = view.clone().downcast::<Editor>() {
482 diff_editor.update(cx, |diff_editor, cx| {
483 diff_editor.set_text_style_refinement(
484 diff_editor_text_style_refinement(cx),
485 );
486 cx.notify();
487 })
488 }
489 }
490 }
491 }
492 }
493 }
494}
495
496impl EventEmitter<EntryViewEvent> for EntryViewState {}
497
498pub struct EntryViewEvent {
499 pub entry_index: usize,
500 pub view_event: ViewEvent,
501}
502
503pub enum ViewEvent {
504 NewDiff(acp::ToolCallId),
505 NewTerminal(acp::ToolCallId),
506 TerminalMovedToBackground(acp::ToolCallId),
507 MessageEditorEvent(Entity<MessageEditor>, MessageEditorEvent),
508 OpenDiffLocation {
509 path: String,
510 position: Point,
511 split: bool,
512 },
513}
514
515#[derive(Debug)]
516pub struct AssistantMessageEntry {
517 scroll_handles_by_chunk_index: HashMap<usize, ScrollHandle>,
518 focus_handle: FocusHandle,
519}
520
521impl AssistantMessageEntry {
522 pub fn scroll_handle_for_chunk(&self, ix: usize) -> Option<ScrollHandle> {
523 self.scroll_handles_by_chunk_index.get(&ix).cloned()
524 }
525
526 pub fn sync(&mut self, message: &acp_thread::AssistantMessage) {
527 if let Some(acp_thread::AssistantMessageChunk::Thought { .. }) = message.chunks.last() {
528 let ix = message.chunks.len() - 1;
529 let handle = self.scroll_handles_by_chunk_index.entry(ix).or_default();
530 handle.scroll_to_bottom();
531 }
532 }
533}
534
535#[derive(Debug)]
536pub struct ToolCallEntry {
537 content: HashMap<EntityId, AnyEntity>,
538 focus_handle: FocusHandle,
539}
540
541#[derive(Debug)]
542pub enum Entry {
543 UserMessage(Entity<MessageEditor>),
544 AssistantMessage(AssistantMessageEntry),
545 ToolCall(ToolCallEntry),
546 Elicitation { focus_handle: FocusHandle },
547 CompletedPlan,
548 ContextCompaction,
549 /// OMEGA-DELTA-0045. The view side of [`AgentThreadEntry::SystemNote`].
550 SystemNote,
551}
552
553impl Entry {
554 pub fn focus_handle(&self, cx: &App) -> Option<FocusHandle> {
555 match self {
556 Self::UserMessage(editor) => Some(editor.read(cx).focus_handle(cx)),
557 Self::AssistantMessage(message) => Some(message.focus_handle.clone()),
558 Self::ToolCall(tool_call) => Some(tool_call.focus_handle.clone()),
559 Self::Elicitation { focus_handle } => Some(focus_handle.clone()),
560 Self::CompletedPlan | Self::ContextCompaction | Self::SystemNote => None,
561 }
562 }
563
564 pub fn message_editor(&self) -> Option<&Entity<MessageEditor>> {
565 match self {
566 Self::UserMessage(editor) => Some(editor),
567 Self::AssistantMessage(_)
568 | Self::ToolCall(_)
569 | Self::Elicitation { .. }
570 | Self::CompletedPlan
571 | Self::ContextCompaction
572 | Self::SystemNote => None,
573 }
574 }
575
576 pub fn editor_for_diff(&self, diff: &Entity<acp_thread::Diff>) -> Option<Entity<Editor>> {
577 self.content_map()?
578 .get(&diff.entity_id())
579 .cloned()
580 .and_then(|entity| entity.downcast::<Editor>().ok())
581 }
582
583 pub fn terminal(
584 &self,
585 terminal: &Entity<acp_thread::Terminal>,
586 ) -> Option<Entity<TerminalView>> {
587 self.content_map()?
588 .get(&terminal.entity_id())
589 .cloned()
590 .and_then(|entity| entity.downcast::<TerminalView>().ok())
591 }
592
593 pub fn scroll_handle_for_assistant_message_chunk(
594 &self,
595 chunk_ix: usize,
596 ) -> Option<ScrollHandle> {
597 match self {
598 Self::AssistantMessage(message) => message.scroll_handle_for_chunk(chunk_ix),
599 Self::UserMessage(_)
600 | Self::ToolCall(_)
601 | Self::Elicitation { .. }
602 | Self::CompletedPlan
603 | Self::ContextCompaction
604 | Self::SystemNote => None,
605 }
606 }
607
608 fn content_map(&self) -> Option<&HashMap<EntityId, AnyEntity>> {
609 match self {
610 Self::ToolCall(ToolCallEntry { content, .. }) => Some(content),
611 _ => None,
612 }
613 }
614
615 #[cfg(test)]
616 pub fn has_content(&self) -> bool {
617 match self {
618 Self::ToolCall(ToolCallEntry { content, .. }) => !content.is_empty(),
619 Self::UserMessage(_)
620 | Self::AssistantMessage(_)
621 | Self::Elicitation { .. }
622 | Self::CompletedPlan
623 | Self::ContextCompaction
624 | Self::SystemNote => false,
625 }
626 }
627}
628
629impl Focusable for ToolCallEntry {
630 fn focus_handle(&self, _cx: &App) -> FocusHandle {
631 self.focus_handle.clone()
632 }
633}
634
635impl Focusable for Entry {
636 fn focus_handle(&self, cx: &App) -> FocusHandle {
637 match self {
638 Self::UserMessage(editor) => editor.read(cx).focus_handle(cx),
639 Self::AssistantMessage(message) => message.focus_handle.clone(),
640 Self::ToolCall(tool_call) => tool_call.focus_handle.clone(),
641 Self::Elicitation { focus_handle } => focus_handle.clone(),
642 Self::CompletedPlan | Self::ContextCompaction | Self::SystemNote => cx.focus_handle(),
643 }
644 }
645}
646
647fn create_terminal(
648 workspace: WeakEntity<Workspace>,
649 project: WeakEntity<Project>,
650 terminal: Entity<acp_thread::Terminal>,
651 window: &mut Window,
652 cx: &mut App,
653) -> Entity<TerminalView> {
654 cx.new(|cx| {
655 let mut view = TerminalView::new(
656 terminal.read(cx).inner().clone(),
657 workspace,
658 None,
659 project,
660 window,
661 cx,
662 );
663 view.set_embedded_mode(Some(1000), cx);
664 view
665 })
666}
667
668fn create_editor_diff(
669 diff: Entity<acp_thread::Diff>,
670 window: &mut Window,
671 cx: &mut App,
672) -> Entity<Editor> {
673 cx.new(|cx| {
674 let mut editor = Editor::new(
675 EditorMode::Full {
676 scale_ui_elements_with_buffer_font_size: false,
677 show_active_line_background: false,
678 sizing_behavior: SizingBehavior::SizeByContent,
679 },
680 diff.read(cx).multibuffer().clone(),
681 None,
682 window,
683 cx,
684 );
685 editor.set_show_gutter(false, cx);
686 editor.disable_diagnostics(cx);
687 editor.set_max_diagnostics_severity(DiagnosticSeverity::Off, cx);
688 editor.disable_expand_excerpt_buttons(cx);
689 editor.set_show_vertical_scrollbar(false, cx);
690 editor.set_minimap_visibility(MinimapVisibility::Disabled, window, cx);
691 editor.set_soft_wrap_mode(SoftWrap::None, cx);
692 editor.set_forbid_vertical_scroll(true);
693 editor.set_show_indent_guides(false, cx);
694 editor.set_read_only(true);
695 editor.set_delegate_open_excerpts(true);
696 editor.set_show_bookmarks(false, cx);
697 editor.set_show_breakpoints(false, cx);
698 editor.set_show_code_actions(false, cx);
699 editor.set_show_git_diff_gutter(false, cx);
700 editor.set_expand_all_diff_hunks(cx);
701 editor.set_diff_hunk_delegate(Some(Arc::new(RestoreOnlyUnstagedDiffHunkDelegate)), cx);
702 editor.set_text_style_refinement(diff_editor_text_style_refinement(cx));
703 editor
704 })
705}
706
707fn diff_editor_text_style_refinement(cx: &mut App) -> TextStyleRefinement {
708 TextStyleRefinement {
709 font_size: Some(
710 TextSize::Small
711 .rems(cx)
712 .to_pixels(ThemeSettings::get_global(cx).agent_ui_font_size(cx))
713 .into(),
714 ),
715 ..Default::default()
716 }
717}
718
719#[cfg(test)]
720mod tests {
721 use std::path::Path;
722 use std::rc::Rc;
723 use std::sync::Arc;
724
725 use acp_thread::{AgentConnection, StubAgentConnection};
726 use agent_client_protocol::schema::v1 as acp;
727 use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
728 use editor::RowInfo;
729 use fs::FakeFs;
730 use gpui::{AppContext as _, TestAppContext};
731 use parking_lot::RwLock;
732
733 use crate::entry_view_state::{Entry, EntryViewState};
734 use crate::message_editor::SessionCapabilities;
735 use multi_buffer::MultiBufferRow;
736 use pretty_assertions::assert_matches;
737 use project::Project;
738 use serde_json::json;
739 use settings::SettingsStore;
740 use util::path;
741 use workspace::{MultiWorkspace, PathList};
742
743 #[test]
744 fn test_reindex_after_removal() {
745 use super::reindex_after_removal;
746
747 // Entries before the removed range keep their index.
748 assert_eq!(reindex_after_removal(0, &(2..4)), Some(0));
749 assert_eq!(reindex_after_removal(1, &(2..4)), Some(1));
750 // Entries inside the removed range are dropped.
751 assert_eq!(reindex_after_removal(2, &(2..4)), None);
752 assert_eq!(reindex_after_removal(3, &(2..4)), None);
753 // Entries after the removed range slide down by its length.
754 assert_eq!(reindex_after_removal(4, &(2..4)), Some(2));
755 assert_eq!(reindex_after_removal(5, &(2..4)), Some(3));
756 // An empty removal range leaves indices untouched.
757 assert_eq!(reindex_after_removal(3, &(2..2)), Some(3));
758 }
759
760 #[gpui::test]
761 async fn test_diff_sync(cx: &mut TestAppContext) {
762 init_test(cx);
763 let fs = FakeFs::new(cx.executor());
764 fs.insert_tree(
765 "/project",
766 json!({
767 "hello.txt": "hi world"
768 }),
769 )
770 .await;
771 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
772
773 let (multi_workspace, cx) =
774 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
775 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
776
777 let tool_call = acp::ToolCall::new("tool", "Tool call")
778 .status(acp::ToolCallStatus::InProgress)
779 .content(vec![acp::ToolCallContent::Diff(
780 acp::Diff::new("/project/hello.txt", "hello world").old_text("hi world"),
781 )]);
782 let connection = Rc::new(StubAgentConnection::new());
783 let thread = cx
784 .update(|_, cx| {
785 connection.clone().new_session(
786 project.clone(),
787 PathList::new(&[Path::new(path!("/project"))]),
788 cx,
789 )
790 })
791 .await
792 .unwrap();
793 let session_id = thread.update(cx, |thread, _| thread.session_id().clone());
794
795 cx.update(|_, cx| {
796 connection.send_update(session_id, acp::SessionUpdate::ToolCall(tool_call), cx)
797 });
798
799 let thread_store = None;
800
801 let view_state = cx.new(|_cx| {
802 EntryViewState::new(
803 workspace.downgrade(),
804 project.downgrade(),
805 thread_store,
806 Arc::new(RwLock::new(SessionCapabilities::default())),
807 "Test Agent".into(),
808 )
809 });
810
811 view_state.update_in(cx, |view_state, window, cx| {
812 view_state.sync_entry(0, &thread, window, cx)
813 });
814
815 let diff = thread.read_with(cx, |thread, _| {
816 thread
817 .entries()
818 .get(0)
819 .unwrap()
820 .diffs()
821 .next()
822 .unwrap()
823 .clone()
824 });
825
826 cx.run_until_parked();
827
828 let diff_editor = view_state.read_with(cx, |view_state, _cx| {
829 view_state.entry(0).unwrap().editor_for_diff(&diff).unwrap()
830 });
831 assert_eq!(
832 diff_editor.read_with(cx, |editor, cx| editor.text(cx)),
833 "hi world\nhello world"
834 );
835 let row_infos = diff_editor.read_with(cx, |editor, cx| {
836 let multibuffer = editor.buffer().read(cx);
837 multibuffer
838 .snapshot(cx)
839 .row_infos(MultiBufferRow(0))
840 .collect::<Vec<_>>()
841 });
842 assert_matches!(
843 row_infos.as_slice(),
844 [
845 RowInfo {
846 multibuffer_row: Some(MultiBufferRow(0)),
847 diff_status: Some(DiffHunkStatus {
848 kind: DiffHunkStatusKind::Deleted,
849 ..
850 }),
851 ..
852 },
853 RowInfo {
854 multibuffer_row: Some(MultiBufferRow(1)),
855 diff_status: Some(DiffHunkStatus {
856 kind: DiffHunkStatusKind::Added,
857 ..
858 }),
859 ..
860 }
861 ]
862 );
863 }
864
865 #[gpui::test]
866 async fn test_elicitation_preserves_entry_index(cx: &mut TestAppContext) {
867 init_test(cx);
868
869 let fs = FakeFs::new(cx.executor());
870 fs.insert_tree("/project", json!({})).await;
871 let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
872
873 let (multi_workspace, cx) =
874 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
875 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
876
877 let connection = Rc::new(StubAgentConnection::new());
878 let thread = cx
879 .update(|_, cx| {
880 connection.clone().new_session(
881 project.clone(),
882 PathList::new(&[Path::new(path!("/project"))]),
883 cx,
884 )
885 })
886 .await
887 .unwrap();
888 let session_id = thread.update(cx, |thread, _| thread.session_id().clone());
889
890 let _response_task = thread.update(cx, |thread, cx| {
891 thread
892 .request_elicitation(
893 acp::CreateElicitationRequest::new(
894 acp::ElicitationFormMode::new(
895 acp::ElicitationSessionScope::new(session_id.clone()),
896 acp::ElicitationSchema::new().string("name", true),
897 ),
898 "Provide a name",
899 ),
900 cx,
901 )
902 .unwrap()
903 });
904 cx.update(|_, cx| {
905 connection.send_update(
906 session_id,
907 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
908 acp::ContentBlock::Text(acp::TextContent::new("hello")),
909 )),
910 cx,
911 );
912 });
913
914 let view_state = cx.new(|_cx| {
915 EntryViewState::new(
916 workspace.downgrade(),
917 project.downgrade(),
918 None,
919 Arc::new(RwLock::new(SessionCapabilities::default())),
920 "Test Agent".into(),
921 )
922 });
923
924 view_state.update_in(cx, |view_state, window, cx| {
925 view_state.sync_entry(0, &thread, window, cx);
926 view_state.sync_entry(1, &thread, window, cx);
927 });
928
929 view_state.read_with(cx, |view_state, _cx| {
930 assert!(matches!(
931 view_state.entry(0),
932 Some(Entry::Elicitation { .. })
933 ));
934 assert!(matches!(
935 view_state.entry(1),
936 Some(Entry::AssistantMessage(_))
937 ));
938 });
939 }
940
941 fn init_test(cx: &mut TestAppContext) {
942 cx.update(|cx| {
943 let mut settings_store = SettingsStore::test(cx);
944 settings_store.register_setting::<feature_flags::FeatureFlagsSettings>();
945 cx.set_global(settings_store);
946 theme_settings::init(theme::LoadThemes::JustBase, cx);
947 release_channel::init(semver::Version::new(0, 0, 0), cx);
948 });
949 }
950}
951