BlueGit

ict rusty-teams

Files

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

conversation.rs

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