BlueGit

ict rusty-teams

Files

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

conversation.rs

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