BlueGit

ict rusty-teams

feat(orgs): toasts and unread badges for the org that is not open

Like Teams, every org that is not open in the window stays live: its
own realtime socket through a tenant session, a toast for each new chat
message from someone else (muted chats and channel posts stay quiet),
and a count of chats with new messages beside the org in the account
menu. The toast names the org and has no quick reply; clicking it
restarts on that org and opens the chat.

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

metis Michael Wallner · pushed by metis

Authored 2026-11-15 · 2 weeks ago

Hash
9fdb6c833ca5275124aea34feeaf1641d1ef49e9
Parent
ea9903e4
17 files changed +443 −40
crates/app-base/src/orgs.rs +6 −1
@@ -7,6 +7,8 @@ use std::path::{Path, PathBuf};
7 7 use serde::{Deserialize, Serialize};
8 8
9 9 pub const ORGS_FILE: &str = "orgs.json";
10 /// Start flag that opens one chat once its org has loaded, used when a toast of another org is clicked.
11 pub const OPEN_CONVERSATION_FLAG: &str = "--open-conversation";
10 12 const HOME_DATABASE: &str = "cache.sqlite3";
11 13
12 14 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -78,7 +80,10 @@ impl Orgs {
78 80
79 81 /// Tenant ids are GUIDs; anything else must not end up in a file name.
80 82 fn is_tenant_id(id: &str) -> bool {
81 !id.is_empty() && id.chars().all(|character| character.is_ascii_hexdigit() || character == '-')
83 !id.is_empty()
84 && id
85 .chars()
86 .all(|character| character.is_ascii_hexdigit() || character == '-')
82 87 }
83 88
84 89 #[cfg(test)]
@@ -7,6 +7,8 @@ use std::path::{Path, PathBuf};
7use serde::{Deserialize, Serialize};
7use serde::{Deserialize, Serialize};
8
8
9pub const ORGS_FILE: &str = "orgs.json";
9pub const ORGS_FILE: &str = "orgs.json";
10/// Start flag that opens one chat once its org has loaded, used when a toast of another org is clicked.
11pub const OPEN_CONVERSATION_FLAG: &str = "--open-conversation";
10const HOME_DATABASE: &str = "cache.sqlite3";
12const HOME_DATABASE: &str = "cache.sqlite3";
11
13
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -78,7 +80,10 @@ impl Orgs {
78
80
79/// Tenant ids are GUIDs; anything else must not end up in a file name.
81/// Tenant ids are GUIDs; anything else must not end up in a file name.
80fn is_tenant_id(id: &str) -> bool {
82fn is_tenant_id(id: &str) -> bool {
81 !id.is_empty() && id.chars().all(|character| character.is_ascii_hexdigit() || character == '-')
83 !id.is_empty()
84 && id
85 .chars()
86 .all(|character| character.is_ascii_hexdigit() || character == '-')
82}
87}
83
88
84#[cfg(test)]
89#[cfg(test)]
crates/app-state/src/app_state.rs +17 −1
@@ -104,7 +104,12 @@ pub enum AppEvent {
104 104 CallTone(chatsvc::sounds::CallTone),
105 105 SoundSettings,
106 106 ChatSettings,
107 FollowedStatus { user_id: String, text: &'static str },
107 FollowedStatus {
108 user_id: String,
109 text: &'static str,
110 },
111 /// A new message in an org that is not open in this window.
112 OrgMessage(crate::org_watch::OrgMessage),
108 113 }
109 114
110 115 #[derive(Debug, Clone, Copy, Default)]
@@ -135,6 +140,8 @@ pub struct AppState {
135 140 pub start_on_channels: bool,
136 141 /// The account's organizations and the one this window shows.
137 142 pub orgs: app_base::orgs::Orgs,
143 /// Chats with new messages per org that is not open, for the account menu badge.
144 pub org_unread: HashMap<String, HashSet<String>>,
138 145 pub pending_jump: Option<(String, String)>,
139 146 pub cards: CardState,
140 147 pub task_dialog: Option<TaskDialogState>,
@@ -303,6 +310,7 @@ impl AppState {
303 310 expanded_lists: HashSet::new(),
304 311 start_on_channels: false,
305 312 orgs: app_base::orgs::Orgs::default(),
313 org_unread: HashMap::new(),
306 314 pending_jump: None,
307 315 cards: CardState::default(),
308 316 task_dialog: None,
@@ -1254,6 +1262,14 @@ impl AppState {
1254 1262 self.take_org_list(list);
1255 1263 cx.notify();
1256 1264 }
1265 BackendEvent::OrgMessage(message) => {
1266 self.org_unread
1267 .entry(message.org.id.clone())
1268 .or_default()
1269 .insert(message.conversation_id.clone());
1270 cx.emit(AppEvent::OrgMessage(message));
1271 cx.notify();
1272 }
1257 1273 BackendEvent::Favorites(ids) => {
1258 1274 self.favorite_ids = ids;
1259 1275 if !self.mode.demo {
@@ -104,7 +104,12 @@ pub enum AppEvent {
104 CallTone(chatsvc::sounds::CallTone),
104 CallTone(chatsvc::sounds::CallTone),
105 SoundSettings,
105 SoundSettings,
106 ChatSettings,
106 ChatSettings,
107 FollowedStatus { user_id: String, text: &'static str },
107 FollowedStatus {
108 user_id: String,
109 text: &'static str,
110 },
111 /// A new message in an org that is not open in this window.
112 OrgMessage(crate::org_watch::OrgMessage),
108}
113}
109
114
110#[derive(Debug, Clone, Copy, Default)]
115#[derive(Debug, Clone, Copy, Default)]
@@ -135,6 +140,8 @@ pub struct AppState {
135 pub start_on_channels: bool,
140 pub start_on_channels: bool,
136 /// The account's organizations and the one this window shows.
141 /// The account's organizations and the one this window shows.
137 pub orgs: app_base::orgs::Orgs,
142 pub orgs: app_base::orgs::Orgs,
143 /// Chats with new messages per org that is not open, for the account menu badge.
144 pub org_unread: HashMap<String, HashSet<String>>,
138 pub pending_jump: Option<(String, String)>,
145 pub pending_jump: Option<(String, String)>,
139 pub cards: CardState,
146 pub cards: CardState,
140 pub task_dialog: Option<TaskDialogState>,
147 pub task_dialog: Option<TaskDialogState>,
@@ -303,6 +310,7 @@ impl AppState {
303 expanded_lists: HashSet::new(),
310 expanded_lists: HashSet::new(),
304 start_on_channels: false,
311 start_on_channels: false,
305 orgs: app_base::orgs::Orgs::default(),
312 orgs: app_base::orgs::Orgs::default(),
313 org_unread: HashMap::new(),
306 pending_jump: None,
314 pending_jump: None,
307 cards: CardState::default(),
315 cards: CardState::default(),
308 task_dialog: None,
316 task_dialog: None,
@@ -1254,6 +1262,14 @@ impl AppState {
1254 self.take_org_list(list);
1262 self.take_org_list(list);
1255 cx.notify();
1263 cx.notify();
1256 }
1264 }
1265 BackendEvent::OrgMessage(message) => {
1266 self.org_unread
1267 .entry(message.org.id.clone())
1268 .or_default()
1269 .insert(message.conversation_id.clone());
1270 cx.emit(AppEvent::OrgMessage(message));
1271 cx.notify();
1272 }
1257 BackendEvent::Favorites(ids) => {
1273 BackendEvent::Favorites(ids) => {
1258 self.favorite_ids = ids;
1274 self.favorite_ids = ids;
1259 if !self.mode.demo {
1275 if !self.mode.demo {
crates/app-state/src/backend.rs +29 −8
@@ -74,6 +74,7 @@ pub enum BackendEvent {
74 74 Synced(DateTime<Utc>),
75 75 LiveRetry(Arc<Notify>),
76 76 Orgs(Vec<app_base::orgs::Org>),
77 OrgMessage(crate::org_watch::OrgMessage),
77 78 }
78 79
79 80 impl BackendEvent {
@@ -98,6 +99,7 @@ impl BackendEvent {
98 99 BackendEvent::Synced(_) => "Synced".into(),
99 100 BackendEvent::LiveRetry(_) => "LiveRetry".into(),
100 101 BackendEvent::Orgs(_) => "Orgs".into(),
102 BackendEvent::OrgMessage(_) => "OrgMessage".into(),
101 103 }
102 104 }
103 105 }
@@ -185,7 +187,7 @@ async fn supervise(
185 187 }
186 188 }
187 189 };
188 tokio::spawn(org_list(home.clone(), events.clone()));
190 tokio::spawn(org_list(home.clone(), guest_tenant.clone(), events.clone()));
189 191 // Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.
190 192 let session = match &guest_tenant {
191 193 Some(tenant) => home.in_tenant(tenant),
@@ -235,19 +237,38 @@ async fn supervise(
235 237 refresh_loop(engine, events, nudges).await;
236 238 }
237 239
238 /// Fetches the account's organizations once per start; retried a few times while sign-in settles.
239 async fn org_list(home: Session, events: EventSender) {
240 /// Fetches the account's organizations once per start, retried a few times while sign-in settles,
241 /// and keeps every org that is not open live for notifications.
242 async fn org_list(home: Session, open_guest: Option<String>, events: EventSender) {
240 243 for _ in 0..ORG_LIST_ATTEMPTS {
241 244 match chatsvc::list_tenants(&home).await {
242 245 Ok(tenants) => {
243 let orgs = tenants
244 .into_iter()
245 .map(|tenant| app_base::orgs::Org {
246 let mut orgs = Vec::with_capacity(tenants.len());
247 for tenant in tenants {
248 let org = app_base::orgs::Org {
246 249 id: tenant.id,
247 250 name: tenant.name,
248 251 guest: tenant.guest,
249 })
250 .collect();
252 };
253 let open = match &open_guest {
254 Some(open) => *open == org.id,
255 None => !org.guest,
256 };
257 if !open {
258 let session = if org.guest {
259 home.in_tenant(&org.id)
260 } else {
261 home.clone()
262 };
263 tokio::spawn(crate::org_watch::watch(
264 session,
265 org.clone(),
266 tenant.user_id,
267 events.clone(),
268 ));
269 }
270 orgs.push(org);
271 }
251 272 let _ = events.send(BackendEvent::Orgs(orgs));
252 273 return;
253 274 }
@@ -74,6 +74,7 @@ pub enum BackendEvent {
74 Synced(DateTime<Utc>),
74 Synced(DateTime<Utc>),
75 LiveRetry(Arc<Notify>),
75 LiveRetry(Arc<Notify>),
76 Orgs(Vec<app_base::orgs::Org>),
76 Orgs(Vec<app_base::orgs::Org>),
77 OrgMessage(crate::org_watch::OrgMessage),
77}
78}
78
79
79impl BackendEvent {
80impl BackendEvent {
@@ -98,6 +99,7 @@ impl BackendEvent {
98 BackendEvent::Synced(_) => "Synced".into(),
99 BackendEvent::Synced(_) => "Synced".into(),
99 BackendEvent::LiveRetry(_) => "LiveRetry".into(),
100 BackendEvent::LiveRetry(_) => "LiveRetry".into(),
100 BackendEvent::Orgs(_) => "Orgs".into(),
101 BackendEvent::Orgs(_) => "Orgs".into(),
102 BackendEvent::OrgMessage(_) => "OrgMessage".into(),
101 }
103 }
102 }
104 }
103}
105}
@@ -185,7 +187,7 @@ async fn supervise(
185 }
187 }
186 }
188 }
187 };
189 };
188 tokio::spawn(org_list(home.clone(), events.clone()));
190 tokio::spawn(org_list(home.clone(), guest_tenant.clone(), events.clone()));
189 // Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.
191 // Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.
190 let session = match &guest_tenant {
192 let session = match &guest_tenant {
191 Some(tenant) => home.in_tenant(tenant),
193 Some(tenant) => home.in_tenant(tenant),
@@ -235,19 +237,38 @@ async fn supervise(
235 refresh_loop(engine, events, nudges).await;
237 refresh_loop(engine, events, nudges).await;
236}
238}
237
239
238/// Fetches the account's organizations once per start; retried a few times while sign-in settles.
240/// Fetches the account's organizations once per start, retried a few times while sign-in settles,
239async fn org_list(home: Session, events: EventSender) {
241/// and keeps every org that is not open live for notifications.
242async fn org_list(home: Session, open_guest: Option<String>, events: EventSender) {
240 for _ in 0..ORG_LIST_ATTEMPTS {
243 for _ in 0..ORG_LIST_ATTEMPTS {
241 match chatsvc::list_tenants(&home).await {
244 match chatsvc::list_tenants(&home).await {
242 Ok(tenants) => {
245 Ok(tenants) => {
243 let orgs = tenants
246 let mut orgs = Vec::with_capacity(tenants.len());
244 .into_iter()
247 for tenant in tenants {
245 .map(|tenant| app_base::orgs::Org {
248 let org = app_base::orgs::Org {
246 id: tenant.id,
249 id: tenant.id,
247 name: tenant.name,
250 name: tenant.name,
248 guest: tenant.guest,
251 guest: tenant.guest,
249 })
252 };
250 .collect();
253 let open = match &open_guest {
254 Some(open) => *open == org.id,
255 None => !org.guest,
256 };
257 if !open {
258 let session = if org.guest {
259 home.in_tenant(&org.id)
260 } else {
261 home.clone()
262 };
263 tokio::spawn(crate::org_watch::watch(
264 session,
265 org.clone(),
266 tenant.user_id,
267 events.clone(),
268 ));
269 }
270 orgs.push(org);
271 }
251 let _ = events.send(BackendEvent::Orgs(orgs));
272 let _ = events.send(BackendEvent::Orgs(orgs));
252 return;
273 return;
253 }
274 }
crates/app-state/src/lib.rs +1 −0
@@ -40,6 +40,7 @@ pub mod message_actions;
40 40 pub mod notice;
41 41 pub mod notify;
42 42 mod org_actions;
43 pub mod org_watch;
43 44 pub mod outbox;
44 45 pub mod outgoing;
45 46 pub mod own_status;
@@ -40,6 +40,7 @@ pub mod message_actions;
40pub mod notice;
40pub mod notice;
41pub mod notify;
41pub mod notify;
42mod org_actions;
42mod org_actions;
43pub mod org_watch;
43pub mod outbox;
44pub mod outbox;
44pub mod outgoing;
45pub mod outgoing;
45pub mod own_status;
46pub mod own_status;
crates/app-state/src/notify/layout.rs +1 −0
@@ -202,6 +202,7 @@ mod tests {
202 202 agent: None,
203 203 status_change: false,
204 204 urgent: false,
205 org: None,
205 206 };
206 207 assert_eq!(toast_height(&model("Hi"), 1), 112.);
207 208 assert_eq!(toast_height(&model("Hi"), 2), 130.);
@@ -202,6 +202,7 @@ mod tests {
202 agent: None,
202 agent: None,
203 status_change: false,
203 status_change: false,
204 urgent: false,
204 urgent: false,
205 org: None,
205 };
206 };
206 assert_eq!(toast_height(&model("Hi"), 1), 112.);
207 assert_eq!(toast_height(&model("Hi"), 1), 112.);
207 assert_eq!(toast_height(&model("Hi"), 2), 130.);
208 assert_eq!(toast_height(&model("Hi"), 2), 130.);
crates/app-state/src/notify/stack.rs +45 −0
@@ -196,6 +196,8 @@ pub struct ToastModel {
196 196 pub agent: Option<AgentToast>,
197 197 pub status_change: bool,
198 198 pub urgent: bool,
199 /// Set for a message in an org that is not open; clicking switches to that org.
200 pub org: Option<app_base::orgs::Org>,
199 201 }
200 202
201 203 impl ToastModel {
@@ -236,6 +238,7 @@ impl ToastStack {
236 238 if let Some(existing) = self.toasts.iter_mut().find(|toast| {
237 239 toast.agent.is_none()
238 240 && !toast.status_change
241 && toast.org.is_none()
239 242 && !toast.dismissed
240 243 && !toast.is_leaving()
241 244 && toast.conversation_id == incoming.conversation_id
@@ -280,6 +283,7 @@ impl ToastStack {
280 283 agent: None,
281 284 status_change: false,
282 285 urgent: incoming.is_urgent(),
286 org: None,
283 287 });
284 288 PushOutcome {
285 289 id: self.next_id,
@@ -319,6 +323,7 @@ impl ToastStack {
319 323 agent: Some(agent),
320 324 status_change: false,
321 325 urgent: false,
326 org: None,
322 327 });
323 328 self.next_id
324 329 }
@@ -355,6 +360,46 @@ impl ToastStack {
355 360 agent: None,
356 361 status_change: true,
357 362 urgent: false,
363 org: None,
364 });
365 self.next_id
366 }
367
368 /// A chat message from an org that is not open. No quick reply: the open org's engine cannot send there.
369 pub fn push_org_message(
370 &mut self,
371 message: &crate::org_watch::OrgMessage,
372 now: Instant,
373 ) -> u64 {
374 self.next_id += 1;
375 let queued = self.toasts.len() >= MAX_VISIBLE;
376 self.toasts.push(ToastModel {
377 id: self.next_id,
378 conversation_id: message.conversation_id.clone(),
379 message_id: message.message_id.clone(),
380 kind: if message.direct {
381 ChatKind::Direct
382 } else {
383 ChatKind::Group { member_count: 0 }
384 },
385 chat_title: message.chat_title.clone(),
386 sender_id: None,
387 sender_name: message.sender_name.clone(),
388 preview: Preview::Text(message.preview.clone()),
389 mentions_me: false,
390 count: 1,
391 timer: ToastTimer::new(now, false),
392 reply: ReplyState::Closed,
393 reply_text: String::new(),
394 hovered: false,
395 time: String::new(),
396 queued,
397 dismissed: false,
398 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
399 agent: None,
400 status_change: false,
401 urgent: false,
402 org: Some(message.org.clone()),
358 403 });
359 404 self.next_id
360 405 }
@@ -196,6 +196,8 @@ pub struct ToastModel {
196 pub agent: Option<AgentToast>,
196 pub agent: Option<AgentToast>,
197 pub status_change: bool,
197 pub status_change: bool,
198 pub urgent: bool,
198 pub urgent: bool,
199 /// Set for a message in an org that is not open; clicking switches to that org.
200 pub org: Option<app_base::orgs::Org>,
199}
201}
200
202
201impl ToastModel {
203impl ToastModel {
@@ -236,6 +238,7 @@ impl ToastStack {
236 if let Some(existing) = self.toasts.iter_mut().find(|toast| {
238 if let Some(existing) = self.toasts.iter_mut().find(|toast| {
237 toast.agent.is_none()
239 toast.agent.is_none()
238 && !toast.status_change
240 && !toast.status_change
241 && toast.org.is_none()
239 && !toast.dismissed
242 && !toast.dismissed
240 && !toast.is_leaving()
243 && !toast.is_leaving()
241 && toast.conversation_id == incoming.conversation_id
244 && toast.conversation_id == incoming.conversation_id
@@ -280,6 +283,7 @@ impl ToastStack {
280 agent: None,
283 agent: None,
281 status_change: false,
284 status_change: false,
282 urgent: incoming.is_urgent(),
285 urgent: incoming.is_urgent(),
286 org: None,
283 });
287 });
284 PushOutcome {
288 PushOutcome {
285 id: self.next_id,
289 id: self.next_id,
@@ -319,6 +323,7 @@ impl ToastStack {
319 agent: Some(agent),
323 agent: Some(agent),
320 status_change: false,
324 status_change: false,
321 urgent: false,
325 urgent: false,
326 org: None,
322 });
327 });
323 self.next_id
328 self.next_id
324 }
329 }
@@ -355,6 +360,46 @@ impl ToastStack {
355 agent: None,
360 agent: None,
356 status_change: true,
361 status_change: true,
357 urgent: false,
362 urgent: false,
363 org: None,
364 });
365 self.next_id
366 }
367
368 /// A chat message from an org that is not open. No quick reply: the open org's engine cannot send there.
369 pub fn push_org_message(
370 &mut self,
371 message: &crate::org_watch::OrgMessage,
372 now: Instant,
373 ) -> u64 {
374 self.next_id += 1;
375 let queued = self.toasts.len() >= MAX_VISIBLE;
376 self.toasts.push(ToastModel {
377 id: self.next_id,
378 conversation_id: message.conversation_id.clone(),
379 message_id: message.message_id.clone(),
380 kind: if message.direct {
381 ChatKind::Direct
382 } else {
383 ChatKind::Group { member_count: 0 }
384 },
385 chat_title: message.chat_title.clone(),
386 sender_id: None,
387 sender_name: message.sender_name.clone(),
388 preview: Preview::Text(message.preview.clone()),
389 mentions_me: false,
390 count: 1,
391 timer: ToastTimer::new(now, false),
392 reply: ReplyState::Closed,
393 reply_text: String::new(),
394 hovered: false,
395 time: String::new(),
396 queued,
397 dismissed: false,
398 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
399 agent: None,
400 status_change: false,
401 urgent: false,
402 org: Some(message.org.clone()),
358 });
403 });
359 self.next_id
404 self.next_id
360 }
405 }
crates/app-state/src/notify/text.rs +5 −1
@@ -32,7 +32,10 @@ pub fn describe(model: &ToastModel, preview_on: bool) -> ToastText {
32 32 ChatKind::Group { .. } => model.chat_title.clone(),
33 33 ChatKind::Direct | ChatKind::Channel { .. } => sender.to_owned(),
34 34 };
35 let subtitle = subtitle_of(&model.kind);
35 let subtitle = match &model.org {
36 Some(org) => org.name.clone(),
37 None => subtitle_of(&model.kind),
38 };
36 39 let body = match (&model.preview, preview_on) {
37 40 (Preview::Text(text), false) if model.status_change => text.clone(),
38 41 (_, false) => PREVIEW_OFF.to_owned(),
@@ -109,6 +112,7 @@ mod tests {
109 112 agent: None,
110 113 status_change: false,
111 114 urgent: false,
115 org: None,
112 116 }
113 117 }
114 118
@@ -32,7 +32,10 @@ pub fn describe(model: &ToastModel, preview_on: bool) -> ToastText {
32 ChatKind::Group { .. } => model.chat_title.clone(),
32 ChatKind::Group { .. } => model.chat_title.clone(),
33 ChatKind::Direct | ChatKind::Channel { .. } => sender.to_owned(),
33 ChatKind::Direct | ChatKind::Channel { .. } => sender.to_owned(),
34 };
34 };
35 let subtitle = subtitle_of(&model.kind);
35 let subtitle = match &model.org {
36 Some(org) => org.name.clone(),
37 None => subtitle_of(&model.kind),
38 };
36 let body = match (&model.preview, preview_on) {
39 let body = match (&model.preview, preview_on) {
37 (Preview::Text(text), false) if model.status_change => text.clone(),
40 (Preview::Text(text), false) if model.status_change => text.clone(),
38 (_, false) => PREVIEW_OFF.to_owned(),
41 (_, false) => PREVIEW_OFF.to_owned(),
@@ -109,6 +112,7 @@ mod tests {
109 agent: None,
112 agent: None,
110 status_change: false,
113 status_change: false,
111 urgent: false,
114 urgent: false,
115 org: None,
112 }
116 }
113 }
117 }
114
118
crates/app-state/src/org_actions.rs +60 −5
@@ -1,4 +1,4 @@
1 use app_base::orgs::{Org, Orgs};
1 use app_base::orgs::{OPEN_CONVERSATION_FLAG, Org, Orgs};
2 2 use gpui_kit::Context;
3 3
4 4 use crate::app_state::AppState;
@@ -21,8 +21,19 @@ impl AppState {
21 21 }
22 22 }
23 23
24 /// Chats with new messages in `org` since this window opened; zero for the open org.
25 pub fn org_unread_count(&self, org: &Org) -> usize {
26 self.org_unread.get(&org.id).map_or(0, |chats| chats.len())
27 }
28
24 29 /// Restarts the app on `org`: its own cache opens at once and the backend signs in to its tenant.
25 pub fn switch_org(&mut self, org: &Org, cx: &mut Context<Self>) {
30 /// `open_conversation` opens that chat once the org has loaded.
31 pub fn switch_org(
32 &mut self,
33 org: &Org,
34 open_conversation: Option<&str>,
35 cx: &mut Context<Self>,
36 ) {
26 37 if self.orgs.is_active(org) {
27 38 return;
28 39 }
@@ -34,8 +45,14 @@ impl AppState {
34 45 self.orgs = next;
35 46 match std::env::current_exe().and_then(|exe| {
36 47 std::process::Command::new(exe)
37 .args(std::env::args_os().skip(1))
38 .env(app_base::updater::RELAUNCH_ENV, std::process::id().to_string())
48 .args(restart_arguments(
49 std::env::args_os().skip(1),
50 open_conversation,
51 ))
52 .env(
53 app_base::updater::RELAUNCH_ENV,
54 std::process::id().to_string(),
55 )
39 56 .spawn()
40 57 }) {
41 58 Ok(_) => cx.quit(),
@@ -51,8 +68,46 @@ impl AppState {
51 68 }
52 69 let saved = Orgs::path().map(|path| orgs.save(&path));
53 70 if let Some(Err(error)) = &saved {
54 crate::diagnostics::record(format!("orgs: {} not saved: {error}", app_base::orgs::ORGS_FILE));
71 crate::diagnostics::record(format!(
72 "orgs: {} not saved: {error}",
73 app_base::orgs::ORGS_FILE
74 ));
55 75 }
56 76 matches!(saved, Some(Ok(())))
57 77 }
58 78 }
79
80 /// The process's own flags without an earlier open target, plus the chat to open now.
81 fn restart_arguments(
82 current: impl Iterator<Item = std::ffi::OsString>,
83 open_conversation: Option<&str>,
84 ) -> Vec<std::ffi::OsString> {
85 let mut arguments = Vec::new();
86 let mut current = current;
87 while let Some(argument) = current.next() {
88 if argument == OPEN_CONVERSATION_FLAG {
89 current.next();
90 continue;
91 }
92 arguments.push(argument);
93 }
94 if let Some(conversation_id) = open_conversation {
95 arguments.push(OPEN_CONVERSATION_FLAG.into());
96 arguments.push(conversation_id.into());
97 }
98 arguments
99 }
100
101 #[cfg(test)]
102 mod tests {
103 use super::*;
104
105 #[test]
106 fn a_restart_keeps_the_flags_and_replaces_the_open_target() {
107 let current = ["--endpoint", "x", OPEN_CONVERSATION_FLAG, "19:old"].map(Into::into);
108 assert_eq!(
109 restart_arguments(current.into_iter(), Some("19:new")),
110 ["--endpoint", "x", OPEN_CONVERSATION_FLAG, "19:new"].map(std::ffi::OsString::from)
111 );
112 }
113 }
@@ -1,4 +1,4 @@
1use app_base::orgs::{Org, Orgs};
1use app_base::orgs::{OPEN_CONVERSATION_FLAG, Org, Orgs};
2use gpui_kit::Context;
2use gpui_kit::Context;
3
3
4use crate::app_state::AppState;
4use crate::app_state::AppState;
@@ -21,8 +21,19 @@ impl AppState {
21 }
21 }
22 }
22 }
23
23
24 /// Chats with new messages in `org` since this window opened; zero for the open org.
25 pub fn org_unread_count(&self, org: &Org) -> usize {
26 self.org_unread.get(&org.id).map_or(0, |chats| chats.len())
27 }
28
24 /// Restarts the app on `org`: its own cache opens at once and the backend signs in to its tenant.
29 /// Restarts the app on `org`: its own cache opens at once and the backend signs in to its tenant.
25 pub fn switch_org(&mut self, org: &Org, cx: &mut Context<Self>) {
30 /// `open_conversation` opens that chat once the org has loaded.
31 pub fn switch_org(
32 &mut self,
33 org: &Org,
34 open_conversation: Option<&str>,
35 cx: &mut Context<Self>,
36 ) {
26 if self.orgs.is_active(org) {
37 if self.orgs.is_active(org) {
27 return;
38 return;
28 }
39 }
@@ -34,8 +45,14 @@ impl AppState {
34 self.orgs = next;
45 self.orgs = next;
35 match std::env::current_exe().and_then(|exe| {
46 match std::env::current_exe().and_then(|exe| {
36 std::process::Command::new(exe)
47 std::process::Command::new(exe)
37 .args(std::env::args_os().skip(1))
48 .args(restart_arguments(
38 .env(app_base::updater::RELAUNCH_ENV, std::process::id().to_string())
49 std::env::args_os().skip(1),
50 open_conversation,
51 ))
52 .env(
53 app_base::updater::RELAUNCH_ENV,
54 std::process::id().to_string(),
55 )
39 .spawn()
56 .spawn()
40 }) {
57 }) {
41 Ok(_) => cx.quit(),
58 Ok(_) => cx.quit(),
@@ -51,8 +68,46 @@ impl AppState {
51 }
68 }
52 let saved = Orgs::path().map(|path| orgs.save(&path));
69 let saved = Orgs::path().map(|path| orgs.save(&path));
53 if let Some(Err(error)) = &saved {
70 if let Some(Err(error)) = &saved {
54 crate::diagnostics::record(format!("orgs: {} not saved: {error}", app_base::orgs::ORGS_FILE));
71 crate::diagnostics::record(format!(
72 "orgs: {} not saved: {error}",
73 app_base::orgs::ORGS_FILE
74 ));
55 }
75 }
56 matches!(saved, Some(Ok(())))
76 matches!(saved, Some(Ok(())))
57 }
77 }
58}
78}
79
80/// The process's own flags without an earlier open target, plus the chat to open now.
81fn restart_arguments(
82 current: impl Iterator<Item = std::ffi::OsString>,
83 open_conversation: Option<&str>,
84) -> Vec<std::ffi::OsString> {
85 let mut arguments = Vec::new();
86 let mut current = current;
87 while let Some(argument) = current.next() {
88 if argument == OPEN_CONVERSATION_FLAG {
89 current.next();
90 continue;
91 }
92 arguments.push(argument);
93 }
94 if let Some(conversation_id) = open_conversation {
95 arguments.push(OPEN_CONVERSATION_FLAG.into());
96 arguments.push(conversation_id.into());
97 }
98 arguments
99}
100
101#[cfg(test)]
102mod tests {
103 use super::*;
104
105 #[test]
106 fn a_restart_keeps_the_flags_and_replaces_the_open_target() {
107 let current = ["--endpoint", "x", OPEN_CONVERSATION_FLAG, "19:old"].map(Into::into);
108 assert_eq!(
109 restart_arguments(current.into_iter(), Some("19:new")),
110 ["--endpoint", "x", OPEN_CONVERSATION_FLAG, "19:new"].map(std::ffi::OsString::from)
111 );
112 }
113}
crates/app-state/src/org_watch.rs added +193 −0
@@ -0,0 +1,193 @@
1 //! Keeps an org that is not open in the window live for notifications, like Teams does for other orgs:
2 //! its own realtime socket, and a toast for every new chat message from someone else.
3 use std::collections::HashMap;
4 use std::time::Duration;
5
6 use app_base::orgs::Org;
7 use chatsvc::{ChatListing, Conversations, EventKind, Realtime, RealtimeConfig, RealtimeEvent};
8 use serde_json::Value;
9 use session::Session;
10 use tokio::sync::mpsc;
11
12 use crate::backend::BackendEvent;
13
14 const RETRY: Duration = Duration::from_secs(30);
15 const PREVIEW_CHARS: usize = 200;
16 /// Chats only, like the default Teams settings for other orgs; channel posts and system threads stay quiet.
17 const CHANNEL_SUFFIX: &str = "@thread.tacv2";
18 const SYSTEM_PREFIX: &str = "48:";
19 const MESSAGE_TYPES: [&str; 2] = ["RichText/Html", "Text"];
20
21 #[derive(Debug, Clone, PartialEq, Eq)]
22 pub struct OrgMessage {
23 pub org: Org,
24 pub conversation_id: String,
25 pub message_id: String,
26 pub chat_title: String,
27 pub sender_name: String,
28 pub preview: String,
29 pub direct: bool,
30 }
31
32 pub(crate) async fn watch(
33 session: Session,
34 org: Org,
35 me: Option<String>,
36 events: mpsc::UnboundedSender<BackendEvent>,
37 ) {
38 let listing = ChatListing::new(&session);
39 let conversations = Conversations::new(&session);
40 let mut muted: HashMap<String, bool> = HashMap::new();
41 loop {
42 match Realtime::start_with(&session, RealtimeConfig::default()).await {
43 Ok(mut realtime) => {
44 while let Some(event) = realtime.recv().await {
45 let RealtimeEvent::Message(event) = event else {
46 continue;
47 };
48 let (EventKind::NewMessage, Some(conversation_id), Some(message_id)) =
49 (event.kind, event.conversation_id, event.message_id)
50 else {
51 continue;
52 };
53 if !is_chat(&conversation_id) {
54 continue;
55 }
56 if !muted.contains_key(&conversation_id)
57 && let Ok(states) = conversations.conversation_states().await
58 {
59 muted.extend(states.into_iter().map(|state| (state.id, state.muted)));
60 }
61 if muted.get(&conversation_id).copied().unwrap_or(false) {
62 continue;
63 }
64 let Ok(message) = listing.message(&conversation_id, &message_id).await else {
65 continue;
66 };
67 let conversation = listing.conversation(&conversation_id).await.ok();
68 let parsed = org_message(
69 &org,
70 me.as_deref(),
71 &conversation_id,
72 &message_id,
73 &message,
74 conversation.as_ref(),
75 );
76 if let Some(parsed) = parsed
77 && events.send(BackendEvent::OrgMessage(parsed)).is_err()
78 {
79 return;
80 }
81 }
82 }
83 Err(error) => crate::diagnostics::record(format!(
84 "orgs: live updates for another org failed: {error}"
85 )),
86 }
87 tokio::time::sleep(RETRY).await;
88 }
89 }
90
91 fn is_chat(conversation_id: &str) -> bool {
92 !conversation_id.starts_with(SYSTEM_PREFIX) && !conversation_id.ends_with(CHANNEL_SUFFIX)
93 }
94
95 fn org_message(
96 org: &Org,
97 me: Option<&str>,
98 conversation_id: &str,
99 message_id: &str,
100 message: &Value,
101 conversation: Option<&Value>,
102 ) -> Option<OrgMessage> {
103 let message_type = message["messagetype"].as_str()?;
104 if !MESSAGE_TYPES.contains(&message_type) {
105 return None;
106 }
107 let from = message["from"]
108 .as_str()
109 .unwrap_or_default()
110 .to_ascii_lowercase();
111 if me.is_some_and(|me| from.ends_with(me)) {
112 return None;
113 }
114 let sender_name = message["imdisplayname"]
115 .as_str()
116 .unwrap_or_default()
117 .to_owned();
118 let text = store::plain_text(message["content"].as_str().unwrap_or_default());
119 let preview: String = text.trim().chars().take(PREVIEW_CHARS).collect();
120 if preview.is_empty() {
121 return None;
122 }
123 let properties = conversation.map(|conversation| &conversation["threadProperties"]);
124 let topic = properties
125 .and_then(|properties| properties["topic"].as_str())
126 .map(str::trim)
127 .filter(|topic| !topic.is_empty());
128 let direct = properties
129 .and_then(|properties| properties["uniquerosterthread"].as_str())
130 .is_some_and(|flag| flag == "true")
131 || conversation_id.ends_with("@unq.gbl.spaces");
132 Some(OrgMessage {
133 org: org.clone(),
134 conversation_id: conversation_id.to_owned(),
135 message_id: message_id.to_owned(),
136 chat_title: topic.unwrap_or(&sender_name).to_owned(),
137 sender_name,
138 preview,
139 direct,
140 })
141 }
142
143 #[cfg(test)]
144 mod tests {
145 use super::*;
146 use serde_json::json;
147
148 fn org() -> Org {
149 Org {
150 id: "bbbb".into(),
151 name: "Guest Org".into(),
152 guest: true,
153 }
154 }
155
156 fn message(from: &str, kind: &str, content: &str) -> Value {
157 json!({"messagetype": kind, "from": format!("https://x/v1/users/ME/contacts/8:orgid:{from}"), "imdisplayname": "Ann Example", "content": content})
158 }
159
160 #[test]
161 fn a_chat_message_from_someone_else_becomes_a_toast_with_the_topic() {
162 let parsed = org_message(
163 &org(),
164 Some("me-1"),
165 "19:abc@thread.v2",
166 "1",
167 &message("ann-2", "RichText/Html", "<p>Hello <b>there</b></p>"),
168 Some(&json!({"threadProperties": {"topic": "Release"}})),
169 )
170 .unwrap();
171 assert_eq!(parsed.chat_title, "Release");
172 assert_eq!(parsed.sender_name, "Ann Example");
173 assert!(parsed.preview.starts_with("Hello"));
174 assert!(!parsed.direct);
175 }
176
177 #[test]
178 fn own_messages_control_messages_and_channels_stay_quiet() {
179 let own = message("ME-1", "RichText/Html", "hi");
180 assert_eq!(
181 org_message(&org(), Some("me-1"), "19:a@thread.v2", "1", &own, None),
182 None
183 );
184 let control = message("ann-2", "ThreadActivity/AddMember", "x");
185 assert_eq!(
186 org_message(&org(), Some("me-1"), "19:a@thread.v2", "1", &control, None),
187 None
188 );
189 assert!(!is_chat("19:general@thread.tacv2"));
190 assert!(!is_chat("48:notifications"));
191 assert!(is_chat("19:a_b@unq.gbl.spaces"));
192 }
193 }
@@ -0,0 +1,193 @@
1//! Keeps an org that is not open in the window live for notifications, like Teams does for other orgs:
2//! its own realtime socket, and a toast for every new chat message from someone else.
3use std::collections::HashMap;
4use std::time::Duration;
5
6use app_base::orgs::Org;
7use chatsvc::{ChatListing, Conversations, EventKind, Realtime, RealtimeConfig, RealtimeEvent};
8use serde_json::Value;
9use session::Session;
10use tokio::sync::mpsc;
11
12use crate::backend::BackendEvent;
13
14const RETRY: Duration = Duration::from_secs(30);
15const PREVIEW_CHARS: usize = 200;
16/// Chats only, like the default Teams settings for other orgs; channel posts and system threads stay quiet.
17const CHANNEL_SUFFIX: &str = "@thread.tacv2";
18const SYSTEM_PREFIX: &str = "48:";
19const MESSAGE_TYPES: [&str; 2] = ["RichText/Html", "Text"];
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct OrgMessage {
23 pub org: Org,
24 pub conversation_id: String,
25 pub message_id: String,
26 pub chat_title: String,
27 pub sender_name: String,
28 pub preview: String,
29 pub direct: bool,
30}
31
32pub(crate) async fn watch(
33 session: Session,
34 org: Org,
35 me: Option<String>,
36 events: mpsc::UnboundedSender<BackendEvent>,
37) {
38 let listing = ChatListing::new(&session);
39 let conversations = Conversations::new(&session);
40 let mut muted: HashMap<String, bool> = HashMap::new();
41 loop {
42 match Realtime::start_with(&session, RealtimeConfig::default()).await {
43 Ok(mut realtime) => {
44 while let Some(event) = realtime.recv().await {
45 let RealtimeEvent::Message(event) = event else {
46 continue;
47 };
48 let (EventKind::NewMessage, Some(conversation_id), Some(message_id)) =
49 (event.kind, event.conversation_id, event.message_id)
50 else {
51 continue;
52 };
53 if !is_chat(&conversation_id) {
54 continue;
55 }
56 if !muted.contains_key(&conversation_id)
57 && let Ok(states) = conversations.conversation_states().await
58 {
59 muted.extend(states.into_iter().map(|state| (state.id, state.muted)));
60 }
61 if muted.get(&conversation_id).copied().unwrap_or(false) {
62 continue;
63 }
64 let Ok(message) = listing.message(&conversation_id, &message_id).await else {
65 continue;
66 };
67 let conversation = listing.conversation(&conversation_id).await.ok();
68 let parsed = org_message(
69 &org,
70 me.as_deref(),
71 &conversation_id,
72 &message_id,
73 &message,
74 conversation.as_ref(),
75 );
76 if let Some(parsed) = parsed
77 && events.send(BackendEvent::OrgMessage(parsed)).is_err()
78 {
79 return;
80 }
81 }
82 }
83 Err(error) => crate::diagnostics::record(format!(
84 "orgs: live updates for another org failed: {error}"
85 )),
86 }
87 tokio::time::sleep(RETRY).await;
88 }
89}
90
91fn is_chat(conversation_id: &str) -> bool {
92 !conversation_id.starts_with(SYSTEM_PREFIX) && !conversation_id.ends_with(CHANNEL_SUFFIX)
93}
94
95fn org_message(
96 org: &Org,
97 me: Option<&str>,
98 conversation_id: &str,
99 message_id: &str,
100 message: &Value,
101 conversation: Option<&Value>,
102) -> Option<OrgMessage> {
103 let message_type = message["messagetype"].as_str()?;
104 if !MESSAGE_TYPES.contains(&message_type) {
105 return None;
106 }
107 let from = message["from"]
108 .as_str()
109 .unwrap_or_default()
110 .to_ascii_lowercase();
111 if me.is_some_and(|me| from.ends_with(me)) {
112 return None;
113 }
114 let sender_name = message["imdisplayname"]
115 .as_str()
116 .unwrap_or_default()
117 .to_owned();
118 let text = store::plain_text(message["content"].as_str().unwrap_or_default());
119 let preview: String = text.trim().chars().take(PREVIEW_CHARS).collect();
120 if preview.is_empty() {
121 return None;
122 }
123 let properties = conversation.map(|conversation| &conversation["threadProperties"]);
124 let topic = properties
125 .and_then(|properties| properties["topic"].as_str())
126 .map(str::trim)
127 .filter(|topic| !topic.is_empty());
128 let direct = properties
129 .and_then(|properties| properties["uniquerosterthread"].as_str())
130 .is_some_and(|flag| flag == "true")
131 || conversation_id.ends_with("@unq.gbl.spaces");
132 Some(OrgMessage {
133 org: org.clone(),
134 conversation_id: conversation_id.to_owned(),
135 message_id: message_id.to_owned(),
136 chat_title: topic.unwrap_or(&sender_name).to_owned(),
137 sender_name,
138 preview,
139 direct,
140 })
141}
142
143#[cfg(test)]
144mod tests {
145 use super::*;
146 use serde_json::json;
147
148 fn org() -> Org {
149 Org {
150 id: "bbbb".into(),
151 name: "Guest Org".into(),
152 guest: true,
153 }
154 }
155
156 fn message(from: &str, kind: &str, content: &str) -> Value {
157 json!({"messagetype": kind, "from": format!("https://x/v1/users/ME/contacts/8:orgid:{from}"), "imdisplayname": "Ann Example", "content": content})
158 }
159
160 #[test]
161 fn a_chat_message_from_someone_else_becomes_a_toast_with_the_topic() {
162 let parsed = org_message(
163 &org(),
164 Some("me-1"),
165 "19:abc@thread.v2",
166 "1",
167 &message("ann-2", "RichText/Html", "<p>Hello <b>there</b></p>"),
168 Some(&json!({"threadProperties": {"topic": "Release"}})),
169 )
170 .unwrap();
171 assert_eq!(parsed.chat_title, "Release");
172 assert_eq!(parsed.sender_name, "Ann Example");
173 assert!(parsed.preview.starts_with("Hello"));
174 assert!(!parsed.direct);
175 }
176
177 #[test]
178 fn own_messages_control_messages_and_channels_stay_quiet() {
179 let own = message("ME-1", "RichText/Html", "hi");
180 assert_eq!(
181 org_message(&org(), Some("me-1"), "19:a@thread.v2", "1", &own, None),
182 None
183 );
184 let control = message("ann-2", "ThreadActivity/AddMember", "x");
185 assert_eq!(
186 org_message(&org(), Some("me-1"), "19:a@thread.v2", "1", &control, None),
187 None
188 );
189 assert!(!is_chat("19:general@thread.tacv2"));
190 assert!(!is_chat("48:notifications"));
191 assert!(is_chat("19:a_b@unq.gbl.spaces"));
192 }
193}
crates/app/src/main.rs +3 −0
@@ -107,6 +107,9 @@ fn parse_arguments() -> Arguments {
107 107 .and_then(|value| value.parse().ok())
108 108 .map(OpenTarget::Chat)
109 109 }
110 app_base::orgs::OPEN_CONVERSATION_FLAG => {
111 arguments.open_target = input.next().map(OpenTarget::Conversation)
112 }
110 113 "--open-channel" => {
111 114 arguments.open_target = input
112 115 .next()
@@ -107,6 +107,9 @@ fn parse_arguments() -> Arguments {
107 .and_then(|value| value.parse().ok())
107 .and_then(|value| value.parse().ok())
108 .map(OpenTarget::Chat)
108 .map(OpenTarget::Chat)
109 }
109 }
110 app_base::orgs::OPEN_CONVERSATION_FLAG => {
111 arguments.open_target = input.next().map(OpenTarget::Conversation)
112 }
110 "--open-channel" => {
113 "--open-channel" => {
111 arguments.open_target = input
114 arguments.open_target = input
112 .next()
115 .next()
crates/app/src/notify/center.rs +31 −0
@@ -39,6 +39,7 @@ use crate::appearance::AppIcon;
39 39 use crate::autostart::{self, StartupSettings};
40 40 use crate::call::DemoScene;
41 41 use crate::data::{self, Directory, PresenceKind};
42 use crate::org_watch::OrgMessage;
42 43 use crate::runtime;
43 44 use crate::settings_section::SettingsSection;
44 45 use crate::single_instance;
@@ -432,6 +433,7 @@ impl NotificationCenter {
432 433 AppEvent::Call => self.sync_call_sounds(cx),
433 434 AppEvent::SoundSettings => self.on_account_sounds(cx),
434 435 AppEvent::ChatSettings => self.on_account_notifications(cx),
436 AppEvent::OrgMessage(message) => self.present_org_message(message, cx),
435 437 AppEvent::FollowedStatus { user_id, text } => {
436 438 self.present_status_change(user_id, text, cx)
437 439 }
@@ -573,6 +575,24 @@ impl NotificationCenter {
573 575 )
574 576 }
575 577
578 fn present_org_message(&mut self, message: &OrgMessage, cx: &mut Context<Self>) {
579 let decision = self.own_feature_decision(cx);
580 if !decision.toast {
581 return;
582 }
583 let now = Instant::now();
584 let id = self.stack.push_org_message(message, now);
585 if let Some(model) = self.stack.get_mut(id) {
586 model.time = chrono::Local::now()
587 .format(crate::format::clock_format())
588 .to_string();
589 }
590 if decision.sound && self.throttle.allow(&message.conversation_id, now) {
591 self.play_notification_sound(cx);
592 }
593 self.sync_windows(cx);
594 }
595
576 596 fn present_status_change(&mut self, user_id: &str, text: &str, cx: &mut Context<Self>) {
577 597 if !self.own_feature_decision(cx).toast {
578 598 return;
@@ -1425,6 +1445,17 @@ impl NotificationCenter {
1425 1445 if self.is_dismissed(id) {
1426 1446 return;
1427 1447 }
1448 if let Some((org, conversation_id)) = self
1449 .stack
1450 .get(id)
1451 .and_then(|toast| Some((toast.org.clone()?, toast.conversation_id.clone())))
1452 {
1453 self.drop_toast(id, cx);
1454 self.app.update(cx, |state, cx| {
1455 state.switch_org(&org, Some(&conversation_id), cx)
1456 });
1457 return;
1458 }
1428 1459 let Some((conversation_id, message_id, proposal_id)) = self.stack.get(id).map(|toast| {
1429 1460 (
1430 1461 toast.conversation_id.clone(),
@@ -39,6 +39,7 @@ use crate::appearance::AppIcon;
39use crate::autostart::{self, StartupSettings};
39use crate::autostart::{self, StartupSettings};
40use crate::call::DemoScene;
40use crate::call::DemoScene;
41use crate::data::{self, Directory, PresenceKind};
41use crate::data::{self, Directory, PresenceKind};
42use crate::org_watch::OrgMessage;
42use crate::runtime;
43use crate::runtime;
43use crate::settings_section::SettingsSection;
44use crate::settings_section::SettingsSection;
44use crate::single_instance;
45use crate::single_instance;
@@ -432,6 +433,7 @@ impl NotificationCenter {
432 AppEvent::Call => self.sync_call_sounds(cx),
433 AppEvent::Call => self.sync_call_sounds(cx),
433 AppEvent::SoundSettings => self.on_account_sounds(cx),
434 AppEvent::SoundSettings => self.on_account_sounds(cx),
434 AppEvent::ChatSettings => self.on_account_notifications(cx),
435 AppEvent::ChatSettings => self.on_account_notifications(cx),
436 AppEvent::OrgMessage(message) => self.present_org_message(message, cx),
435 AppEvent::FollowedStatus { user_id, text } => {
437 AppEvent::FollowedStatus { user_id, text } => {
436 self.present_status_change(user_id, text, cx)
438 self.present_status_change(user_id, text, cx)
437 }
439 }
@@ -573,6 +575,24 @@ impl NotificationCenter {
573 )
575 )
574 }
576 }
575
577
578 fn present_org_message(&mut self, message: &OrgMessage, cx: &mut Context<Self>) {
579 let decision = self.own_feature_decision(cx);
580 if !decision.toast {
581 return;
582 }
583 let now = Instant::now();
584 let id = self.stack.push_org_message(message, now);
585 if let Some(model) = self.stack.get_mut(id) {
586 model.time = chrono::Local::now()
587 .format(crate::format::clock_format())
588 .to_string();
589 }
590 if decision.sound && self.throttle.allow(&message.conversation_id, now) {
591 self.play_notification_sound(cx);
592 }
593 self.sync_windows(cx);
594 }
595
576 fn present_status_change(&mut self, user_id: &str, text: &str, cx: &mut Context<Self>) {
596 fn present_status_change(&mut self, user_id: &str, text: &str, cx: &mut Context<Self>) {
577 if !self.own_feature_decision(cx).toast {
597 if !self.own_feature_decision(cx).toast {
578 return;
598 return;
@@ -1425,6 +1445,17 @@ impl NotificationCenter {
1425 if self.is_dismissed(id) {
1445 if self.is_dismissed(id) {
1426 return;
1446 return;
1427 }
1447 }
1448 if let Some((org, conversation_id)) = self
1449 .stack
1450 .get(id)
1451 .and_then(|toast| Some((toast.org.clone()?, toast.conversation_id.clone())))
1452 {
1453 self.drop_toast(id, cx);
1454 self.app.update(cx, |state, cx| {
1455 state.switch_org(&org, Some(&conversation_id), cx)
1456 });
1457 return;
1458 }
1428 let Some((conversation_id, message_id, proposal_id)) = self.stack.get(id).map(|toast| {
1459 let Some((conversation_id, message_id, proposal_id)) = self.stack.get(id).map(|toast| {
1429 (
1460 (
1430 toast.conversation_id.clone(),
1461 toast.conversation_id.clone(),
crates/app/src/notify/toast.rs +1 −1
@@ -537,7 +537,7 @@ impl Render for ToastView {
537 537 .child(self.avatar(&model, fill, cx))
538 538 .child(self.body(&model, &text, hovered)),
539 539 )
540 .when(!model.status_change, |content| {
540 .when(!model.status_change && model.org.is_none(), |content| {
541 541 content.child(self.action_row(mention, cx))
542 542 }),
543 543 };
@@ -537,7 +537,7 @@ impl Render for ToastView {
537 .child(self.avatar(&model, fill, cx))
537 .child(self.avatar(&model, fill, cx))
538 .child(self.body(&model, &text, hovered)),
538 .child(self.body(&model, &text, hovered)),
539 )
539 )
540 .when(!model.status_change, |content| {
540 .when(!model.status_change && model.org.is_none(), |content| {
541 content.child(self.action_row(mention, cx))
541 content.child(self.action_row(mention, cx))
542 }),
542 }),
543 };
543 };
crates/app/src/views/conversation.rs +1 −0
@@ -776,6 +776,7 @@ impl ConversationView {
776 776 | AppEvent::CallTone(_)
777 777 | AppEvent::SoundSettings
778 778 | AppEvent::FollowedStatus { .. }
779 | AppEvent::OrgMessage(_)
779 780 | AppEvent::Call => {}
780 781 AppEvent::LiveMeeting => cx.notify(),
781 782 AppEvent::Saved => cx.notify(),
@@ -776,6 +776,7 @@ impl ConversationView {
776 | AppEvent::CallTone(_)
776 | AppEvent::CallTone(_)
777 | AppEvent::SoundSettings
777 | AppEvent::SoundSettings
778 | AppEvent::FollowedStatus { .. }
778 | AppEvent::FollowedStatus { .. }
779 | AppEvent::OrgMessage(_)
779 | AppEvent::Call => {}
780 | AppEvent::Call => {}
780 AppEvent::LiveMeeting => cx.notify(),
781 AppEvent::LiveMeeting => cx.notify(),
781 AppEvent::Saved => cx.notify(),
782 AppEvent::Saved => cx.notify(),
crates/app/src/views/shell.rs +7 −4
@@ -69,10 +69,12 @@ pub fn bind_keys(cx: &mut App) {
69 69 );
70 70 }
71 71
72 #[derive(Debug, Clone, Copy)]
72 #[derive(Debug, Clone)]
73 73 pub enum OpenTarget {
74 74 Chat(usize),
75 75 Channel(usize),
76 /// A chat or channel by id; waits until a sync has brought it into the sidebar.
77 Conversation(String),
76 78 }
77 79
78 80 #[derive(Default)]
@@ -590,21 +592,22 @@ impl AppShell {
590 592 }
591 593
592 594 fn apply_open_target(&mut self, cx: &mut Context<Self>) {
593 let Some(target) = self.open_target else {
595 let Some(target) = &self.open_target else {
594 596 return;
595 597 };
596 598 let sidebar = &self.state.read(cx).sidebar;
597 599 let selection = match target {
598 600 OpenTarget::Chat(index) => sidebar
599 601 .chats
600 .get(index)
602 .get(*index)
601 603 .map(|chat| Selection::Chat(chat.id.clone())),
602 604 OpenTarget::Channel(index) => sidebar
603 605 .teams
604 606 .iter()
605 607 .flat_map(|team| team.channels.iter())
606 .nth(index)
608 .nth(*index)
607 609 .map(|channel| Selection::Channel(channel.id.clone())),
610 OpenTarget::Conversation(id) => crate::app_state::selection_for(sidebar, id),
608 611 };
609 612 if let Some(selection) = selection {
610 613 self.open_target = None;
@@ -69,10 +69,12 @@ pub fn bind_keys(cx: &mut App) {
69 );
69 );
70}
70}
71
71
72#[derive(Debug, Clone, Copy)]
72#[derive(Debug, Clone)]
73pub enum OpenTarget {
73pub enum OpenTarget {
74 Chat(usize),
74 Chat(usize),
75 Channel(usize),
75 Channel(usize),
76 /// A chat or channel by id; waits until a sync has brought it into the sidebar.
77 Conversation(String),
76}
78}
77
79
78#[derive(Default)]
80#[derive(Default)]
@@ -590,21 +592,22 @@ impl AppShell {
590 }
592 }
591
593
592 fn apply_open_target(&mut self, cx: &mut Context<Self>) {
594 fn apply_open_target(&mut self, cx: &mut Context<Self>) {
593 let Some(target) = self.open_target else {
595 let Some(target) = &self.open_target else {
594 return;
596 return;
595 };
597 };
596 let sidebar = &self.state.read(cx).sidebar;
598 let sidebar = &self.state.read(cx).sidebar;
597 let selection = match target {
599 let selection = match target {
598 OpenTarget::Chat(index) => sidebar
600 OpenTarget::Chat(index) => sidebar
599 .chats
601 .chats
600 .get(index)
602 .get(*index)
601 .map(|chat| Selection::Chat(chat.id.clone())),
603 .map(|chat| Selection::Chat(chat.id.clone())),
602 OpenTarget::Channel(index) => sidebar
604 OpenTarget::Channel(index) => sidebar
603 .teams
605 .teams
604 .iter()
606 .iter()
605 .flat_map(|team| team.channels.iter())
607 .flat_map(|team| team.channels.iter())
606 .nth(index)
608 .nth(*index)
607 .map(|channel| Selection::Channel(channel.id.clone())),
609 .map(|channel| Selection::Channel(channel.id.clone())),
610 OpenTarget::Conversation(id) => crate::app_state::selection_for(sidebar, id),
608 };
611 };
609 if let Some(selection) = selection {
612 if let Some(selection) = selection {
610 self.open_target = None;
613 self.open_target = None;
crates/app/src/views/status_menu.rs +32 −14
@@ -7,11 +7,12 @@ use gpui_kit::component::{
7 7 menu::{DropdownMenu as _, PopupMenu, PopupMenuItem},
8 8 v_flex,
9 9 };
10 use gpui_kit::prelude::FluentBuilder as _;
10 11 use gpui_kit::*;
11 12 use teams_core::{ForcedAvailability, ForcedKind, PresenceStatus, WorkLocationKind};
12 13
13 14 use super::avatar::{person_avatar, status_glyph, with_presence, with_presence_badge};
14 use super::widgets::{menu_icon, symbol};
15 use super::widgets::{count_badge, menu_icon, symbol};
15 16 use crate::app_state::AppState;
16 17 use crate::data::{Person, PresenceKind};
17 18 use crate::i18n::tr;
@@ -220,31 +221,48 @@ fn status_menu(
220 221 )
221 222 }
222 223
223 /// One row per organization of the account, the open one checked; picking another restarts on it.
224 /// One row per organization of the account, the open one checked and the others with their
225 /// count of chats with new messages; picking another org restarts on it.
224 226 fn org_items(popup: PopupMenu, app: &Entity<AppState>, cx: &mut Context<PopupMenu>) -> PopupMenu {
225 227 let state = app.read(cx);
226 228 let rows: Vec<_> = state
227 229 .switchable_orgs()
228 230 .iter()
229 .map(|org| (org.clone(), state.orgs.is_active(org)))
230 .collect();
231 if rows.is_empty() {
232 return popup;
233 }
234 rows.into_iter()
235 .fold(popup, |popup, (org, active)| {
231 .map(|org| {
236 232 let label = if org.guest {
237 233 tr("status_menu.guest_org").replace("%{name}", &org.name)
238 234 } else {
239 235 org.name.clone()
240 236 };
237 (
238 org.clone(),
239 label,
240 state.orgs.is_active(org),
241 state.org_unread_count(org),
242 )
243 })
244 .collect();
245 if rows.is_empty() {
246 return popup;
247 }
248 rows.into_iter()
249 .fold(popup, |popup, (org, label, active, unread)| {
241 250 let app = app.clone();
242 251 popup.item(
243 PopupMenuItem::new(label)
244 .checked(active)
245 .on_click(move |_, _, cx| {
246 app.update(cx, |state, cx| state.switch_org(&org, cx));
247 }),
252 PopupMenuItem::element(move |_, _| {
253 h_flex()
254 .w_full()
255 .gap(px(8.))
256 .items_center()
257 .child(div().flex_1().min_w_0().truncate().child(label.clone()))
258 .when(unread > 0, |row| {
259 row.child(count_badge(unread.min(u32::MAX as usize) as u32, false))
260 })
261 })
262 .checked(active)
263 .on_click(move |_, _, cx| {
264 app.update(cx, |state, cx| state.switch_org(&org, None, cx));
265 }),
248 266 )
249 267 })
250 268 .separator()
@@ -7,11 +7,12 @@ use gpui_kit::component::{
7 menu::{DropdownMenu as _, PopupMenu, PopupMenuItem},
7 menu::{DropdownMenu as _, PopupMenu, PopupMenuItem},
8 v_flex,
8 v_flex,
9};
9};
10use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::*;
11use gpui_kit::*;
11use teams_core::{ForcedAvailability, ForcedKind, PresenceStatus, WorkLocationKind};
12use teams_core::{ForcedAvailability, ForcedKind, PresenceStatus, WorkLocationKind};
12
13
13use super::avatar::{person_avatar, status_glyph, with_presence, with_presence_badge};
14use super::avatar::{person_avatar, status_glyph, with_presence, with_presence_badge};
14use super::widgets::{menu_icon, symbol};
15use super::widgets::{count_badge, menu_icon, symbol};
15use crate::app_state::AppState;
16use crate::app_state::AppState;
16use crate::data::{Person, PresenceKind};
17use crate::data::{Person, PresenceKind};
17use crate::i18n::tr;
18use crate::i18n::tr;
@@ -220,31 +221,48 @@ fn status_menu(
220 )
221 )
221}
222}
222
223
223/// One row per organization of the account, the open one checked; picking another restarts on it.
224/// One row per organization of the account, the open one checked and the others with their
225/// count of chats with new messages; picking another org restarts on it.
224fn org_items(popup: PopupMenu, app: &Entity<AppState>, cx: &mut Context<PopupMenu>) -> PopupMenu {
226fn org_items(popup: PopupMenu, app: &Entity<AppState>, cx: &mut Context<PopupMenu>) -> PopupMenu {
225 let state = app.read(cx);
227 let state = app.read(cx);
226 let rows: Vec<_> = state
228 let rows: Vec<_> = state
227 .switchable_orgs()
229 .switchable_orgs()
228 .iter()
230 .iter()
229 .map(|org| (org.clone(), state.orgs.is_active(org)))
231 .map(|org| {
230 .collect();
231 if rows.is_empty() {
232 return popup;
233 }
234 rows.into_iter()
235 .fold(popup, |popup, (org, active)| {
236 let label = if org.guest {
232 let label = if org.guest {
237 tr("status_menu.guest_org").replace("%{name}", &org.name)
233 tr("status_menu.guest_org").replace("%{name}", &org.name)
238 } else {
234 } else {
239 org.name.clone()
235 org.name.clone()
240 };
236 };
237 (
238 org.clone(),
239 label,
240 state.orgs.is_active(org),
241 state.org_unread_count(org),
242 )
243 })
244 .collect();
245 if rows.is_empty() {
246 return popup;
247 }
248 rows.into_iter()
249 .fold(popup, |popup, (org, label, active, unread)| {
241 let app = app.clone();
250 let app = app.clone();
242 popup.item(
251 popup.item(
243 PopupMenuItem::new(label)
252 PopupMenuItem::element(move |_, _| {
244 .checked(active)
253 h_flex()
245 .on_click(move |_, _, cx| {
254 .w_full()
246 app.update(cx, |state, cx| state.switch_org(&org, cx));
255 .gap(px(8.))
247 }),
256 .items_center()
257 .child(div().flex_1().min_w_0().truncate().child(label.clone()))
258 .when(unread > 0, |row| {
259 row.child(count_badge(unread.min(u32::MAX as usize) as u32, false))
260 })
261 })
262 .checked(active)
263 .on_click(move |_, _, cx| {
264 app.update(cx, |state, cx| state.switch_org(&org, None, cx));
265 }),
248 )
266 )
249 })
267 })
250 .separator()
268 .separator()
crates/chatsvc/src/lib.rs +1 −1
@@ -82,7 +82,6 @@ pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, use
82 82 pub use error::{Error, Result};
83 83 pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
84 84 pub use gifs::{Gif, Gifs};
85 pub use tenants::{Tenant, list_tenants};
86 85 pub use google_calendar::{
87 86 AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,
88 87 client_id_from_env, exchange_code, google_event_body, google_rsvp_query, google_rsvp_status,
@@ -138,6 +137,7 @@ pub use substrate_search::{
138 137 pub use team_admin::{
139 138 ChannelEdit, ChannelPrivacy, ExistingChannel, Mailbox, NewChannel, TeamAdmin,
140 139 };
140 pub use tenants::{Tenant, list_tenants};
141 141 pub use thread_activity::{ThreadActivity, ThreadActivityKind};
142 142 pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};
143 143 pub use translate::{
@@ -82,7 +82,6 @@ pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, use
82pub use error::{Error, Result};
82pub use error::{Error, Result};
83pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
83pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
84pub use gifs::{Gif, Gifs};
84pub use gifs::{Gif, Gifs};
85pub use tenants::{Tenant, list_tenants};
86pub use google_calendar::{
85pub use google_calendar::{
87 AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,
86 AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,
88 client_id_from_env, exchange_code, google_event_body, google_rsvp_query, google_rsvp_status,
87 client_id_from_env, exchange_code, google_event_body, google_rsvp_query, google_rsvp_status,
@@ -138,6 +137,7 @@ pub use substrate_search::{
138pub use team_admin::{
137pub use team_admin::{
139 ChannelEdit, ChannelPrivacy, ExistingChannel, Mailbox, NewChannel, TeamAdmin,
138 ChannelEdit, ChannelPrivacy, ExistingChannel, Mailbox, NewChannel, TeamAdmin,
140};
139};
140pub use tenants::{Tenant, list_tenants};
141pub use thread_activity::{ThreadActivity, ThreadActivityKind};
141pub use thread_activity::{ThreadActivity, ThreadActivityKind};
142pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};
142pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};
143pub use translate::{
143pub use translate::{
crates/chatsvc/src/tenants.rs +10 −4
@@ -11,11 +11,14 @@ pub struct Tenant {
11 11 pub name: String,
12 12 /// The account is a guest here; its home tenant is the one with `guest == false`.
13 13 pub guest: bool,
14 /// The account's user id in this tenant; a guest has its own id in every tenant.
15 pub user_id: Option<String>,
14 16 }
15 17
16 18 /// Every tenant of the account, home tenant first.
17 19 pub async fn list_tenants(session: &Session) -> Result<Vec<Tenant>> {
18 let url = format!("https://teams.cloud.microsoft/api/mt/{DEFAULT_MT_REGION}/beta/users/tenants");
20 let url =
21 format!("https://teams.cloud.microsoft/api/mt/{DEFAULT_MT_REGION}/beta/users/tenants");
19 22 let answer = session
20 23 .request(Method::Get, &url, &spaces_scope(), None)
21 24 .await?;
@@ -34,6 +37,7 @@ fn parse_tenants(body: &Value) -> Option<Vec<Tenant>> {
34 37 guest: entry["userType"]
35 38 .as_str()
36 39 .is_some_and(|kind| kind.eq_ignore_ascii_case("guest")),
40 user_id: entry["userId"].as_str().map(str::to_ascii_lowercase),
37 41 })
38 42 })
39 43 .collect();
@@ -49,7 +53,7 @@ mod tests {
49 53 #[test]
50 54 fn lists_the_home_tenant_first_and_marks_guest_tenants() {
51 55 let body = json!([
52 {"tenantId": "BBBB-GUEST", "tenantName": "Guest Org", "userType": "guest"},
56 {"tenantId": "BBBB-GUEST", "tenantName": "Guest Org", "userType": "guest", "userId": "AB-12"},
53 57 {"tenantId": "aaaa-home", "tenantName": "Home Org", "userType": "member"},
54 58 {"tenantName": "no id"},
55 59 ]);
@@ -59,12 +63,14 @@ mod tests {
59 63 Tenant {
60 64 id: "aaaa-home".into(),
61 65 name: "Home Org".into(),
62 guest: false
66 guest: false,
67 user_id: None,
63 68 },
64 69 Tenant {
65 70 id: "bbbb-guest".into(),
66 71 name: "Guest Org".into(),
67 guest: true
72 guest: true,
73 user_id: Some("ab-12".into()),
68 74 },
69 75 ]
70 76 );
@@ -11,11 +11,14 @@ pub struct Tenant {
11 pub name: String,
11 pub name: String,
12 /// The account is a guest here; its home tenant is the one with `guest == false`.
12 /// The account is a guest here; its home tenant is the one with `guest == false`.
13 pub guest: bool,
13 pub guest: bool,
14 /// The account's user id in this tenant; a guest has its own id in every tenant.
15 pub user_id: Option<String>,
14}
16}
15
17
16/// Every tenant of the account, home tenant first.
18/// Every tenant of the account, home tenant first.
17pub async fn list_tenants(session: &Session) -> Result<Vec<Tenant>> {
19pub async fn list_tenants(session: &Session) -> Result<Vec<Tenant>> {
18 let url = format!("https://teams.cloud.microsoft/api/mt/{DEFAULT_MT_REGION}/beta/users/tenants");
20 let url =
21 format!("https://teams.cloud.microsoft/api/mt/{DEFAULT_MT_REGION}/beta/users/tenants");
19 let answer = session
22 let answer = session
20 .request(Method::Get, &url, &spaces_scope(), None)
23 .request(Method::Get, &url, &spaces_scope(), None)
21 .await?;
24 .await?;
@@ -34,6 +37,7 @@ fn parse_tenants(body: &Value) -> Option<Vec<Tenant>> {
34 guest: entry["userType"]
37 guest: entry["userType"]
35 .as_str()
38 .as_str()
36 .is_some_and(|kind| kind.eq_ignore_ascii_case("guest")),
39 .is_some_and(|kind| kind.eq_ignore_ascii_case("guest")),
40 user_id: entry["userId"].as_str().map(str::to_ascii_lowercase),
37 })
41 })
38 })
42 })
39 .collect();
43 .collect();
@@ -49,7 +53,7 @@ mod tests {
49 #[test]
53 #[test]
50 fn lists_the_home_tenant_first_and_marks_guest_tenants() {
54 fn lists_the_home_tenant_first_and_marks_guest_tenants() {
51 let body = json!([
55 let body = json!([
52 {"tenantId": "BBBB-GUEST", "tenantName": "Guest Org", "userType": "guest"},
56 {"tenantId": "BBBB-GUEST", "tenantName": "Guest Org", "userType": "guest", "userId": "AB-12"},
53 {"tenantId": "aaaa-home", "tenantName": "Home Org", "userType": "member"},
57 {"tenantId": "aaaa-home", "tenantName": "Home Org", "userType": "member"},
54 {"tenantName": "no id"},
58 {"tenantName": "no id"},
55 ]);
59 ]);
@@ -59,12 +63,14 @@ mod tests {
59 Tenant {
63 Tenant {
60 id: "aaaa-home".into(),
64 id: "aaaa-home".into(),
61 name: "Home Org".into(),
65 name: "Home Org".into(),
62 guest: false
66 guest: false,
67 user_id: None,
63 },
68 },
64 Tenant {
69 Tenant {
65 id: "bbbb-guest".into(),
70 id: "bbbb-guest".into(),
66 name: "Guest Org".into(),
71 name: "Guest Org".into(),
67 guest: true
72 guest: true,
73 user_id: Some("ab-12".into()),
68 },
74 },
69 ]
75 ]
70 );
76 );