BlueGit

ict rusty-teams

Files

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

conversation.rs

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