BlueGit

ict rusty-teams

Files

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

conversation.rs

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