BlueGit

ict rusty-teams

Files

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

conversation.rs

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