BlueGit

ict rusty-teams

Files

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

conversation.rs

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