BlueGit

ict rusty-teams

Files

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

conversation.rs

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