BlueGit

ict rusty-teams

Files

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

conversation.rs

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