BlueGit

ict rusty-teams

Files

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

conversation.rs

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