BlueGit

ict rusty-teams

Files

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

conversation.rs

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