BlueGit

ict rusty-teams

Files

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

conversation.rs

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