BlueGit

ict rusty-teams

Files

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

conversation.rs

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