BlueGit

ict rusty-teams

Files

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

conversation.rs

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