BlueGit

ict rusty-teams

Files

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

conversation.rs

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