BlueGit

ict rusty-teams

Files

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

conversation.rs

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