BlueGit

ict rusty-teams

feat(chat): typing indicator, shown and sent like Teams

- Line above the composer: dots + "Lena is typing" / "A and B are typing" / "A, B, and N others are typing" (Teams wording); 20 px always reserved so the list never jumps
- Chat list preview reads "typing..." (1:1) or "Jonas is typing..." (group) in accent italic
- Remote typers drop on Control/ClearTyping, on their next message, or 22 s after the last signal (Teams userTimeout)
- My typing goes out as Control/Typing at most every 20 s (Teams notificationFrequency), ClearTyping when the draft is emptied or I leave the chat; never in demo or read-only mode
- trouter.js forwards sender id, name and start/clear for typing events

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-08 · 7 weeks ago

Hash
a3649f1dfd4a691d20a21fee8fcc3c22e7da3a45
Parent
11f04c1c
24 files changed +1007 −21
README.md +1 −1
@@ -16,7 +16,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
16 16 - Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
17 17 - Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
18 18 - Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)
19 - Read receipts, presence (last known status shown at start), unread jump
19 - Read receipts, typing indicator (shown and sent), presence (last known status shown at start), unread jump
20 20 - Select and copy message text, `Ctrl+A` in the composer
21 21 - Local full-text search and a `Ctrl+K` switcher, served from the cache
22 22 - Activity bell: feed of new messages, @mentions and reactions to your messages, kept for 14 days
@@ -16,7 +16,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
16- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
16- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
17- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
17- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
18- Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)
18- Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)
19- Read receipts, presence (last known status shown at start), unread jump
19- Read receipts, typing indicator (shown and sent), presence (last known status shown at start), unread jump
20- Select and copy message text, `Ctrl+A` in the composer
20- Select and copy message text, `Ctrl+A` in the composer
21- Local full-text search and a `Ctrl+K` switcher, served from the cache
21- Local full-text search and a `Ctrl+K` switcher, served from the cache
22- Activity bell: feed of new messages, @mentions and reactions to your messages, kept for 14 days
22- Activity bell: feed of new messages, @mentions and reactions to your messages, kept for 14 days
ROADMAP.md +4 −5
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 64 %** (52 done, 4 partial, 29 missing of 85). Partial counts half.
5 **Parity: 65 %** (53 done, 4 partial, 28 missing of 85). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -10,7 +10,7 @@ Feature parity with the Microsoft Teams desktop client.
10 10 |---|---|---|---|---|
11 11 | [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
12 12 | [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13 | [Reading](#reading) | 71 % | 13 | 1 | 5 |
13 | [Reading](#reading) | 76 % | 14 | 1 | 4 |
14 14 | [Writing](#writing) | 75 % | 10 | 1 | 3 |
15 15 | [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16 16 | [Channels](#channels) | 36 % | 2 | 1 | 4 |
@@ -28,8 +28,7 @@ Feature parity with the Microsoft Teams desktop client.
28 28 | 2 | Sign in on Linux without Chrome on a debug port | |
29 29 | 3 | Emoji picker in the composer | Reaction picker exists |
30 30 | 4 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
31 | 5 | Typing indicator | |
32 | 6 | Unsent messages survive a restart | |
31 | 5 | Unsent messages survive a restart | |
33 32
34 33 ## Sign-in and app
35 34
@@ -76,7 +75,7 @@ Feature parity with the Microsoft Teams desktop client.
76 75 | Read receipts | Done | |
77 76 | Select and copy message text | Done | |
78 77 | Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). Input fields work in messages and card dialogs (text, number, date, time, toggle, choice set) with validation. URL task dialogs run in a hosted window on Windows (Teams JS SDK host, see docs/research/card-actions.md), in the browser on Linux. Date and time are plain text fields, no picker |
79 | Typing indicator | Missing | Event arrives, ignored |
78 | Typing indicator | Done | Shows who types in the chat, thread and list preview; sends your own typing |
80 79 | Link previews | Missing | |
81 80 | Loop components | Missing | |
82 81 | Translate a message | Missing | |
@@ -2,7 +2,7 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 64 %** (52 done, 4 partial, 29 missing of 85). Partial counts half.
5**Parity: 65 %** (53 done, 4 partial, 28 missing of 85). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -10,7 +10,7 @@ Feature parity with the Microsoft Teams desktop client.
10|---|---|---|---|---|
10|---|---|---|---|---|
11| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
11| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
12| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
12| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13| [Reading](#reading) | 71 % | 13 | 1 | 5 |
13| [Reading](#reading) | 76 % | 14 | 1 | 4 |
14| [Writing](#writing) | 75 % | 10 | 1 | 3 |
14| [Writing](#writing) | 75 % | 10 | 1 | 3 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16| [Channels](#channels) | 36 % | 2 | 1 | 4 |
16| [Channels](#channels) | 36 % | 2 | 1 | 4 |
@@ -28,8 +28,7 @@ Feature parity with the Microsoft Teams desktop client.
28| 2 | Sign in on Linux without Chrome on a debug port | |
28| 2 | Sign in on Linux without Chrome on a debug port | |
29| 3 | Emoji picker in the composer | Reaction picker exists |
29| 3 | Emoji picker in the composer | Reaction picker exists |
30| 4 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
30| 4 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
31| 5 | Typing indicator | |
31| 5 | Unsent messages survive a restart | |
32| 6 | Unsent messages survive a restart | |
33
32
34## Sign-in and app
33## Sign-in and app
35
34
@@ -76,7 +75,7 @@ Feature parity with the Microsoft Teams desktop client.
76| Read receipts | Done | |
75| Read receipts | Done | |
77| Select and copy message text | Done | |
76| Select and copy message text | Done | |
78| Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). Input fields work in messages and card dialogs (text, number, date, time, toggle, choice set) with validation. URL task dialogs run in a hosted window on Windows (Teams JS SDK host, see docs/research/card-actions.md), in the browser on Linux. Date and time are plain text fields, no picker |
77| Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). Input fields work in messages and card dialogs (text, number, date, time, toggle, choice set) with validation. URL task dialogs run in a hosted window on Windows (Teams JS SDK host, see docs/research/card-actions.md), in the browser on Linux. Date and time are plain text fields, no picker |
79| Typing indicator | Missing | Event arrives, ignored |
78| Typing indicator | Done | Shows who types in the chat, thread and list preview; sends your own typing |
80| Link previews | Missing | |
79| Link previews | Missing | |
81| Loop components | Missing | |
80| Loop components | Missing | |
82| Translate a message | Missing | |
81| Translate a message | Missing | |
crates/app/src/app_state.rs +161 −2
@@ -2,6 +2,7 @@ use std::collections::{HashMap, HashSet};
2 2 use std::sync::Arc;
3 3 use std::time::Instant;
4 4
5 use chatsvc::TypingEvent;
5 6 use chrono::{DateTime, Utc};
6 7 use gpui_kit::*;
7 8 use store::{ChatRecord, Sidebar, Store};
@@ -12,8 +13,10 @@ use crate::card_state::{CardState, TaskDialogState};
12 13 use crate::data::{self, Directory};
13 14 use crate::notice::Notice;
14 15 use crate::notify;
16 use crate::typing::TypingState;
15 17
16 18 const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
19 const RECENT_MESSAGES_FOR_TYPING: usize = 5;
17 20
18 21 #[derive(Debug, Clone, PartialEq, Eq)]
19 22 pub enum Selection {
@@ -39,6 +42,7 @@ pub enum AppEvent {
39 42 Directory,
40 43 Cards(String),
41 44 TaskDialog,
45 Typing,
42 46 }
43 47
44 48 #[derive(Debug, Clone, Copy, Default)]
@@ -71,6 +75,8 @@ pub struct AppState {
71 75 pub notice: Option<Notice>,
72 76 pub notice_count: u64,
73 77 pub keep_unread: Option<String>,
78 pub typing: TypingState,
79 typing_timer_running: bool,
74 80 }
75 81
76 82 pub struct AppHandle(pub Entity<AppState>);
@@ -140,6 +146,8 @@ impl AppState {
140 146 notice: None,
141 147 notice_count: 0,
142 148 keep_unread: None,
149 typing: TypingState::default(),
150 typing_timer_running: false,
143 151 };
144 152 state.collapsed = state.load_collapsed();
145 153 state.followed_channels = notify::load_followed_channels(&state.store);
@@ -443,6 +451,85 @@ impl AppState {
443 451 cx.notify();
444 452 }
445 453
454 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
455 let is_me = self
456 .directory
457 .me
458 .as_ref()
459 .is_some_and(|me| me.user_id == event.user_id);
460 if is_me {
461 return;
462 }
463 if event.active {
464 self.typing.start(
465 &event.conversation_id,
466 &event.user_id,
467 &event.display_name,
468 Instant::now(),
469 event.received_at,
470 );
471 self.schedule_typing_expiry(cx);
472 } else {
473 self.typing.clear(&event.conversation_id, &event.user_id);
474 }
475 cx.emit(AppEvent::Typing);
476 cx.notify();
477 }
478
479 fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
480 if !self.typing.is_active(conversation_id) {
481 return;
482 }
483 let Ok(recent) = self
484 .store
485 .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING)
486 else {
487 return;
488 };
489 let mut changed = false;
490 for message in recent {
491 if let Some(sender_id) = message.sender_id.as_deref() {
492 changed |= self
493 .typing
494 .message_from(conversation_id, sender_id, message.created_at);
495 }
496 }
497 if changed {
498 cx.emit(AppEvent::Typing);
499 cx.notify();
500 }
501 }
502
503 fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) {
504 if self.typing_timer_running {
505 return;
506 }
507 self.typing_timer_running = true;
508 cx.spawn(async move |this, cx| {
509 loop {
510 let next = this.update(cx, |state, _| {
511 let next = state.typing.next_expiry();
512 state.typing_timer_running = next.is_some();
513 next
514 });
515 let Ok(Some(next)) = next else { return };
516 cx.background_executor()
517 .timer(next.saturating_duration_since(Instant::now()))
518 .await;
519 let alive = this.update(cx, |state, cx| {
520 if state.typing.expire(Instant::now()) {
521 cx.emit(AppEvent::Typing);
522 cx.notify();
523 }
524 });
525 if alive.is_err() {
526 return;
527 }
528 }
529 })
530 .detach();
531 }
532
446 533 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
447 534 if let Ok(sidebar) = self.store.sidebar() {
448 535 self.sidebar = sidebar;
@@ -472,6 +559,7 @@ impl AppState {
472 559 CoreEvent::MessagesChanged { conversation_id }
473 560 | CoreEvent::ReceiptsChanged { conversation_id },
474 561 ) => {
562 self.clear_typists_who_sent(&conversation_id, cx);
475 563 cx.emit(AppEvent::Messages(conversation_id));
476 564 }
477 565 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
@@ -502,6 +590,7 @@ impl AppState {
502 590 }
503 591 cx.emit(AppEvent::Directory);
504 592 }
593 BackendEvent::Typing(event) => self.apply_typing(event, cx),
505 594 BackendEvent::Live(live) => {
506 595 self.live = live;
507 596 cx.emit(AppEvent::Status);
@@ -524,9 +613,17 @@ impl AppState {
524 613
525 614 #[cfg(test)]
526 615 mod tests {
527 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
616 use std::sync::Arc;
528 617
529 use super::{Selection, chat_title, selection_title};
618 use chatsvc::TypingEvent;
619 use chrono::{Duration, Utc};
620 use gpui_kit::{AppContext as _, TestAppContext};
621 use store::{ChannelRecord, ChatRecord, MessageRecord, SidebarTeam, Store, TeamRecord};
622 use teams_core::CoreEvent;
623
624 use super::{AppState, Mode, Selection, chat_title, selection_title};
625 use crate::backend::BackendEvent;
626 use crate::data::Person;
530 627 use store::Sidebar;
531 628
532 629 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
@@ -580,4 +677,66 @@ mod tests {
580 677 "First"
581 678 );
582 679 }
680
681 fn typing_event(user_id: &str, active: bool) -> BackendEvent {
682 BackendEvent::Typing(TypingEvent {
683 conversation_id: "c1".into(),
684 user_id: user_id.into(),
685 display_name: format!("Name {user_id}"),
686 active,
687 received_at: Utc::now(),
688 })
689 }
690
691 #[gpui_kit::test]
692 fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) {
693 cx.update(gpui_kit::init);
694 let store = Arc::new(Store::open_in_memory().unwrap());
695 let app = cx.update(|cx| {
696 cx.new(|_| {
697 let mut state = AppState::new(store.clone(), Mode::default());
698 state.directory.me = Some(Person {
699 user_id: "me".into(),
700 display_name: "Me".into(),
701 });
702 state
703 })
704 });
705 let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1"));
706 cx.update(|cx| {
707 app.update(cx, |state, cx| {
708 state.apply(typing_event("me", true), cx);
709 state.apply(typing_event("ada", true), cx);
710 })
711 });
712 assert_eq!(names(cx), vec!["Name ada".to_owned()]);
713
714 let message = MessageRecord {
715 conversation_id: "c1".into(),
716 message_id: "m1".into(),
717 sender_id: Some("ada".into()),
718 created_at: Utc::now() + Duration::seconds(1),
719 ..Default::default()
720 };
721 store.upsert_messages(&[message]).unwrap();
722 cx.update(|cx| {
723 app.update(cx, |state, cx| {
724 state.apply(
725 BackendEvent::Core(CoreEvent::MessagesChanged {
726 conversation_id: "c1".into(),
727 }),
728 cx,
729 )
730 })
731 });
732 assert!(names(cx).is_empty());
733
734 cx.update(|cx| {
735 app.update(cx, |state, cx| {
736 state.apply(typing_event("ada", true), cx);
737 state.apply(typing_event("ada", false), cx);
738 })
739 });
740 assert!(names(cx).is_empty());
741 }
583 742 }
@@ -2,6 +2,7 @@ use std::collections::{HashMap, HashSet};
2use std::sync::Arc;
2use std::sync::Arc;
3use std::time::Instant;
3use std::time::Instant;
4
4
5use chatsvc::TypingEvent;
5use chrono::{DateTime, Utc};
6use chrono::{DateTime, Utc};
6use gpui_kit::*;
7use gpui_kit::*;
7use store::{ChatRecord, Sidebar, Store};
8use store::{ChatRecord, Sidebar, Store};
@@ -12,8 +13,10 @@ use crate::card_state::{CardState, TaskDialogState};
12use crate::data::{self, Directory};
13use crate::data::{self, Directory};
13use crate::notice::Notice;
14use crate::notice::Notice;
14use crate::notify;
15use crate::notify;
16use crate::typing::TypingState;
15
17
16const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
18const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
19const RECENT_MESSAGES_FOR_TYPING: usize = 5;
17
20
18#[derive(Debug, Clone, PartialEq, Eq)]
21#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum Selection {
22pub enum Selection {
@@ -39,6 +42,7 @@ pub enum AppEvent {
39 Directory,
42 Directory,
40 Cards(String),
43 Cards(String),
41 TaskDialog,
44 TaskDialog,
45 Typing,
42}
46}
43
47
44#[derive(Debug, Clone, Copy, Default)]
48#[derive(Debug, Clone, Copy, Default)]
@@ -71,6 +75,8 @@ pub struct AppState {
71 pub notice: Option<Notice>,
75 pub notice: Option<Notice>,
72 pub notice_count: u64,
76 pub notice_count: u64,
73 pub keep_unread: Option<String>,
77 pub keep_unread: Option<String>,
78 pub typing: TypingState,
79 typing_timer_running: bool,
74}
80}
75
81
76pub struct AppHandle(pub Entity<AppState>);
82pub struct AppHandle(pub Entity<AppState>);
@@ -140,6 +146,8 @@ impl AppState {
140 notice: None,
146 notice: None,
141 notice_count: 0,
147 notice_count: 0,
142 keep_unread: None,
148 keep_unread: None,
149 typing: TypingState::default(),
150 typing_timer_running: false,
143 };
151 };
144 state.collapsed = state.load_collapsed();
152 state.collapsed = state.load_collapsed();
145 state.followed_channels = notify::load_followed_channels(&state.store);
153 state.followed_channels = notify::load_followed_channels(&state.store);
@@ -443,6 +451,85 @@ impl AppState {
443 cx.notify();
451 cx.notify();
444 }
452 }
445
453
454 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
455 let is_me = self
456 .directory
457 .me
458 .as_ref()
459 .is_some_and(|me| me.user_id == event.user_id);
460 if is_me {
461 return;
462 }
463 if event.active {
464 self.typing.start(
465 &event.conversation_id,
466 &event.user_id,
467 &event.display_name,
468 Instant::now(),
469 event.received_at,
470 );
471 self.schedule_typing_expiry(cx);
472 } else {
473 self.typing.clear(&event.conversation_id, &event.user_id);
474 }
475 cx.emit(AppEvent::Typing);
476 cx.notify();
477 }
478
479 fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
480 if !self.typing.is_active(conversation_id) {
481 return;
482 }
483 let Ok(recent) = self
484 .store
485 .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING)
486 else {
487 return;
488 };
489 let mut changed = false;
490 for message in recent {
491 if let Some(sender_id) = message.sender_id.as_deref() {
492 changed |= self
493 .typing
494 .message_from(conversation_id, sender_id, message.created_at);
495 }
496 }
497 if changed {
498 cx.emit(AppEvent::Typing);
499 cx.notify();
500 }
501 }
502
503 fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) {
504 if self.typing_timer_running {
505 return;
506 }
507 self.typing_timer_running = true;
508 cx.spawn(async move |this, cx| {
509 loop {
510 let next = this.update(cx, |state, _| {
511 let next = state.typing.next_expiry();
512 state.typing_timer_running = next.is_some();
513 next
514 });
515 let Ok(Some(next)) = next else { return };
516 cx.background_executor()
517 .timer(next.saturating_duration_since(Instant::now()))
518 .await;
519 let alive = this.update(cx, |state, cx| {
520 if state.typing.expire(Instant::now()) {
521 cx.emit(AppEvent::Typing);
522 cx.notify();
523 }
524 });
525 if alive.is_err() {
526 return;
527 }
528 }
529 })
530 .detach();
531 }
532
446 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
533 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
447 if let Ok(sidebar) = self.store.sidebar() {
534 if let Ok(sidebar) = self.store.sidebar() {
448 self.sidebar = sidebar;
535 self.sidebar = sidebar;
@@ -472,6 +559,7 @@ impl AppState {
472 CoreEvent::MessagesChanged { conversation_id }
559 CoreEvent::MessagesChanged { conversation_id }
473 | CoreEvent::ReceiptsChanged { conversation_id },
560 | CoreEvent::ReceiptsChanged { conversation_id },
474 ) => {
561 ) => {
562 self.clear_typists_who_sent(&conversation_id, cx);
475 cx.emit(AppEvent::Messages(conversation_id));
563 cx.emit(AppEvent::Messages(conversation_id));
476 }
564 }
477 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
565 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
@@ -502,6 +590,7 @@ impl AppState {
502 }
590 }
503 cx.emit(AppEvent::Directory);
591 cx.emit(AppEvent::Directory);
504 }
592 }
593 BackendEvent::Typing(event) => self.apply_typing(event, cx),
505 BackendEvent::Live(live) => {
594 BackendEvent::Live(live) => {
506 self.live = live;
595 self.live = live;
507 cx.emit(AppEvent::Status);
596 cx.emit(AppEvent::Status);
@@ -524,9 +613,17 @@ impl AppState {
524
613
525#[cfg(test)]
614#[cfg(test)]
526mod tests {
615mod tests {
527 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
616 use std::sync::Arc;
528
617
529 use super::{Selection, chat_title, selection_title};
618 use chatsvc::TypingEvent;
619 use chrono::{Duration, Utc};
620 use gpui_kit::{AppContext as _, TestAppContext};
621 use store::{ChannelRecord, ChatRecord, MessageRecord, SidebarTeam, Store, TeamRecord};
622 use teams_core::CoreEvent;
623
624 use super::{AppState, Mode, Selection, chat_title, selection_title};
625 use crate::backend::BackendEvent;
626 use crate::data::Person;
530 use store::Sidebar;
627 use store::Sidebar;
531
628
532 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
629 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
@@ -580,4 +677,66 @@ mod tests {
580 "First"
677 "First"
581 );
678 );
582 }
679 }
680
681 fn typing_event(user_id: &str, active: bool) -> BackendEvent {
682 BackendEvent::Typing(TypingEvent {
683 conversation_id: "c1".into(),
684 user_id: user_id.into(),
685 display_name: format!("Name {user_id}"),
686 active,
687 received_at: Utc::now(),
688 })
689 }
690
691 #[gpui_kit::test]
692 fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) {
693 cx.update(gpui_kit::init);
694 let store = Arc::new(Store::open_in_memory().unwrap());
695 let app = cx.update(|cx| {
696 cx.new(|_| {
697 let mut state = AppState::new(store.clone(), Mode::default());
698 state.directory.me = Some(Person {
699 user_id: "me".into(),
700 display_name: "Me".into(),
701 });
702 state
703 })
704 });
705 let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1"));
706 cx.update(|cx| {
707 app.update(cx, |state, cx| {
708 state.apply(typing_event("me", true), cx);
709 state.apply(typing_event("ada", true), cx);
710 })
711 });
712 assert_eq!(names(cx), vec!["Name ada".to_owned()]);
713
714 let message = MessageRecord {
715 conversation_id: "c1".into(),
716 message_id: "m1".into(),
717 sender_id: Some("ada".into()),
718 created_at: Utc::now() + Duration::seconds(1),
719 ..Default::default()
720 };
721 store.upsert_messages(&[message]).unwrap();
722 cx.update(|cx| {
723 app.update(cx, |state, cx| {
724 state.apply(
725 BackendEvent::Core(CoreEvent::MessagesChanged {
726 conversation_id: "c1".into(),
727 }),
728 cx,
729 )
730 })
731 });
732 assert!(names(cx).is_empty());
733
734 cx.update(|cx| {
735 app.update(cx, |state, cx| {
736 state.apply(typing_event("ada", true), cx);
737 state.apply(typing_event("ada", false), cx);
738 })
739 });
740 assert!(names(cx).is_empty());
741 }
583}
742}
crates/app/src/backend.rs +5 −1
@@ -1,7 +1,7 @@
1 1 use std::sync::Arc;
2 2 use std::time::Duration;
3 3
4 use chatsvc::{EventKind, MessageEvent, Pins, Realtime, RealtimeEvent, StatusKind};
4 use chatsvc::{EventKind, MessageEvent, Pins, Realtime, RealtimeEvent, StatusKind, TypingEvent};
5 5 use chrono::{DateTime, Utc};
6 6 use graph::Graph;
7 7 use session::{Session, SessionConfig, Transport};
@@ -46,6 +46,7 @@ pub enum BackendEvent {
46 46 Engine(Arc<Engine>),
47 47 Core(CoreEvent),
48 48 Live(LiveState),
49 Typing(TypingEvent),
49 50 Favorites(Vec<String>),
50 51 Synced(DateTime<Utc>),
51 52 }
@@ -204,6 +205,9 @@ async fn realtime_loop(
204 205 message,
205 206 ));
206 207 }
208 RealtimeEvent::Typing(typing) => {
209 let _ = events.send(BackendEvent::Typing(typing));
210 }
207 211 RealtimeEvent::Status(status) => {
208 212 let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
209 213 let receipt_engine = engine.clone();
@@ -1,7 +1,7 @@
1use std::sync::Arc;
1use std::sync::Arc;
2use std::time::Duration;
2use std::time::Duration;
3
3
4use chatsvc::{EventKind, MessageEvent, Pins, Realtime, RealtimeEvent, StatusKind};
4use chatsvc::{EventKind, MessageEvent, Pins, Realtime, RealtimeEvent, StatusKind, TypingEvent};
5use chrono::{DateTime, Utc};
5use chrono::{DateTime, Utc};
6use graph::Graph;
6use graph::Graph;
7use session::{Session, SessionConfig, Transport};
7use session::{Session, SessionConfig, Transport};
@@ -46,6 +46,7 @@ pub enum BackendEvent {
46 Engine(Arc<Engine>),
46 Engine(Arc<Engine>),
47 Core(CoreEvent),
47 Core(CoreEvent),
48 Live(LiveState),
48 Live(LiveState),
49 Typing(TypingEvent),
49 Favorites(Vec<String>),
50 Favorites(Vec<String>),
50 Synced(DateTime<Utc>),
51 Synced(DateTime<Utc>),
51}
52}
@@ -204,6 +205,9 @@ async fn realtime_loop(
204 message,
205 message,
205 ));
206 ));
206 }
207 }
208 RealtimeEvent::Typing(typing) => {
209 let _ = events.send(BackendEvent::Typing(typing));
210 }
207 RealtimeEvent::Status(status) => {
211 RealtimeEvent::Status(status) => {
208 let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
212 let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
209 let receipt_engine = engine.clone();
213 let receipt_engine = engine.clone();
crates/app/src/chat_actions.rs +1 −0
@@ -195,6 +195,7 @@ impl AppState {
195 195 chats: &self.sidebar.chats,
196 196 directory: &self.directory,
197 197 collapsed: &self.collapsed,
198 typing: &self.typing,
198 199 now: Utc::now(),
199 200 offset: Local::now().offset().fix(),
200 201 };
@@ -195,6 +195,7 @@ impl AppState {
195 chats: &self.sidebar.chats,
195 chats: &self.sidebar.chats,
196 directory: &self.directory,
196 directory: &self.directory,
197 collapsed: &self.collapsed,
197 collapsed: &self.collapsed,
198 typing: &self.typing,
198 now: Utc::now(),
199 now: Utc::now(),
199 offset: Local::now().offset().fix(),
200 offset: Local::now().offset().fix(),
200 };
201 };
crates/app/src/demo.rs +8 −0
@@ -1,5 +1,6 @@
1 1 use std::path::PathBuf;
2 2 use std::sync::Arc;
3 use std::time::Instant;
3 4
4 5 use chrono::{DateTime, Duration, Local, TimeZone, Utc};
5 6 use gpui_kit::Image;
@@ -650,6 +651,13 @@ pub fn seed_directory(state: &mut AppState) {
650 651 state.directory.set_image(STAGING_IMAGE_KEY, &path);
651 652 }
652 653 }
654 state.typing.start(
655 "demo-chat-mara",
656 MARA_ID,
657 "Mara Lindqvist",
658 Instant::now(),
659 Utc::now(),
660 );
653 661 state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
654 662 state.last_sync = Some(Utc::now());
655 663 state.apply_bot_titles();
@@ -1,5 +1,6 @@
1use std::path::PathBuf;
1use std::path::PathBuf;
2use std::sync::Arc;
2use std::sync::Arc;
3use std::time::Instant;
3
4
4use chrono::{DateTime, Duration, Local, TimeZone, Utc};
5use chrono::{DateTime, Duration, Local, TimeZone, Utc};
5use gpui_kit::Image;
6use gpui_kit::Image;
@@ -650,6 +651,13 @@ pub fn seed_directory(state: &mut AppState) {
650 state.directory.set_image(STAGING_IMAGE_KEY, &path);
651 state.directory.set_image(STAGING_IMAGE_KEY, &path);
651 }
652 }
652 }
653 }
654 state.typing.start(
655 "demo-chat-mara",
656 MARA_ID,
657 "Mara Lindqvist",
658 Instant::now(),
659 Utc::now(),
660 );
653 state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
661 state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
654 state.last_sync = Some(Utc::now());
662 state.last_sync = Some(Utc::now());
655 state.apply_bot_titles();
663 state.apply_bot_titles();
crates/app/src/main.rs +1 −0
@@ -31,6 +31,7 @@ mod runtime;
31 31 mod sidebar_model;
32 32 mod task_dialog;
33 33 mod theme;
34 mod typing;
34 35 mod updater;
35 36 mod views;
36 37
@@ -31,6 +31,7 @@ mod runtime;
31mod sidebar_model;
31mod sidebar_model;
32mod task_dialog;
32mod task_dialog;
33mod theme;
33mod theme;
34mod typing;
34mod updater;
35mod updater;
35mod views;
36mod views;
36
37
crates/app/src/sidebar_model.rs +56 −1
@@ -8,6 +8,7 @@ use crate::data::{
8 8 Directory, FolderKind, Person, face_members, is_one_on_one, others, unread_count,
9 9 };
10 10 use crate::format;
11 use crate::typing::{TypingState, preview_label};
11 12
12 13 pub const FAVORITES_FALLBACK_NAME: &str = "Pinned";
13 14 pub const OTHERS_NAME: &str = "Other chats";
@@ -21,6 +22,7 @@ const GROUP_KIND: &str = "group";
21 22 pub enum Preview {
22 23 Empty,
23 24 Deleted,
25 Typing(String),
24 26 Text {
25 27 prefix: Option<String>,
26 28 text: String,
@@ -90,6 +92,7 @@ pub struct SectionInput<'a> {
90 92 pub chats: &'a [ChatRecord],
91 93 pub directory: &'a Directory,
92 94 pub collapsed: &'a HashSet<String>,
95 pub typing: &'a TypingState,
93 96 pub now: DateTime<Utc>,
94 97 pub offset: FixedOffset,
95 98 }
@@ -165,6 +168,12 @@ pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<
165 168 .find_map(|(user_id, _)| user_id)
166 169 })
167 170 .flatten();
171 let typing_names = input.typing.names(&chat.id);
172 let preview = if typing_names.is_empty() {
173 preview_for(chat, me)
174 } else {
175 Preview::Typing(preview_label(&typing_names, is_one_on_one(chat)))
176 };
168 177 ChatItem {
169 178 id: chat.id.clone(),
170 179 title: chat_title(chat),
@@ -178,7 +187,7 @@ pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<
178 187 )
179 188 })
180 189 .unwrap_or_default(),
181 preview: preview_for(chat, me),
190 preview,
182 191 unread,
183 192 muted: chat.muted,
184 193 is_group: chat.kind == GROUP_KIND,
@@ -342,11 +351,24 @@ mod tests {
342 351 chats: &'a [ChatRecord],
343 352 directory: &'a Directory,
344 353 collapsed: &'a HashSet<String>,
354 ) -> SectionInput<'a> {
355 typing_input(chats, directory, collapsed, &NO_TYPING)
356 }
357
358 static NO_TYPING: std::sync::LazyLock<TypingState> =
359 std::sync::LazyLock::new(TypingState::default);
360
361 fn typing_input<'a>(
362 chats: &'a [ChatRecord],
363 directory: &'a Directory,
364 collapsed: &'a HashSet<String>,
365 typing: &'a TypingState,
345 366 ) -> SectionInput<'a> {
346 367 SectionInput {
347 368 chats,
348 369 directory,
349 370 collapsed,
371 typing,
350 372 now: Utc.with_ymd_and_hms(2026, 10, 7, 12, 0, 0).unwrap(),
351 373 offset: FixedOffset::east_opt(0).unwrap(),
352 374 }
@@ -550,6 +572,39 @@ mod tests {
550 572 assert!(matches!(group.avatar, AvatarSpec::Pair(..)));
551 573 }
552 574
575 #[test]
576 fn typing_replaces_the_preview_even_in_muted_chats() {
577 let mut direct = chat("d", "oneOnOne", false);
578 direct.last_message_preview = Some("Earlier".into());
579 direct.muted = true;
580 let group = chat("g", "group", false);
581 let chats = vec![direct, group];
582 let directory = Directory::default();
583 let collapsed = HashSet::new();
584 let now = std::time::Instant::now();
585 let mut typing = TypingState::default();
586 typing.start("d", "ada", "Ada Example", now, Utc::now());
587 typing.start("g", "ada", "Ada Example", now, Utc::now());
588 let context = typing_input(&chats, &directory, &collapsed, &typing);
589 assert_eq!(
590 chat_item(&chats[0], &context, None).preview,
591 Preview::Typing("typing...".into())
592 );
593 assert_eq!(
594 chat_item(&chats[1], &context, None).preview,
595 Preview::Typing("Ada is typing...".into())
596 );
597 typing.clear("d", "ada");
598 let context = typing_input(&chats, &directory, &collapsed, &typing);
599 assert_eq!(
600 chat_item(&chats[0], &context, None).preview,
601 Preview::Text {
602 prefix: None,
603 text: "Earlier".into()
604 }
605 );
606 }
607
553 608 #[test]
554 609 fn time_label_uses_the_list_rules() {
555 610 let chats = vec![chat("a", "group", false)];
@@ -8,6 +8,7 @@ use crate::data::{
8 Directory, FolderKind, Person, face_members, is_one_on_one, others, unread_count,
8 Directory, FolderKind, Person, face_members, is_one_on_one, others, unread_count,
9};
9};
10use crate::format;
10use crate::format;
11use crate::typing::{TypingState, preview_label};
11
12
12pub const FAVORITES_FALLBACK_NAME: &str = "Pinned";
13pub const FAVORITES_FALLBACK_NAME: &str = "Pinned";
13pub const OTHERS_NAME: &str = "Other chats";
14pub const OTHERS_NAME: &str = "Other chats";
@@ -21,6 +22,7 @@ const GROUP_KIND: &str = "group";
21pub enum Preview {
22pub enum Preview {
22 Empty,
23 Empty,
23 Deleted,
24 Deleted,
25 Typing(String),
24 Text {
26 Text {
25 prefix: Option<String>,
27 prefix: Option<String>,
26 text: String,
28 text: String,
@@ -90,6 +92,7 @@ pub struct SectionInput<'a> {
90 pub chats: &'a [ChatRecord],
92 pub chats: &'a [ChatRecord],
91 pub directory: &'a Directory,
93 pub directory: &'a Directory,
92 pub collapsed: &'a HashSet<String>,
94 pub collapsed: &'a HashSet<String>,
95 pub typing: &'a TypingState,
93 pub now: DateTime<Utc>,
96 pub now: DateTime<Utc>,
94 pub offset: FixedOffset,
97 pub offset: FixedOffset,
95}
98}
@@ -165,6 +168,12 @@ pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<
165 .find_map(|(user_id, _)| user_id)
168 .find_map(|(user_id, _)| user_id)
166 })
169 })
167 .flatten();
170 .flatten();
171 let typing_names = input.typing.names(&chat.id);
172 let preview = if typing_names.is_empty() {
173 preview_for(chat, me)
174 } else {
175 Preview::Typing(preview_label(&typing_names, is_one_on_one(chat)))
176 };
168 ChatItem {
177 ChatItem {
169 id: chat.id.clone(),
178 id: chat.id.clone(),
170 title: chat_title(chat),
179 title: chat_title(chat),
@@ -178,7 +187,7 @@ pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<
178 )
187 )
179 })
188 })
180 .unwrap_or_default(),
189 .unwrap_or_default(),
181 preview: preview_for(chat, me),
190 preview,
182 unread,
191 unread,
183 muted: chat.muted,
192 muted: chat.muted,
184 is_group: chat.kind == GROUP_KIND,
193 is_group: chat.kind == GROUP_KIND,
@@ -342,11 +351,24 @@ mod tests {
342 chats: &'a [ChatRecord],
351 chats: &'a [ChatRecord],
343 directory: &'a Directory,
352 directory: &'a Directory,
344 collapsed: &'a HashSet<String>,
353 collapsed: &'a HashSet<String>,
354 ) -> SectionInput<'a> {
355 typing_input(chats, directory, collapsed, &NO_TYPING)
356 }
357
358 static NO_TYPING: std::sync::LazyLock<TypingState> =
359 std::sync::LazyLock::new(TypingState::default);
360
361 fn typing_input<'a>(
362 chats: &'a [ChatRecord],
363 directory: &'a Directory,
364 collapsed: &'a HashSet<String>,
365 typing: &'a TypingState,
345 ) -> SectionInput<'a> {
366 ) -> SectionInput<'a> {
346 SectionInput {
367 SectionInput {
347 chats,
368 chats,
348 directory,
369 directory,
349 collapsed,
370 collapsed,
371 typing,
350 now: Utc.with_ymd_and_hms(2026, 10, 7, 12, 0, 0).unwrap(),
372 now: Utc.with_ymd_and_hms(2026, 10, 7, 12, 0, 0).unwrap(),
351 offset: FixedOffset::east_opt(0).unwrap(),
373 offset: FixedOffset::east_opt(0).unwrap(),
352 }
374 }
@@ -550,6 +572,39 @@ mod tests {
550 assert!(matches!(group.avatar, AvatarSpec::Pair(..)));
572 assert!(matches!(group.avatar, AvatarSpec::Pair(..)));
551 }
573 }
552
574
575 #[test]
576 fn typing_replaces_the_preview_even_in_muted_chats() {
577 let mut direct = chat("d", "oneOnOne", false);
578 direct.last_message_preview = Some("Earlier".into());
579 direct.muted = true;
580 let group = chat("g", "group", false);
581 let chats = vec![direct, group];
582 let directory = Directory::default();
583 let collapsed = HashSet::new();
584 let now = std::time::Instant::now();
585 let mut typing = TypingState::default();
586 typing.start("d", "ada", "Ada Example", now, Utc::now());
587 typing.start("g", "ada", "Ada Example", now, Utc::now());
588 let context = typing_input(&chats, &directory, &collapsed, &typing);
589 assert_eq!(
590 chat_item(&chats[0], &context, None).preview,
591 Preview::Typing("typing...".into())
592 );
593 assert_eq!(
594 chat_item(&chats[1], &context, None).preview,
595 Preview::Typing("Ada is typing...".into())
596 );
597 typing.clear("d", "ada");
598 let context = typing_input(&chats, &directory, &collapsed, &typing);
599 assert_eq!(
600 chat_item(&chats[0], &context, None).preview,
601 Preview::Text {
602 prefix: None,
603 text: "Earlier".into()
604 }
605 );
606 }
607
553 #[test]
608 #[test]
554 fn time_label_uses_the_list_rules() {
609 fn time_label_uses_the_list_rules() {
555 let chats = vec![chat("a", "group", false)];
610 let chats = vec![chat("a", "group", false)];
crates/app/src/typing.rs added +340 −0
@@ -0,0 +1,340 @@
1 use std::collections::HashMap;
2 use std::time::{Duration, Instant};
3
4 use chrono::{DateTime, Utc};
5
6 use crate::format::first_name;
7
8 pub const SEND_INTERVAL: Duration = Duration::from_secs(20);
9 pub const REMOTE_TIMEOUT: Duration = Duration::from_secs(22);
10 const UNKNOWN_NAME: &str = "Someone";
11 const LISTED_FIRST_NAMES: usize = 2;
12
13 #[derive(Debug, Clone, PartialEq, Eq)]
14 struct Typer {
15 user_id: String,
16 name: String,
17 last_seen: Instant,
18 last_seen_at: DateTime<Utc>,
19 }
20
21 #[derive(Debug, Default)]
22 pub struct TypingState {
23 conversations: HashMap<String, Vec<Typer>>,
24 }
25
26 impl TypingState {
27 pub fn start(
28 &mut self,
29 conversation_id: &str,
30 user_id: &str,
31 name: &str,
32 now: Instant,
33 at: DateTime<Utc>,
34 ) {
35 let typers = self
36 .conversations
37 .entry(conversation_id.to_owned())
38 .or_default();
39 match typers.iter_mut().find(|typer| typer.user_id == user_id) {
40 Some(typer) => {
41 typer.last_seen = now;
42 typer.last_seen_at = at;
43 if !name.is_empty() {
44 typer.name = name.to_owned();
45 }
46 }
47 None => typers.push(Typer {
48 user_id: user_id.to_owned(),
49 name: name.to_owned(),
50 last_seen: now,
51 last_seen_at: at,
52 }),
53 }
54 }
55
56 pub fn clear(&mut self, conversation_id: &str, user_id: &str) -> bool {
57 self.remove_where(conversation_id, |typer| typer.user_id == user_id)
58 }
59
60 pub fn message_from(
61 &mut self,
62 conversation_id: &str,
63 user_id: &str,
64 sent_at: DateTime<Utc>,
65 ) -> bool {
66 self.remove_where(conversation_id, |typer| {
67 typer.user_id == user_id && sent_at >= typer.last_seen_at
68 })
69 }
70
71 pub fn expire(&mut self, now: Instant) -> bool {
72 let before = self.conversations.values().map(Vec::len).sum::<usize>();
73 for typers in self.conversations.values_mut() {
74 typers.retain(|typer| now.duration_since(typer.last_seen) < REMOTE_TIMEOUT);
75 }
76 self.conversations.retain(|_, typers| !typers.is_empty());
77 before != self.conversations.values().map(Vec::len).sum::<usize>()
78 }
79
80 pub fn next_expiry(&self) -> Option<Instant> {
81 self.conversations
82 .values()
83 .flatten()
84 .map(|typer| typer.last_seen + REMOTE_TIMEOUT)
85 .min()
86 }
87
88 pub fn names(&self, conversation_id: &str) -> Vec<String> {
89 self.conversations
90 .get(conversation_id)
91 .into_iter()
92 .flatten()
93 .map(|typer| match typer.name.trim() {
94 "" => UNKNOWN_NAME.to_owned(),
95 name => name.to_owned(),
96 })
97 .collect()
98 }
99
100 pub fn is_active(&self, conversation_id: &str) -> bool {
101 self.conversations.contains_key(conversation_id)
102 }
103
104 fn remove_where(&mut self, conversation_id: &str, matches: impl Fn(&Typer) -> bool) -> bool {
105 let Some(typers) = self.conversations.get_mut(conversation_id) else {
106 return false;
107 };
108 let before = typers.len();
109 typers.retain(|typer| !matches(typer));
110 let changed = typers.len() != before;
111 if typers.is_empty() {
112 self.conversations.remove(conversation_id);
113 }
114 changed
115 }
116 }
117
118 pub fn typing_label(names: &[String]) -> String {
119 match names {
120 [] => String::new(),
121 [only] => format!("{only} is typing"),
122 [first, second] => {
123 format!("{first} and {second} are typing")
124 }
125 [first, second, third] => format!(
126 "{}, {}, and {} are typing",
127 first_name(first),
128 first_name(second),
129 first_name(third)
130 ),
131 _ => format!(
132 "{}, {}, and {} others are typing",
133 first_name(&names[0]),
134 first_name(&names[1]),
135 names.len() - LISTED_FIRST_NAMES
136 ),
137 }
138 }
139
140 pub fn preview_label(names: &[String], one_on_one: bool) -> String {
141 match names {
142 [] => String::new(),
143 [_] if one_on_one => "typing...".to_owned(),
144 [only] => format!("{} is typing...", first_name(only)),
145 _ => format!("{} people are typing...", names.len()),
146 }
147 }
148
149 #[derive(Debug, Default)]
150 pub struct OutgoingTyping {
151 sent_at: Option<Instant>,
152 }
153
154 impl OutgoingTyping {
155 /// `Some(true)` asks for a Typing signal, `Some(false)` for a ClearTyping.
156 pub fn on_text(&mut self, has_text: bool, now: Instant) -> Option<bool> {
157 if !has_text {
158 return self.sent_at.take().map(|_| false);
159 }
160 let due = self
161 .sent_at
162 .is_none_or(|sent_at| now.duration_since(sent_at) >= SEND_INTERVAL);
163 due.then(|| {
164 self.sent_at = Some(now);
165 true
166 })
167 }
168
169 pub fn stop(&mut self) -> bool {
170 self.sent_at.take().is_some()
171 }
172
173 pub fn reset(&mut self) {
174 self.sent_at = None;
175 }
176 }
177
178 #[cfg(test)]
179 mod tests {
180 use super::*;
181
182 fn names(list: &[&str]) -> Vec<String> {
183 list.iter().map(|name| (*name).to_owned()).collect()
184 }
185
186 fn at(seconds: i64) -> DateTime<Utc> {
187 DateTime::from_timestamp(1_790_000_000 + seconds, 0).unwrap()
188 }
189
190 #[test]
191 fn label_has_four_forms() {
192 assert_eq!(typing_label(&[]), "");
193 assert_eq!(
194 typing_label(&names(&["Ada Lovelace"])),
195 "Ada Lovelace is typing"
196 );
197 assert_eq!(
198 typing_label(&names(&["Ada Lovelace", "Alan Turing"])),
199 "Ada Lovelace and Alan Turing are typing"
200 );
201 assert_eq!(
202 typing_label(&names(&["Ada Lovelace", "Alan Turing", "Grace Hopper"])),
203 "Ada, Alan, and Grace are typing"
204 );
205 assert_eq!(
206 typing_label(&names(&[
207 "Ada Lovelace",
208 "Alan Turing",
209 "Grace Hopper",
210 "Linus T"
211 ])),
212 "Ada, Alan, and 2 others are typing"
213 );
214 assert_eq!(
215 typing_label(&names(&["A B", "C D", "E F", "G H", "I J"])),
216 "A, C, and 3 others are typing"
217 );
218 }
219
220 #[test]
221 fn preview_label_depends_on_chat_kind_and_count() {
222 assert_eq!(preview_label(&names(&["Ada Lovelace"]), true), "typing...");
223 assert_eq!(
224 preview_label(&names(&["Ada Lovelace"]), false),
225 "Ada is typing..."
226 );
227 assert_eq!(
228 preview_label(&names(&["Ada Lovelace", "Alan Turing"]), false),
229 "2 people are typing..."
230 );
231 assert_eq!(preview_label(&[], false), "");
232 }
233
234 #[test]
235 fn start_refreshes_without_duplicating_and_keeps_order() {
236 let mut state = TypingState::default();
237 let now = Instant::now();
238 state.start("c", "u1", "Ada", now, at(0));
239 state.start("c", "u2", "Alan", now, at(0));
240 state.start("c", "u1", "", now + Duration::from_secs(5), at(5));
241 assert_eq!(state.names("c"), names(&["Ada", "Alan"]));
242 assert!(state.is_active("c"));
243 assert!(!state.is_active("other"));
244 }
245
246 #[test]
247 fn blank_names_read_as_someone() {
248 let mut state = TypingState::default();
249 state.start("c", "u1", " ", Instant::now(), at(0));
250 assert_eq!(state.names("c"), names(&["Someone"]));
251 }
252
253 #[test]
254 fn clear_removes_only_that_user() {
255 let mut state = TypingState::default();
256 let now = Instant::now();
257 state.start("c", "u1", "Ada", now, at(0));
258 state.start("c", "u2", "Alan", now, at(0));
259 assert!(state.clear("c", "u1"));
260 assert!(!state.clear("c", "u1"));
261 assert_eq!(state.names("c"), names(&["Alan"]));
262 assert!(state.clear("c", "u2"));
263 assert!(!state.is_active("c"));
264 }
265
266 #[test]
267 fn a_message_clears_its_sender_only_when_sent_after_the_typing() {
268 let mut state = TypingState::default();
269 let now = Instant::now();
270 state.start("c", "u1", "Ada", now, at(10));
271 assert!(!state.message_from("c", "u1", at(9)));
272 assert!(!state.message_from("c", "u2", at(11)));
273 assert!(!state.message_from("other", "u1", at(11)));
274 assert!(state.message_from("c", "u1", at(11)));
275 assert!(!state.is_active("c"));
276 }
277
278 #[test]
279 fn typers_expire_after_the_timeout_and_a_refresh_extends_it() {
280 let mut state = TypingState::default();
281 let start = Instant::now();
282 state.start("c", "u1", "Ada", start, at(0));
283 state.start("c", "u2", "Alan", start + Duration::from_secs(10), at(10));
284 assert_eq!(state.next_expiry(), Some(start + REMOTE_TIMEOUT));
285 assert!(!state.expire(start + REMOTE_TIMEOUT - Duration::from_millis(1)));
286 assert!(state.expire(start + REMOTE_TIMEOUT));
287 assert_eq!(state.names("c"), names(&["Alan"]));
288 assert_eq!(
289 state.next_expiry(),
290 Some(start + Duration::from_secs(10) + REMOTE_TIMEOUT)
291 );
292 assert!(state.expire(start + Duration::from_secs(32)));
293 assert_eq!(state.next_expiry(), None);
294 assert!(!state.expire(start + Duration::from_secs(100)));
295 }
296
297 #[test]
298 fn outgoing_sends_at_most_every_twenty_seconds_while_typing() {
299 let mut outgoing = OutgoingTyping::default();
300 let start = Instant::now();
301 assert_eq!(outgoing.on_text(true, start), Some(true));
302 assert_eq!(
303 outgoing.on_text(true, start + Duration::from_secs(19)),
304 None
305 );
306 assert_eq!(
307 outgoing.on_text(true, start + Duration::from_secs(20)),
308 Some(true)
309 );
310 }
311
312 #[test]
313 fn outgoing_clears_once_when_the_text_empties() {
314 let mut outgoing = OutgoingTyping::default();
315 let start = Instant::now();
316 assert_eq!(outgoing.on_text(false, start), None);
317 outgoing.on_text(true, start);
318 assert_eq!(outgoing.on_text(false, start), Some(false));
319 assert_eq!(outgoing.on_text(false, start), None);
320 assert_eq!(outgoing.on_text(true, start), Some(true));
321 }
322
323 #[test]
324 fn outgoing_stop_reports_only_after_a_typing_was_sent() {
325 let mut outgoing = OutgoingTyping::default();
326 assert!(!outgoing.stop());
327 outgoing.on_text(true, Instant::now());
328 assert!(outgoing.stop());
329 assert!(!outgoing.stop());
330 }
331
332 #[test]
333 fn outgoing_reset_forgets_without_a_clear() {
334 let mut outgoing = OutgoingTyping::default();
335 let start = Instant::now();
336 outgoing.on_text(true, start);
337 outgoing.reset();
338 assert_eq!(outgoing.on_text(false, start), None);
339 }
340 }
@@ -0,0 +1,340 @@
1use std::collections::HashMap;
2use std::time::{Duration, Instant};
3
4use chrono::{DateTime, Utc};
5
6use crate::format::first_name;
7
8pub const SEND_INTERVAL: Duration = Duration::from_secs(20);
9pub const REMOTE_TIMEOUT: Duration = Duration::from_secs(22);
10const UNKNOWN_NAME: &str = "Someone";
11const LISTED_FIRST_NAMES: usize = 2;
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14struct Typer {
15 user_id: String,
16 name: String,
17 last_seen: Instant,
18 last_seen_at: DateTime<Utc>,
19}
20
21#[derive(Debug, Default)]
22pub struct TypingState {
23 conversations: HashMap<String, Vec<Typer>>,
24}
25
26impl TypingState {
27 pub fn start(
28 &mut self,
29 conversation_id: &str,
30 user_id: &str,
31 name: &str,
32 now: Instant,
33 at: DateTime<Utc>,
34 ) {
35 let typers = self
36 .conversations
37 .entry(conversation_id.to_owned())
38 .or_default();
39 match typers.iter_mut().find(|typer| typer.user_id == user_id) {
40 Some(typer) => {
41 typer.last_seen = now;
42 typer.last_seen_at = at;
43 if !name.is_empty() {
44 typer.name = name.to_owned();
45 }
46 }
47 None => typers.push(Typer {
48 user_id: user_id.to_owned(),
49 name: name.to_owned(),
50 last_seen: now,
51 last_seen_at: at,
52 }),
53 }
54 }
55
56 pub fn clear(&mut self, conversation_id: &str, user_id: &str) -> bool {
57 self.remove_where(conversation_id, |typer| typer.user_id == user_id)
58 }
59
60 pub fn message_from(
61 &mut self,
62 conversation_id: &str,
63 user_id: &str,
64 sent_at: DateTime<Utc>,
65 ) -> bool {
66 self.remove_where(conversation_id, |typer| {
67 typer.user_id == user_id && sent_at >= typer.last_seen_at
68 })
69 }
70
71 pub fn expire(&mut self, now: Instant) -> bool {
72 let before = self.conversations.values().map(Vec::len).sum::<usize>();
73 for typers in self.conversations.values_mut() {
74 typers.retain(|typer| now.duration_since(typer.last_seen) < REMOTE_TIMEOUT);
75 }
76 self.conversations.retain(|_, typers| !typers.is_empty());
77 before != self.conversations.values().map(Vec::len).sum::<usize>()
78 }
79
80 pub fn next_expiry(&self) -> Option<Instant> {
81 self.conversations
82 .values()
83 .flatten()
84 .map(|typer| typer.last_seen + REMOTE_TIMEOUT)
85 .min()
86 }
87
88 pub fn names(&self, conversation_id: &str) -> Vec<String> {
89 self.conversations
90 .get(conversation_id)
91 .into_iter()
92 .flatten()
93 .map(|typer| match typer.name.trim() {
94 "" => UNKNOWN_NAME.to_owned(),
95 name => name.to_owned(),
96 })
97 .collect()
98 }
99
100 pub fn is_active(&self, conversation_id: &str) -> bool {
101 self.conversations.contains_key(conversation_id)
102 }
103
104 fn remove_where(&mut self, conversation_id: &str, matches: impl Fn(&Typer) -> bool) -> bool {
105 let Some(typers) = self.conversations.get_mut(conversation_id) else {
106 return false;
107 };
108 let before = typers.len();
109 typers.retain(|typer| !matches(typer));
110 let changed = typers.len() != before;
111 if typers.is_empty() {
112 self.conversations.remove(conversation_id);
113 }
114 changed
115 }
116}
117
118pub fn typing_label(names: &[String]) -> String {
119 match names {
120 [] => String::new(),
121 [only] => format!("{only} is typing"),
122 [first, second] => {
123 format!("{first} and {second} are typing")
124 }
125 [first, second, third] => format!(
126 "{}, {}, and {} are typing",
127 first_name(first),
128 first_name(second),
129 first_name(third)
130 ),
131 _ => format!(
132 "{}, {}, and {} others are typing",
133 first_name(&names[0]),
134 first_name(&names[1]),
135 names.len() - LISTED_FIRST_NAMES
136 ),
137 }
138}
139
140pub fn preview_label(names: &[String], one_on_one: bool) -> String {
141 match names {
142 [] => String::new(),
143 [_] if one_on_one => "typing...".to_owned(),
144 [only] => format!("{} is typing...", first_name(only)),
145 _ => format!("{} people are typing...", names.len()),
146 }
147}
148
149#[derive(Debug, Default)]
150pub struct OutgoingTyping {
151 sent_at: Option<Instant>,
152}
153
154impl OutgoingTyping {
155 /// `Some(true)` asks for a Typing signal, `Some(false)` for a ClearTyping.
156 pub fn on_text(&mut self, has_text: bool, now: Instant) -> Option<bool> {
157 if !has_text {
158 return self.sent_at.take().map(|_| false);
159 }
160 let due = self
161 .sent_at
162 .is_none_or(|sent_at| now.duration_since(sent_at) >= SEND_INTERVAL);
163 due.then(|| {
164 self.sent_at = Some(now);
165 true
166 })
167 }
168
169 pub fn stop(&mut self) -> bool {
170 self.sent_at.take().is_some()
171 }
172
173 pub fn reset(&mut self) {
174 self.sent_at = None;
175 }
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181
182 fn names(list: &[&str]) -> Vec<String> {
183 list.iter().map(|name| (*name).to_owned()).collect()
184 }
185
186 fn at(seconds: i64) -> DateTime<Utc> {
187 DateTime::from_timestamp(1_790_000_000 + seconds, 0).unwrap()
188 }
189
190 #[test]
191 fn label_has_four_forms() {
192 assert_eq!(typing_label(&[]), "");
193 assert_eq!(
194 typing_label(&names(&["Ada Lovelace"])),
195 "Ada Lovelace is typing"
196 );
197 assert_eq!(
198 typing_label(&names(&["Ada Lovelace", "Alan Turing"])),
199 "Ada Lovelace and Alan Turing are typing"
200 );
201 assert_eq!(
202 typing_label(&names(&["Ada Lovelace", "Alan Turing", "Grace Hopper"])),
203 "Ada, Alan, and Grace are typing"
204 );
205 assert_eq!(
206 typing_label(&names(&[
207 "Ada Lovelace",
208 "Alan Turing",
209 "Grace Hopper",
210 "Linus T"
211 ])),
212 "Ada, Alan, and 2 others are typing"
213 );
214 assert_eq!(
215 typing_label(&names(&["A B", "C D", "E F", "G H", "I J"])),
216 "A, C, and 3 others are typing"
217 );
218 }
219
220 #[test]
221 fn preview_label_depends_on_chat_kind_and_count() {
222 assert_eq!(preview_label(&names(&["Ada Lovelace"]), true), "typing...");
223 assert_eq!(
224 preview_label(&names(&["Ada Lovelace"]), false),
225 "Ada is typing..."
226 );
227 assert_eq!(
228 preview_label(&names(&["Ada Lovelace", "Alan Turing"]), false),
229 "2 people are typing..."
230 );
231 assert_eq!(preview_label(&[], false), "");
232 }
233
234 #[test]
235 fn start_refreshes_without_duplicating_and_keeps_order() {
236 let mut state = TypingState::default();
237 let now = Instant::now();
238 state.start("c", "u1", "Ada", now, at(0));
239 state.start("c", "u2", "Alan", now, at(0));
240 state.start("c", "u1", "", now + Duration::from_secs(5), at(5));
241 assert_eq!(state.names("c"), names(&["Ada", "Alan"]));
242 assert!(state.is_active("c"));
243 assert!(!state.is_active("other"));
244 }
245
246 #[test]
247 fn blank_names_read_as_someone() {
248 let mut state = TypingState::default();
249 state.start("c", "u1", " ", Instant::now(), at(0));
250 assert_eq!(state.names("c"), names(&["Someone"]));
251 }
252
253 #[test]
254 fn clear_removes_only_that_user() {
255 let mut state = TypingState::default();
256 let now = Instant::now();
257 state.start("c", "u1", "Ada", now, at(0));
258 state.start("c", "u2", "Alan", now, at(0));
259 assert!(state.clear("c", "u1"));
260 assert!(!state.clear("c", "u1"));
261 assert_eq!(state.names("c"), names(&["Alan"]));
262 assert!(state.clear("c", "u2"));
263 assert!(!state.is_active("c"));
264 }
265
266 #[test]
267 fn a_message_clears_its_sender_only_when_sent_after_the_typing() {
268 let mut state = TypingState::default();
269 let now = Instant::now();
270 state.start("c", "u1", "Ada", now, at(10));
271 assert!(!state.message_from("c", "u1", at(9)));
272 assert!(!state.message_from("c", "u2", at(11)));
273 assert!(!state.message_from("other", "u1", at(11)));
274 assert!(state.message_from("c", "u1", at(11)));
275 assert!(!state.is_active("c"));
276 }
277
278 #[test]
279 fn typers_expire_after_the_timeout_and_a_refresh_extends_it() {
280 let mut state = TypingState::default();
281 let start = Instant::now();
282 state.start("c", "u1", "Ada", start, at(0));
283 state.start("c", "u2", "Alan", start + Duration::from_secs(10), at(10));
284 assert_eq!(state.next_expiry(), Some(start + REMOTE_TIMEOUT));
285 assert!(!state.expire(start + REMOTE_TIMEOUT - Duration::from_millis(1)));
286 assert!(state.expire(start + REMOTE_TIMEOUT));
287 assert_eq!(state.names("c"), names(&["Alan"]));
288 assert_eq!(
289 state.next_expiry(),
290 Some(start + Duration::from_secs(10) + REMOTE_TIMEOUT)
291 );
292 assert!(state.expire(start + Duration::from_secs(32)));
293 assert_eq!(state.next_expiry(), None);
294 assert!(!state.expire(start + Duration::from_secs(100)));
295 }
296
297 #[test]
298 fn outgoing_sends_at_most_every_twenty_seconds_while_typing() {
299 let mut outgoing = OutgoingTyping::default();
300 let start = Instant::now();
301 assert_eq!(outgoing.on_text(true, start), Some(true));
302 assert_eq!(
303 outgoing.on_text(true, start + Duration::from_secs(19)),
304 None
305 );
306 assert_eq!(
307 outgoing.on_text(true, start + Duration::from_secs(20)),
308 Some(true)
309 );
310 }
311
312 #[test]
313 fn outgoing_clears_once_when_the_text_empties() {
314 let mut outgoing = OutgoingTyping::default();
315 let start = Instant::now();
316 assert_eq!(outgoing.on_text(false, start), None);
317 outgoing.on_text(true, start);
318 assert_eq!(outgoing.on_text(false, start), Some(false));
319 assert_eq!(outgoing.on_text(false, start), None);
320 assert_eq!(outgoing.on_text(true, start), Some(true));
321 }
322
323 #[test]
324 fn outgoing_stop_reports_only_after_a_typing_was_sent() {
325 let mut outgoing = OutgoingTyping::default();
326 assert!(!outgoing.stop());
327 outgoing.on_text(true, Instant::now());
328 assert!(outgoing.stop());
329 assert!(!outgoing.stop());
330 }
331
332 #[test]
333 fn outgoing_reset_forgets_without_a_clear() {
334 let mut outgoing = OutgoingTyping::default();
335 let start = Instant::now();
336 outgoing.on_text(true, start);
337 outgoing.reset();
338 assert_eq!(outgoing.on_text(false, start), None);
339 }
340}
crates/app/src/views/composer.rs +20 −1
@@ -4,7 +4,7 @@ use std::ops::Range;
4 4 use std::path::PathBuf;
5 5 use std::rc::Rc;
6 6 use std::sync::Arc;
7 use std::time::Duration;
7 use std::time::{Duration, Instant};
8 8
9 9 use gpui_kit::assets::IconName;
10 10 use gpui_kit::component::{
@@ -39,6 +39,7 @@ use crate::app_state::AppState;
39 39 use crate::emoji;
40 40 use crate::runtime;
41 41 use crate::theme;
42 use crate::typing::OutgoingTyping;
42 43
43 44 const MIN_ROWS: usize = 1;
44 45 const MAX_ROWS: usize = 8;
@@ -184,6 +185,7 @@ impl UploadHandle {
184 185 pub enum ComposerEvent {
185 186 Submit(Box<Outgoing>),
186 187 EditLast,
188 Typing(bool),
187 189 }
188 190
189 191 struct MentionPopup {
@@ -244,6 +246,7 @@ pub struct Composer {
244 246 conversion: Option<Conversion>,
245 247 undone_value: Option<String>,
246 248 previous_value: String,
249 typing: OutgoingTyping,
247 250 draft: Draft,
248 251 decorations: DraftDecorations,
249 252 pending_style: Option<TypingStyle>,
@@ -421,6 +424,7 @@ impl Composer {
421 424 conversion: None,
422 425 undone_value: None,
423 426 previous_value: String::new(),
427 typing: OutgoingTyping::default(),
424 428 draft: Draft::default(),
425 429 decorations,
426 430 pending_style: None,
@@ -503,9 +507,23 @@ impl Composer {
503 507 self.lookup = None;
504 508 }
505 509
510 fn report_typing(&mut self, has_text: bool, cx: &mut Context<Self>) {
511 if self.editing.is_some() {
512 return;
513 }
514 if let Some(active) = self.typing.on_text(has_text, Instant::now()) {
515 cx.emit(ComposerEvent::Typing(active));
516 }
517 }
518
519 pub fn stop_typing(&mut self) -> bool {
520 self.typing.stop()
521 }
522
506 523 fn on_change(&mut self, window: &mut Window, cx: &mut Context<Self>) {
507 524 let state = self.input.read(cx);
508 525 let (value, input_cursor) = (state.value().to_string(), state.cursor());
526 self.report_typing(!value.trim().is_empty(), cx);
509 527 let previous = std::mem::replace(&mut self.previous_value, value.clone());
510 528 if previous != value {
511 529 let (start, old_end, new_end) = changed_span(&previous, &value);
@@ -1838,6 +1856,7 @@ impl Composer {
1838 1856 let Some(outgoing) = self.outgoing(cx) else {
1839 1857 return;
1840 1858 };
1859 self.typing.reset();
1841 1860 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
1842 1861 self.mention_inputs.clear();
1843 1862 if self.editing.is_none() {
@@ -4,7 +4,7 @@ use std::ops::Range;
4use std::path::PathBuf;
4use std::path::PathBuf;
5use std::rc::Rc;
5use std::rc::Rc;
6use std::sync::Arc;
6use std::sync::Arc;
7use std::time::Duration;
7use std::time::{Duration, Instant};
8
8
9use gpui_kit::assets::IconName;
9use gpui_kit::assets::IconName;
10use gpui_kit::component::{
10use gpui_kit::component::{
@@ -39,6 +39,7 @@ use crate::app_state::AppState;
39use crate::emoji;
39use crate::emoji;
40use crate::runtime;
40use crate::runtime;
41use crate::theme;
41use crate::theme;
42use crate::typing::OutgoingTyping;
42
43
43const MIN_ROWS: usize = 1;
44const MIN_ROWS: usize = 1;
44const MAX_ROWS: usize = 8;
45const MAX_ROWS: usize = 8;
@@ -184,6 +185,7 @@ impl UploadHandle {
184pub enum ComposerEvent {
185pub enum ComposerEvent {
185 Submit(Box<Outgoing>),
186 Submit(Box<Outgoing>),
186 EditLast,
187 EditLast,
188 Typing(bool),
187}
189}
188
190
189struct MentionPopup {
191struct MentionPopup {
@@ -244,6 +246,7 @@ pub struct Composer {
244 conversion: Option<Conversion>,
246 conversion: Option<Conversion>,
245 undone_value: Option<String>,
247 undone_value: Option<String>,
246 previous_value: String,
248 previous_value: String,
249 typing: OutgoingTyping,
247 draft: Draft,
250 draft: Draft,
248 decorations: DraftDecorations,
251 decorations: DraftDecorations,
249 pending_style: Option<TypingStyle>,
252 pending_style: Option<TypingStyle>,
@@ -421,6 +424,7 @@ impl Composer {
421 conversion: None,
424 conversion: None,
422 undone_value: None,
425 undone_value: None,
423 previous_value: String::new(),
426 previous_value: String::new(),
427 typing: OutgoingTyping::default(),
424 draft: Draft::default(),
428 draft: Draft::default(),
425 decorations,
429 decorations,
426 pending_style: None,
430 pending_style: None,
@@ -503,9 +507,23 @@ impl Composer {
503 self.lookup = None;
507 self.lookup = None;
504 }
508 }
505
509
510 fn report_typing(&mut self, has_text: bool, cx: &mut Context<Self>) {
511 if self.editing.is_some() {
512 return;
513 }
514 if let Some(active) = self.typing.on_text(has_text, Instant::now()) {
515 cx.emit(ComposerEvent::Typing(active));
516 }
517 }
518
519 pub fn stop_typing(&mut self) -> bool {
520 self.typing.stop()
521 }
522
506 fn on_change(&mut self, window: &mut Window, cx: &mut Context<Self>) {
523 fn on_change(&mut self, window: &mut Window, cx: &mut Context<Self>) {
507 let state = self.input.read(cx);
524 let state = self.input.read(cx);
508 let (value, input_cursor) = (state.value().to_string(), state.cursor());
525 let (value, input_cursor) = (state.value().to_string(), state.cursor());
526 self.report_typing(!value.trim().is_empty(), cx);
509 let previous = std::mem::replace(&mut self.previous_value, value.clone());
527 let previous = std::mem::replace(&mut self.previous_value, value.clone());
510 if previous != value {
528 if previous != value {
511 let (start, old_end, new_end) = changed_span(&previous, &value);
529 let (start, old_end, new_end) = changed_span(&previous, &value);
@@ -1838,6 +1856,7 @@ impl Composer {
1838 let Some(outgoing) = self.outgoing(cx) else {
1856 let Some(outgoing) = self.outgoing(cx) else {
1839 return;
1857 return;
1840 };
1858 };
1859 self.typing.reset();
1841 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
1860 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
1842 self.mention_inputs.clear();
1861 self.mention_inputs.clear();
1843 if self.editing.is_none() {
1862 if self.editing.is_none() {
crates/app/src/views/conversation.rs +108 −1
@@ -18,11 +18,11 @@ use gpui_kit::*;
18 18 use store::MessageRecord;
19 19 use teams_core::{FileCard, ImageRef};
20 20
21 use super::adaptive_card::ensure_cards_inputs;
21 22 use super::attachments::FileActions;
22 23 use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
23 24 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
24 25 use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
25 use super::adaptive_card::ensure_cards_inputs;
26 26 use super::message_row::{RowActions, render_message_row, render_skeleton_row};
27 27 use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
28 28 use super::reaction_picker::{PickHandler, ReactionPicker};
@@ -47,6 +47,7 @@ use crate::rows::{
47 47 use crate::runtime;
48 48 use crate::sidebar_model::{AvatarSpec, Face};
49 49 use crate::theme;
50 use crate::typing::typing_label;
50 51
51 52 const CHAT_OPEN_LIMIT: usize = 60;
52 53 const CHANNEL_OPEN_LIMIT: usize = 300;
@@ -64,6 +65,10 @@ const SLOW_AFTER: Duration = Duration::from_secs(8);
64 65 const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500);
65 66 const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400);
66 67 const PROGRESS_BAR_WIDTH: f32 = 0.35;
68 const TYPING_LINE_HEIGHT: f32 = 20.;
69 const TYPING_DOT_SIZE: f32 = 5.;
70 const TYPING_DOT_COUNT: usize = 3;
71 const TYPING_PULSE_PERIOD: Duration = Duration::from_millis(1200);
67 72
68 73 actions!(teams, [ReplyToHovered]);
69 74
@@ -454,6 +459,7 @@ impl ConversationView {
454 459 cx.notify();
455 460 }
456 461 AppEvent::TaskDialog => {}
462 AppEvent::Typing => cx.notify(),
457 463 AppEvent::Sidebar => {
458 464 self.mark_read(ReadTrigger::Incoming, cx);
459 465 self.refresh_reactor_names(cx);
@@ -490,10 +496,86 @@ impl ConversationView {
490 496 }
491 497 ComposerEvent::Submit(outgoing) => self.send((**outgoing).clone(), window, cx),
492 498 ComposerEvent::EditLast => self.edit_last_own(window, cx),
499 ComposerEvent::Typing(active) => self.send_typing(*active, cx),
500 }
501 }
502
503 fn typing_target(&self) -> Option<(String, Option<String>)> {
504 let current = self.current.as_ref().filter(|_| !self.draft_active)?;
505 let thread_root_id = match &current.mode {
506 ViewMode::Thread(root_id) => Some(root_id.clone()),
507 ViewMode::Flat | ViewMode::ThreadList => None,
508 };
509 Some((
510 current.selection.conversation_id().to_owned(),
511 thread_root_id,
512 ))
513 }
514
515 fn send_typing(&self, active: bool, cx: &App) {
516 let state = self.app.read(cx);
517 if state.mode.demo || state.mode.read_only {
518 return;
519 }
520 let (Some(engine), Some((conversation_id, thread_root_id))) =
521 (state.engine.clone(), self.typing_target())
522 else {
523 return;
524 };
525 drop(runtime::spawn(async move {
526 let sent = engine
527 .send_typing(&conversation_id, thread_root_id.as_deref(), active)
528 .await;
529 if let Err(error) = sent
530 && cfg!(debug_assertions)
531 {
532 eprintln!("typing indicator not sent: {error}");
533 }
534 }));
535 }
536
537 fn stop_typing(&mut self, cx: &mut Context<Self>) {
538 if self
539 .composer
540 .update(cx, |composer, _| composer.stop_typing())
541 {
542 self.send_typing(false, cx);
493 543 }
494 544 }
495 545
546 fn render_typing_line(&self, cx: &App) -> impl IntoElement {
547 let names = self
548 .current
549 .as_ref()
550 .filter(|_| !self.draft_active)
551 .map(|current| {
552 self.app
553 .read(cx)
554 .typing
555 .names(current.selection.conversation_id())
556 })
557 .unwrap_or_default();
558 h_flex()
559 .h(px(TYPING_LINE_HEIGHT))
560 .flex_none()
561 .px(px(24.))
562 .gap(px(6.))
563 .items_center()
564 .text_size(px(12.))
565 .text_color(theme::text_muted())
566 .when(!names.is_empty(), |line| {
567 line.child(typing_dots()).child(
568 div()
569 .flex_1()
570 .min_w_0()
571 .truncate()
572 .child(typing_label(&names)),
573 )
574 })
575 }
576
496 577 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
578 self.stop_typing(cx);
497 579 self.toolbar_hovered = None;
498 580 self.toolbar_pinned = None;
499 581 self.toolbar_suppressed = None;
@@ -545,6 +627,7 @@ impl ConversationView {
545 627
546 628 fn enter_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
547 629 if !self.draft_active {
630 self.stop_typing(cx);
548 631 self.draft_active = true;
549 632 self.current = None;
550 633 self.clear_pending();
@@ -1517,6 +1600,7 @@ impl ConversationView {
1517 1600 }
1518 1601
1519 1602 fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
1603 self.stop_typing(cx);
1520 1604 if let Some(current) = self.current.as_mut() {
1521 1605 current.mode = ViewMode::Thread(root_id);
1522 1606 }
@@ -1525,6 +1609,7 @@ impl ConversationView {
1525 1609 }
1526 1610
1527 1611 fn back_to_threads(&mut self, cx: &mut Context<Self>) {
1612 self.stop_typing(cx);
1528 1613 if let Some(current) = self.current.as_mut() {
1529 1614 current.mode = ViewMode::ThreadList;
1530 1615 }
@@ -2852,6 +2937,7 @@ impl Render for ConversationView {
2852 2937 .child(body),
2853 2938 )
2854 2939 .children(self.render_draft_error(cx))
2940 .child(self.render_typing_line(cx))
2855 2941 .child(self.composer.clone())
2856 2942 .child(self.render_drop_overlay(cx)),
2857 2943 )
@@ -2872,6 +2958,27 @@ impl Render for ConversationView {
2872 2958 }
2873 2959 }
2874 2960
2961 fn typing_dots() -> impl IntoElement {
2962 h_flex()
2963 .gap(px(3.))
2964 .flex_none()
2965 .children((0..TYPING_DOT_COUNT).map(|index| {
2966 let phase_offset = index as f32 / TYPING_DOT_COUNT as f32;
2967 div()
2968 .size(px(TYPING_DOT_SIZE))
2969 .rounded_full()
2970 .bg(theme::text_muted())
2971 .with_animation(
2972 ElementId::NamedInteger("typing-dot".into(), index as u64),
2973 Animation::new(TYPING_PULSE_PERIOD).repeat(),
2974 move |dot, delta| {
2975 let wave = 1. - ((delta - phase_offset).rem_euclid(1.) * 2. - 1.).abs();
2976 dot.opacity(0.3 + 0.7 * wave)
2977 },
2978 )
2979 }))
2980 }
2981
2875 2982 fn progress_bar() -> impl IntoElement {
2876 2983 div()
2877 2984 .absolute()
@@ -18,11 +18,11 @@ use gpui_kit::*;
18use store::MessageRecord;
18use store::MessageRecord;
19use teams_core::{FileCard, ImageRef};
19use teams_core::{FileCard, ImageRef};
20
20
21use super::adaptive_card::ensure_cards_inputs;
21use super::attachments::FileActions;
22use super::attachments::FileActions;
22use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
23use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
23use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
24use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
24use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
25use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
25use super::adaptive_card::ensure_cards_inputs;
26use super::message_row::{RowActions, render_message_row, render_skeleton_row};
26use super::message_row::{RowActions, render_message_row, render_skeleton_row};
27use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
27use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
28use super::reaction_picker::{PickHandler, ReactionPicker};
28use super::reaction_picker::{PickHandler, ReactionPicker};
@@ -47,6 +47,7 @@ use crate::rows::{
47use crate::runtime;
47use crate::runtime;
48use crate::sidebar_model::{AvatarSpec, Face};
48use crate::sidebar_model::{AvatarSpec, Face};
49use crate::theme;
49use crate::theme;
50use crate::typing::typing_label;
50
51
51const CHAT_OPEN_LIMIT: usize = 60;
52const CHAT_OPEN_LIMIT: usize = 60;
52const CHANNEL_OPEN_LIMIT: usize = 300;
53const CHANNEL_OPEN_LIMIT: usize = 300;
@@ -64,6 +65,10 @@ const SLOW_AFTER: Duration = Duration::from_secs(8);
64const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500);
65const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500);
65const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400);
66const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400);
66const PROGRESS_BAR_WIDTH: f32 = 0.35;
67const PROGRESS_BAR_WIDTH: f32 = 0.35;
68const TYPING_LINE_HEIGHT: f32 = 20.;
69const TYPING_DOT_SIZE: f32 = 5.;
70const TYPING_DOT_COUNT: usize = 3;
71const TYPING_PULSE_PERIOD: Duration = Duration::from_millis(1200);
67
72
68actions!(teams, [ReplyToHovered]);
73actions!(teams, [ReplyToHovered]);
69
74
@@ -454,6 +459,7 @@ impl ConversationView {
454 cx.notify();
459 cx.notify();
455 }
460 }
456 AppEvent::TaskDialog => {}
461 AppEvent::TaskDialog => {}
462 AppEvent::Typing => cx.notify(),
457 AppEvent::Sidebar => {
463 AppEvent::Sidebar => {
458 self.mark_read(ReadTrigger::Incoming, cx);
464 self.mark_read(ReadTrigger::Incoming, cx);
459 self.refresh_reactor_names(cx);
465 self.refresh_reactor_names(cx);
@@ -490,10 +496,86 @@ impl ConversationView {
490 }
496 }
491 ComposerEvent::Submit(outgoing) => self.send((**outgoing).clone(), window, cx),
497 ComposerEvent::Submit(outgoing) => self.send((**outgoing).clone(), window, cx),
492 ComposerEvent::EditLast => self.edit_last_own(window, cx),
498 ComposerEvent::EditLast => self.edit_last_own(window, cx),
499 ComposerEvent::Typing(active) => self.send_typing(*active, cx),
500 }
501 }
502
503 fn typing_target(&self) -> Option<(String, Option<String>)> {
504 let current = self.current.as_ref().filter(|_| !self.draft_active)?;
505 let thread_root_id = match &current.mode {
506 ViewMode::Thread(root_id) => Some(root_id.clone()),
507 ViewMode::Flat | ViewMode::ThreadList => None,
508 };
509 Some((
510 current.selection.conversation_id().to_owned(),
511 thread_root_id,
512 ))
513 }
514
515 fn send_typing(&self, active: bool, cx: &App) {
516 let state = self.app.read(cx);
517 if state.mode.demo || state.mode.read_only {
518 return;
519 }
520 let (Some(engine), Some((conversation_id, thread_root_id))) =
521 (state.engine.clone(), self.typing_target())
522 else {
523 return;
524 };
525 drop(runtime::spawn(async move {
526 let sent = engine
527 .send_typing(&conversation_id, thread_root_id.as_deref(), active)
528 .await;
529 if let Err(error) = sent
530 && cfg!(debug_assertions)
531 {
532 eprintln!("typing indicator not sent: {error}");
533 }
534 }));
535 }
536
537 fn stop_typing(&mut self, cx: &mut Context<Self>) {
538 if self
539 .composer
540 .update(cx, |composer, _| composer.stop_typing())
541 {
542 self.send_typing(false, cx);
493 }
543 }
494 }
544 }
495
545
546 fn render_typing_line(&self, cx: &App) -> impl IntoElement {
547 let names = self
548 .current
549 .as_ref()
550 .filter(|_| !self.draft_active)
551 .map(|current| {
552 self.app
553 .read(cx)
554 .typing
555 .names(current.selection.conversation_id())
556 })
557 .unwrap_or_default();
558 h_flex()
559 .h(px(TYPING_LINE_HEIGHT))
560 .flex_none()
561 .px(px(24.))
562 .gap(px(6.))
563 .items_center()
564 .text_size(px(12.))
565 .text_color(theme::text_muted())
566 .when(!names.is_empty(), |line| {
567 line.child(typing_dots()).child(
568 div()
569 .flex_1()
570 .min_w_0()
571 .truncate()
572 .child(typing_label(&names)),
573 )
574 })
575 }
576
496 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
577 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
578 self.stop_typing(cx);
497 self.toolbar_hovered = None;
579 self.toolbar_hovered = None;
498 self.toolbar_pinned = None;
580 self.toolbar_pinned = None;
499 self.toolbar_suppressed = None;
581 self.toolbar_suppressed = None;
@@ -545,6 +627,7 @@ impl ConversationView {
545
627
546 fn enter_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
628 fn enter_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
547 if !self.draft_active {
629 if !self.draft_active {
630 self.stop_typing(cx);
548 self.draft_active = true;
631 self.draft_active = true;
549 self.current = None;
632 self.current = None;
550 self.clear_pending();
633 self.clear_pending();
@@ -1517,6 +1600,7 @@ impl ConversationView {
1517 }
1600 }
1518
1601
1519 fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
1602 fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
1603 self.stop_typing(cx);
1520 if let Some(current) = self.current.as_mut() {
1604 if let Some(current) = self.current.as_mut() {
1521 current.mode = ViewMode::Thread(root_id);
1605 current.mode = ViewMode::Thread(root_id);
1522 }
1606 }
@@ -1525,6 +1609,7 @@ impl ConversationView {
1525 }
1609 }
1526
1610
1527 fn back_to_threads(&mut self, cx: &mut Context<Self>) {
1611 fn back_to_threads(&mut self, cx: &mut Context<Self>) {
1612 self.stop_typing(cx);
1528 if let Some(current) = self.current.as_mut() {
1613 if let Some(current) = self.current.as_mut() {
1529 current.mode = ViewMode::ThreadList;
1614 current.mode = ViewMode::ThreadList;
1530 }
1615 }
@@ -2852,6 +2937,7 @@ impl Render for ConversationView {
2852 .child(body),
2937 .child(body),
2853 )
2938 )
2854 .children(self.render_draft_error(cx))
2939 .children(self.render_draft_error(cx))
2940 .child(self.render_typing_line(cx))
2855 .child(self.composer.clone())
2941 .child(self.composer.clone())
2856 .child(self.render_drop_overlay(cx)),
2942 .child(self.render_drop_overlay(cx)),
2857 )
2943 )
@@ -2872,6 +2958,27 @@ impl Render for ConversationView {
2872 }
2958 }
2873}
2959}
2874
2960
2961fn typing_dots() -> impl IntoElement {
2962 h_flex()
2963 .gap(px(3.))
2964 .flex_none()
2965 .children((0..TYPING_DOT_COUNT).map(|index| {
2966 let phase_offset = index as f32 / TYPING_DOT_COUNT as f32;
2967 div()
2968 .size(px(TYPING_DOT_SIZE))
2969 .rounded_full()
2970 .bg(theme::text_muted())
2971 .with_animation(
2972 ElementId::NamedInteger("typing-dot".into(), index as u64),
2973 Animation::new(TYPING_PULSE_PERIOD).repeat(),
2974 move |dot, delta| {
2975 let wave = 1. - ((delta - phase_offset).rem_euclid(1.) * 2. - 1.).abs();
2976 dot.opacity(0.3 + 0.7 * wave)
2977 },
2978 )
2979 }))
2980}
2981
2875fn progress_bar() -> impl IntoElement {
2982fn progress_bar() -> impl IntoElement {
2876 div()
2983 div()
2877 .absolute()
2984 .absolute()
crates/app/src/views/sidebar.rs +6 −2
@@ -268,6 +268,7 @@ fn preview_text(preview: &Preview) -> Option<(String, bool)> {
268 268 match preview {
269 269 Preview::Empty => None,
270 270 Preview::Deleted => Some((DELETED_PREVIEW.to_owned(), true)),
271 Preview::Typing(text) => Some((text.clone(), true)),
271 272 Preview::Text {
272 273 prefix: Some(prefix),
273 274 text,
@@ -292,7 +293,7 @@ impl SidebarView {
292 293 }
293 294 if matches!(
294 295 event,
295 AppEvent::Sidebar | AppEvent::Selection | AppEvent::Directory
296 AppEvent::Sidebar | AppEvent::Selection | AppEvent::Directory | AppEvent::Typing
296 297 ) {
297 298 cx.notify();
298 299 }
@@ -560,7 +561,9 @@ impl SidebarView {
560 561 ))
561 562 })
562 563 .child(item.time_label.clone());
563 let preview_color = if item.muted {
564 let preview_color = if matches!(item.preview, Preview::Typing(_)) {
565 theme::accent_text()
566 } else if item.muted {
564 567 theme::text_faint()
565 568 } else if unread {
566 569 theme::text_strong()
@@ -653,6 +656,7 @@ impl SidebarView {
653 656 chats: &state.sidebar.chats,
654 657 directory: &state.directory,
655 658 collapsed: &state.collapsed,
659 typing: &state.typing,
656 660 now,
657 661 offset,
658 662 };
@@ -268,6 +268,7 @@ fn preview_text(preview: &Preview) -> Option<(String, bool)> {
268 match preview {
268 match preview {
269 Preview::Empty => None,
269 Preview::Empty => None,
270 Preview::Deleted => Some((DELETED_PREVIEW.to_owned(), true)),
270 Preview::Deleted => Some((DELETED_PREVIEW.to_owned(), true)),
271 Preview::Typing(text) => Some((text.clone(), true)),
271 Preview::Text {
272 Preview::Text {
272 prefix: Some(prefix),
273 prefix: Some(prefix),
273 text,
274 text,
@@ -292,7 +293,7 @@ impl SidebarView {
292 }
293 }
293 if matches!(
294 if matches!(
294 event,
295 event,
295 AppEvent::Sidebar | AppEvent::Selection | AppEvent::Directory
296 AppEvent::Sidebar | AppEvent::Selection | AppEvent::Directory | AppEvent::Typing
296 ) {
297 ) {
297 cx.notify();
298 cx.notify();
298 }
299 }
@@ -560,7 +561,9 @@ impl SidebarView {
560 ))
561 ))
561 })
562 })
562 .child(item.time_label.clone());
563 .child(item.time_label.clone());
563 let preview_color = if item.muted {
564 let preview_color = if matches!(item.preview, Preview::Typing(_)) {
565 theme::accent_text()
566 } else if item.muted {
564 theme::text_faint()
567 theme::text_faint()
565 } else if unread {
568 } else if unread {
566 theme::text_strong()
569 theme::text_strong()
@@ -653,6 +656,7 @@ impl SidebarView {
653 chats: &state.sidebar.chats,
656 chats: &state.sidebar.chats,
654 directory: &state.directory,
657 directory: &state.directory,
655 collapsed: &state.collapsed,
658 collapsed: &state.collapsed,
659 typing: &state.typing,
656 now,
660 now,
657 offset,
661 offset,
658 };
662 };
crates/chatsvc/assets/trouter.js +12 −1
@@ -1,5 +1,5 @@
1 1 (() => {
2 const VERSION = 2;
2 const VERSION = 3;
3 3 const GLOBAL_NAME = '__chatsvcTrouter';
4 4 const BINDING_NAME = '__chatsvcRealtime';
5 5 const EPID_KEY = '__chatsvcEpid';
@@ -13,6 +13,7 @@
13 13 const MAX_QUEUE = 200;
14 14 const MAX_PRESENCE_ENTRIES = 1000;
15 15 const MAX_PRESENCE_FIELD = 128;
16 const MAX_SENDER_NAME = 256;
16 17
17 18 if (window.top !== window || !location.origin.startsWith('https://teams.')) return;
18 19 const existing = window[GLOBAL_NAME];
@@ -69,6 +70,15 @@
69 70 if (resourceType === 'ThreadUpdate') return 'thread_update';
70 71 return 'other';
71 72 };
73 const typingDetails = (resource) => {
74 const sender = /\/contacts\/8:orgid:([0-9a-f-]{1,64})\/?$/i.exec(String((resource && resource.from) || ''));
75 const name = resource && resource.imdisplayname;
76 return {
77 typing: /^Control\/ClearTyping/.test(String((resource && resource.messagetype) || '')) ? 'clear' : 'start',
78 senderId: sender ? sender[1] : null,
79 senderName: typeof name === 'string' ? name.slice(0, MAX_SENDER_NAME) : null,
80 };
81 };
72 82 const forwardNotification = (path, body) => {
73 83 const receivedAt = Date.now();
74 84 if (path === 'unifiedPresenceService') {
@@ -88,6 +98,7 @@
88 98 channel: 'event', resourceType, eventKind, receivedAt,
89 99 conversationId: resource ? conversationOf(resource) || null : null,
90 100 messageId: messageLike && resource.id ? String(resource.id) : null,
101 ...(eventKind === 'typing' ? typingDetails(resource) : {}),
91 102 });
92 103 };
93 104
@@ -1,5 +1,5 @@
1(() => {
1(() => {
2 const VERSION = 2;
2 const VERSION = 3;
3 const GLOBAL_NAME = '__chatsvcTrouter';
3 const GLOBAL_NAME = '__chatsvcTrouter';
4 const BINDING_NAME = '__chatsvcRealtime';
4 const BINDING_NAME = '__chatsvcRealtime';
5 const EPID_KEY = '__chatsvcEpid';
5 const EPID_KEY = '__chatsvcEpid';
@@ -13,6 +13,7 @@
13 const MAX_QUEUE = 200;
13 const MAX_QUEUE = 200;
14 const MAX_PRESENCE_ENTRIES = 1000;
14 const MAX_PRESENCE_ENTRIES = 1000;
15 const MAX_PRESENCE_FIELD = 128;
15 const MAX_PRESENCE_FIELD = 128;
16 const MAX_SENDER_NAME = 256;
16
17
17 if (window.top !== window || !location.origin.startsWith('https://teams.')) return;
18 if (window.top !== window || !location.origin.startsWith('https://teams.')) return;
18 const existing = window[GLOBAL_NAME];
19 const existing = window[GLOBAL_NAME];
@@ -69,6 +70,15 @@
69 if (resourceType === 'ThreadUpdate') return 'thread_update';
70 if (resourceType === 'ThreadUpdate') return 'thread_update';
70 return 'other';
71 return 'other';
71 };
72 };
73 const typingDetails = (resource) => {
74 const sender = /\/contacts\/8:orgid:([0-9a-f-]{1,64})\/?$/i.exec(String((resource && resource.from) || ''));
75 const name = resource && resource.imdisplayname;
76 return {
77 typing: /^Control\/ClearTyping/.test(String((resource && resource.messagetype) || '')) ? 'clear' : 'start',
78 senderId: sender ? sender[1] : null,
79 senderName: typeof name === 'string' ? name.slice(0, MAX_SENDER_NAME) : null,
80 };
81 };
72 const forwardNotification = (path, body) => {
82 const forwardNotification = (path, body) => {
73 const receivedAt = Date.now();
83 const receivedAt = Date.now();
74 if (path === 'unifiedPresenceService') {
84 if (path === 'unifiedPresenceService') {
@@ -88,6 +98,7 @@
88 channel: 'event', resourceType, eventKind, receivedAt,
98 channel: 'event', resourceType, eventKind, receivedAt,
89 conversationId: resource ? conversationOf(resource) || null : null,
99 conversationId: resource ? conversationOf(resource) || null : null,
90 messageId: messageLike && resource.id ? String(resource.id) : null,
100 messageId: messageLike && resource.id ? String(resource.id) : null,
101 ...(eventKind === 'typing' ? typingDetails(resource) : {}),
91 });
102 });
92 };
103 };
93
104
crates/chatsvc/examples/live.rs +9 −0
@@ -45,6 +45,15 @@ fn describe(event: &RealtimeEvent) -> String {
45 45 .map(mask_conversation_id)
46 46 .unwrap_or_else(|| "-".into()),
47 47 ),
48 RealtimeEvent::Typing(typing) => format!(
49 "{} typing {} conv={}",
50 typing
51 .received_at
52 .with_timezone(&Local)
53 .format("%H:%M:%S%.3f"),
54 if typing.active { "start" } else { "clear" },
55 mask_conversation_id(&typing.conversation_id),
56 ),
48 57 RealtimeEvent::Status(status) => format!("# status {:?} {}", status.kind, status.detail),
49 58 RealtimeEvent::Presence(updates) => format!("# presence updates={}", updates.len()),
50 59 RealtimeEvent::Endpoint(endpoint) => format!(
@@ -45,6 +45,15 @@ fn describe(event: &RealtimeEvent) -> String {
45 .map(mask_conversation_id)
45 .map(mask_conversation_id)
46 .unwrap_or_else(|| "-".into()),
46 .unwrap_or_else(|| "-".into()),
47 ),
47 ),
48 RealtimeEvent::Typing(typing) => format!(
49 "{} typing {} conv={}",
50 typing
51 .received_at
52 .with_timezone(&Local)
53 .format("%H:%M:%S%.3f"),
54 if typing.active { "start" } else { "clear" },
55 mask_conversation_id(&typing.conversation_id),
56 ),
48 RealtimeEvent::Status(status) => format!("# status {:?} {}", status.kind, status.detail),
57 RealtimeEvent::Status(status) => format!("# status {:?} {}", status.kind, status.detail),
49 RealtimeEvent::Presence(updates) => format!("# presence updates={}", updates.len()),
58 RealtimeEvent::Presence(updates) => format!("# presence updates={}", updates.len()),
50 RealtimeEvent::Endpoint(endpoint) => format!(
59 RealtimeEvent::Endpoint(endpoint) => format!(
crates/chatsvc/src/lib.rs +1 −1
@@ -21,6 +21,6 @@ pub use pins::{
21 21 pub use reactions::{emotion_key, emotion_keys};
22 22 pub use realtime::{
23 23 EventKind, MessageEvent, PresenceUpdate, Realtime, RealtimeConfig, RealtimeEvent, StatusEvent,
24 StatusKind, TrouterEndpoint,
24 StatusKind, TrouterEndpoint, TypingEvent,
25 25 };
26 26 pub use receipts::{MemberHorizon, Receipts};
@@ -21,6 +21,6 @@ pub use pins::{
21pub use reactions::{emotion_key, emotion_keys};
21pub use reactions::{emotion_key, emotion_keys};
22pub use realtime::{
22pub use realtime::{
23 EventKind, MessageEvent, PresenceUpdate, Realtime, RealtimeConfig, RealtimeEvent, StatusEvent,
23 EventKind, MessageEvent, PresenceUpdate, Realtime, RealtimeConfig, RealtimeEvent, StatusEvent,
24 StatusKind, TrouterEndpoint,
24 StatusKind, TrouterEndpoint, TypingEvent,
25};
25};
26pub use receipts::{MemberHorizon, Receipts};
26pub use receipts::{MemberHorizon, Receipts};
crates/chatsvc/src/messages.rs +21 −0
@@ -208,6 +208,19 @@ impl<T: MessageTransport> Messages<T> {
208 208 }
209 209 }
210 210
211 pub async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
212 let url = format!(
213 "{}/{}/messages",
214 self.base_url,
215 encode(&conversation.conversation_id())
216 );
217 let answer = self
218 .transport
219 .send(Request::with_body(Method::Post, &url, typing_body(active)))
220 .await?;
221 ensure_success(&answer)
222 }
223
211 224 fn emotions_url(&self, conversation: &ConversationRef, message_id: &str) -> String {
212 225 format!(
213 226 "{}/properties?name=emotions",
@@ -247,6 +260,14 @@ fn edit_body(message_id: &str, html: &str) -> Value {
247 260 })
248 261 }
249 262
263 fn typing_body(active: bool) -> Value {
264 json!({
265 "content": "",
266 "messagetype": if active { "Control/Typing" } else { "Control/ClearTyping" },
267 "contenttype": "Application/Message",
268 })
269 }
270
250 271 pub(crate) fn ensure_success(answer: &ApiResponse) -> Result<()> {
251 272 if answer.is_success() {
252 273 Ok(())
@@ -208,6 +208,19 @@ impl<T: MessageTransport> Messages<T> {
208 }
208 }
209 }
209 }
210
210
211 pub async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
212 let url = format!(
213 "{}/{}/messages",
214 self.base_url,
215 encode(&conversation.conversation_id())
216 );
217 let answer = self
218 .transport
219 .send(Request::with_body(Method::Post, &url, typing_body(active)))
220 .await?;
221 ensure_success(&answer)
222 }
223
211 fn emotions_url(&self, conversation: &ConversationRef, message_id: &str) -> String {
224 fn emotions_url(&self, conversation: &ConversationRef, message_id: &str) -> String {
212 format!(
225 format!(
213 "{}/properties?name=emotions",
226 "{}/properties?name=emotions",
@@ -247,6 +260,14 @@ fn edit_body(message_id: &str, html: &str) -> Value {
247 })
260 })
248}
261}
249
262
263fn typing_body(active: bool) -> Value {
264 json!({
265 "content": "",
266 "messagetype": if active { "Control/Typing" } else { "Control/ClearTyping" },
267 "contenttype": "Application/Message",
268 })
269}
270
250pub(crate) fn ensure_success(answer: &ApiResponse) -> Result<()> {
271pub(crate) fn ensure_success(answer: &ApiResponse) -> Result<()> {
251 if answer.is_success() {
272 if answer.is_success() {
252 Ok(())
273 Ok(())
crates/chatsvc/src/realtime/event.rs +131 −3
@@ -31,6 +31,15 @@ pub struct MessageEvent {
31 31 pub received_at: DateTime<Utc>,
32 32 }
33 33
34 #[derive(Debug, Clone, PartialEq, Eq)]
35 pub struct TypingEvent {
36 pub conversation_id: String,
37 pub user_id: String,
38 pub display_name: String,
39 pub active: bool,
40 pub received_at: DateTime<Utc>,
41 }
42
34 43 #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
35 44 #[serde(rename_all = "snake_case")]
36 45 pub enum StatusKind {
@@ -62,6 +71,7 @@ pub struct TrouterEndpoint {
62 71 #[derive(Debug, Clone, PartialEq, Eq)]
63 72 pub enum RealtimeEvent {
64 73 Message(MessageEvent),
74 Typing(TypingEvent),
65 75 Status(StatusEvent),
66 76 Presence(Vec<PresenceUpdate>),
67 77 Endpoint(TrouterEndpoint),
@@ -89,6 +99,12 @@ enum Wire {
89 99 message_id: Option<String>,
90 100 #[serde(rename = "receivedAt")]
91 101 received_at: i64,
102 #[serde(default)]
103 typing: Option<String>,
104 #[serde(rename = "senderId", default)]
105 sender_id: Option<String>,
106 #[serde(rename = "senderName", default)]
107 sender_name: Option<String>,
92 108 },
93 109 Status {
94 110 kind: StatusKind,
@@ -116,15 +132,30 @@ pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> {
116 132 conversation_id,
117 133 message_id,
118 134 received_at,
135 typing,
136 sender_id,
137 sender_name,
119 138 } => {
120 139 let received_at = DateTime::from_timestamp_millis(received_at)
121 140 .ok_or_else(|| Error::Decode("receivedAt out of range".into()))?;
141 let conversation_id = conversation_id
142 .map(bounded)
143 .filter(|value| !value.is_empty());
144 if event_kind == EventKind::Typing
145 && let Some(event) = typing_event(
146 conversation_id.clone(),
147 typing.as_deref(),
148 sender_id,
149 sender_name,
150 received_at,
151 )
152 {
153 return Ok(RealtimeEvent::Typing(event));
154 }
122 155 Ok(RealtimeEvent::Message(MessageEvent {
123 156 resource_type: bounded(resource_type),
124 157 kind: event_kind,
125 conversation_id: conversation_id
126 .map(bounded)
127 .filter(|value| !value.is_empty()),
158 conversation_id,
128 159 message_id: message_id.map(bounded).filter(|value| !value.is_empty()),
129 160 received_at,
130 161 }))
@@ -169,6 +200,31 @@ pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> {
169 200 }
170 201 }
171 202
203 fn typing_event(
204 conversation_id: Option<String>,
205 signal: Option<&str>,
206 sender_id: Option<String>,
207 sender_name: Option<String>,
208 received_at: DateTime<Utc>,
209 ) -> Option<TypingEvent> {
210 let active = match signal? {
211 "start" => true,
212 "clear" => false,
213 _ => return None,
214 };
215 let user_id = bounded(sender_id?);
216 if user_id.is_empty() {
217 return None;
218 }
219 Some(TypingEvent {
220 conversation_id: conversation_id?,
221 user_id,
222 display_name: bounded(sender_name.unwrap_or_default()),
223 active,
224 received_at,
225 })
226 }
227
172 228 fn without_port(authority: &str) -> &str {
173 229 match authority.rsplit_once(':') {
174 230 Some((host, port))
@@ -223,6 +279,78 @@ mod tests {
223 279 assert_eq!(event.kind, EventKind::Other);
224 280 }
225 281
282 fn typing_payload(extra: &str) -> String {
283 format!(
284 r#"{{"channel":"event","resourceType":"NewMessage","eventKind":"typing",
285 "conversationId":"19:abc@thread.v2","messageId":null,"receivedAt":5{extra}}}"#
286 )
287 }
288
289 #[test]
290 fn decodes_typing_start_and_clear() {
291 for (signal, active) in [("start", true), ("clear", false)] {
292 let payload = typing_payload(&format!(
293 r#","typing":"{signal}","senderId":"abc-1","senderName":"Ada Lovelace""#
294 ));
295 assert_eq!(
296 decode_payload(&payload).unwrap(),
297 RealtimeEvent::Typing(TypingEvent {
298 conversation_id: "19:abc@thread.v2".into(),
299 user_id: "abc-1".into(),
300 display_name: "Ada Lovelace".into(),
301 active,
302 received_at: DateTime::from_timestamp_millis(5).unwrap(),
303 })
304 );
305 }
306 }
307
308 #[test]
309 fn typing_without_a_name_keeps_an_empty_name_and_cuts_long_ones() {
310 let RealtimeEvent::Typing(event) =
311 decode_payload(&typing_payload(r#","typing":"start","senderId":"a""#)).unwrap()
312 else {
313 panic!("expected typing")
314 };
315 assert_eq!(event.display_name, "");
316 let long = typing_payload(&format!(
317 r#","typing":"start","senderId":"a","senderName":"{}""#,
318 "n".repeat(1000)
319 ));
320 let RealtimeEvent::Typing(event) = decode_payload(&long).unwrap() else {
321 panic!("expected typing")
322 };
323 assert_eq!(event.display_name.chars().count(), MAX_FIELD_LENGTH);
324 }
325
326 #[test]
327 fn typing_without_a_valid_sender_or_signal_stays_a_plain_message() {
328 for extra in [
329 "",
330 r#","typing":"start""#,
331 r#","typing":"start","senderId":null"#,
332 r##","typing":"start","senderId":"""##,
333 r#","typing":"bogus","senderId":"a""#,
334 r#","senderId":"a""#,
335 ] {
336 let RealtimeEvent::Message(event) = decode_payload(&typing_payload(extra)).unwrap()
337 else {
338 panic!("expected message for {extra}")
339 };
340 assert_eq!(event.kind, EventKind::Typing);
341 }
342 }
343
344 #[test]
345 fn typing_without_a_conversation_stays_a_plain_message() {
346 let payload = r#"{"channel":"event","resourceType":"NewMessage","eventKind":"typing",
347 "conversationId":null,"receivedAt":5,"typing":"start","senderId":"a"}"#;
348 assert!(matches!(
349 decode_payload(payload).unwrap(),
350 RealtimeEvent::Message(_)
351 ));
352 }
353
226 354 #[test]
227 355 fn decodes_every_status_kind() {
228 356 for (name, kind) in [
@@ -31,6 +31,15 @@ pub struct MessageEvent {
31 pub received_at: DateTime<Utc>,
31 pub received_at: DateTime<Utc>,
32}
32}
33
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct TypingEvent {
36 pub conversation_id: String,
37 pub user_id: String,
38 pub display_name: String,
39 pub active: bool,
40 pub received_at: DateTime<Utc>,
41}
42
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
35#[serde(rename_all = "snake_case")]
44#[serde(rename_all = "snake_case")]
36pub enum StatusKind {
45pub enum StatusKind {
@@ -62,6 +71,7 @@ pub struct TrouterEndpoint {
62#[derive(Debug, Clone, PartialEq, Eq)]
71#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum RealtimeEvent {
72pub enum RealtimeEvent {
64 Message(MessageEvent),
73 Message(MessageEvent),
74 Typing(TypingEvent),
65 Status(StatusEvent),
75 Status(StatusEvent),
66 Presence(Vec<PresenceUpdate>),
76 Presence(Vec<PresenceUpdate>),
67 Endpoint(TrouterEndpoint),
77 Endpoint(TrouterEndpoint),
@@ -89,6 +99,12 @@ enum Wire {
89 message_id: Option<String>,
99 message_id: Option<String>,
90 #[serde(rename = "receivedAt")]
100 #[serde(rename = "receivedAt")]
91 received_at: i64,
101 received_at: i64,
102 #[serde(default)]
103 typing: Option<String>,
104 #[serde(rename = "senderId", default)]
105 sender_id: Option<String>,
106 #[serde(rename = "senderName", default)]
107 sender_name: Option<String>,
92 },
108 },
93 Status {
109 Status {
94 kind: StatusKind,
110 kind: StatusKind,
@@ -116,15 +132,30 @@ pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> {
116 conversation_id,
132 conversation_id,
117 message_id,
133 message_id,
118 received_at,
134 received_at,
135 typing,
136 sender_id,
137 sender_name,
119 } => {
138 } => {
120 let received_at = DateTime::from_timestamp_millis(received_at)
139 let received_at = DateTime::from_timestamp_millis(received_at)
121 .ok_or_else(|| Error::Decode("receivedAt out of range".into()))?;
140 .ok_or_else(|| Error::Decode("receivedAt out of range".into()))?;
141 let conversation_id = conversation_id
142 .map(bounded)
143 .filter(|value| !value.is_empty());
144 if event_kind == EventKind::Typing
145 && let Some(event) = typing_event(
146 conversation_id.clone(),
147 typing.as_deref(),
148 sender_id,
149 sender_name,
150 received_at,
151 )
152 {
153 return Ok(RealtimeEvent::Typing(event));
154 }
122 Ok(RealtimeEvent::Message(MessageEvent {
155 Ok(RealtimeEvent::Message(MessageEvent {
123 resource_type: bounded(resource_type),
156 resource_type: bounded(resource_type),
124 kind: event_kind,
157 kind: event_kind,
125 conversation_id: conversation_id
158 conversation_id,
126 .map(bounded)
127 .filter(|value| !value.is_empty()),
128 message_id: message_id.map(bounded).filter(|value| !value.is_empty()),
159 message_id: message_id.map(bounded).filter(|value| !value.is_empty()),
129 received_at,
160 received_at,
130 }))
161 }))
@@ -169,6 +200,31 @@ pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> {
169 }
200 }
170}
201}
171
202
203fn typing_event(
204 conversation_id: Option<String>,
205 signal: Option<&str>,
206 sender_id: Option<String>,
207 sender_name: Option<String>,
208 received_at: DateTime<Utc>,
209) -> Option<TypingEvent> {
210 let active = match signal? {
211 "start" => true,
212 "clear" => false,
213 _ => return None,
214 };
215 let user_id = bounded(sender_id?);
216 if user_id.is_empty() {
217 return None;
218 }
219 Some(TypingEvent {
220 conversation_id: conversation_id?,
221 user_id,
222 display_name: bounded(sender_name.unwrap_or_default()),
223 active,
224 received_at,
225 })
226}
227
172fn without_port(authority: &str) -> &str {
228fn without_port(authority: &str) -> &str {
173 match authority.rsplit_once(':') {
229 match authority.rsplit_once(':') {
174 Some((host, port))
230 Some((host, port))
@@ -223,6 +279,78 @@ mod tests {
223 assert_eq!(event.kind, EventKind::Other);
279 assert_eq!(event.kind, EventKind::Other);
224 }
280 }
225
281
282 fn typing_payload(extra: &str) -> String {
283 format!(
284 r#"{{"channel":"event","resourceType":"NewMessage","eventKind":"typing",
285 "conversationId":"19:abc@thread.v2","messageId":null,"receivedAt":5{extra}}}"#
286 )
287 }
288
289 #[test]
290 fn decodes_typing_start_and_clear() {
291 for (signal, active) in [("start", true), ("clear", false)] {
292 let payload = typing_payload(&format!(
293 r#","typing":"{signal}","senderId":"abc-1","senderName":"Ada Lovelace""#
294 ));
295 assert_eq!(
296 decode_payload(&payload).unwrap(),
297 RealtimeEvent::Typing(TypingEvent {
298 conversation_id: "19:abc@thread.v2".into(),
299 user_id: "abc-1".into(),
300 display_name: "Ada Lovelace".into(),
301 active,
302 received_at: DateTime::from_timestamp_millis(5).unwrap(),
303 })
304 );
305 }
306 }
307
308 #[test]
309 fn typing_without_a_name_keeps_an_empty_name_and_cuts_long_ones() {
310 let RealtimeEvent::Typing(event) =
311 decode_payload(&typing_payload(r#","typing":"start","senderId":"a""#)).unwrap()
312 else {
313 panic!("expected typing")
314 };
315 assert_eq!(event.display_name, "");
316 let long = typing_payload(&format!(
317 r#","typing":"start","senderId":"a","senderName":"{}""#,
318 "n".repeat(1000)
319 ));
320 let RealtimeEvent::Typing(event) = decode_payload(&long).unwrap() else {
321 panic!("expected typing")
322 };
323 assert_eq!(event.display_name.chars().count(), MAX_FIELD_LENGTH);
324 }
325
326 #[test]
327 fn typing_without_a_valid_sender_or_signal_stays_a_plain_message() {
328 for extra in [
329 "",
330 r#","typing":"start""#,
331 r#","typing":"start","senderId":null"#,
332 r##","typing":"start","senderId":"""##,
333 r#","typing":"bogus","senderId":"a""#,
334 r#","senderId":"a""#,
335 ] {
336 let RealtimeEvent::Message(event) = decode_payload(&typing_payload(extra)).unwrap()
337 else {
338 panic!("expected message for {extra}")
339 };
340 assert_eq!(event.kind, EventKind::Typing);
341 }
342 }
343
344 #[test]
345 fn typing_without_a_conversation_stays_a_plain_message() {
346 let payload = r#"{"channel":"event","resourceType":"NewMessage","eventKind":"typing",
347 "conversationId":null,"receivedAt":5,"typing":"start","senderId":"a"}"#;
348 assert!(matches!(
349 decode_payload(payload).unwrap(),
350 RealtimeEvent::Message(_)
351 ));
352 }
353
226 #[test]
354 #[test]
227 fn decodes_every_status_kind() {
355 fn decodes_every_status_kind() {
228 for (name, kind) in [
356 for (name, kind) in [
crates/chatsvc/src/realtime/mod.rs +1 −1
@@ -13,7 +13,7 @@ use tokio::task::JoinHandle;
13 13
14 14 pub use event::{
15 15 EventKind, MessageEvent, PresenceUpdate, RealtimeEvent, StatusEvent, StatusKind,
16 TrouterEndpoint, decode_payload,
16 TrouterEndpoint, TypingEvent, decode_payload,
17 17 };
18 18 pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
19 19
@@ -13,7 +13,7 @@ use tokio::task::JoinHandle;
13
13
14pub use event::{
14pub use event::{
15 EventKind, MessageEvent, PresenceUpdate, RealtimeEvent, StatusEvent, StatusKind,
15 EventKind, MessageEvent, PresenceUpdate, RealtimeEvent, StatusEvent, StatusKind,
16 TrouterEndpoint, decode_payload,
16 TrouterEndpoint, TypingEvent, decode_payload,
17};
17};
18pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
18pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
19
19
crates/chatsvc/tests/messages.rs +40 −0
@@ -251,3 +251,43 @@ async fn unset_emotions_fails_when_every_key_fails() {
251 251 .is_err()
252 252 );
253 253 }
254
255 #[tokio::test]
256 async fn send_typing_posts_a_control_message_without_retrying() {
257 let mock = Mock::new(&[201, 201, 500]);
258 let chat = ConversationRef::chat("19:a@thread.v2");
259 messages(&mock).send_typing(&chat, true).await.unwrap();
260 messages(&mock).send_typing(&chat, false).await.unwrap();
261 assert!(messages(&mock).send_typing(&chat, true).await.is_err());
262 let requests = mock.requests();
263 assert_eq!(requests.len(), 3);
264 assert_eq!(requests[0].method, Method::Post);
265 assert_eq!(
266 requests[0].url,
267 format!("{BASE}/19%3Aa%40thread.v2/messages")
268 );
269 let start = requests[0].body.as_ref().unwrap();
270 assert_eq!(start["messagetype"], "Control/Typing");
271 assert_eq!(start["content"], "");
272 assert_eq!(start["contenttype"], "Application/Message");
273 assert_eq!(
274 requests[1].body.as_ref().unwrap()["messagetype"],
275 "Control/ClearTyping"
276 );
277 }
278
279 #[tokio::test]
280 async fn send_typing_addresses_a_channel_reply_thread() {
281 let mock = Mock::new(&[201]);
282 messages(&mock)
283 .send_typing(
284 &ConversationRef::channel_reply("19:c@thread.tacv2", "99"),
285 true,
286 )
287 .await
288 .unwrap();
289 assert_eq!(
290 mock.requests()[0].url,
291 format!("{BASE}/19%3Ac%40thread.tacv2%3Bmessageid%3D99/messages")
292 );
293 }
@@ -251,3 +251,43 @@ async fn unset_emotions_fails_when_every_key_fails() {
251 .is_err()
251 .is_err()
252 );
252 );
253}
253}
254
255#[tokio::test]
256async fn send_typing_posts_a_control_message_without_retrying() {
257 let mock = Mock::new(&[201, 201, 500]);
258 let chat = ConversationRef::chat("19:a@thread.v2");
259 messages(&mock).send_typing(&chat, true).await.unwrap();
260 messages(&mock).send_typing(&chat, false).await.unwrap();
261 assert!(messages(&mock).send_typing(&chat, true).await.is_err());
262 let requests = mock.requests();
263 assert_eq!(requests.len(), 3);
264 assert_eq!(requests[0].method, Method::Post);
265 assert_eq!(
266 requests[0].url,
267 format!("{BASE}/19%3Aa%40thread.v2/messages")
268 );
269 let start = requests[0].body.as_ref().unwrap();
270 assert_eq!(start["messagetype"], "Control/Typing");
271 assert_eq!(start["content"], "");
272 assert_eq!(start["contenttype"], "Application/Message");
273 assert_eq!(
274 requests[1].body.as_ref().unwrap()["messagetype"],
275 "Control/ClearTyping"
276 );
277}
278
279#[tokio::test]
280async fn send_typing_addresses_a_channel_reply_thread() {
281 let mock = Mock::new(&[201]);
282 messages(&mock)
283 .send_typing(
284 &ConversationRef::channel_reply("19:c@thread.tacv2", "99"),
285 true,
286 )
287 .await
288 .unwrap();
289 assert_eq!(
290 mock.requests()[0].url,
291 format!("{BASE}/19%3Ac%40thread.tacv2%3Bmessageid%3D99/messages")
292 );
293}
crates/chatsvc/tests/realtime.rs +8 −0
@@ -58,6 +58,7 @@ async fn serve(mut stream: TcpStream, port: u16, calls: Calls) {
58 58 json!({"channel": "status", "kind": "connected", "detail": ""}),
59 59 json!({"channel": "event", "resourceType": "NewMessage", "eventKind": "new_message", "conversationId": "19:abc@thread.v2", "messageId": "1", "receivedAt": 1791368146999i64}),
60 60 json!({"channel": "event", "resourceType": "NewMessage", "eventKind": "typing", "conversationId": null, "messageId": null, "receivedAt": 1791368147000i64}),
61 json!({"channel": "event", "resourceType": "NewMessage", "eventKind": "typing", "conversationId": "19:abc@thread.v2", "messageId": null, "receivedAt": 1791368148000i64, "typing": "start", "senderId": "abc-1", "senderName": "Ada"}),
61 62 ];
62 63 for payload in payloads {
63 64 websocket.send(binding_event(payload)).await.unwrap();
@@ -108,6 +109,13 @@ async fn forwards_decoded_events_and_drops_foreign_or_garbage_payloads() {
108 109 };
109 110 assert_eq!(typing.kind, EventKind::Typing);
110 111 assert_eq!(typing.conversation_id, None);
112 let RealtimeEvent::Typing(sender_typing) = realtime.recv().await.unwrap() else {
113 panic!("expected typing with sender")
114 };
115 assert!(sender_typing.active);
116 assert_eq!(sender_typing.user_id, "abc-1");
117 assert_eq!(sender_typing.display_name, "Ada");
118 assert_eq!(sender_typing.conversation_id, "19:abc@thread.v2");
111 119
112 120 let methods: Vec<String> = calls
113 121 .lock()
@@ -58,6 +58,7 @@ async fn serve(mut stream: TcpStream, port: u16, calls: Calls) {
58 json!({"channel": "status", "kind": "connected", "detail": ""}),
58 json!({"channel": "status", "kind": "connected", "detail": ""}),
59 json!({"channel": "event", "resourceType": "NewMessage", "eventKind": "new_message", "conversationId": "19:abc@thread.v2", "messageId": "1", "receivedAt": 1791368146999i64}),
59 json!({"channel": "event", "resourceType": "NewMessage", "eventKind": "new_message", "conversationId": "19:abc@thread.v2", "messageId": "1", "receivedAt": 1791368146999i64}),
60 json!({"channel": "event", "resourceType": "NewMessage", "eventKind": "typing", "conversationId": null, "messageId": null, "receivedAt": 1791368147000i64}),
60 json!({"channel": "event", "resourceType": "NewMessage", "eventKind": "typing", "conversationId": null, "messageId": null, "receivedAt": 1791368147000i64}),
61 json!({"channel": "event", "resourceType": "NewMessage", "eventKind": "typing", "conversationId": "19:abc@thread.v2", "messageId": null, "receivedAt": 1791368148000i64, "typing": "start", "senderId": "abc-1", "senderName": "Ada"}),
61 ];
62 ];
62 for payload in payloads {
63 for payload in payloads {
63 websocket.send(binding_event(payload)).await.unwrap();
64 websocket.send(binding_event(payload)).await.unwrap();
@@ -108,6 +109,13 @@ async fn forwards_decoded_events_and_drops_foreign_or_garbage_payloads() {
108 };
109 };
109 assert_eq!(typing.kind, EventKind::Typing);
110 assert_eq!(typing.kind, EventKind::Typing);
110 assert_eq!(typing.conversation_id, None);
111 assert_eq!(typing.conversation_id, None);
112 let RealtimeEvent::Typing(sender_typing) = realtime.recv().await.unwrap() else {
113 panic!("expected typing with sender")
114 };
115 assert!(sender_typing.active);
116 assert_eq!(sender_typing.user_id, "abc-1");
117 assert_eq!(sender_typing.display_name, "Ada");
118 assert_eq!(sender_typing.conversation_id, "19:abc@thread.v2");
111
119
112 let methods: Vec<String> = calls
120 let methods: Vec<String> = calls
113 .lock()
121 .lock()
crates/core/examples/live_presence.rs +1 −1
@@ -55,7 +55,7 @@ async fn main() {
55 55 println!("{at:6.1}s presence push {} entries, known {known}/{}", updates.len(), user_ids.len());
56 56 }
57 57 RealtimeEvent::Status(status) => println!("{at:6.1}s status {:?} {}", status.kind, status.detail),
58 RealtimeEvent::Message(_) => {}
58 RealtimeEvent::Message(_) | RealtimeEvent::Typing(_) => {}
59 59 }
60 60 }
61 61 _ = &mut deadline => break,
@@ -55,7 +55,7 @@ async fn main() {
55 println!("{at:6.1}s presence push {} entries, known {known}/{}", updates.len(), user_ids.len());
55 println!("{at:6.1}s presence push {} entries, known {known}/{}", updates.len(), user_ids.len());
56 }
56 }
57 RealtimeEvent::Status(status) => println!("{at:6.1}s status {:?} {}", status.kind, status.detail),
57 RealtimeEvent::Status(status) => println!("{at:6.1}s status {:?} {}", status.kind, status.detail),
58 RealtimeEvent::Message(_) => {}
58 RealtimeEvent::Message(_) | RealtimeEvent::Typing(_) => {}
59 }
59 }
60 }
60 }
61 _ = &mut deadline => break,
61 _ = &mut deadline => break,
crates/core/src/actions.rs +17 −0
@@ -1,3 +1,4 @@
1 use chatsvc::ConversationRef;
1 2 use chrono::{Duration, Utc};
2 3 use graph::{
3 4 FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
@@ -399,6 +400,22 @@ impl<R: Remote> SyncEngine<R> {
399 400 Ok(())
400 401 }
401 402
403 pub async fn send_typing(
404 &self,
405 conversation_id: &str,
406 thread_root_id: Option<&str>,
407 active: bool,
408 ) -> Result<()> {
409 let conversation = match (self.resolve(conversation_id)?, thread_root_id) {
410 (Conversation::Chat, _) => ConversationRef::chat(conversation_id),
411 (Conversation::Channel { .. }, None) => ConversationRef::channel_root(conversation_id),
412 (Conversation::Channel { .. }, Some(root_id)) => {
413 ConversationRef::channel_reply(conversation_id, root_id)
414 }
415 };
416 self.remote.send_typing(&conversation, active).await
417 }
418
402 419 pub async fn set_reaction(
403 420 &self,
404 421 conversation_id: &str,
@@ -1,3 +1,4 @@
1use chatsvc::ConversationRef;
1use chrono::{Duration, Utc};
2use chrono::{Duration, Utc};
2use graph::{
3use graph::{
3 FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
4 FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
@@ -399,6 +400,22 @@ impl<R: Remote> SyncEngine<R> {
399 Ok(())
400 Ok(())
400 }
401 }
401
402
403 pub async fn send_typing(
404 &self,
405 conversation_id: &str,
406 thread_root_id: Option<&str>,
407 active: bool,
408 ) -> Result<()> {
409 let conversation = match (self.resolve(conversation_id)?, thread_root_id) {
410 (Conversation::Chat, _) => ConversationRef::chat(conversation_id),
411 (Conversation::Channel { .. }, None) => ConversationRef::channel_root(conversation_id),
412 (Conversation::Channel { .. }, Some(root_id)) => {
413 ConversationRef::channel_reply(conversation_id, root_id)
414 }
415 };
416 self.remote.send_typing(&conversation, active).await
417 }
418
402 pub async fn set_reaction(
419 pub async fn set_reaction(
403 &self,
420 &self,
404 conversation_id: &str,
421 conversation_id: &str,
crates/core/src/remote.rs +7 −0
@@ -118,6 +118,7 @@ pub trait Remote {
118 118 async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;
119 119 async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>>;
120 120 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
121 async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()>;
121 122 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
122 123 async fn unset_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
123 124 async fn edit_message(
@@ -408,6 +409,12 @@ impl Remote for Graph {
408 409 .await?)
409 410 }
410 411
412 async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
413 Ok(Messages::new(self.session())
414 .send_typing(conversation, active)
415 .await?)
416 }
417
411 418 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
412 419 if let Some(key) = chatsvc::emotion_key(reaction_type) {
413 420 return Ok(Messages::new(self.session())
@@ -118,6 +118,7 @@ pub trait Remote {
118 async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;
118 async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;
119 async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>>;
119 async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>>;
120 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
120 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
121 async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()>;
121 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
122 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
122 async fn unset_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
123 async fn unset_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
123 async fn edit_message(
124 async fn edit_message(
@@ -408,6 +409,12 @@ impl Remote for Graph {
408 .await?)
409 .await?)
409 }
410 }
410
411
412 async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
413 Ok(Messages::new(self.session())
414 .send_typing(conversation, active)
415 .await?)
416 }
417
411 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
418 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
412 if let Some(key) = chatsvc::emotion_key(reaction_type) {
419 if let Some(key) = chatsvc::emotion_key(reaction_type) {
413 return Ok(Messages::new(self.session())
420 return Ok(Messages::new(self.session())
crates/core/tests/engine.rs +48 −0
@@ -1,6 +1,7 @@
1 1 use std::collections::HashMap;
2 2 use std::sync::{Arc, Mutex};
3 3
4 use chatsvc::ConversationRef;
4 5 use chrono::{DateTime, Duration, TimeZone, Utc};
5 6 use graph::{
6 7 Channel, Chat, DriveFolder, HostedImage, Member, Message, MessageExtras, MessageTarget,
@@ -425,6 +426,14 @@ impl Remote for Handle {
425 426 Ok(())
426 427 }
427 428
429 async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
430 self.record(format!(
431 "typing {} {active}",
432 conversation.conversation_id()
433 ));
434 Ok(())
435 }
436
428 437 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
429 438 self.record(format!("set_reaction {} {reaction_type}", describe(target)));
430 439 Ok(())
@@ -1543,6 +1552,45 @@ async fn refresh_message_upserts_an_edit_older_than_the_newest_cached() {
1543 1552 assert!(engine.refresh_message(CHAT, "m0999").await.is_err());
1544 1553 }
1545 1554
1555 #[tokio::test]
1556 async fn send_typing_addresses_chats_channels_and_threads() {
1557 let chat_fake = Arc::new(Fake::default());
1558 let chat_engine = chat_engine(&chat_fake, small_pages()).await;
1559 chat_engine.send_typing(CHAT, None, true).await.unwrap();
1560 chat_engine.send_typing(CHAT, None, false).await.unwrap();
1561 assert!(
1562 chat_engine
1563 .send_typing("19:unknown@thread.v2", None, true)
1564 .await
1565 .is_err()
1566 );
1567 assert_eq!(
1568 chat_fake.calls(),
1569 [
1570 format!("typing {CHAT} true"),
1571 format!("typing {CHAT} false")
1572 ]
1573 );
1574
1575 let channel_fake = Arc::new(Fake::default());
1576 let channel_engine = channel_engine(&channel_fake).await;
1577 channel_engine
1578 .send_typing(CHANNEL, None, true)
1579 .await
1580 .unwrap();
1581 channel_engine
1582 .send_typing(CHANNEL, Some("m0042"), true)
1583 .await
1584 .unwrap();
1585 assert_eq!(
1586 channel_fake.calls(),
1587 [
1588 format!("typing {CHANNEL} true"),
1589 format!("typing {CHANNEL};messageid=m0042 true"),
1590 ]
1591 );
1592 }
1593
1546 1594 #[tokio::test]
1547 1595 async fn chat_actions_call_graph_with_the_right_ids() {
1548 1596 let fake = Arc::new(Fake::default());
@@ -1,6 +1,7 @@
1use std::collections::HashMap;
1use std::collections::HashMap;
2use std::sync::{Arc, Mutex};
2use std::sync::{Arc, Mutex};
3
3
4use chatsvc::ConversationRef;
4use chrono::{DateTime, Duration, TimeZone, Utc};
5use chrono::{DateTime, Duration, TimeZone, Utc};
5use graph::{
6use graph::{
6 Channel, Chat, DriveFolder, HostedImage, Member, Message, MessageExtras, MessageTarget,
7 Channel, Chat, DriveFolder, HostedImage, Member, Message, MessageExtras, MessageTarget,
@@ -425,6 +426,14 @@ impl Remote for Handle {
425 Ok(())
426 Ok(())
426 }
427 }
427
428
429 async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
430 self.record(format!(
431 "typing {} {active}",
432 conversation.conversation_id()
433 ));
434 Ok(())
435 }
436
428 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
437 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
429 self.record(format!("set_reaction {} {reaction_type}", describe(target)));
438 self.record(format!("set_reaction {} {reaction_type}", describe(target)));
430 Ok(())
439 Ok(())
@@ -1543,6 +1552,45 @@ async fn refresh_message_upserts_an_edit_older_than_the_newest_cached() {
1543 assert!(engine.refresh_message(CHAT, "m0999").await.is_err());
1552 assert!(engine.refresh_message(CHAT, "m0999").await.is_err());
1544}
1553}
1545
1554
1555#[tokio::test]
1556async fn send_typing_addresses_chats_channels_and_threads() {
1557 let chat_fake = Arc::new(Fake::default());
1558 let chat_engine = chat_engine(&chat_fake, small_pages()).await;
1559 chat_engine.send_typing(CHAT, None, true).await.unwrap();
1560 chat_engine.send_typing(CHAT, None, false).await.unwrap();
1561 assert!(
1562 chat_engine
1563 .send_typing("19:unknown@thread.v2", None, true)
1564 .await
1565 .is_err()
1566 );
1567 assert_eq!(
1568 chat_fake.calls(),
1569 [
1570 format!("typing {CHAT} true"),
1571 format!("typing {CHAT} false")
1572 ]
1573 );
1574
1575 let channel_fake = Arc::new(Fake::default());
1576 let channel_engine = channel_engine(&channel_fake).await;
1577 channel_engine
1578 .send_typing(CHANNEL, None, true)
1579 .await
1580 .unwrap();
1581 channel_engine
1582 .send_typing(CHANNEL, Some("m0042"), true)
1583 .await
1584 .unwrap();
1585 assert_eq!(
1586 channel_fake.calls(),
1587 [
1588 format!("typing {CHANNEL} true"),
1589 format!("typing {CHANNEL};messageid=m0042 true"),
1590 ]
1591 );
1592}
1593
1546#[tokio::test]
1594#[tokio::test]
1547async fn chat_actions_call_graph_with_the_right_ids() {
1595async fn chat_actions_call_graph_with_the_right_ids() {
1548 let fake = Arc::new(Fake::default());
1596 let fake = Arc::new(Fake::default());