BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / conversation.rs

conversation.rs

conversation.rs 128.2 KiB Download Raw
1use std::cell::{Cell, RefCell};
2use std::collections::{HashMap, HashSet};
3use std::path::{Path, PathBuf};
4use std::rc::Rc;
5use std::time::{Duration, Instant};
6
7use chrono::{DateTime, Local, Offset, Utc};
8use gpui_kit::assets::IconName;
9use gpui_kit::component::{
10 button::{Button, ButtonVariants as _},
11 h_flex,
12 input::{Escape, InputState},
13 message_scroller::{MessageScroller, MessageScrollerState},
14 tooltip::Tooltip,
15 v_flex,
16};
17use gpui_kit::prelude::FluentBuilder as _;
18use gpui_kit::*;
19use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget};
20use teams_core::{ExecuteAction, FileCard, LinkPreview};
21
22mod feed;
23mod pins;
24mod proposal;
25mod render_env;
26mod scheduled;
27mod shared;
28
29use super::attachments::FileActions;
30use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
31use super::call_controls::header_call_controls;
32use super::channel_tabs::ChannelPane;
33use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
34use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};
35use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
36use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
37use super::post_card::render_post;
38use super::profile_card::opens_profile;
39use super::reaction_picker::{PickHandler, ReactionPicker};
40use super::reaction_pills::{ReactionControls, ReactionPopover};
41use super::toolbar_placement::{TimelineBounds, record_bounds};
42use super::widgets::{icon, symbol};
43use crate::agents::{AgentRun, StartRequest};
44use crate::app_state::{AppEvent, AppState, Selection, selection_title};
45use crate::backend::Engine;
46use crate::card_state::CardScope;
47use crate::channel_files::DownloadSource;
48use crate::data::{is_one_on_one, others};
49use crate::demo_library::DemoLibrary;
50use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
51use crate::emoji;
52use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of};
53use crate::notice::short_error;
54use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
55use crate::pending_rows::pending_row;
56use crate::people::{local_names, resolve_names};
57use crate::reaction_model::UNKNOWN_REACTOR;
58use crate::read_state::{ReadTrigger, plan_read};
59use crate::rows::{
60 Delivery, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,
61 apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows,
62 has_own_reaction, message_draft, message_text, place_local_rows, placeholder_rows,
63 reaction_glyph, reply_excerpt, set_own_reaction, thread_list_rows, thread_rows,
64};
65use crate::runtime;
66use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
67use crate::sidebar_model::{AvatarSpec, Face};
68use crate::theme;
69use crate::translation::TranslationLine;
70use crate::typing::typing_tooltip;
71use feed::{FeedStash, subject_input};
72use render_env::RenderEnv;
73use shared::SharedState;
74
75const CHAT_OPEN_LIMIT: usize = 60;
76const CHANNEL_OPEN_LIMIT: usize = 300;
77const GROWTH_HEADROOM: usize = 20;
78const META_USER_ID: &str = "me_user_id";
79const PENDING_KEY_PREFIX: &str = "pending-";
80const DEMO_DOWNLOAD_STEPS: u8 = 10;
81const DEMO_DOWNLOAD_STEP: Duration = Duration::from_millis(100);
82const JUMP_SCAN_LIMIT: usize = 5000;
83const JUMP_CONTEXT_MESSAGES: usize = 12;
84const HIGHLIGHT_DURATION: Duration = Duration::from_secs(2);
85const PROGRESS_DELAY: Duration = Duration::from_millis(400);
86const SLOW_AFTER: Duration = Duration::from_secs(8);
87const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500);
88const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400);
89const PROGRESS_BAR_WIDTH: f32 = 0.35;
90const TYPING_LINE_HEIGHT: f32 = 22.;
91const TYPING_DOT_SIZE: f32 = 5.;
92const TYPING_DOT_COUNT: usize = 3;
93const TYPING_PULSE_PERIOD: Duration = Duration::from_millis(1200);
94
95actions!(teams, [ReplyToHovered]);
96
97#[derive(Clone, Copy)]
98enum HoverSlot {
99 Row,
100 Toolbar,
101}
102
103#[derive(Debug, Clone, PartialEq, Eq)]
104enum ViewMode {
105 Flat,
106 ThreadList,
107 Thread(String),
108}
109
110#[derive(Default)]
111struct SyncProgress {
112 messages: bool,
113 receipts: bool,
114 empty_cache: bool,
115 newest_cached: Option<DateTime<Utc>>,
116 shown_at: Option<Instant>,
117 slow: bool,
118 failed: bool,
119}
120
121impl SyncProgress {
122 fn running(&self) -> bool {
123 self.messages || self.receipts
124 }
125}
126
127struct Current {
128 selection: Selection,
129 title: String,
130 mode: ViewMode,
131 loaded_limit: usize,
132 loaded_count: usize,
133 has_older: bool,
134 loading_older: bool,
135 older_blocked: bool,
136 fetched: bool,
137 first_unread: Option<String>,
138 sync: SyncProgress,
139}
140
141struct ReactionDetails {
142 message_key: String,
143 anchor_glyph: String,
144 tab: Option<String>,
145}
146
147pub struct ConversationView {
148 app: Entity<AppState>,
149 pinned: bool,
150 scroller: Entity<MessageScrollerState>,
151 composer: Entity<Composer>,
152 subject: Entity<InputState>,
153 new_post_open: bool,
154 reply_composer: Option<Entity<Composer>>,
155 reply_root: Option<String>,
156 feed_stash: Option<FeedStash>,
157 feed_rows_seen: Rc<Cell<usize>>,
158 feed_at_top: bool,
159 draft: Entity<NewChatDraft>,
160 draft_active: bool,
161 draft_created: Option<(Vec<String>, String)>,
162 draft_error: Option<String>,
163 rows: Rc<RefCell<Vec<Row>>>,
164 current: Option<Current>,
165 pending: Vec<MessageRow>,
166 pending_counter: usize,
167 pending_outgoing: HashMap<String, Outgoing>,
168 pending_reactions: PendingReactions,
169 downloads: Downloads,
170 hovered_message: Option<String>,
171 toolbar_hovered: Option<String>,
172 timeline_bounds: TimelineBounds,
173 toolbar_pinned: Option<String>,
174 toolbar_suppressed: Option<String>,
175 recent: Entity<emoji::Recent>,
176 picker: Entity<ReactionPicker>,
177 reaction_details: Option<ReactionDetails>,
178 highlighted_message: Option<String>,
179 pin_index: usize,
180 pin_previews: HashMap<String, pins::PinPreview>,
181 notice: Option<String>,
182 scheduled_failure: Option<scheduled::ScheduledFailure>,
183 scheduled_in_flight: HashSet<String>,
184 drag_file_count: usize,
185 sync_generation: u64,
186 window_active: bool,
187 pane: ChannelPane,
188 channel_tabs: Vec<ChannelTabRecord>,
189 tab_links: HashMap<String, String>,
190 focus_handle: FocusHandle,
191 shared: SharedState,
192 demo_library: DemoLibrary,
193 new_folder_input: Option<Entity<InputState>>,
194 agent_layouts: HashMap<String, (usize, bool)>,
195 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
196 _subscriptions: Vec<Subscription>,
197}
198
199fn open_limit(selection: &Selection) -> usize {
200 match selection {
201 Selection::Chat(_) => CHAT_OPEN_LIMIT,
202 Selection::Channel(_) => CHANNEL_OPEN_LIMIT,
203 }
204}
205
206#[derive(Debug, Clone, Copy, PartialEq, Eq)]
207enum DropTarget {
208 Chat,
209 Channel,
210 Library,
211 NewChat,
212}
213
214fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String, String) {
215 let files = if count == 1 {
216 "1 file".to_owned()
217 } else {
218 format!("{count} files")
219 };
220 match target {
221 DropTarget::Chat => (
222 format!("Drop to attach to {title}"),
223 format!("{files}. Images go into the message, other files to your OneDrive."),
224 ),
225 DropTarget::Channel => (
226 format!("Drop to attach to {title}"),
227 format!("{files}. Images go into the message, other files to the channel's Files."),
228 ),
229 DropTarget::Library => (
230 format!("Drop to upload to {title}"),
231 format!("{files}. Files go into the folder you have open."),
232 ),
233 DropTarget::NewChat => (
234 "Drop to attach to the new chat".to_owned(),
235 format!(
236 "{files}. Images go into the message. Files can be added once the chat exists."
237 ),
238 ),
239 }
240}
241
242fn shown_in_view(mode: &ViewMode, record: &store::OutboxRecord) -> bool {
243 match mode {
244 ViewMode::Flat => record.target == OutboxTarget::Flat,
245 ViewMode::ThreadList => matches!(record.target, OutboxTarget::Post | OutboxTarget::Thread),
246 ViewMode::Thread(root_id) => {
247 record.target == OutboxTarget::Thread
248 && record.thread_root_id.as_deref() == Some(root_id.as_str())
249 }
250 }
251}
252
253enum DownloadEvent {
254 Progress(u8),
255 Finished(Result<PathBuf, String>),
256}
257
258async fn save_file(
259 engine: &Engine,
260 card: &FileCard,
261 source: &DownloadSource,
262 events: &tokio::sync::mpsc::UnboundedSender<DownloadEvent>,
263) -> Result<PathBuf, String> {
264 let mut part = PartFile::create(&downloads::downloads_directory(), &card.name)
265 .map_err(|error| short_error(&error))?;
266 let write = |bytes: &[u8]| part.write(bytes);
267 let progress = |percent| {
268 let _ = events.send(DownloadEvent::Progress(percent));
269 };
270 match source {
271 DownloadSource::Share => engine.download_file(&card.open_url, write, progress).await,
272 DownloadSource::Library(file) => engine.download_library_file(file, write, progress).await,
273 }
274 .map_err(|error| short_error(&error))?;
275 part.finish().map_err(|error| short_error(&error))
276}
277
278impl ConversationView {
279 fn file_actions(
280 &self,
281 message_key: &str,
282 files: &[FileCard],
283 view: WeakEntity<Self>,
284 ) -> FileActions {
285 let conversation_id = self.conversation_id().unwrap_or_default();
286 let (key, cards) = (message_key.to_owned(), files.to_vec());
287 let open_urls: Vec<&str> = files.iter().map(|card| card.open_url.as_str()).collect();
288 FileActions {
289 states: self
290 .downloads
291 .states_for(&conversation_id, message_key, &open_urls),
292 activate: Rc::new(move |index, cx| {
293 let Some(card) = cards.get(index).cloned() else {
294 return;
295 };
296 let key = key.clone();
297 let conversation_id = conversation_id.clone();
298 view.update(cx, |this, cx| {
299 this.activate_file(&conversation_id, &key, card, DownloadSource::Share, cx)
300 })
301 .ok();
302 }),
303 }
304 }
305
306 fn open_image_viewer(&mut self, message_key: &str, url: &str, cx: &mut Context<Self>) {
307 let Some(current) = self.current.as_ref() else {
308 return;
309 };
310 let now = Local::now();
311 let items = collect_gallery(&self.rows.borrow(), now.date_naive(), now.offset().fix());
312 let Some(index) = position_of(&items, message_key, url) else {
313 return;
314 };
315 let request = ViewerRequest {
316 conversation_id: current.selection.conversation_id().to_owned(),
317 conversation_title: selection_title(&self.app.read(cx).sidebar, &current.selection),
318 items,
319 index,
320 };
321 self.app
322 .update(cx, |state, cx| state.request_image_viewer(request, cx));
323 }
324
325 fn activate_file(
326 &mut self,
327 conversation_id: &str,
328 message_key: &str,
329 card: FileCard,
330 source: DownloadSource,
331 cx: &mut Context<Self>,
332 ) {
333 let key = DownloadKey::new(conversation_id, message_key, &card.open_url);
334 match downloads::click_action(self.downloads.state(&key)) {
335 ClickAction::Ignore => {}
336 ClickAction::Start => self.start_download(key, card, source, cx),
337 ClickAction::Reveal(path) => {
338 let folder = path
339 .parent()
340 .map(Path::to_path_buf)
341 .unwrap_or_else(downloads::downloads_directory);
342 match downloads::reveal_target(&path, path.exists(), folder) {
343 RevealTarget::File(path) => downloads::reveal_in_file_manager(&path),
344 RevealTarget::Folder(folder) => cx.open_with_system(&folder),
345 }
346 }
347 }
348 }
349
350 fn start_download(
351 &mut self,
352 key: DownloadKey,
353 card: FileCard,
354 source: DownloadSource,
355 cx: &mut Context<Self>,
356 ) {
357 if !self.downloads.begin(&key) {
358 return;
359 }
360 cx.notify();
361 let state = self.app.read(cx);
362 let (demo, engine) = (state.mode.demo, state.engine.clone());
363 let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel::<DownloadEvent>();
364 if demo {
365 cx.spawn(async move |this, cx| {
366 for step in 1..=DEMO_DOWNLOAD_STEPS {
367 cx.background_executor().timer(DEMO_DOWNLOAD_STEP).await;
368 let percent = (u32::from(step) * 100 / u32::from(DEMO_DOWNLOAD_STEPS)) as u8;
369 let progressed = this.update(cx, |this, cx| {
370 this.downloads.set_progress(&key, percent);
371 cx.notify();
372 });
373 if progressed.is_err() {
374 return;
375 }
376 }
377 let outcome =
378 downloads::write_demo_file(&card.name).map_err(|error| short_error(&error));
379 this.update(cx, |this, cx| {
380 this.downloads.finish(&key, outcome);
381 cx.notify();
382 })
383 .ok();
384 })
385 .detach();
386 return;
387 }
388 let Some(engine) = engine else {
389 self.downloads.finish(&key, Err("not connected".to_owned()));
390 return;
391 };
392 drop(runtime::spawn(async move {
393 let outcome = save_file(&engine, &card, &source, &sender).await;
394 let _ = sender.send(DownloadEvent::Finished(outcome));
395 }));
396 cx.spawn(async move |this, cx| {
397 while let Some(event) = receiver.recv().await {
398 let updated = this.update(cx, |this, cx| {
399 match event {
400 DownloadEvent::Progress(percent) => {
401 this.downloads.set_progress(&key, percent)
402 }
403 DownloadEvent::Finished(outcome) => this.downloads.finish(&key, outcome),
404 }
405 cx.notify();
406 });
407 if updated.is_err() {
408 break;
409 }
410 }
411 })
412 .detach();
413 }
414
415 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
416 Self::build(app, None, window, cx)
417 }
418
419 pub fn pinned_to(
420 app: Entity<AppState>,
421 selection: Selection,
422 window: &mut Window,
423 cx: &mut Context<Self>,
424 ) -> Self {
425 Self::build(app, Some(selection), window, cx)
426 }
427
428 fn build(
429 app: Entity<AppState>,
430 pinned: Option<Selection>,
431 window: &mut Window,
432 cx: &mut Context<Self>,
433 ) -> Self {
434 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
435 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
436 let subject = subject_input(window, cx);
437 let recent = cx.new(|cx| emoji::Recent::load(&app.read(cx).store));
438 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), recent.clone(), window, cx));
439 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
440 let mut subscriptions = vec![
441 cx.subscribe_in(&app, window, Self::on_app_event),
442 cx.observe(&app, |_, _, cx| cx.notify()),
443 cx.subscribe_in(&composer, window, Self::on_composer_event),
444 cx.subscribe_in(&draft, window, Self::on_draft_event),
445 cx.subscribe_in(&subject, window, Self::on_subject_event),
446 cx.observe_window_activation(window, Self::on_window_activation),
447 cx.on_app_quit(|this, cx| {
448 this.composer
449 .update(cx, |composer, cx| composer.save_draft_now(cx));
450 async {}
451 }),
452 cx.observe_keystrokes(|this, event, _, cx| {
453 if event.keystroke.key == "escape" {
454 this.close_reaction_details(cx);
455 }
456 }),
457 ];
458 if let Some(runs) = crate::agents::runs_handle(cx) {
459 subscriptions.push(cx.observe(&runs, |this, _, cx| this.sync_agent_chips(cx)));
460 }
461 let mut view = ConversationView {
462 app,
463 pinned: pinned.is_some(),
464 scroller,
465 composer,
466 subject,
467 new_post_open: false,
468 reply_composer: None,
469 reply_root: None,
470 feed_stash: None,
471 feed_rows_seen: Rc::new(Cell::new(usize::MAX)),
472 feed_at_top: true,
473 draft,
474 draft_active: false,
475 draft_created: None,
476 draft_error: None,
477 rows: Rc::new(RefCell::new(Vec::new())),
478 current: None,
479 pending: Vec::new(),
480 pending_counter: 0,
481 pending_outgoing: HashMap::new(),
482 pending_reactions: HashMap::new(),
483 downloads: Downloads::default(),
484 hovered_message: None,
485 toolbar_hovered: None,
486 timeline_bounds: TimelineBounds::default(),
487 toolbar_pinned: None,
488 toolbar_suppressed: None,
489 recent,
490 picker,
491 reaction_details: None,
492 highlighted_message: None,
493 pin_index: 0,
494 pin_previews: HashMap::new(),
495 notice: None,
496 scheduled_failure: None,
497 scheduled_in_flight: HashSet::new(),
498 drag_file_count: 0,
499 sync_generation: 0,
500 window_active: window.is_window_active(),
501 pane: ChannelPane::Posts,
502 channel_tabs: Vec::new(),
503 tab_links: HashMap::new(),
504 focus_handle: cx.focus_handle(),
505 shared: SharedState::default(),
506 demo_library: DemoLibrary::default(),
507 new_folder_input: None,
508 agent_layouts: HashMap::new(),
509 agent_runs: Rc::new(RefCell::new(HashMap::new())),
510 _subscriptions: subscriptions,
511 };
512 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
513 view.open(selection, window, cx);
514 }
515 view
516 }
517
518 #[cfg_attr(not(windows), allow(dead_code))]
519 pub fn composer_is_empty(&self, cx: &App) -> bool {
520 self.composer.read(cx).is_empty(cx)
521 }
522
523 #[cfg_attr(not(windows), allow(dead_code))]
524 pub fn send_in_flight(&self) -> bool {
525 self.pending
526 .iter()
527 .any(|row| matches!(row.delivery, Delivery::Sending))
528 }
529
530 fn on_window_activation(&mut self, window: &mut Window, cx: &mut Context<Self>) {
531 self.window_active = window.is_window_active();
532 self.mark_read(ReadTrigger::Activation, cx);
533 }
534
535 fn on_app_event(
536 &mut self,
537 _: &Entity<AppState>,
538 event: &AppEvent,
539 window: &mut Window,
540 cx: &mut Context<Self>,
541 ) {
542 match event {
543 AppEvent::Selection if self.pinned => {}
544 AppEvent::Selection => {
545 self.reaction_details = None;
546 let (new_chat, selection) = {
547 let state = self.app.read(cx);
548 (state.new_chat, state.selection.clone())
549 };
550 if new_chat {
551 self.enter_draft(window, cx);
552 return;
553 }
554 if self.draft_active {
555 let created = self
556 .draft_created
557 .as_ref()
558 .map(|(_, chat_id)| chat_id.clone());
559 if let Some(chat_id) = created {
560 self.composer
561 .update(cx, |composer, _| composer.carry_images_into(chat_id));
562 }
563 self.leave_draft(window, cx);
564 }
565 match selection {
566 Some(selection) => self.open(selection, window, cx),
567 None => {
568 self.current = None;
569 self.rebuild(true, cx);
570 }
571 }
572 }
573 AppEvent::Messages(conversation_id) => {
574 let is_current = self
575 .current
576 .as_ref()
577 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
578 if is_current {
579 if self.shared_active() {
580 self.refresh_shared_items(cx);
581 }
582 self.rebuild(false, cx);
583 self.mark_read(ReadTrigger::Incoming, cx);
584 self.on_pins_changed(conversation_id, cx);
585 }
586 }
587 AppEvent::Images(keys) => self.remeasure_images(keys, cx),
588 AppEvent::Cards(conversation_id) => self.refresh_cards(conversation_id, cx),
589 AppEvent::Jump => self.apply_pending_jump(cx),
590 AppEvent::Status => {
591 if let Some(current) = self.current.as_mut()
592 && current.sync.failed
593 {
594 current.fetched = false;
595 }
596 self.start_fetch(cx)
597 }
598 AppEvent::Directory => {
599 self.refresh_reactor_names(cx);
600 cx.notify();
601 }
602 AppEvent::TaskDialog
603 | AppEvent::LocalPreviews
604 | AppEvent::Forward
605 | AppEvent::ImageViewer
606 | AppEvent::StatusMessage
607 | AppEvent::NotificationSettings
608 | AppEvent::Profile
609 | AppEvent::CallHistory
610 | AppEvent::Ring
611 | AppEvent::MissedCall(_)
612 | AppEvent::Call => {}
613 AppEvent::LiveMeeting => cx.notify(),
614 AppEvent::Saved => cx.notify(),
615 AppEvent::Translation => self.rebuild(false, cx),
616 AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),
617 AppEvent::Typing => cx.notify(),
618 AppEvent::Scheduled => self.rebuild(false, cx),
619 AppEvent::Outbox(conversation_id) => {
620 let is_current = self
621 .current
622 .as_ref()
623 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
624 if is_current {
625 self.reload_pending(cx);
626 self.rebuild(false, cx);
627 }
628 }
629 AppEvent::Sidebar => {
630 self.reload_channel_tabs(cx);
631 self.mark_read(ReadTrigger::Incoming, cx);
632 self.refresh_reactor_names(cx);
633 if self.draft_active {
634 self.on_draft_changed(window, cx);
635 } else if let Some(current) = self.current.as_mut() {
636 let title = selection_title(&self.app.read(cx).sidebar, &current.selection);
637 if current.title != title {
638 current.title = title.clone();
639 let conversation_id = current.selection.conversation_id().to_owned();
640 self.composer.update(cx, |composer, cx| {
641 composer.set_conversation(&conversation_id, &title, window, cx)
642 });
643 cx.notify();
644 }
645 }
646 }
647 }
648 }
649
650 fn on_composer_event(
651 &mut self,
652 _: &Entity<Composer>,
653 event: &ComposerEvent,
654 window: &mut Window,
655 cx: &mut Context<Self>,
656 ) {
657 self.report_composer_activity(event, cx);
658 match event {
659 ComposerEvent::Submit(outgoing) => self.submit_main((**outgoing).clone(), window, cx),
660 ComposerEvent::Schedule { outgoing, send_at } => {
661 self.schedule((**outgoing).clone(), *send_at, window, cx)
662 }
663 ComposerEvent::EditLast => self.edit_last_own(window, cx),
664 ComposerEvent::Typing(active) => self.send_typing(*active, cx),
665 }
666 }
667
668 fn submit_main(&mut self, mut outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
669 if self.draft_active {
670 return self.send_new_chat(outgoing, window, cx);
671 }
672 let in_feed = self.in_feed();
673 if in_feed && outgoing.edit.is_none() {
674 outgoing.subject = self.take_subject(window, cx);
675 }
676 if in_feed {
677 self.close_new_post(cx);
678 }
679 match &outgoing.edit {
680 Some(edit) if edit.scheduled.is_some() => {
681 self.send_scheduled_edit(outgoing, window, cx)
682 }
683 Some(_) => self.send_edit(outgoing, window, cx),
684 None => self.send(outgoing, window, cx),
685 }
686 }
687
688 fn typing_root(&self) -> Option<String> {
689 match self.current.as_ref().map(|current| &current.mode) {
690 Some(ViewMode::Thread(root_id)) => Some(root_id.clone()),
691 _ => None,
692 }
693 }
694
695 fn send_typing(&self, active: bool, cx: &App) {
696 self.send_typing_in(self.typing_root(), active, cx);
697 }
698
699 fn send_typing_in(&self, thread_root_id: Option<String>, active: bool, cx: &App) {
700 let state = self.app.read(cx);
701 if state.mode.demo || state.mode.read_only || self.draft_active {
702 return;
703 }
704 let (Some(engine), Some(conversation_id)) = (state.engine.clone(), self.conversation_id())
705 else {
706 return;
707 };
708 drop(runtime::spawn(async move {
709 let sent = engine
710 .send_typing(&conversation_id, thread_root_id.as_deref(), active)
711 .await;
712 if let Err(error) = sent
713 && cfg!(debug_assertions)
714 {
715 crate::diagnostics::record(format!("typing indicator not sent: {error}"));
716 }
717 }));
718 }
719
720 fn stop_typing(&mut self, cx: &mut Context<Self>) {
721 if self
722 .composer
723 .update(cx, |composer, _| composer.stop_typing())
724 {
725 self.send_typing(false, cx);
726 }
727 }
728
729 fn render_typing_line(&self, cx: &App) -> impl IntoElement {
730 let app = self.app.read(cx);
731 let faces = self
732 .current
733 .as_ref()
734 .filter(|_| !self.draft_active)
735 .map(|current| app.typing.faces(current.selection.conversation_id()))
736 .unwrap_or_default();
737 let tooltip_text = typing_tooltip(
738 &faces
739 .iter()
740 .map(|face| face.name.clone())
741 .collect::<Vec<_>>(),
742 );
743 let flat = matches!(
744 self.current.as_ref().map(|current| &current.mode),
745 Some(ViewMode::Flat)
746 );
747 let faces_element = match faces.as_slice() {
748 [face] if flat => person_avatar(
749 &app.directory,
750 face.user_id.as_deref(),
751 &face.name,
752 AVATAR_SIZE,
753 ),
754 _ => member_stack(&app.directory, &faces, faces.len()).into_any_element(),
755 };
756 h_flex()
757 .h(px(if flat {
758 AVATAR_SIZE + 4.
759 } else {
760 TYPING_LINE_HEIGHT
761 }))
762 .flex_none()
763 .px(px(20.))
764 .gap(px(if flat { AVATAR_GAP } else { 6. }))
765 .items_center()
766 .when(!faces.is_empty(), |line| {
767 line.child(
768 div()
769 .id("typing-faces")
770 .tooltip(move |window, cx| {
771 Tooltip::new(tooltip_text.clone()).build(window, cx)
772 })
773 .child(faces_element),
774 )
775 .child(typing_dots())
776 })
777 }
778
779 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
780 self.stop_typing(cx);
781 self.stop_reply_typing(cx);
782 self.new_post_open = false;
783 self.feed_stash = None;
784 self.feed_at_top = true;
785 self.restore_subject(None, window, cx);
786 self.toolbar_hovered = None;
787 self.toolbar_pinned = None;
788 self.toolbar_suppressed = None;
789 self.agent_layouts.clear();
790 self.agent_runs.borrow_mut().clear();
791 let title = selection_title(&self.app.read(cx).sidebar, &selection);
792 let mode = match selection {
793 Selection::Chat(_) => ViewMode::Flat,
794 Selection::Channel(_) => ViewMode::ThreadList,
795 };
796 let first_unread = self.first_unread_id(&selection, cx);
797 self.current = Some(Current {
798 loaded_limit: open_limit(&selection),
799 selection,
800 title,
801 mode,
802 loaded_count: 0,
803 has_older: false,
804 loading_older: false,
805 older_blocked: false,
806 fetched: false,
807 first_unread,
808 sync: SyncProgress::default(),
809 });
810 self.refresh_agent_runs(cx);
811 self.sync_generation += 1;
812 self.reset_channel_tabs(cx);
813 self.reload_pending(cx);
814 self.notice = None;
815 self.scheduled_failure = None;
816 self.app.update(cx, |state, cx| state.refresh_scheduled(cx));
817 self.rebuild(true, cx);
818 self.start_fetch(cx);
819 self.mark_read(ReadTrigger::Open, cx);
820 self.refresh_pin_previews(cx);
821 if let Some(chat_id) = self.chat_id() {
822 self.app
823 .update(cx, |state, cx| state.refresh_pins(&chat_id, cx));
824 }
825 let target = self
826 .current
827 .as_ref()
828 .map(|current| {
829 (
830 current.selection.conversation_id().to_owned(),
831 current.title.clone(),
832 )
833 })
834 .unwrap_or_default();
835 self.composer.update(cx, |composer, cx| {
836 composer.set_conversation(&target.0, &target.1, window, cx);
837 });
838 self.sync_reply_composer(window, cx);
839 if !self.draft_active && !self.in_feed() {
840 self.composer
841 .update(cx, |composer, cx| composer.focus(window, cx));
842 }
843 self.hovered_message = None;
844 self.apply_pending_jump(cx);
845 }
846
847 fn enter_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
848 if !self.draft_active {
849 self.stop_typing(cx);
850 self.draft_active = true;
851 self.current = None;
852 self.clear_pending();
853 self.notice = None;
854 self.draft_created = None;
855 self.draft_error = None;
856 self.toolbar_hovered = None;
857 self.toolbar_pinned = None;
858 self.toolbar_suppressed = None;
859 self.hovered_message = None;
860 self.sync_generation += 1;
861 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
862 self.composer.update(cx, |composer, cx| {
863 composer.set_conversation("", "", window, cx)
864 });
865 self.on_draft_changed(window, cx);
866 self.rebuild(true, cx);
867 }
868 self.draft
869 .update(cx, |draft, cx| draft.focus_query(window, cx));
870 cx.notify();
871 }
872
873 fn leave_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
874 self.draft_active = false;
875 self.draft_created = None;
876 self.draft_error = None;
877 self.clear_pending();
878 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
879 }
880
881 fn on_draft_event(
882 &mut self,
883 _: &Entity<NewChatDraft>,
884 event: &NewChatEvent,
885 window: &mut Window,
886 cx: &mut Context<Self>,
887 ) {
888 match event {
889 NewChatEvent::Changed => self.on_draft_changed(window, cx),
890 NewChatEvent::FocusComposer => self
891 .composer
892 .update(cx, |composer, cx| composer.focus(window, cx)),
893 NewChatEvent::Close => self.app.update(cx, |state, cx| state.close_new_chat(cx)),
894 }
895 }
896
897 fn draft_target_chat(&self, cx: &App) -> Option<String> {
898 let chips = self.draft.read(cx).chips();
899 let [chip] = chips else {
900 return None;
901 };
902 let state = self.app.read(cx);
903 existing_one_on_one(
904 &state.sidebar.chats,
905 state.directory.me.as_ref(),
906 &chip.user_id,
907 )
908 .map(|chat| chat.id.clone())
909 }
910
911 fn on_draft_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
912 if !self.draft_active {
913 return;
914 }
915 let target = self.draft_target_chat(cx);
916 if target != self.conversation_id() {
917 match target {
918 Some(chat_id) => {
919 self.composer.update(cx, |composer, _| {
920 composer.carry_images_into(chat_id.clone())
921 });
922 self.open(Selection::Chat(chat_id), window, cx)
923 }
924 None => {
925 self.composer.update(cx, |composer, cx| {
926 composer.carry_images_into(String::new());
927 composer.set_conversation("", "", window, cx);
928 });
929 self.current = None;
930 self.sync_generation += 1;
931 self.rebuild(true, cx);
932 }
933 }
934 }
935 let placeholder = {
936 let draft = self.draft.read(cx);
937 composer_placeholder(draft.chips(), &draft.group_name(cx))
938 };
939 self.composer.update(cx, |composer, cx| {
940 composer.set_placeholder(&placeholder, window, cx)
941 });
942 cx.notify();
943 }
944
945 fn remeasure_images(&mut self, keys: &[String], cx: &mut Context<Self>) {
946 let indices: Vec<usize> = self
947 .rows
948 .borrow()
949 .iter()
950 .enumerate()
951 .filter(|(_, row)| {
952 row.messages().any(|message| {
953 message.images.iter().any(|image| keys.contains(&image.url))
954 || message
955 .link_preview
956 .as_ref()
957 .and_then(LinkPreview::image)
958 .is_some_and(|image| keys.contains(&image.url))
959 })
960 })
961 .map(|(index, _)| index)
962 .collect();
963 self.scroller.update(cx, |scroller, cx| {
964 for index in indices {
965 scroller.remeasure_items(index..index + 1, cx);
966 }
967 });
968 cx.notify();
969 }
970
971 fn refresh_cards(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
972 let is_current = self
973 .current
974 .as_ref()
975 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
976 if !is_current {
977 return;
978 }
979 self.rebuild(false, cx);
980 let indices: Vec<usize> = self
981 .rows
982 .borrow()
983 .iter()
984 .enumerate()
985 .filter(|(_, row)| {
986 row.messages()
987 .any(|message| !message.adaptive_cards.is_empty())
988 })
989 .map(|(index, _)| index)
990 .collect();
991 self.scroller.update(cx, |scroller, cx| {
992 for index in indices {
993 scroller.remeasure_items(index..index + 1, cx);
994 }
995 });
996 cx.notify();
997 }
998
999 fn apply_pending_jump(&mut self, cx: &mut Context<Self>) {
1000 let Some(conversation_id) = self
1001 .current
1002 .as_ref()
1003 .map(|current| current.selection.conversation_id().to_owned())
1004 else {
1005 return;
1006 };
1007 let jump = self
1008 .app
1009 .update(cx, |state, _| match state.pending_jump.take() {
1010 Some((target, message_id)) if target == conversation_id => Some(message_id),
1011 other => {
1012 state.pending_jump = other;
1013 None
1014 }
1015 });
1016 if let Some(message_id) = jump {
1017 self.jump_to_message(&conversation_id, &message_id, cx);
1018 }
1019 }
1020
1021 fn jump_to_message(&mut self, conversation_id: &str, message_id: &str, cx: &mut Context<Self>) {
1022 let store = self.app.read(cx).store.clone();
1023 let Some(record) = store
1024 .messages_by_id(conversation_id, &[message_id.to_owned()])
1025 .ok()
1026 .and_then(|mut found| found.remove(message_id))
1027 else {
1028 return;
1029 };
1030 let messages_from_target = store
1031 .messages(conversation_id, None, JUMP_SCAN_LIMIT)
1032 .ok()
1033 .and_then(|all| {
1034 all.iter()
1035 .position(|candidate| candidate.message_id == message_id)
1036 .map(|position| all.len() - position)
1037 })
1038 .unwrap_or_default();
1039 let row_key = record
1040 .reply_to_id
1041 .clone()
1042 .unwrap_or_else(|| message_id.to_owned());
1043 let Some(current) = self.current.as_mut() else {
1044 return;
1045 };
1046 current.loaded_limit = current
1047 .loaded_limit
1048 .max(messages_from_target + JUMP_CONTEXT_MESSAGES);
1049 current.first_unread = None;
1050 let in_channel = matches!(current.selection, Selection::Channel(_));
1051 if in_channel {
1052 self.pane = ChannelPane::Posts;
1053 match record.reply_to_id.clone() {
1054 Some(root_id) => {
1055 self.enter_thread_mode(root_id.clone(), cx);
1056 self.refresh_thread(root_id, cx);
1057 }
1058 None => {
1059 self.enter_feed_mode();
1060 }
1061 }
1062 }
1063 let in_thread = self
1064 .current
1065 .as_ref()
1066 .is_some_and(|current| matches!(current.mode, ViewMode::Thread(_)));
1067 let target_key = if in_thread {
1068 message_id.to_owned()
1069 } else {
1070 row_key
1071 };
1072 self.reload_pending(cx);
1073 self.rebuild(true, cx);
1074 let index = self
1075 .rows
1076 .borrow()
1077 .iter()
1078 .position(|row| row.key() == target_key);
1079 if let Some(index) = index {
1080 self.scroller
1081 .update(cx, |scroller, cx| scroller.scroll_to_item(index, cx));
1082 self.highlight(target_key, cx);
1083 }
1084 }
1085
1086 fn highlight(&mut self, key: String, cx: &mut Context<Self>) {
1087 self.highlighted_message = Some(key.clone());
1088 cx.notify();
1089 cx.spawn(async move |this, cx| {
1090 cx.background_executor().timer(HIGHLIGHT_DURATION).await;
1091 this.update(cx, |this, cx| {
1092 if this.highlighted_message.as_deref() == Some(key.as_str()) {
1093 this.highlighted_message = None;
1094 cx.notify();
1095 }
1096 })
1097 .ok();
1098 })
1099 .detach();
1100 }
1101
1102 pub fn set_composer_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1103 self.composer
1104 .update(cx, |composer, cx| composer.set_text(text, window, cx));
1105 self.composer
1106 .update(cx, |composer, cx| composer.focus(window, cx));
1107 }
1108
1109 pub fn reply_to_latest_from_others(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1110 let key = self
1111 .rows
1112 .borrow()
1113 .iter()
1114 .rev()
1115 .flat_map(Row::messages)
1116 .find(|message| !message.own)
1117 .map(|message| message.key.clone());
1118 if let Some(key) = key {
1119 self.begin_reply(&key, window, cx);
1120 }
1121 }
1122
1123 pub fn reply_to_hovered(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1124 if let Some(message_id) = self.hovered_message.clone() {
1125 self.begin_reply(&message_id, window, cx);
1126 }
1127 }
1128
1129 fn reply_target(&self, message_id: &str, cx: &App) -> Option<(MessageRecord, ReplyPreview)> {
1130 let conversation_id = self.conversation_id()?;
1131 let record = self
1132 .app
1133 .read(cx)
1134 .store
1135 .messages_by_id(&conversation_id, &[message_id.to_owned()])
1136 .ok()
1137 .and_then(|mut found| found.remove(message_id))
1138 .filter(|record| !record.deleted)?;
1139 let preview = ReplyPreview {
1140 message_id: record.message_id.clone(),
1141 author: record
1142 .sender_name
1143 .clone()
1144 .unwrap_or_else(|| "Unknown".to_owned()),
1145 excerpt: reply_excerpt(&record),
1146 };
1147 Some((record, preview))
1148 }
1149
1150 fn begin_reply(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
1151 let Some((record, preview)) = self.reply_target(message_id, cx) else {
1152 return;
1153 };
1154 if self.in_feed() {
1155 let root_id = record
1156 .reply_to_id
1157 .clone()
1158 .unwrap_or_else(|| record.message_id.clone());
1159 let quote = record.reply_to_id.is_some().then_some(preview);
1160 self.open_reply_editor(root_id, quote, window, cx);
1161 return;
1162 }
1163 self.composer.update(cx, |composer, cx| {
1164 composer.set_reply(Some(preview), cx);
1165 composer.focus(window, cx);
1166 });
1167 }
1168
1169 fn first_unread_id(&self, selection: &Selection, cx: &App) -> Option<String> {
1170 let Selection::Chat(chat_id) = selection else {
1171 return None;
1172 };
1173 let state = self.app.read(cx);
1174 if state.mode.demo {
1175 return crate::demo::first_unread(chat_id);
1176 }
1177 state.engine.as_ref()?.first_unread_message_id(chat_id)
1178 }
1179
1180 fn row_context(&self, cx: &App) -> RowContext {
1181 let now = Local::now();
1182 let app = self.app.read(cx);
1183 let names = local_names(app);
1184 let card_overrides = self
1185 .current
1186 .as_ref()
1187 .map(|current| app.cards.overrides_for(current.selection.conversation_id()))
1188 .unwrap_or_default();
1189 let translation = self
1190 .current
1191 .as_ref()
1192 .map(|current| {
1193 app.translation
1194 .context_for(current.selection.conversation_id())
1195 })
1196 .unwrap_or_default();
1197 RowContext {
1198 offset: now.offset().fix(),
1199 today: now.date_naive(),
1200 my_user_id: app.store.meta(META_USER_ID).ok().flatten(),
1201 names,
1202 pending_reactions: self.pending_reactions.clone(),
1203 card_overrides,
1204 translation,
1205 }
1206 }
1207
1208 fn unknown_reactor_ids(&self) -> Vec<String> {
1209 self.rows
1210 .borrow()
1211 .iter()
1212 .flat_map(Row::messages)
1213 .flat_map(|message| message.reactions.iter())
1214 .flat_map(|chip| chip.reactors.iter())
1215 .filter(|reactor| reactor.name == UNKNOWN_REACTOR)
1216 .filter_map(|reactor| reactor.user_id.clone())
1217 .collect()
1218 }
1219
1220 fn refresh_reactor_names(&mut self, cx: &mut Context<Self>) {
1221 if self.current.is_none() {
1222 return;
1223 }
1224 let unknown = self.unknown_reactor_ids();
1225 if unknown.is_empty() {
1226 return;
1227 }
1228 let names = resolve_names(self.app.read(cx), &unknown);
1229 if !names.is_empty() {
1230 self.rebuild(false, cx);
1231 }
1232 }
1233
1234 fn drop_stale_reaction_details(&mut self) {
1235 let Some(details) = self.reaction_details.as_ref() else {
1236 return;
1237 };
1238 let present = self
1239 .rows
1240 .borrow()
1241 .iter()
1242 .flat_map(Row::messages)
1243 .any(|message| {
1244 message.key == details.message_key
1245 && message
1246 .reactions
1247 .iter()
1248 .any(|chip| chip.glyph() == details.anchor_glyph)
1249 });
1250 if !present {
1251 self.reaction_details = None;
1252 }
1253 }
1254
1255 fn open_reaction_details(&mut self, message_key: &str, glyph: &str, cx: &mut Context<Self>) {
1256 let multiple_kinds = self
1257 .rows
1258 .borrow()
1259 .iter()
1260 .flat_map(Row::messages)
1261 .any(|message| message.key == message_key && message.reactions.len() > 1);
1262 self.reaction_details = Some(ReactionDetails {
1263 message_key: message_key.to_owned(),
1264 anchor_glyph: glyph.to_owned(),
1265 tab: multiple_kinds.then(|| glyph.to_owned()),
1266 });
1267 cx.notify();
1268 }
1269
1270 fn select_reaction_tab(&mut self, tab: Option<String>, cx: &mut Context<Self>) {
1271 if let Some(details) = self.reaction_details.as_mut() {
1272 details.tab = tab;
1273 cx.notify();
1274 }
1275 }
1276
1277 fn close_reaction_details(&mut self, cx: &mut Context<Self>) {
1278 if self.reaction_details.take().is_some() {
1279 cx.notify();
1280 }
1281 }
1282
1283 fn reaction_controls(&self, key: &str, view: WeakEntity<Self>) -> ReactionControls {
1284 let open = {
1285 let (view, key) = (view.clone(), key.to_owned());
1286 Rc::new(move |glyph: &str, cx: &mut App| {
1287 view.update(cx, |this, cx| this.open_reaction_details(&key, glyph, cx))
1288 .ok();
1289 })
1290 };
1291 let select_tab = {
1292 let view = view.clone();
1293 Rc::new(move |tab: Option<String>, cx: &mut App| {
1294 view.update(cx, |this, cx| this.select_reaction_tab(tab, cx))
1295 .ok();
1296 })
1297 };
1298 let close = Rc::new(move |cx: &mut App| {
1299 view.update(cx, |this, cx| this.close_reaction_details(cx))
1300 .ok();
1301 });
1302 let popover = self
1303 .reaction_details
1304 .as_ref()
1305 .filter(|details| details.message_key == key)
1306 .map(|details| ReactionPopover {
1307 anchor_glyph: details.anchor_glyph.clone(),
1308 tab: details.tab.clone(),
1309 });
1310 ReactionControls {
1311 open,
1312 select_tab,
1313 close,
1314 popover,
1315 }
1316 }
1317
1318 fn start_info(&self, cx: &App) -> Option<StartInfo> {
1319 let current = self.current.as_ref()?;
1320 let app = self.app.read(cx);
1321 let user_id = match &current.selection {
1322 Selection::Chat(chat_id) => app
1323 .sidebar
1324 .chats
1325 .iter()
1326 .find(|chat| &chat.id == chat_id)
1327 .filter(|chat| is_one_on_one(chat))
1328 .and_then(|chat| others(chat, app.directory.me.as_ref()).into_iter().next())
1329 .and_then(|(user_id, _)| user_id),
1330 Selection::Channel(_) => None,
1331 };
1332 Some(StartInfo {
1333 title: current.title.clone(),
1334 user_id,
1335 })
1336 }
1337
1338 fn rebuild(&mut self, reset: bool, cx: &mut Context<Self>) {
1339 let Some(current) = self.current.as_ref() else {
1340 let mut rows: Vec<Row> = self
1341 .pending
1342 .iter()
1343 .cloned()
1344 .map(|row| Row::Message(Box::new(row)))
1345 .collect();
1346 assign_series(&mut rows);
1347 self.apply_rows(rows, true, cx);
1348 return;
1349 };
1350 let conversation_id = current.selection.conversation_id().to_owned();
1351 let limit = if reset {
1352 current.loaded_limit
1353 } else {
1354 current
1355 .loaded_limit
1356 .max(current.loaded_count + GROWTH_HEADROOM)
1357 };
1358 let store = self.app.read(cx).store.clone();
1359 let thread_root = match &current.mode {
1360 ViewMode::Thread(root_id) => Some(root_id.clone()),
1361 ViewMode::Flat | ViewMode::ThreadList => None,
1362 };
1363 let records: Vec<MessageRecord> = match &thread_root {
1364 Some(root_id) => store.thread_messages(&conversation_id, root_id),
1365 None => store.messages(&conversation_id, None, limit),
1366 }
1367 .unwrap_or_default();
1368 let sync_has_more = store
1369 .sync_state(&conversation_id)
1370 .ok()
1371 .flatten()
1372 .is_none_or(|state| state.has_more);
1373 let mut context = self.row_context(cx);
1374 let reactor_ids: Vec<String> = records
1375 .iter()
1376 .flat_map(teams_core::reactions)
1377 .filter(|reaction| reaction.user_name.is_none())
1378 .filter_map(|reaction| reaction.user_id)
1379 .filter(|user_id| !context.names.contains_key(user_id))
1380 .collect();
1381 for (user_id, name) in resolve_names(self.app.read(cx), &reactor_ids) {
1382 context.names.entry(user_id).or_insert(name);
1383 }
1384 for record in &records {
1385 if let (Some(user_id), Some(name)) = (&record.sender_id, &record.sender_name) {
1386 context
1387 .names
1388 .entry(user_id.clone())
1389 .or_insert_with(|| name.clone());
1390 }
1391 }
1392 let can_load_older = self.app.read(cx).engine.is_some();
1393 let start = self.start_info(cx);
1394 let current = self.current.as_mut().expect("checked above");
1395 let first_unread = current.first_unread.clone();
1396 current.loaded_limit = limit;
1397 if thread_root.is_none() {
1398 current.loaded_count = records.len();
1399 }
1400 let has_older = sync_has_more && !current.older_blocked && can_load_older;
1401 let placeholders = current.sync.messages
1402 && records.is_empty()
1403 && !matches!(current.mode, ViewMode::Thread(_));
1404 let in_feed = current.mode == ViewMode::ThreadList;
1405 let mut rows = match &current.mode {
1406 _ if placeholders => {
1407 current.has_older = false;
1408 placeholder_rows()
1409 }
1410 ViewMode::Flat => {
1411 current.has_older = has_older;
1412 let mut rows = flat_rows(&records, &context, has_older);
1413 if !has_older && let Some(start) = start {
1414 rows.insert(0, Row::Start(start));
1415 }
1416 rows
1417 }
1418 ViewMode::ThreadList => {
1419 current.has_older = has_older;
1420 thread_list_rows(&records, &context, has_older)
1421 }
1422 ViewMode::Thread(root_id) => {
1423 current.has_older = false;
1424 thread_rows(&records, root_id, &context)
1425 }
1426 };
1427 let local: Vec<MessageRow> = self
1428 .pending
1429 .iter()
1430 .cloned()
1431 .chain(self.scheduled_rows(context.my_user_id.as_deref(), cx))
1432 .collect();
1433 if in_feed {
1434 place_local_rows(&mut rows, local);
1435 } else {
1436 rows.extend(local.into_iter().map(|row| Row::Message(Box::new(row))));
1437 }
1438 let receipts = self.receipts(&records, cx);
1439 for row in rows.iter_mut() {
1440 if let Row::Message(message) = row
1441 && message.own
1442 {
1443 message.receipt = receipts.get(&message.key).copied().unwrap_or_default();
1444 }
1445 }
1446 if let Some(unread_id) = &first_unread {
1447 for row in rows.iter_mut() {
1448 if let Row::Message(message) = row
1449 && &message.key == unread_id
1450 {
1451 message.new_marker = true;
1452 }
1453 }
1454 }
1455 assign_series(&mut rows);
1456 self.apply_rows(rows, reset, cx);
1457 }
1458
1459 fn apply_rows(&mut self, new_rows: Vec<Row>, reset: bool, cx: &mut Context<Self>) {
1460 let old_rows = std::mem::replace(&mut *self.rows.borrow_mut(), new_rows);
1461 self.drop_stale_reaction_details();
1462 let new_len = self.rows.borrow().len();
1463 let in_feed = self.in_feed();
1464 if reset {
1465 let marker_index = self
1466 .rows
1467 .borrow()
1468 .iter()
1469 .position(|row| matches!(row, Row::Message(message) if message.new_marker));
1470 self.feed_at_top = true;
1471 self.scroller.update(cx, |scroller, cx| {
1472 scroller.reset(new_len, cx);
1473 if in_feed {
1474 scroller.scroll_to_item(0, cx);
1475 return;
1476 }
1477 match marker_index {
1478 Some(index) if !scroller.scroll_to_item(index, cx) => {
1479 scroller.scroll_to_end(cx)
1480 }
1481 Some(_) => {}
1482 None => scroller.scroll_to_end(cx),
1483 }
1484 });
1485 cx.notify();
1486 return;
1487 }
1488 let (splice, changed) = {
1489 let new_rows = self.rows.borrow();
1490 let old_keys: Vec<String> = old_rows.iter().map(|row| row.key().to_owned()).collect();
1491 let new_keys: Vec<String> = new_rows.iter().map(|row| row.key().to_owned()).collect();
1492 (
1493 diff_keys(&old_keys, &new_keys),
1494 changed_indices(&old_rows, &new_rows),
1495 )
1496 };
1497 let top_changed = splice
1498 .as_ref()
1499 .is_some_and(|splice| splice.range.start == 0);
1500 let keep_top = in_feed && (old_rows.is_empty() || (self.feed_at_top && top_changed));
1501 self.scroller.update(cx, |scroller, cx| {
1502 if let Some(splice) = splice
1503 && !scroller.splice(splice.range, splice.count, cx)
1504 {
1505 scroller.reset(new_len, cx);
1506 }
1507 if keep_top {
1508 scroller.scroll_to_item(0, cx);
1509 }
1510 for index in changed {
1511 scroller.remeasure_items(index..index + 1, cx);
1512 }
1513 });
1514 cx.notify();
1515 }
1516
1517 fn start_fetch(&mut self, cx: &mut Context<Self>) {
1518 let state = self.app.read(cx);
1519 let (engine, demo_sync) = (state.engine.clone(), state.mode.demo_sync);
1520 if engine.is_none() && demo_sync.is_none() {
1521 return;
1522 }
1523 let Some(current) = self.current.as_mut() else {
1524 return;
1525 };
1526 if current.fetched {
1527 return;
1528 }
1529 current.fetched = true;
1530 let is_chat = matches!(current.selection, Selection::Chat(_));
1531 let newest_cached = self
1532 .rows
1533 .borrow()
1534 .iter()
1535 .flat_map(Row::messages)
1536 .filter(|message| !message.key.starts_with(PENDING_KEY_PREFIX))
1537 .map(|message| message.created_at)
1538 .max();
1539 let current = self.current.as_mut().expect("checked above");
1540 if current.sync.failed {
1541 self.notice = None;
1542 }
1543 current.sync = SyncProgress {
1544 messages: true,
1545 receipts: is_chat,
1546 empty_cache: newest_cached.is_none(),
1547 newest_cached,
1548 ..SyncProgress::default()
1549 };
1550 self.sync_generation += 1;
1551 let generation = self.sync_generation;
1552 let conversation_id = current.selection.conversation_id().to_owned();
1553 match (engine, demo_sync) {
1554 (Some(engine), _) => {
1555 let receiver =
1556 runtime::spawn(async move { engine.fetch_newer(&conversation_id).await });
1557 cx.spawn(async move |this, cx| {
1558 let result = receiver.await;
1559 this.update(cx, |this, cx| this.finish_fetch(generation, result, cx))
1560 .ok();
1561 })
1562 .detach();
1563 }
1564 (None, Some(delay)) => self.simulate_sync(generation, delay, cx),
1565 (None, None) => {}
1566 }
1567 self.schedule_progress(generation, cx);
1568 self.rebuild(false, cx);
1569 self.mark_read(ReadTrigger::Incoming, cx);
1570 self.refresh_receipts(generation, cx);
1571 }
1572
1573 fn simulate_sync(&mut self, generation: u64, delay: Duration, cx: &mut Context<Self>) {
1574 cx.spawn(async move |this, cx| {
1575 cx.background_executor().timer(delay).await;
1576 this.update(cx, |this, cx| {
1577 if let Some(sync) = this.sync_of(generation) {
1578 sync.receipts = false;
1579 }
1580 this.finish_fetch(generation, Ok(Ok(teams_core::Delta::default())), cx)
1581 })
1582 .ok();
1583 })
1584 .detach();
1585 }
1586
1587 fn sync_of(&mut self, generation: u64) -> Option<&mut SyncProgress> {
1588 if generation != self.sync_generation {
1589 return None;
1590 }
1591 self.current.as_mut().map(|current| &mut current.sync)
1592 }
1593
1594 fn schedule_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
1595 cx.spawn(async move |this, cx| {
1596 let stages = [
1597 (PROGRESS_DELAY, Duration::ZERO),
1598 (SLOW_AFTER, PROGRESS_DELAY),
1599 ];
1600 for (stage, (at, previous)) in stages.into_iter().enumerate() {
1601 cx.background_executor().timer(at - previous).await;
1602 let running = this
1603 .update(cx, |this, cx| this.advance_progress(generation, stage, cx))
1604 .unwrap_or(false);
1605 if !running {
1606 return;
1607 }
1608 }
1609 })
1610 .detach();
1611 }
1612
1613 fn advance_progress(&mut self, generation: u64, stage: usize, cx: &mut Context<Self>) -> bool {
1614 let Some(sync) = self.sync_of(generation) else {
1615 return false;
1616 };
1617 if !sync.running() {
1618 return false;
1619 }
1620 match stage {
1621 0 => sync.shown_at = Some(Instant::now()),
1622 _ => sync.slow = true,
1623 }
1624 cx.notify();
1625 true
1626 }
1627
1628 fn finish_fetch(
1629 &mut self,
1630 generation: u64,
1631 result: Result<
1632 teams_core::Result<teams_core::Delta>,
1633 tokio::sync::oneshot::error::RecvError,
1634 >,
1635 cx: &mut Context<Self>,
1636 ) {
1637 let Some(sync) = self.sync_of(generation) else {
1638 return;
1639 };
1640 sync.messages = false;
1641 let newest_cached = sync.newest_cached;
1642 match result {
1643 Ok(Ok(_)) => self.mark_fetched_new(newest_cached, cx),
1644 Ok(Err(error)) => self.fail_sync(generation, short_error(&error)),
1645 Err(error) => self.fail_sync(generation, short_error(&error)),
1646 }
1647 self.rebuild(false, cx);
1648 self.settle_progress(generation, cx);
1649 }
1650
1651 fn fail_sync(&mut self, generation: u64, error: String) {
1652 if let Some(sync) = self.sync_of(generation) {
1653 sync.failed = true;
1654 sync.receipts = false;
1655 }
1656 self.notice = Some(format!("Could not refresh: {error}"));
1657 }
1658
1659 fn mark_fetched_new(&mut self, newest_cached: Option<DateTime<Utc>>, cx: &mut Context<Self>) {
1660 let Some(newest_cached) = newest_cached else {
1661 return;
1662 };
1663 let Some(my_user_id) = self.row_context(cx).my_user_id else {
1664 return;
1665 };
1666 let store = self.app.read(cx).store.clone();
1667 let Some(current) = self.current.as_mut() else {
1668 return;
1669 };
1670 if current.first_unread.is_some() || current.mode != ViewMode::Flat {
1671 return;
1672 }
1673 let limit = current
1674 .loaded_limit
1675 .max(current.loaded_count + GROWTH_HEADROOM);
1676 current.first_unread = store
1677 .messages(current.selection.conversation_id(), None, limit)
1678 .unwrap_or_default()
1679 .into_iter()
1680 .find(|record| {
1681 record.created_at > newest_cached && record.sender_id.as_ref() != Some(&my_user_id)
1682 })
1683 .map(|record| record.message_id);
1684 }
1685
1686 fn settle_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
1687 let Some(sync) = self.sync_of(generation) else {
1688 return;
1689 };
1690 if sync.running() {
1691 return;
1692 }
1693 let remaining = sync
1694 .shown_at
1695 .map(|shown_at| PROGRESS_MIN_VISIBLE.saturating_sub(shown_at.elapsed()))
1696 .unwrap_or_default();
1697 if remaining.is_zero() {
1698 sync.shown_at = None;
1699 sync.slow = false;
1700 cx.notify();
1701 return;
1702 }
1703 cx.spawn(async move |this, cx| {
1704 cx.background_executor().timer(remaining).await;
1705 this.update(cx, |this, cx| {
1706 if let Some(sync) = this.sync_of(generation) {
1707 sync.shown_at = None;
1708 sync.slow = false;
1709 cx.notify();
1710 }
1711 })
1712 .ok();
1713 })
1714 .detach();
1715 }
1716
1717 fn retry_fetch(&mut self, cx: &mut Context<Self>) {
1718 if let Some(current) = self.current.as_mut() {
1719 current.fetched = false;
1720 }
1721 self.start_fetch(cx);
1722 }
1723
1724 fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {
1725 let state = self.app.read(cx);
1726 let receipts_syncing = self
1727 .current
1728 .as_ref()
1729 .is_some_and(|current| current.sync.receipts);
1730 if state.mode.demo {
1731 let read_ids = crate::demo::read_message_ids(records);
1732 return records
1733 .iter()
1734 .map(|record| {
1735 let receipt = if receipts_syncing {
1736 Receipt::Pending
1737 } else if read_ids.contains(&record.message_id) {
1738 Receipt::Read
1739 } else {
1740 Receipt::Sent
1741 };
1742 (record.message_id.clone(), receipt)
1743 })
1744 .collect();
1745 }
1746 let Some(engine) = state.engine.as_ref() else {
1747 return HashMap::new();
1748 };
1749 let unknown = if receipts_syncing {
1750 Receipt::Pending
1751 } else {
1752 Receipt::Hidden
1753 };
1754 records
1755 .iter()
1756 .map(|record| {
1757 let receipt = match engine.receipt_state_for(record) {
1758 teams_core::ReceiptState::Read { .. } => Receipt::Read,
1759 teams_core::ReceiptState::Sent => Receipt::Sent,
1760 teams_core::ReceiptState::Unknown => unknown,
1761 };
1762 (record.message_id.clone(), receipt)
1763 })
1764 .collect()
1765 }
1766
1767 fn refresh_receipts(&mut self, generation: u64, cx: &mut Context<Self>) {
1768 let state = self.app.read(cx);
1769 let (Some(engine), Some(Selection::Chat(chat_id))) = (
1770 state.engine.clone(),
1771 self.current.as_ref().map(|c| c.selection.clone()),
1772 ) else {
1773 return;
1774 };
1775 let receiver = runtime::spawn(async move { engine.refresh_receipts(&chat_id).await });
1776 cx.spawn(async move |this, cx| {
1777 receiver.await.ok();
1778 this.update(cx, |this, cx| {
1779 let Some(sync) = this.sync_of(generation) else {
1780 return;
1781 };
1782 sync.receipts = false;
1783 this.rebuild(false, cx);
1784 this.settle_progress(generation, cx);
1785 })
1786 .ok();
1787 })
1788 .detach();
1789 }
1790
1791 fn mark_read(&mut self, trigger: ReadTrigger, cx: &mut Context<Self>) {
1792 if self.draft_active {
1793 return;
1794 }
1795 let state = self.app.read(cx);
1796 if state.viewing_call() && !self.pinned {
1797 return;
1798 }
1799 let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|c| c.selection.clone())
1800 else {
1801 return;
1802 };
1803 if (state.engine.is_none() && !state.mode.demo) || state.mode.read_only {
1804 return;
1805 }
1806 let unread = state
1807 .sidebar
1808 .chats
1809 .iter()
1810 .any(|chat| chat.id == chat_id && chat.unread)
1811 && !state.keeps_unread(&chat_id);
1812 let Some(plan) = plan_read(self.window_active, unread, trigger) else {
1813 return;
1814 };
1815 self.app
1816 .update(cx, |state, cx| state.mark_chat_read(&chat_id, cx));
1817 if plan.clear_divider
1818 && let Some(current) = self.current.as_mut()
1819 && current.first_unread.take().is_some()
1820 {
1821 self.rebuild(false, cx);
1822 }
1823 }
1824
1825 fn request_older(&mut self, cx: &mut Context<Self>) {
1826 let Some(engine) = self.app.read(cx).engine.clone() else {
1827 return;
1828 };
1829 let Some(current) = self.current.as_mut() else {
1830 return;
1831 };
1832 if current.loading_older || current.older_blocked || !current.has_older {
1833 return;
1834 }
1835 current.loading_older = true;
1836 let conversation_id = current.selection.conversation_id().to_owned();
1837 let task_id = conversation_id.clone();
1838 let receiver = runtime::spawn(async move { engine.load_older(&task_id).await });
1839 cx.spawn(async move |this, cx| {
1840 let result = receiver.await;
1841 this.update(cx, |this, cx| {
1842 this.finish_older(&conversation_id, result, cx)
1843 })
1844 .ok();
1845 })
1846 .detach();
1847 }
1848
1849 fn finish_older(
1850 &mut self,
1851 conversation_id: &str,
1852 result: Result<
1853 teams_core::Result<Vec<MessageRecord>>,
1854 tokio::sync::oneshot::error::RecvError,
1855 >,
1856 cx: &mut Context<Self>,
1857 ) {
1858 let Some(current) = self.current.as_mut() else {
1859 return;
1860 };
1861 if current.selection.conversation_id() != conversation_id {
1862 return;
1863 }
1864 current.loading_older = false;
1865 match result {
1866 Ok(Ok(records)) if !records.is_empty() => {
1867 current.loaded_limit = current.loaded_count + records.len();
1868 }
1869 Ok(Ok(_)) => current.older_blocked = true,
1870 Ok(Err(error)) => {
1871 current.older_blocked = true;
1872 self.notice = Some(format!(
1873 "Could not load older messages: {}",
1874 short_error(&error)
1875 ));
1876 }
1877 Err(_) => current.older_blocked = true,
1878 }
1879 self.rebuild(false, cx);
1880 }
1881
1882 fn clear_pending(&mut self) {
1883 self.pending.clear();
1884 self.pending_outgoing.clear();
1885 }
1886
1887 fn outbox_route(&self, reply_root: Option<String>) -> (OutboxTarget, Option<String>) {
1888 if let Some(root_id) = reply_root {
1889 return (OutboxTarget::Thread, Some(root_id));
1890 }
1891 match self.current.as_ref().map(|current| &current.mode) {
1892 Some(ViewMode::Thread(root_id)) => (OutboxTarget::Thread, Some(root_id.clone())),
1893 Some(ViewMode::ThreadList) => (OutboxTarget::Post, None),
1894 _ => (OutboxTarget::Flat, None),
1895 }
1896 }
1897
1898 fn reload_pending(&mut self, cx: &App) {
1899 self.clear_pending();
1900 let state = self.app.read(cx);
1901 if state.mode.demo || state.mode.read_only {
1902 return;
1903 }
1904 let Some(current) = self.current.as_ref() else {
1905 return;
1906 };
1907 let conversation_id = current.selection.conversation_id().to_owned();
1908 let Ok(records) = state.store.outbox_for_conversation(&conversation_id) else {
1909 return;
1910 };
1911 let my_user_id = state.store.meta(META_USER_ID).ok().flatten();
1912 let mut pending = Vec::new();
1913 for record in records {
1914 if !shown_in_view(&current.mode, &record) {
1915 continue;
1916 }
1917 let Some(outgoing) = outgoing_of(&record) else {
1918 continue;
1919 };
1920 let delivery = match record.state {
1921 OutboxState::Sending => Delivery::Sending,
1922 OutboxState::Failed => Delivery::Failed(record.last_error.unwrap_or_default()),
1923 };
1924 let mut row = pending_row(
1925 record.id.clone(),
1926 conversation_id.clone(),
1927 my_user_id.clone(),
1928 record.created_at,
1929 &outgoing,
1930 delivery,
1931 );
1932 row.reply_root = record.thread_root_id.clone();
1933 pending.push((row, record.id, outgoing));
1934 }
1935 for (row, id, outgoing) in pending {
1936 self.pending.push(row);
1937 self.pending_outgoing.insert(id, outgoing);
1938 }
1939 }
1940
1941 fn discard_outbox_row(&self, id: &str, cx: &mut Context<Self>) {
1942 self.app.read(cx).store.delete_outbox(id).ok();
1943 self.app
1944 .update(cx, |state, cx| state.refresh_local_previews(cx));
1945 }
1946
1947 fn delete_pending(&mut self, key: &str, cx: &mut Context<Self>) {
1948 self.pending.retain(|row| row.key != key);
1949 self.pending_outgoing.remove(key);
1950 self.discard_outbox_row(key, cx);
1951 self.rebuild(false, cx);
1952 }
1953
1954 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1955 self.send_as(new_outbox_id(), outgoing, None, window, cx);
1956 }
1957
1958 fn send_in_thread(
1959 &mut self,
1960 root_id: String,
1961 outgoing: Outgoing,
1962 window: &mut Window,
1963 cx: &mut Context<Self>,
1964 ) {
1965 self.send_as(new_outbox_id(), outgoing, Some(root_id), window, cx);
1966 }
1967
1968 fn send_as(
1969 &mut self,
1970 id: String,
1971 outgoing: Outgoing,
1972 reply_root: Option<String>,
1973 window: &mut Window,
1974 cx: &mut Context<Self>,
1975 ) {
1976 let state = self.app.read(cx);
1977 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1978 let Some(current) = self.current.as_ref() else {
1979 return;
1980 };
1981 if mode.read_only || mode.demo {
1982 self.restore_unsent(
1983 "Read-only mode: nothing was sent",
1984 &outgoing,
1985 reply_root.as_deref(),
1986 window,
1987 cx,
1988 );
1989 return;
1990 }
1991 let Some(engine) = engine else {
1992 self.discard_outbox_row(&id, cx);
1993 self.restore_unsent(
1994 "Not connected yet: nothing was sent",
1995 &outgoing,
1996 reply_root.as_deref(),
1997 window,
1998 cx,
1999 );
2000 return;
2001 };
2002 let conversation_id = current.selection.conversation_id().to_owned();
2003 let (target, thread_root_id) = self.outbox_route(reply_root);
2004 let created_at = Utc::now();
2005 self.push_pending(
2006 id.clone(),
2007 created_at,
2008 &outgoing,
2009 thread_root_id.clone(),
2010 cx,
2011 );
2012 if let Some(record) = outbox_record(
2013 &id,
2014 &conversation_id,
2015 target,
2016 thread_root_id.as_deref(),
2017 &outgoing,
2018 created_at,
2019 ) {
2020 store.put_outbox(&record).ok();
2021 }
2022 self.notice = None;
2023 self.rebuild(false, cx);
2024 if self.in_feed() {
2025 self.scroller
2026 .update(cx, |scroller, cx| scroller.scroll_to_item(0, cx));
2027 } else {
2028 self.scroller
2029 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
2030 }
2031
2032 let receiver = runtime::spawn(async move {
2033 deliver(
2034 &engine,
2035 &conversation_id,
2036 target,
2037 thread_root_id.as_deref(),
2038 &outgoing,
2039 )
2040 .await
2041 });
2042 cx.spawn_in(window, async move |this, cx| {
2043 let result = receiver.await;
2044 this.update(cx, |this, cx| this.finish_send(&id, result, cx))
2045 .ok();
2046 })
2047 .detach();
2048 }
2049
2050 fn restore_unsent(
2051 &mut self,
2052 message: &str,
2053 outgoing: &Outgoing,
2054 reply_root: Option<&str>,
2055 window: &mut Window,
2056 cx: &mut Context<Self>,
2057 ) {
2058 self.notice = Some(message.to_owned());
2059 if let (Some(root_id), true) = (reply_root, self.in_feed()) {
2060 self.open_reply_editor(root_id.to_owned(), outgoing.reply.clone(), window, cx);
2061 if let Some(composer) = self.reply_composer.clone() {
2062 composer.update(cx, |composer, cx| composer.restore(outgoing, window, cx));
2063 }
2064 } else {
2065 self.show_main_composer(cx);
2066 self.restore_subject(outgoing.subject.as_deref(), window, cx);
2067 self.composer
2068 .update(cx, |composer, cx| composer.restore(outgoing, window, cx));
2069 }
2070 cx.notify();
2071 }
2072
2073 fn next_pending_key(&mut self) -> String {
2074 self.pending_counter += 1;
2075 format!("{PENDING_KEY_PREFIX}{}", self.pending_counter)
2076 }
2077
2078 fn push_pending(
2079 &mut self,
2080 key: String,
2081 created_at: DateTime<Utc>,
2082 outgoing: &Outgoing,
2083 reply_root: Option<String>,
2084 cx: &App,
2085 ) {
2086 let my_user_id = self.row_context(cx).my_user_id;
2087 let conversation_id = self
2088 .current
2089 .as_ref()
2090 .map(|current| current.selection.conversation_id().to_owned())
2091 .unwrap_or_default();
2092 let mut row = pending_row(
2093 key.clone(),
2094 conversation_id,
2095 my_user_id,
2096 created_at,
2097 outgoing,
2098 Delivery::Sending,
2099 );
2100 row.reply_root = reply_root;
2101 self.pending.push(row);
2102 self.pending_outgoing.insert(key, outgoing.clone());
2103 }
2104
2105 fn send_new_chat(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2106 let (recipients, topic) = {
2107 let draft = self.draft.read(cx);
2108 let topic = Some(draft.group_name(cx)).filter(|name| !name.is_empty());
2109 (draft.chips().to_vec(), topic)
2110 };
2111 if recipients.is_empty() {
2112 self.restore_unsent("Add at least one person first", &outgoing, None, window, cx);
2113 self.draft
2114 .update(cx, |draft, cx| draft.focus_query(window, cx));
2115 return;
2116 }
2117 if self
2118 .pending
2119 .iter()
2120 .any(|row| matches!(row.delivery, Delivery::Sending))
2121 {
2122 self.restore_unsent("Still creating the chat", &outgoing, None, window, cx);
2123 return;
2124 }
2125 let state = self.app.read(cx);
2126 let (mode, engine) = (state.mode, state.engine.clone());
2127 if mode.read_only {
2128 self.restore_unsent(
2129 "Read-only mode: nothing was sent",
2130 &outgoing,
2131 None,
2132 window,
2133 cx,
2134 );
2135 return;
2136 }
2137 if mode.demo && outgoing.has_attachments() {
2138 self.restore_unsent(
2139 "Read-only mode: nothing was sent",
2140 &outgoing,
2141 None,
2142 window,
2143 cx,
2144 );
2145 return;
2146 }
2147 if mode.demo {
2148 self.send_demo_new_chat(&outgoing, &recipients, topic.as_deref(), cx);
2149 return;
2150 }
2151 let Some(engine) = engine else {
2152 self.restore_unsent(
2153 "Not connected yet: nothing was sent",
2154 &outgoing,
2155 None,
2156 window,
2157 cx,
2158 );
2159 return;
2160 };
2161 let user_ids: Vec<String> = recipients.into_iter().map(|pick| pick.user_id).collect();
2162 let known_chat = self
2163 .draft_created
2164 .as_ref()
2165 .filter(|(created_for, _)| *created_for == user_ids)
2166 .map(|(_, chat_id)| chat_id.clone())
2167 .or_else(|| self.draft_target_chat(cx));
2168 self.pending.clear();
2169 self.pending_outgoing.clear();
2170 self.draft_error = None;
2171 self.notice = None;
2172 let key = self.next_pending_key();
2173 self.push_pending(key.clone(), Utc::now(), &outgoing, None, cx);
2174 self.rebuild(true, cx);
2175 let recipients_for_finish = user_ids.clone();
2176 let receiver = runtime::spawn(async move {
2177 let chat_id = match known_chat {
2178 Some(chat_id) => chat_id,
2179 None => {
2180 let created = match user_ids.as_slice() {
2181 [user_id] => engine.create_one_on_one(user_id).await,
2182 _ => engine.create_group(&user_ids, topic.as_deref()).await,
2183 };
2184 match created {
2185 Ok(chat_id) => chat_id,
2186 Err(error) => return (None, Some(short_error(&error))),
2187 }
2188 }
2189 };
2190 let sent = engine
2191 .send_message_with_extras(
2192 &chat_id,
2193 &outgoing.html(),
2194 None,
2195 &outgoing.mentions,
2196 &outgoing.extras(),
2197 )
2198 .await;
2199 if let (Ok(record), Some(preview)) = (&sent, &outgoing.link_preview) {
2200 let _ = engine
2201 .attach_link_preview(&chat_id, &record.message_id, preview)
2202 .await;
2203 }
2204 (Some(chat_id), sent.err().map(|error| short_error(&error)))
2205 });
2206 cx.spawn_in(window, async move |this, cx| {
2207 let result = receiver.await;
2208 this.update_in(cx, |this, _, cx| {
2209 this.finish_new_chat(&key, recipients_for_finish, result, cx)
2210 })
2211 .ok();
2212 })
2213 .detach();
2214 }
2215
2216 fn finish_new_chat(
2217 &mut self,
2218 key: &str,
2219 user_ids: Vec<String>,
2220 result: Result<(Option<String>, Option<String>), tokio::sync::oneshot::error::RecvError>,
2221 cx: &mut Context<Self>,
2222 ) {
2223 if !self.draft_active || !self.pending.iter().any(|row| row.key == key) {
2224 return;
2225 }
2226 let (chat_id, error) = result.unwrap_or((None, Some("cancelled".to_owned())));
2227 self.draft_created = chat_id.clone().map(|chat_id| (user_ids, chat_id));
2228 match (chat_id, error) {
2229 (Some(chat_id), None) => {
2230 self.app.update(cx, |state, cx| {
2231 state.reload_sidebar(cx);
2232 state.select(Selection::Chat(chat_id), cx);
2233 });
2234 }
2235 (created, error) => {
2236 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
2237 row.delivery = Delivery::Failed(error.unwrap_or_default());
2238 }
2239 self.draft_error = Some(
2240 if created.is_some() {
2241 "Couldn't send the message."
2242 } else {
2243 "Couldn't create the chat."
2244 }
2245 .to_owned(),
2246 );
2247 self.rebuild(false, cx);
2248 }
2249 }
2250 }
2251
2252 fn send_demo_new_chat(
2253 &mut self,
2254 outgoing: &Outgoing,
2255 recipients: &[super::new_chat::Pick],
2256 topic: Option<&str>,
2257 cx: &mut Context<Self>,
2258 ) {
2259 let (store, chats) = {
2260 let state = self.app.read(cx);
2261 (state.store.clone(), state.sidebar.chats.clone())
2262 };
2263 let people: Vec<(String, String)> = recipients
2264 .iter()
2265 .map(|pick| (pick.user_id.clone(), pick.name.clone()))
2266 .collect();
2267 let (chat, message) = match self.draft_target_chat(cx) {
2268 Some(chat_id) => {
2269 let Some(chat) = chats.iter().find(|chat| chat.id == chat_id) else {
2270 return;
2271 };
2272 crate::demo::send_in_chat(chat, &outgoing.text(), &outgoing.html(), Utc::now())
2273 }
2274 None => crate::demo::new_chat(
2275 &chats,
2276 &people,
2277 topic,
2278 &outgoing.text(),
2279 &outgoing.html(),
2280 Utc::now(),
2281 ),
2282 };
2283 let _ = store.upsert_chats(std::slice::from_ref(&chat));
2284 let _ = store.upsert_messages(std::slice::from_ref(&message));
2285 self.app.update(cx, |state, cx| {
2286 state.reload_sidebar(cx);
2287 state.select(Selection::Chat(chat.id.clone()), cx);
2288 });
2289 }
2290
2291 fn conversation_id(&self) -> Option<String> {
2292 self.current
2293 .as_ref()
2294 .map(|current| current.selection.conversation_id().to_owned())
2295 }
2296
2297 fn own_record(&self, message_id: &str, cx: &App) -> Option<MessageRecord> {
2298 let conversation_id = self.conversation_id()?;
2299 let my_user_id = self.row_context(cx).my_user_id?;
2300 self.app
2301 .read(cx)
2302 .store
2303 .messages_by_id(&conversation_id, &[message_id.to_owned()])
2304 .ok()?
2305 .remove(message_id)
2306 .filter(|record| !record.deleted && record.sender_id.as_deref() == Some(&my_user_id))
2307 }
2308
2309 fn set_hover(&mut self, slot: HoverSlot, key: &str, hovered: bool, cx: &mut Context<Self>) {
2310 let target = match slot {
2311 HoverSlot::Row => &mut self.hovered_message,
2312 HoverSlot::Toolbar => &mut self.toolbar_hovered,
2313 };
2314 if hovered {
2315 *target = Some(key.to_owned());
2316 } else if target.as_deref() == Some(key) {
2317 *target = None;
2318 }
2319 if let Some(suppressed) = self.toolbar_suppressed.as_deref()
2320 && self.hovered_message.as_deref() != Some(suppressed)
2321 && self.toolbar_hovered.as_deref() != Some(suppressed)
2322 {
2323 self.toolbar_suppressed = None;
2324 }
2325 cx.notify();
2326 }
2327
2328 fn suppress_toolbar(&mut self, key: &str, cx: &mut Context<Self>) {
2329 if self.toolbar_hovered.as_deref() == Some(key) {
2330 self.toolbar_hovered = None;
2331 }
2332 self.toolbar_suppressed = Some(key.to_owned());
2333 cx.notify();
2334 }
2335
2336 fn set_pinned(&mut self, key: &str, open: bool, cx: &mut Context<Self>) {
2337 if open {
2338 self.toolbar_pinned = Some(key.to_owned());
2339 } else if self.toolbar_pinned.as_deref() == Some(key) {
2340 self.toolbar_pinned = None;
2341 }
2342 cx.notify();
2343 }
2344
2345 fn toolbar_visible(&self, key: &str) -> bool {
2346 self.toolbar_suppressed.as_deref() != Some(key)
2347 && self
2348 .toolbar_pinned
2349 .as_deref()
2350 .or(self.toolbar_hovered.as_deref())
2351 .or(self.hovered_message.as_deref())
2352 == Some(key)
2353 }
2354
2355 fn toggle_reaction(&mut self, message_id: &str, glyph: &str, cx: &mut Context<Self>) {
2356 let Some(conversation_id) = self.conversation_id() else {
2357 return;
2358 };
2359 let state = self.app.read(cx);
2360 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2361 let engine = engine.filter(|_| !mode.read_only);
2362 if !mode.demo && engine.is_none() {
2363 self.show_notice("Read-only mode: reaction not sent", cx);
2364 return;
2365 }
2366 let my_user_id = self.row_context(cx).my_user_id;
2367 let Some(mut record) = store
2368 .messages_by_id(&conversation_id, &[message_id.to_owned()])
2369 .ok()
2370 .and_then(|mut found| found.remove(message_id))
2371 else {
2372 return;
2373 };
2374 let wanted = reaction_glyph(glyph);
2375 let mut visible = teams_core::reactions(&record);
2376 apply_pending_reactions(
2377 &mut visible,
2378 self.pending_reactions.get(message_id),
2379 my_user_id.as_deref(),
2380 Utc::now(),
2381 );
2382 let added = !has_own_reaction(&visible, glyph, my_user_id.as_deref());
2383 let Some(engine) = engine.filter(|_| !mode.demo) else {
2384 let mut reactions = teams_core::reactions(&record);
2385 set_own_reaction(
2386 &mut reactions,
2387 glyph,
2388 my_user_id.as_deref(),
2389 added,
2390 Utc::now(),
2391 );
2392 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
2393 let _ = store.upsert_messages(std::slice::from_ref(&record));
2394 if added {
2395 self.record_reaction_use(glyph, cx);
2396 }
2397 self.rebuild(false, cx);
2398 return;
2399 };
2400 let entries = self
2401 .pending_reactions
2402 .entry(message_id.to_owned())
2403 .or_default();
2404 entries.retain(|(pending, _)| *pending != wanted);
2405 entries.push((wanted.clone(), added));
2406 self.rebuild(false, cx);
2407 let (message_id, glyph) = (message_id.to_owned(), glyph.to_owned());
2408 let reaction_type = api_reaction(&wanted);
2409 let receiver = runtime::spawn({
2410 let (conversation_id, message_id) = (conversation_id.clone(), message_id.clone());
2411 async move {
2412 if added {
2413 engine
2414 .set_reaction(&conversation_id, &message_id, &reaction_type)
2415 .await
2416 } else {
2417 engine
2418 .unset_reaction(&conversation_id, &message_id, &reaction_type)
2419 .await
2420 }
2421 }
2422 });
2423 cx.spawn(async move |this, cx| {
2424 let outcome = match receiver.await {
2425 Ok(Ok(())) => Ok(()),
2426 Ok(Err(error)) => Err(short_error(&error)),
2427 Err(_) => Err("cancelled".to_owned()),
2428 };
2429 this.update(cx, |this, cx| {
2430 this.finish_reaction(&conversation_id, &message_id, &glyph, added, outcome, cx)
2431 })
2432 .ok();
2433 })
2434 .detach();
2435 }
2436
2437 fn finish_reaction(
2438 &mut self,
2439 conversation_id: &str,
2440 message_id: &str,
2441 glyph: &str,
2442 added: bool,
2443 outcome: Result<(), String>,
2444 cx: &mut Context<Self>,
2445 ) {
2446 let wanted = reaction_glyph(glyph);
2447 let store = self.app.read(cx).store.clone();
2448 if outcome.is_ok() {
2449 let my_user_id = self.row_context(cx).my_user_id;
2450 if let Some(mut record) = store
2451 .messages_by_id(conversation_id, &[message_id.to_owned()])
2452 .ok()
2453 .and_then(|mut found| found.remove(message_id))
2454 {
2455 let mut reactions = teams_core::reactions(&record);
2456 set_own_reaction(
2457 &mut reactions,
2458 glyph,
2459 my_user_id.as_deref(),
2460 added,
2461 Utc::now(),
2462 );
2463 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
2464 let _ = store.upsert_messages(std::slice::from_ref(&record));
2465 }
2466 if added {
2467 self.record_reaction_use(glyph, cx);
2468 }
2469 }
2470 if let Some(entries) = self.pending_reactions.get_mut(message_id) {
2471 entries.retain(|entry| *entry != (wanted.clone(), added));
2472 if entries.is_empty() {
2473 self.pending_reactions.remove(message_id);
2474 }
2475 }
2476 self.rebuild(false, cx);
2477 if let Err(error) = outcome {
2478 self.show_notice(&format!("Reaction failed: {error}"), cx);
2479 }
2480 }
2481
2482 fn record_reaction_use(&mut self, glyph: &str, cx: &mut Context<Self>) {
2483 let store = self.app.read(cx).store.clone();
2484 self.recent.update(cx, |recent, cx| {
2485 recent.reload(&store);
2486 recent.record_use(glyph);
2487 recent.save(&store);
2488 cx.notify();
2489 });
2490 }
2491
2492 fn begin_edit(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
2493 let Some(record) = self.own_record(message_id, cx) else {
2494 return;
2495 };
2496 let edit = EditPreview {
2497 message_id: record.message_id.clone(),
2498 excerpt: reply_excerpt(&record),
2499 scheduled: None,
2500 };
2501 let in_chat = matches!(
2502 self.current.as_ref().map(|current| &current.selection),
2503 Some(Selection::Chat(_))
2504 );
2505 let mentions = if in_chat {
2506 teams_core::user_mention_inputs(&record)
2507 } else {
2508 Vec::new()
2509 };
2510 let draft = Outgoing {
2511 draft: message_draft(&record),
2512 subject: None,
2513 mentions,
2514 reply: None,
2515 edit: Some(edit),
2516 images: Vec::new(),
2517 files: Vec::new(),
2518 link_preview: None,
2519 };
2520 self.show_main_composer(cx);
2521 self.composer
2522 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
2523 }
2524
2525 fn edit_last_own(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2526 if self.draft_active {
2527 return;
2528 }
2529 let key = self
2530 .rows
2531 .borrow()
2532 .iter()
2533 .flat_map(Row::messages)
2534 .filter(|message| {
2535 message.own && !message.deleted && !message.key.starts_with(PENDING_KEY_PREFIX)
2536 })
2537 .max_by_key(|message| message.created_at)
2538 .map(|message| message.key.clone());
2539 if let Some(key) = key {
2540 self.begin_edit(&key, window, cx);
2541 }
2542 }
2543
2544 fn send_edit(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2545 let Some(edit) = outgoing.edit.clone() else {
2546 return;
2547 };
2548 let Some(conversation_id) = self.conversation_id() else {
2549 return;
2550 };
2551 let state = self.app.read(cx);
2552 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2553 if mode.demo {
2554 if let Some(mut record) = self.own_record(&edit.message_id, cx) {
2555 record.body_html = outgoing.html();
2556 record.edited_at = Some(Utc::now());
2557 let _ = store.upsert_messages(std::slice::from_ref(&record));
2558 self.rebuild(false, cx);
2559 }
2560 return;
2561 }
2562 let Some(engine) = engine.filter(|_| !mode.read_only) else {
2563 self.notice = Some("Read-only mode: edit not saved".to_owned());
2564 self.show_main_composer(cx);
2565 self.composer
2566 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
2567 cx.notify();
2568 return;
2569 };
2570 let sent = outgoing.clone();
2571 let receiver = runtime::spawn(async move {
2572 engine
2573 .edit_message_html(
2574 &conversation_id,
2575 &edit.message_id,
2576 &sent.html(),
2577 &sent.mentions,
2578 )
2579 .await
2580 });
2581 cx.spawn_in(window, async move |this, cx| {
2582 let failed = !matches!(receiver.await, Ok(Ok(())));
2583 this.update_in(cx, |this, window, cx| {
2584 if failed {
2585 this.show_main_composer(cx);
2586 if this.composer.read(cx).is_empty(cx) {
2587 this.notice =
2588 Some("Edit failed: your text is back in the composer".to_owned());
2589 this.composer
2590 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
2591 } else {
2592 this.notice = Some("Edit failed".to_owned());
2593 }
2594 cx.notify();
2595 }
2596 })
2597 .ok();
2598 })
2599 .detach();
2600 }
2601
2602 fn delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
2603 let Some(mut record) = self.own_record(message_id, cx) else {
2604 return;
2605 };
2606 let state = self.app.read(cx);
2607 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2608 if mode.demo {
2609 record.deleted = true;
2610 let _ = store.upsert_messages(std::slice::from_ref(&record));
2611 self.rebuild(false, cx);
2612 return;
2613 }
2614 let Some(engine) = engine.filter(|_| !mode.read_only) else {
2615 self.show_notice("Read-only mode: message not deleted", cx);
2616 return;
2617 };
2618 let conversation_id = record.conversation_id.clone();
2619 let receiver = runtime::spawn(async move {
2620 engine
2621 .soft_delete_message(&conversation_id, &record.message_id)
2622 .await
2623 });
2624 self.report_failure(receiver, "Delete failed", cx);
2625 }
2626
2627 fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) {
2628 let Some(conversation_id) = self.conversation_id() else {
2629 return;
2630 };
2631 let record = self
2632 .app
2633 .read(cx)
2634 .store
2635 .messages_by_id(&conversation_id, &[message_id.to_owned()])
2636 .ok()
2637 .and_then(|mut found| found.remove(message_id));
2638 if let Some(record) = record {
2639 cx.write_to_clipboard(ClipboardItem::new_string(message_text(&record)));
2640 }
2641 }
2642
2643 fn refresh_card(
2644 &mut self,
2645 key: &str,
2646 card_index: usize,
2647 action: ExecuteAction,
2648 cx: &mut Context<Self>,
2649 ) {
2650 let Some(conversation_id) = self.conversation_id() else {
2651 return;
2652 };
2653 let scope = CardScope::message(&conversation_id, key, card_index);
2654 self.app.update(cx, |state, cx| {
2655 state.refresh_card_manually(scope, action, cx)
2656 });
2657 }
2658
2659 pub(super) fn translate_message(&mut self, key: &str, cx: &mut Context<Self>) {
2660 let Some(conversation_id) = self.conversation_id() else {
2661 return;
2662 };
2663 self.app.update(cx, |state, cx| {
2664 state.translate_message(&conversation_id, key, cx)
2665 });
2666 }
2667
2668 fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) {
2669 self.app.update(cx, |state, cx| {
2670 state.raise_notice(message.to_owned(), None, cx)
2671 });
2672 }
2673
2674 fn report_failure(
2675 &mut self,
2676 receiver: tokio::sync::oneshot::Receiver<teams_core::Result<()>>,
2677 label: &'static str,
2678 cx: &mut Context<Self>,
2679 ) {
2680 cx.spawn(async move |this, cx| {
2681 let error = match receiver.await {
2682 Ok(Ok(())) => return,
2683 Ok(Err(error)) => short_error(&error),
2684 Err(_) => "cancelled".to_owned(),
2685 };
2686 this.update(cx, |this, cx| {
2687 this.show_notice(&format!("{label}: {error}"), cx)
2688 })
2689 .ok();
2690 })
2691 .detach();
2692 }
2693
2694 fn delegate_entries(&self, key: &str, cx: &App) -> (Vec<DelegateEntry>, Option<Action>) {
2695 let (Some(conversation_id), Some(runs)) =
2696 (self.conversation_id(), crate::agents::runs_handle(cx))
2697 else {
2698 return (Vec::new(), None);
2699 };
2700 if key.starts_with(PENDING_KEY_PREFIX) || key.starts_with(SCHEDULED_KEY_PREFIX) {
2701 return (Vec::new(), None);
2702 }
2703 let settings = runs.read(cx).settings();
2704 let entries: Vec<DelegateEntry> = settings
2705 .actions
2706 .iter()
2707 .map(|action| {
2708 let request = StartRequest {
2709 action_id: action.id.clone(),
2710 conversation_id: conversation_id.clone(),
2711 message_id: key.to_owned(),
2712 };
2713 let agent_name = settings
2714 .agents
2715 .iter()
2716 .find(|agent| agent.id == action.agent_id)
2717 .map(|agent| agent.name.clone())
2718 .unwrap_or_default();
2719 DelegateEntry {
2720 label: action.label.clone(),
2721 agent_name,
2722 action: Rc::new(move |_, cx| crate::agents::delegate(request.clone(), cx)),
2723 }
2724 })
2725 .collect();
2726 let manage_agents = (!entries.is_empty()).then(|| {
2727 Rc::new(|_: &mut Window, cx: &mut App| crate::agents::open_settings(cx)) as Action
2728 });
2729 (entries, manage_agents)
2730 }
2731
2732 fn refresh_agent_runs(&mut self, cx: &App) -> (bool, HashSet<String>) {
2733 let Some(conversation_id) = self.conversation_id() else {
2734 return (false, HashSet::new());
2735 };
2736 let Some(runs) = crate::agents::runs_handle(cx) else {
2737 return (false, HashSet::new());
2738 };
2739 let mut snapshot: HashMap<String, AgentRun> = HashMap::new();
2740 for run in runs.read(cx).for_conversation(&conversation_id) {
2741 snapshot.insert(run.message_id.clone(), run.clone());
2742 }
2743 let layouts: HashMap<String, (usize, bool)> = snapshot
2744 .iter()
2745 .map(|(key, run)| (key.clone(), run.layout_key()))
2746 .collect();
2747 let layout_changed: HashSet<String> = layouts
2748 .iter()
2749 .filter(|(key, layout)| self.agent_layouts.get(*key) != Some(layout))
2750 .map(|(key, _)| key.clone())
2751 .chain(
2752 self.agent_layouts
2753 .keys()
2754 .filter(|key| !layouts.contains_key(*key))
2755 .cloned(),
2756 )
2757 .collect();
2758 self.agent_layouts = layouts;
2759 let snapshot_changed = *self.agent_runs.borrow() != snapshot;
2760 *self.agent_runs.borrow_mut() = snapshot;
2761 (snapshot_changed, layout_changed)
2762 }
2763
2764 fn sync_agent_chips(&mut self, cx: &mut Context<Self>) {
2765 let (snapshot_changed, changed) = self.refresh_agent_runs(cx);
2766 let any_running = self.agent_runs.borrow().values().any(AgentRun::is_running);
2767 if !changed.is_empty() {
2768 let indices: Vec<usize> = self
2769 .rows
2770 .borrow()
2771 .iter()
2772 .enumerate()
2773 .filter(|(_, row)| row.messages().any(|message| changed.contains(&message.key)))
2774 .map(|(index, _)| index)
2775 .collect();
2776 self.scroller.update(cx, |scroller, cx| {
2777 for index in indices {
2778 scroller.remeasure_items(index..index + 1, cx);
2779 }
2780 });
2781 }
2782 if snapshot_changed || any_running {
2783 cx.notify();
2784 }
2785 }
2786
2787 fn message_menu(
2788 &self,
2789 message: &MessageRow,
2790 mine: HashSet<String>,
2791 refresh: Option<(usize, ExecuteAction)>,
2792 view: WeakEntity<Self>,
2793 cx: &App,
2794 ) -> MessageMenu {
2795 let (key, own) = (message.key.as_str(), message.own);
2796 let translate_label = match message.translation {
2797 Some(TranslationLine::Translated {
2798 showing_original: false,
2799 ..
2800 }) => "See original",
2801 Some(TranslationLine::Translated { .. }) => "See translation",
2802 _ => "Translate",
2803 };
2804 let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
2805 let (view, key) = (view.clone(), key.to_owned());
2806 Rc::new(move |window, cx| {
2807 view.update(cx, |this, cx| run(this, &key, window, cx)).ok();
2808 })
2809 };
2810 let react: PickHandler = {
2811 let (view, key) = (view.clone(), key.to_owned());
2812 Rc::new(move |glyph, _, cx| {
2813 view.update(cx, |this, cx| this.toggle_reaction(&key, glyph, cx))
2814 .ok();
2815 })
2816 };
2817 let hover = {
2818 let (view, key) = (view.clone(), key.to_owned());
2819 Rc::new(move |hovered: bool, cx: &mut App| {
2820 view.update(cx, |this, cx| {
2821 this.set_hover(HoverSlot::Toolbar, &key, hovered, cx)
2822 })
2823 .ok();
2824 })
2825 };
2826 let pin = {
2827 let (view, key) = (view.clone(), key.to_owned());
2828 Rc::new(move |open: bool, _: &mut Window, cx: &mut App| {
2829 view.update(cx, |this, cx| this.set_pinned(&key, open, cx))
2830 .ok();
2831 })
2832 };
2833 let refresh_card = refresh.map(|(card_index, refresh_action)| {
2834 let (view, key) = (view.clone(), key.to_owned());
2835 Rc::new(move |_: &mut Window, cx: &mut App| {
2836 view.update(cx, |this, cx| {
2837 this.refresh_card(&key, card_index, refresh_action.clone(), cx)
2838 })
2839 .ok();
2840 }) as Action
2841 });
2842 let chat_id = self.chat_id();
2843 let state = self.app.read(cx);
2844 let saved = self
2845 .conversation_id()
2846 .is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
2847 let pinned = chat_id
2848 .as_deref()
2849 .is_some_and(|chat_id| state.is_pinned(chat_id, key));
2850 let in_chat = chat_id.is_some();
2851 let (delegate, manage_agents) = self.delegate_entries(key, cx);
2852 MessageMenu {
2853 key: key.to_owned(),
2854 react,
2855 reply: Some(action(|this, key, window, cx| {
2856 this.begin_reply(key, window, cx)
2857 })),
2858 forward: Some(action(|this, key, _, cx| this.forward_message(key, cx))),
2859 copy_link: Some(action(|this, key, _, cx| this.copy_link(key, cx))),
2860 copy: action(|this, key, _, cx| this.copy_text(key, cx)),
2861 translate: Some(action(|this, key, _, cx| this.translate_message(key, cx))),
2862 translate_label,
2863 save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
2864 saved,
2865 toggle_pinned: in_chat.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),
2866 pinned,
2867 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
2868 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
2869 mark_unread: (in_chat && !own)
2870 .then(|| action(|this, key, _, cx| this.mark_unread_from(key, cx))),
2871 refresh_card,
2872 delegate,
2873 manage_agents,
2874 pin,
2875 hover,
2876 picker: self.picker.clone(),
2877 quick: self.recent.read(cx).most_used(QUICK_REACTION_COUNT),
2878 mine,
2879 done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),
2880 }
2881 }
2882
2883 fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) {
2884 let Some(outgoing) = self.pending_outgoing.remove(key) else {
2885 return;
2886 };
2887 let reply_root = self
2888 .pending
2889 .iter()
2890 .find(|row| row.key == key)
2891 .and_then(|row| row.reply_root.clone());
2892 self.pending.retain(|row| row.key != key);
2893 if self.draft_active {
2894 self.send_new_chat(outgoing, window, cx);
2895 } else {
2896 self.send_as(key.to_owned(), outgoing, reply_root, window, cx);
2897 }
2898 }
2899
2900 fn finish_send(
2901 &mut self,
2902 key: &str,
2903 result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>,
2904 cx: &mut Context<Self>,
2905 ) {
2906 let failure = match result {
2907 Ok(Ok(())) => None,
2908 Ok(Err(error)) => Some(short_error(&error)),
2909 Err(error) => Some(short_error(&error)),
2910 };
2911 let store = self.app.read(cx).store.clone();
2912 match failure {
2913 None => {
2914 store.delete_outbox(key).ok();
2915 self.pending.retain(|row| row.key != key);
2916 self.pending_outgoing.remove(key);
2917 }
2918 Some(error) => {
2919 store.mark_outbox_failed(key, &error).ok();
2920 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
2921 row.delivery = Delivery::Failed(error.clone());
2922 self.notice = Some(format!("Not sent: {error}"));
2923 }
2924 }
2925 }
2926 self.app
2927 .update(cx, |state, cx| state.refresh_local_previews(cx));
2928 self.rebuild(false, cx);
2929 }
2930
2931 fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
2932 let target = match self.current.as_ref().map(|current| &current.selection) {
2933 Some(Selection::Chat(_)) => DropTarget::Chat,
2934 Some(Selection::Channel(_)) if self.shared_active() => DropTarget::Library,
2935 Some(Selection::Channel(_)) => DropTarget::Channel,
2936 None => DropTarget::NewChat,
2937 };
2938 let title = self
2939 .current
2940 .as_ref()
2941 .map(|current| current.title.as_str())
2942 .unwrap_or_default();
2943 let (heading, detail) = drop_overlay_text(title, target, self.drag_file_count.max(1));
2944 let composer = self.composer.clone();
2945 div()
2946 .id("drop-overlay")
2947 .absolute()
2948 .top_0()
2949 .left_0()
2950 .size_full()
2951 .opacity(0.)
2952 .bg(theme::drop_background())
2953 .drag_over::<ExternalPaths>(move |style, _, _, cx| {
2954 if composer.read(cx).is_editing() {
2955 style
2956 } else {
2957 style.opacity(1.)
2958 }
2959 })
2960 .on_drag_move(
2961 cx.listener(|this, event: &DragMoveEvent<ExternalPaths>, _, cx| {
2962 let count = event.drag(cx).paths().len();
2963 if this.drag_file_count != count {
2964 this.drag_file_count = count;
2965 cx.notify();
2966 }
2967 }),
2968 )
2969 .on_drop(cx.listener(|this, dropped: &ExternalPaths, window, cx| {
2970 let paths = dropped.paths().to_vec();
2971 if this.shared_active() {
2972 this.upload_paths(paths, cx);
2973 return;
2974 }
2975 this.composer
2976 .update(cx, |composer, cx| composer.add_paths(paths, window, cx));
2977 }))
2978 .child(
2979 div()
2980 .absolute()
2981 .inset(px(12.))
2982 .rounded(px(12.))
2983 .border_2()
2984 .border_dashed()
2985 .border_color(theme::accent())
2986 .flex()
2987 .items_center()
2988 .justify_center()
2989 .child(
2990 v_flex()
2991 .items_center()
2992 .gap(px(6.))
2993 .px(px(24.))
2994 .py(px(16.))
2995 .rounded(px(12.))
2996 .bg(black().opacity(0.55))
2997 .child(symbol("upload", 28., theme::accent_text()))
2998 .child(
2999 div()
3000 .text_size(px(15.))
3001 .font_weight(FontWeight::SEMIBOLD)
3002 .text_color(theme::text_strong())
3003 .child(heading),
3004 )
3005 .child(
3006 div()
3007 .text_size(px(12.))
3008 .text_color(theme::text_muted())
3009 .child(detail),
3010 ),
3011 ),
3012 )
3013 }
3014
3015 fn render_draft_error(&self, cx: &mut Context<Self>) -> Option<Div> {
3016 let message = self.draft_error.clone()?;
3017 let failed_key = self
3018 .pending
3019 .iter()
3020 .find(|row| matches!(row.delivery, Delivery::Failed(_)))
3021 .map(|row| row.key.clone())?;
3022 Some(
3023 h_flex()
3024 .w_full()
3025 .flex_none()
3026 .px(px(20.))
3027 .py(px(4.))
3028 .gap(px(8.))
3029 .items_center()
3030 .text_size(px(12.))
3031 .text_color(theme::red_soft())
3032 .child(message)
3033 .child(
3034 Button::new("retry-new-chat")
3035 .ghost()
3036 .compact()
3037 .label("Retry")
3038 .on_click(cx.listener(move |this, _, window, cx| {
3039 this.retry(&failed_key, window, cx)
3040 })),
3041 ),
3042 )
3043 }
3044
3045 fn render_header(&self, current: &Current, cx: &mut Context<Self>) -> impl IntoElement {
3046 let app = self.app.read(cx);
3047 let directory = &app.directory;
3048 let me = directory.me.as_ref();
3049 let mut lead: Option<AnyElement> = None;
3050 let mut subline = String::new();
3051 let mut stack: Option<Div> = None;
3052 match &current.selection {
3053 Selection::Chat(chat_id) => {
3054 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
3055 let faces = others(chat, me);
3056 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
3057 let first = faces.first().cloned().map(face);
3058 if is_one_on_one(chat) || faces.len() < 2 {
3059 let name = first
3060 .as_ref()
3061 .map_or(current.title.as_str(), |face| face.name.as_str());
3062 let user_id = first.as_ref().and_then(|face| face.user_id.as_deref());
3063 let avatar = person_avatar(directory, user_id, name, 36.);
3064 let presence = user_id.map(|id| directory.presence_of(id));
3065 let avatar = match presence {
3066 Some(kind) => with_presence(avatar, kind, 36., theme::surface())
3067 .into_any_element(),
3068 None => avatar,
3069 };
3070 lead = Some(
3071 opens_profile(div().id("header-avatar").flex_none(), user_id)
3072 .child(avatar)
3073 .into_any_element(),
3074 );
3075 subline = match (user_id, presence) {
3076 (Some(id), Some(presence)) => {
3077 directory.status_label(id, presence).to_owned()
3078 }
3079 _ => String::new(),
3080 };
3081 } else {
3082 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3083 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3084 subline = format!("{} participants", chat.members.len());
3085 let shown: Vec<Face> = faces.iter().cloned().map(face).collect();
3086 stack = Some(member_stack(directory, &shown, shown.len()));
3087 }
3088 }
3089 }
3090 Selection::Channel(channel_id) => {
3091 let team = app.sidebar.teams.iter().find(|entry| {
3092 entry
3093 .channels
3094 .iter()
3095 .any(|channel| &channel.id == channel_id)
3096 });
3097 let (name, key) = team
3098 .map_or((current.title.as_str(), current.title.as_str()), |entry| {
3099 (entry.team.name.as_str(), entry.team.id.as_str())
3100 });
3101 lead = Some(square_avatar(name, key, 36., 9.).into_any_element());
3102 }
3103 }
3104 let mut header = h_flex()
3105 .w_full()
3106 .h(px(60.))
3107 .flex_none()
3108 .px(px(20.))
3109 .gap(px(12.))
3110 .items_center();
3111 if matches!(current.mode, ViewMode::Thread(_)) {
3112 header = header.child(
3113 h_flex()
3114 .id("back-to-channel")
3115 .flex_none()
3116 .gap(px(2.))
3117 .pl(px(4.))
3118 .pr(px(8.))
3119 .py(px(4.))
3120 .items_center()
3121 .rounded(px(6.))
3122 .cursor_pointer()
3123 .text_size(px(13.))
3124 .font_weight(FontWeight::SEMIBOLD)
3125 .text_color(theme::accent_text())
3126 .hover(|button| button.bg(theme::row_hover()))
3127 .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx)))
3128 .child(icon(IconName::ChevronLeft, 16., theme::accent_text()))
3129 .child("Back to channel"),
3130 );
3131 }
3132 let channel_note = match current.mode {
3133 ViewMode::Flat => None,
3134 ViewMode::ThreadList => Some("Posts"),
3135 ViewMode::Thread(_) => Some("Conversation"),
3136 };
3137 if let Some(note) = channel_note {
3138 subline = note.to_owned();
3139 }
3140 let call_controls = if self.pinned {
3141 Vec::new()
3142 } else {
3143 header_call_controls(&self.app, app, &current.selection)
3144 };
3145 let sync = &current.sync;
3146 if sync.failed {
3147 subline = "Not up to date".to_owned();
3148 } else if sync.shown_at.is_some() {
3149 subline = if sync.slow {
3150 "Taking longer than usual ..."
3151 } else if sync.empty_cache {
3152 "Loading messages ..."
3153 } else {
3154 "Updating ..."
3155 }
3156 .to_owned();
3157 }
3158 header
3159 .relative()
3160 .when(sync.shown_at.is_some(), |header| {
3161 header.child(progress_bar())
3162 })
3163 .children(lead)
3164 .child(
3165 v_flex()
3166 .flex_1()
3167 .min_w_0()
3168 .overflow_hidden()
3169 .gap(px(1.))
3170 .child(
3171 div()
3172 .truncate()
3173 .text_size(px(15.))
3174 .font_weight(FontWeight::SEMIBOLD)
3175 .text_color(theme::text())
3176 .child(current.title.clone()),
3177 )
3178 .when(!subline.is_empty(), |column| {
3179 column.child(
3180 div()
3181 .text_size(px(12.))
3182 .text_color(theme::text_muted())
3183 .child(subline),
3184 )
3185 }),
3186 )
3187 .children(stack)
3188 .children(call_controls)
3189 }
3190}
3191
3192impl Render for ConversationView {
3193 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3194 let background = theme::surface();
3195 let mut root = v_flex()
3196 .when(!self.pinned, |root| {
3197 root.debug_selector(|| "shell/islands/main".into())
3198 })
3199 .flex_1()
3200 .w_full()
3201 .min_w_0()
3202 .h_full()
3203 .rounded(px(10.))
3204 .bg(background)
3205 .track_focus(&self.focus_handle);
3206 let drafting = self.draft_active;
3207 if self.current.is_none() && !drafting {
3208 return root
3209 .items_center()
3210 .justify_center()
3211 .text_color(theme::text_muted())
3212 .child("Select a chat or channel")
3213 .into_any_element();
3214 }
3215 let in_feed = self.in_feed();
3216 let rows_seen = self.feed_rows_seen.replace(usize::MAX);
3217 if in_feed && rows_seen != usize::MAX {
3218 self.feed_at_top = rows_seen == 0;
3219 }
3220 let rows = self.rows.clone();
3221 let rows_seen = self.feed_rows_seen.clone();
3222 let env = RenderEnv {
3223 view: cx.weak_entity(),
3224 app: self.app.clone(),
3225 highlighted: self.highlighted_message.clone(),
3226 drafting,
3227 reply_editor: self.reply_root.clone().zip(self.reply_composer.clone()),
3228 timeline: self.timeline_bounds.clone(),
3229 agent_runs: self.agent_runs.clone(),
3230 };
3231 let scroller = MessageScroller::new(
3232 "messages",
3233 self.scroller.clone(),
3234 move |index, window, cx| {
3235 rows_seen.set(rows_seen.get().min(index));
3236 let rows = rows.borrow();
3237 match rows.get(index) {
3238 Some(Row::Message(message)) => {
3239 let actions = env.message_actions(message, window, cx);
3240 let state = env.app.read(cx);
3241 render_message_row(message, index, actions, &state.directory, cx)
3242 }
3243 Some(Row::Post(post)) => {
3244 let actions = env.post_actions(post, window, cx);
3245 let state = env.app.read(cx);
3246 render_post(post, index, actions, &state.directory, cx)
3247 }
3248 Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index),
3249 Some(Row::LoadOlder) => {
3250 let view = env.view.clone();
3251 cx.defer(move |cx| {
3252 view.update(cx, |this, cx| this.request_older(cx)).ok();
3253 });
3254 h_flex()
3255 .w_full()
3256 .py_2()
3257 .gap(px(6.))
3258 .justify_center()
3259 .text_size(px(12.))
3260 .text_color(theme::text_muted())
3261 .child(icon(IconName::Loader, 12., theme::text_muted()))
3262 .child("Loading older messages")
3263 .into_any_element()
3264 }
3265 Some(Row::Start(start)) => {
3266 let state = env.app.read(cx);
3267 v_flex()
3268 .w_full()
3269 .items_center()
3270 .gap(px(8.))
3271 .pt(px(32.))
3272 .pb(px(16.))
3273 .child(person_avatar(
3274 &state.directory,
3275 start.user_id.as_deref(),
3276 &start.title,
3277 56.,
3278 ))
3279 .child(
3280 div()
3281 .text_size(px(16.))
3282 .font_weight(FontWeight::SEMIBOLD)
3283 .text_color(theme::text())
3284 .child(start.title.clone()),
3285 )
3286 .child(
3287 div()
3288 .text_size(px(12.))
3289 .text_color(theme::text_muted())
3290 .child("This is the beginning of the conversation"),
3291 )
3292 .into_any_element()
3293 }
3294 None => div().into_any_element(),
3295 }
3296 },
3297 )
3298 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
3299 .jump_button(!in_feed)
3300 .with_bottom_fade(background);
3301
3302 root = match self.current.as_ref().filter(|_| !drafting) {
3303 Some(current) => root.child(self.render_header(current, cx)),
3304 None => root.child(self.draft.clone()),
3305 };
3306 root = root.children(self.render_tab_bar(window, cx).filter(|_| !drafting));
3307 root = root.children(self.render_pin_banner(cx).filter(|_| !drafting));
3308 let sync_failed = self
3309 .current
3310 .as_ref()
3311 .is_some_and(|current| current.sync.failed);
3312 if let Some(notice) = &self.notice {
3313 root = root.child(
3314 h_flex()
3315 .px(px(20.))
3316 .py_1()
3317 .gap(px(8.))
3318 .items_center()
3319 .text_xs()
3320 .bg(theme::amber().opacity(0.15))
3321 .text_color(theme::amber())
3322 .child(div().flex_1().min_w_0().child(notice.clone()))
3323 .when(sync_failed, |bar| {
3324 bar.child(
3325 Button::new("retry-fetch")
3326 .ghost()
3327 .compact()
3328 .label("Retry")
3329 .on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))),
3330 )
3331 }),
3332 );
3333 }
3334 let empty_channel = in_feed && self.rows.borrow().is_empty();
3335 let new_post = self.render_new_post(window, cx);
3336 let body = if drafting && self.current.is_none() && self.rows.borrow().is_empty() {
3337 let draft = self.draft.read(cx);
3338 let group_name = draft.group_name(cx);
3339 draft.render_empty(&self.app.read(cx).directory, &group_name)
3340 } else if self.shared_active() {
3341 self.render_shared(cx)
3342 } else if empty_channel {
3343 div()
3344 .size_full()
3345 .flex()
3346 .items_center()
3347 .justify_center()
3348 .text_size(px(13.))
3349 .text_color(theme::text_muted())
3350 .child("No posts in this channel yet")
3351 .into_any_element()
3352 } else {
3353 scroller.into_any_element()
3354 };
3355 root.child(
3356 v_flex()
3357 .relative()
3358 .flex_1()
3359 .min_h_0()
3360 .children(new_post)
3361 .child(
3362 div()
3363 .relative()
3364 .flex_1()
3365 .min_h_0()
3366 .child(record_bounds(&self.timeline_bounds))
3367 .on_scroll_wheel(
3368 cx.listener(|this, _, _, cx| this.close_reaction_details(cx)),
3369 )
3370 .child(body),
3371 )
3372 .children(self.render_draft_error(cx))
3373 .when(!in_feed, |column| {
3374 column
3375 .child(self.render_typing_line(cx))
3376 .children(self.render_proposal_card(cx))
3377 .child(self.composer.clone())
3378 })
3379 .child(self.render_drop_overlay(cx)),
3380 )
3381 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3382 if this.reaction_details.is_some() {
3383 this.close_reaction_details(cx);
3384 cx.stop_propagation();
3385 }
3386 }))
3387 .on_action(cx.listener(|this, _: &Escape, window, cx| {
3388 if this.draft_active {
3389 if this.draft.read(cx).has_focus(window, cx) {
3390 this.draft.update(cx, |draft, cx| draft.escape(cx));
3391 }
3392 } else if !this.on_escape(window, cx) {
3393 cx.propagate();
3394 }
3395 }))
3396 .into_any_element()
3397 }
3398}
3399
3400fn typing_dots() -> impl IntoElement {
3401 h_flex()
3402 .gap(px(3.))
3403 .flex_none()
3404 .children((0..TYPING_DOT_COUNT).map(|index| {
3405 let phase_offset = index as f32 / TYPING_DOT_COUNT as f32;
3406 div()
3407 .size(px(TYPING_DOT_SIZE))
3408 .rounded_full()
3409 .bg(theme::text_muted())
3410 .with_animation(
3411 ElementId::NamedInteger("typing-dot".into(), index as u64),
3412 Animation::new(TYPING_PULSE_PERIOD).repeat(),
3413 move |dot, delta| {
3414 let wave = 1. - ((delta - phase_offset).rem_euclid(1.) * 2. - 1.).abs();
3415 dot.opacity(0.3 + 0.7 * wave)
3416 },
3417 )
3418 }))
3419}
3420
3421fn progress_bar() -> impl IntoElement {
3422 div()
3423 .absolute()
3424 .left_0()
3425 .right_0()
3426 .bottom(px(-1.))
3427 .h(px(2.))
3428 .overflow_hidden()
3429 .bg(theme::border())
3430 .child(
3431 div()
3432 .absolute()
3433 .top_0()
3434 .h_full()
3435 .w(relative(PROGRESS_BAR_WIDTH))
3436 .bg(theme::own_read())
3437 .with_animation(
3438 "sync-progress",
3439 Animation::new(PROGRESS_BAR_PERIOD).repeat(),
3440 |bar, delta| {
3441 let travel = 1. + PROGRESS_BAR_WIDTH;
3442 // The 0.3 phase keeps the bar on screen in the static reduce-motion frame (delta 0).
3443 bar.left(relative(
3444 (delta + 0.3).fract() * travel - PROGRESS_BAR_WIDTH,
3445 ))
3446 },
3447 ),
3448 )
3449}
3450
3451#[cfg(test)]
3452mod tests {
3453 use std::sync::Arc;
3454
3455 use super::{DropTarget, drop_overlay_text};
3456
3457 use gpui_kit::test::TestWindowExt as _;
3458 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
3459 use store::Store;
3460
3461 use super::ConversationView;
3462 use crate::app_state::{AppState, Mode, Selection};
3463
3464 #[test]
3465 fn chat_overlay_names_the_chat_and_the_onedrive() {
3466 assert_eq!(
3467 drop_overlay_text("Mara Lin", DropTarget::Chat, 3),
3468 (
3469 "Drop to attach to Mara Lin".to_owned(),
3470 "3 files. Images go into the message, other files to your OneDrive.".to_owned()
3471 )
3472 );
3473 }
3474
3475 #[test]
3476 fn channel_overlay_points_to_the_channel_files() {
3477 let (_, detail) = drop_overlay_text("Squad / General", DropTarget::Channel, 1);
3478 assert_eq!(
3479 detail,
3480 "1 file. Images go into the message, other files to the channel's Files."
3481 );
3482 }
3483
3484 #[test]
3485 fn new_chat_overlay_says_files_wait_for_the_chat() {
3486 let (heading, detail) = drop_overlay_text("", DropTarget::NewChat, 2);
3487 assert_eq!(heading, "Drop to attach to the new chat");
3488 assert_eq!(
3489 detail,
3490 "2 files. Images go into the message. Files can be added once the chat exists."
3491 );
3492 }
3493
3494 #[gpui_kit::test]
3495 fn demo_draft_creates_a_chat_and_selects_it(cx: &mut TestAppContext) {
3496 cx.update(gpui_kit::init);
3497 let store = Arc::new(Store::open_in_memory().unwrap());
3498 crate::demo::seed(&store);
3499 let mode = Mode {
3500 demo: true,
3501 read_only: false,
3502 demo_sync: None,
3503 };
3504 let (handle, app, _view) = cx.update(|cx| {
3505 let app = cx.new(|_| {
3506 let mut state = AppState::new(store, mode);
3507 crate::demo::seed_directory(&mut state);
3508 state.selection = Some(crate::demo::first_selection());
3509 state
3510 });
3511 let shared = app.clone();
3512 let (handle, view) =
3513 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3514 cx.new(|cx| ConversationView::new(shared, window, cx))
3515 })
3516 .unwrap();
3517 (handle, app, view)
3518 });
3519 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
3520 let step = |cx: &mut TestAppContext, run: fn(&mut gpui_kit::Window, &mut gpui_kit::App)| {
3521 cx.update_window(handle, move |_, window, cx| {
3522 run(window, cx);
3523 window.render_frame(cx);
3524 })
3525 .unwrap();
3526 };
3527 step(cx, |window, cx| window.render_frame(cx));
3528 step(cx, |window, cx| window.input("lea", cx));
3529 step(cx, |window, cx| window.press("enter", cx));
3530 step(cx, |window, cx| window.press("enter", cx));
3531 step(cx, |window, cx| window.input("Hello Lea", cx));
3532 step(cx, |window, cx| window.press("enter", cx));
3533 cx.update(|cx| {
3534 let state = app.read(cx);
3535 assert!(!state.new_chat);
3536 assert_eq!(
3537 state.selection,
3538 Some(Selection::Chat("demo-chat-new-1".to_owned()))
3539 );
3540 let chat = state
3541 .sidebar
3542 .chats
3543 .iter()
3544 .find(|chat| chat.id == "demo-chat-new-1")
3545 .expect("new chat in the sidebar");
3546 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello Lea"));
3547 });
3548 }
3549
3550 #[gpui_kit::test]
3551 fn escape_closes_the_draft_and_keeps_the_selection(cx: &mut TestAppContext) {
3552 cx.update(gpui_kit::init);
3553 let store = Arc::new(Store::open_in_memory().unwrap());
3554 crate::demo::seed(&store);
3555 let mode = Mode {
3556 demo: true,
3557 read_only: false,
3558 demo_sync: None,
3559 };
3560 let (handle, app) = cx.update(|cx| {
3561 let app = cx.new(|_| {
3562 let mut state = AppState::new(store, mode);
3563 crate::demo::seed_directory(&mut state);
3564 state.selection = Some(crate::demo::first_selection());
3565 state
3566 });
3567 let shared = app.clone();
3568 let (handle, _) = gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3569 cx.new(|cx| ConversationView::new(shared, window, cx))
3570 })
3571 .unwrap();
3572 (handle, app)
3573 });
3574 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
3575 cx.update_window(handle, |_, window, cx| {
3576 window.render_frame(cx);
3577 window.press("escape", cx);
3578 window.render_frame(cx);
3579 window.press("escape", cx);
3580 window.render_frame(cx);
3581 })
3582 .unwrap();
3583 cx.update(|cx| {
3584 let state = app.read(cx);
3585 assert!(!state.new_chat);
3586 assert_eq!(state.selection, Some(crate::demo::first_selection()));
3587 });
3588 }
3589}