BlueGit

ict rusty-teams

Files

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

conversation.rs

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