BlueGit

ict rusty-teams

Files

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

conversation.rs

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