BlueGit

ict rusty-teams

Files

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

conversation.rs

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