BlueGit

ict rusty-teams

Files

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

conversation.rs

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