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