BlueGit

ict rusty-teams

Files

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

conversation.rs

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