BlueGit

ict rusty-teams

Files

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

conversation.rs

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