BlueGit

ict rusty-teams

Files

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

conversation.rs

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