Merge pull request #46: feat(orgs): add multi-org support
- Conflicts with #40, #41 and #44 resolved (roadmap, ADR index, center imports) - Guest org ADR renumbered to 0017 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -83,6 +83,7 @@
83
83
- Dark theme, opens instantly from the cache
84
84
- Self-update from GitHub releases (Windows, and the installed Linux binary)
85
85
- Single instance: a second start brings the window to the front
86
- Guest orgs: the avatar menu lists every org of your account (home and guest tenants) with unread counts; picking one restarts on it with its own cache. Messages from the other orgs show as toasts
86
87
87
88
## Status
88
89
@@ -83,6 +83,7 @@83
- Dark theme, opens instantly from the cache83
- Dark theme, opens instantly from the cache84
- Self-update from GitHub releases (Windows, and the installed Linux binary)84
- Self-update from GitHub releases (Windows, and the installed Linux binary)85
- Single instance: a second start brings the window to the front85
- Single instance: a second start brings the window to the front86
- Guest orgs: the avatar menu lists every org of your account (home and guest tenants) with unread counts; picking one restarts on it with its own cache. Messages from the other orgs show as toasts86
87
87
## Status88
## Status88
89
@@ -38,6 +38,7 @@ Feature parity with the Microsoft Teams desktop client.
38
38
| Sign in on Linux without starting Chrome by hand | Done | The app starts Chrome or Chromium headless with its own profile, shows the window for the login and hides it again afterwards; a watchdog restarts a dead or hung Chrome |
39
39
| Single instance, second start brings the window to front | Done | |
40
40
| Sign in on macOS without starting Chrome by hand | Done | Same managed browser as on Linux, profile in Application Support. Takes the first of Chrome, Chromium, Edge, Brave, Helium, Vivaldi; checked live with Helium |
41
| Guest orgs (one account, several tenants) | Partial | Account menu lists the orgs, the open one checked; picking another restarts on it with its own cache (ADR 0017). Orgs that are not open stay live: toast per new chat message from others, count of chats with new messages in the menu, click switches and opens the chat. Guest org sync checked live; the background toast not run live yet. Calls stay on the home tenant; Outlook calendar is unavailable for a guest |
41
42
42
43
## Chat list
43
44
@@ -38,6 +38,7 @@ Feature parity with the Microsoft Teams desktop client.38
| Sign in on Linux without starting Chrome by hand | Done | The app starts Chrome or Chromium headless with its own profile, shows the window for the login and hides it again afterwards; a watchdog restarts a dead or hung Chrome |38
| Sign in on Linux without starting Chrome by hand | Done | The app starts Chrome or Chromium headless with its own profile, shows the window for the login and hides it again afterwards; a watchdog restarts a dead or hung Chrome |39
| Single instance, second start brings the window to front | Done | |39
| Single instance, second start brings the window to front | Done | |40
| Sign in on macOS without starting Chrome by hand | Done | Same managed browser as on Linux, profile in Application Support. Takes the first of Chrome, Chromium, Edge, Brave, Helium, Vivaldi; checked live with Helium |40
| Sign in on macOS without starting Chrome by hand | Done | Same managed browser as on Linux, profile in Application Support. Takes the first of Chrome, Chromium, Edge, Brave, Helium, Vivaldi; checked live with Helium |41
| Guest orgs (one account, several tenants) | Partial | Account menu lists the orgs, the open one checked; picking another restarts on it with its own cache (ADR 0017). Orgs that are not open stay live: toast per new chat message from others, count of chats with new messages in the menu, click switches and opens the chat. Guest org sync checked live; the background toast not run live yet. Calls stay on the home tenant; Outlook calendar is unavailable for a guest |41
42
42
## Chat list43
## Chat list43
44
@@ -1667,6 +1667,9 @@ shell:
1667
1667
en: Settings and more
1668
1668
de: Einstellungen und mehr
1669
1669
status_menu:
1670
guest_org:
1671
en: "%{name} (Guest)"
1672
de: "%{name} (Gast)"
1670
1673
view_account:
1671
1674
en: View account
1672
1675
de: Konto anzeigen
@@ -1667,6 +1667,9 @@ shell:1667
en: Settings and more1667
en: Settings and more1668
de: Einstellungen und mehr1668
de: Einstellungen und mehr1669
status_menu:1669
status_menu:1670
guest_org:1671
en: "%{name} (Guest)"1672
de: "%{name} (Gast)"1670
view_account:1673
view_account:1671
en: View account1674
en: View account1672
de: Konto anzeigen1675
de: Konto anzeigen@@ -28,6 +28,7 @@ pub mod linux_desktop;
28
28
pub mod linux_fonts;
29
29
pub mod native_dumps;
30
30
pub mod notify;
31
pub mod orgs;
31
32
pub mod presence_link;
32
33
pub mod read_state;
33
34
pub mod recap;
@@ -28,6 +28,7 @@ pub mod linux_desktop;28
pub mod linux_fonts;28
pub mod linux_fonts;29
pub mod native_dumps;29
pub mod native_dumps;30
pub mod notify;30
pub mod notify;31
pub mod orgs;31
pub mod presence_link;32
pub mod presence_link;32
pub mod read_state;33
pub mod read_state;33
pub mod recap;34
pub mod recap;@@ -0,0 +1,127 @@
1
//! The organizations of the signed-in account and which one the window shows.
2
//!
3
//! Lives in its own file beside the caches, because it decides which cache to open.
4
//! The home tenant keeps `cache.sqlite3`; a guest tenant gets `cache-<tenant id>.sqlite3`.
5
use std::path::{Path, PathBuf};
6
7
use serde::{Deserialize, Serialize};
8
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";
12
const HOME_DATABASE: &str = "cache.sqlite3";
13
14
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15
pub struct Org {
16
pub id: String,
17
pub name: String,
18
pub guest: bool,
19
}
20
21
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
22
pub struct Orgs {
23
/// Tenant id of the org the window shows; `None` is the home tenant.
24
pub active: Option<String>,
25
pub list: Vec<Org>,
26
}
27
28
impl Orgs {
29
pub fn path() -> Option<PathBuf> {
30
crate::support::local_data_dir().map(|root| root.join(ORGS_FILE))
31
}
32
33
/// A missing or unreadable file is the home tenant with no known orgs.
34
pub fn load(path: &Path) -> Orgs {
35
std::fs::read(path)
36
.ok()
37
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
38
.unwrap_or_default()
39
}
40
41
pub fn save(&self, path: &Path) -> std::io::Result<()> {
42
let bytes = serde_json::to_vec_pretty(self).map_err(std::io::Error::other)?;
43
std::fs::write(path, bytes)
44
}
45
46
/// The active org when it is a guest tenant, the only case that needs its own tokens and cache.
47
pub fn active_guest(&self) -> Option<&Org> {
48
let active = self.active.as_deref()?;
49
self.list
50
.iter()
51
.find(|org| org.guest && org.id == active && is_tenant_id(&org.id))
52
}
53
54
pub fn is_active(&self, org: &Org) -> bool {
55
match self.active_guest() {
56
Some(active) => active.id == org.id,
57
None => !org.guest,
58
}
59
}
60
61
pub fn database_file(&self) -> String {
62
match self.active_guest() {
63
Some(org) => format!("cache-{}.sqlite3", org.id),
64
None => HOME_DATABASE.to_owned(),
65
}
66
}
67
68
/// Takes the account's current org list; an active org that is gone falls back to home.
69
pub fn replace_list(&mut self, list: Vec<Org>) {
70
self.list = list;
71
if self.active_guest().is_none() {
72
self.active = None;
73
}
74
}
75
76
pub fn activate(&mut self, org: &Org) {
77
self.active = org.guest.then(|| org.id.clone());
78
}
79
}
80
81
/// Tenant ids are GUIDs; anything else must not end up in a file name.
82
fn is_tenant_id(id: &str) -> bool {
83
!id.is_empty()
84
&& id
85
.chars()
86
.all(|character| character.is_ascii_hexdigit() || character == '-')
87
}
88
89
#[cfg(test)]
90
mod tests {
91
use super::*;
92
93
fn org(id: &str, guest: bool) -> Org {
94
Org {
95
id: id.into(),
96
name: id.into(),
97
guest,
98
}
99
}
100
101
#[test]
102
fn a_guest_org_gets_its_own_cache_and_home_keeps_the_old_one() {
103
let mut orgs = Orgs {
104
active: None,
105
list: vec![org("aaaa-01", false), org("bbbb-02", true)],
106
};
107
assert_eq!(orgs.database_file(), "cache.sqlite3");
108
assert!(orgs.is_active(&orgs.list[0].clone()));
109
orgs.activate(&orgs.list[1].clone());
110
assert_eq!(orgs.database_file(), "cache-bbbb-02.sqlite3");
111
assert!(orgs.is_active(&orgs.list[1].clone()));
112
orgs.activate(&orgs.list[0].clone());
113
assert_eq!(orgs.active, None);
114
}
115
116
#[test]
117
fn an_unknown_or_unsafe_active_org_is_the_home_tenant() {
118
let mut orgs = Orgs {
119
active: Some("../evil".into()),
120
list: vec![org("../evil", true)],
121
};
122
assert_eq!(orgs.database_file(), "cache.sqlite3");
123
orgs.active = Some("bbbb-02".into());
124
orgs.replace_list(vec![org("aaaa-01", false)]);
125
assert_eq!(orgs.active, None);
126
}
127
}
@@ -0,0 +1,127 @@1
//! The organizations of the signed-in account and which one the window shows.2
//!3
//! Lives in its own file beside the caches, because it decides which cache to open.4
//! The home tenant keeps `cache.sqlite3`; a guest tenant gets `cache-<tenant id>.sqlite3`.5
use std::path::{Path, PathBuf};6
7
use serde::{Deserialize, Serialize};8
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";12
const HOME_DATABASE: &str = "cache.sqlite3";13
14
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]15
pub struct Org {16
pub id: String,17
pub name: String,18
pub guest: bool,19
}20
21
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]22
pub struct Orgs {23
/// Tenant id of the org the window shows; `None` is the home tenant.24
pub active: Option<String>,25
pub list: Vec<Org>,26
}27
28
impl Orgs {29
pub fn path() -> Option<PathBuf> {30
crate::support::local_data_dir().map(|root| root.join(ORGS_FILE))31
}32
33
/// A missing or unreadable file is the home tenant with no known orgs.34
pub fn load(path: &Path) -> Orgs {35
std::fs::read(path)36
.ok()37
.and_then(|bytes| serde_json::from_slice(&bytes).ok())38
.unwrap_or_default()39
}40
41
pub fn save(&self, path: &Path) -> std::io::Result<()> {42
let bytes = serde_json::to_vec_pretty(self).map_err(std::io::Error::other)?;43
std::fs::write(path, bytes)44
}45
46
/// The active org when it is a guest tenant, the only case that needs its own tokens and cache.47
pub fn active_guest(&self) -> Option<&Org> {48
let active = self.active.as_deref()?;49
self.list50
.iter()51
.find(|org| org.guest && org.id == active && is_tenant_id(&org.id))52
}53
54
pub fn is_active(&self, org: &Org) -> bool {55
match self.active_guest() {56
Some(active) => active.id == org.id,57
None => !org.guest,58
}59
}60
61
pub fn database_file(&self) -> String {62
match self.active_guest() {63
Some(org) => format!("cache-{}.sqlite3", org.id),64
None => HOME_DATABASE.to_owned(),65
}66
}67
68
/// Takes the account's current org list; an active org that is gone falls back to home.69
pub fn replace_list(&mut self, list: Vec<Org>) {70
self.list = list;71
if self.active_guest().is_none() {72
self.active = None;73
}74
}75
76
pub fn activate(&mut self, org: &Org) {77
self.active = org.guest.then(|| org.id.clone());78
}79
}80
81
/// Tenant ids are GUIDs; anything else must not end up in a file name.82
fn is_tenant_id(id: &str) -> bool {83
!id.is_empty()84
&& id85
.chars()86
.all(|character| character.is_ascii_hexdigit() || character == '-')87
}88
89
#[cfg(test)]90
mod tests {91
use super::*;92
93
fn org(id: &str, guest: bool) -> Org {94
Org {95
id: id.into(),96
name: id.into(),97
guest,98
}99
}100
101
#[test]102
fn a_guest_org_gets_its_own_cache_and_home_keeps_the_old_one() {103
let mut orgs = Orgs {104
active: None,105
list: vec![org("aaaa-01", false), org("bbbb-02", true)],106
};107
assert_eq!(orgs.database_file(), "cache.sqlite3");108
assert!(orgs.is_active(&orgs.list[0].clone()));109
orgs.activate(&orgs.list[1].clone());110
assert_eq!(orgs.database_file(), "cache-bbbb-02.sqlite3");111
assert!(orgs.is_active(&orgs.list[1].clone()));112
orgs.activate(&orgs.list[0].clone());113
assert_eq!(orgs.active, None);114
}115
116
#[test]117
fn an_unknown_or_unsafe_active_org_is_the_home_tenant() {118
let mut orgs = Orgs {119
active: Some("../evil".into()),120
list: vec![org("../evil", true)],121
};122
assert_eq!(orgs.database_file(), "cache.sqlite3");123
orgs.active = Some("bbbb-02".into());124
orgs.replace_list(vec![org("aaaa-01", false)]);125
assert_eq!(orgs.active, None);126
}127
}@@ -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)]
@@ -133,6 +138,10 @@ pub struct AppState {
133
138
pub collapsed: HashSet<String>,
134
139
pub expanded_lists: HashSet<String>,
135
140
pub start_on_channels: bool,
141
/// The account's organizations and the one this window shows.
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>>,
136
145
pub pending_jump: Option<(String, String)>,
137
146
pub cards: CardState,
138
147
pub task_dialog: Option<TaskDialogState>,
@@ -310,6 +319,8 @@ impl AppState {
310
319
collapsed: HashSet::new(),
311
320
expanded_lists: HashSet::new(),
312
321
start_on_channels: false,
322
orgs: app_base::orgs::Orgs::default(),
323
org_unread: HashMap::new(),
313
324
pending_jump: None,
314
325
cards: CardState::default(),
315
326
task_dialog: None,
@@ -1269,6 +1280,18 @@ impl AppState {
1269
1280
self.refresh_connection_banner(cx);
1270
1281
cx.emit(AppEvent::Status);
1271
1282
}
1283
BackendEvent::Orgs(list) => {
1284
self.take_org_list(list);
1285
cx.notify();
1286
}
1287
BackendEvent::OrgMessage(message) => {
1288
self.org_unread
1289
.entry(message.org.id.clone())
1290
.or_default()
1291
.insert(message.conversation_id.clone());
1292
cx.emit(AppEvent::OrgMessage(message));
1293
cx.notify();
1294
}
1272
1295
BackendEvent::Favorites(ids) => {
1273
1296
self.favorite_ids = ids;
1274
1297
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)]@@ -133,6 +138,10 @@ pub struct AppState {133
pub collapsed: HashSet<String>,138
pub collapsed: HashSet<String>,134
pub expanded_lists: HashSet<String>,139
pub expanded_lists: HashSet<String>,135
pub start_on_channels: bool,140
pub start_on_channels: bool,141
/// The account's organizations and the one this window shows.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>>,136
pub pending_jump: Option<(String, String)>,145
pub pending_jump: Option<(String, String)>,137
pub cards: CardState,146
pub cards: CardState,138
pub task_dialog: Option<TaskDialogState>,147
pub task_dialog: Option<TaskDialogState>,@@ -310,6 +319,8 @@ impl AppState {310
collapsed: HashSet::new(),319
collapsed: HashSet::new(),311
expanded_lists: HashSet::new(),320
expanded_lists: HashSet::new(),312
start_on_channels: false,321
start_on_channels: false,322
orgs: app_base::orgs::Orgs::default(),323
org_unread: HashMap::new(),313
pending_jump: None,324
pending_jump: None,314
cards: CardState::default(),325
cards: CardState::default(),315
task_dialog: None,326
task_dialog: None,@@ -1269,6 +1280,18 @@ impl AppState {1269
self.refresh_connection_banner(cx);1280
self.refresh_connection_banner(cx);1270
cx.emit(AppEvent::Status);1281
cx.emit(AppEvent::Status);1271
}1282
}1283
BackendEvent::Orgs(list) => {1284
self.take_org_list(list);1285
cx.notify();1286
}1287
BackendEvent::OrgMessage(message) => {1288
self.org_unread1289
.entry(message.org.id.clone())1290
.or_default()1291
.insert(message.conversation_id.clone());1292
cx.emit(AppEvent::OrgMessage(message));1293
cx.notify();1294
}1272
BackendEvent::Favorites(ids) => {1295
BackendEvent::Favorites(ids) => {1273
self.favorite_ids = ids;1296
self.favorite_ids = ids;1274
if !self.mode.demo {1297
if !self.mode.demo {@@ -26,6 +26,7 @@ const REFRESH_SETTLE: Duration = Duration::from_secs(2);
26
26
const PINS_INTERVAL: Duration = Duration::from_secs(90);
27
27
const CALENDAR_INTERVAL: Duration = Duration::from_secs(5 * 60);
28
28
const CALENDAR_MIN_GAP: Duration = Duration::from_secs(30);
29
const ORG_LIST_ATTEMPTS: usize = 5;
29
30
const REALTIME_RETRY: Duration = Duration::from_secs(15);
30
31
const ARRIVAL_RETRY_DELAYS: [Duration; 3] = [
31
32
Duration::from_secs(1),
@@ -72,6 +73,8 @@ pub enum BackendEvent {
72
73
Favorites(Vec<String>),
73
74
Synced(DateTime<Utc>),
74
75
LiveRetry(Arc<Notify>),
76
Orgs(Vec<app_base::orgs::Org>),
77
OrgMessage(crate::org_watch::OrgMessage),
75
78
}
76
79
77
80
impl BackendEvent {
@@ -95,6 +98,8 @@ impl BackendEvent {
95
98
BackendEvent::Favorites(_) => "Favorites".into(),
96
99
BackendEvent::Synced(_) => "Synced".into(),
97
100
BackendEvent::LiveRetry(_) => "LiveRetry".into(),
101
BackendEvent::Orgs(_) => "Orgs".into(),
102
BackendEvent::OrgMessage(_) => "OrgMessage".into(),
98
103
}
99
104
}
100
105
}
@@ -150,9 +155,17 @@ pub fn start(
150
155
transport: Arc<dyn Transport>,
151
156
ringable: bool,
152
157
activity: watch::Receiver<bool>,
158
guest_tenant: Option<String>,
153
159
) -> mpsc::UnboundedReceiver<BackendEvent> {
154
160
let (sender, receiver) = mpsc::unbounded_channel();
155
crate::runtime::handle().spawn(supervise(store, transport, ringable, activity, sender));
161
crate::runtime::handle().spawn(supervise(
162
store,
163
transport,
164
ringable,
165
activity,
166
guest_tenant,
167
sender,
168
));
156
169
receiver
157
170
}
158
171
@@ -161,10 +174,11 @@ async fn supervise(
161
174
transport: Arc<dyn Transport>,
162
175
ringable: bool,
163
176
activity: watch::Receiver<bool>,
177
guest_tenant: Option<String>,
164
178
events: EventSender,
165
179
) {
166
180
let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));
167
let session = loop {
181
let home = loop {
168
182
match Session::with_transport(transport.clone(), SessionConfig::for_app()).await {
169
183
Ok(session) => break session,
170
184
Err(error) => {
@@ -173,6 +187,12 @@ async fn supervise(
173
187
}
174
188
}
175
189
};
190
tokio::spawn(org_list(home.clone(), guest_tenant.clone(), events.clone()));
191
// Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.
192
let session = match &guest_tenant {
193
Some(tenant) => home.in_tenant(tenant),
194
None => home,
195
};
176
196
let build = || {
177
197
SyncEngine::new(Graph::new(session.clone()), store.clone())
178
198
.with_folder_source(Arc::new(ChatsvcFolderSource::new(&session)))
@@ -217,6 +237,49 @@ async fn supervise(
217
237
refresh_loop(engine, events, nudges).await;
218
238
}
219
239
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) {
243
for _ in 0..ORG_LIST_ATTEMPTS {
244
match chatsvc::list_tenants(&home).await {
245
Ok(tenants) => {
246
let mut orgs = Vec::with_capacity(tenants.len());
247
for tenant in tenants {
248
let org = app_base::orgs::Org {
249
id: tenant.id,
250
name: tenant.name,
251
guest: tenant.guest,
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
}
272
let _ = events.send(BackendEvent::Orgs(orgs));
273
return;
274
}
275
Err(error) => {
276
crate::diagnostics::record(format!("orgs: tenant list not loaded: {error}"));
277
tokio::time::sleep(CONNECT_RETRY).await;
278
}
279
}
280
}
281
}
282
220
283
async fn forward_core_events(engine: Arc<Engine>, events: EventSender) {
221
284
let mut receiver = engine.subscribe();
222
285
loop {
@@ -26,6 +26,7 @@ const REFRESH_SETTLE: Duration = Duration::from_secs(2);26
const PINS_INTERVAL: Duration = Duration::from_secs(90);26
const PINS_INTERVAL: Duration = Duration::from_secs(90);27
const CALENDAR_INTERVAL: Duration = Duration::from_secs(5 * 60);27
const CALENDAR_INTERVAL: Duration = Duration::from_secs(5 * 60);28
const CALENDAR_MIN_GAP: Duration = Duration::from_secs(30);28
const CALENDAR_MIN_GAP: Duration = Duration::from_secs(30);29
const ORG_LIST_ATTEMPTS: usize = 5;29
const REALTIME_RETRY: Duration = Duration::from_secs(15);30
const REALTIME_RETRY: Duration = Duration::from_secs(15);30
const ARRIVAL_RETRY_DELAYS: [Duration; 3] = [31
const ARRIVAL_RETRY_DELAYS: [Duration; 3] = [31
Duration::from_secs(1),32
Duration::from_secs(1),@@ -72,6 +73,8 @@ pub enum BackendEvent {72
Favorites(Vec<String>),73
Favorites(Vec<String>),73
Synced(DateTime<Utc>),74
Synced(DateTime<Utc>),74
LiveRetry(Arc<Notify>),75
LiveRetry(Arc<Notify>),76
Orgs(Vec<app_base::orgs::Org>),77
OrgMessage(crate::org_watch::OrgMessage),75
}78
}76
79
77
impl BackendEvent {80
impl BackendEvent {@@ -95,6 +98,8 @@ impl BackendEvent {95
BackendEvent::Favorites(_) => "Favorites".into(),98
BackendEvent::Favorites(_) => "Favorites".into(),96
BackendEvent::Synced(_) => "Synced".into(),99
BackendEvent::Synced(_) => "Synced".into(),97
BackendEvent::LiveRetry(_) => "LiveRetry".into(),100
BackendEvent::LiveRetry(_) => "LiveRetry".into(),101
BackendEvent::Orgs(_) => "Orgs".into(),102
BackendEvent::OrgMessage(_) => "OrgMessage".into(),98
}103
}99
}104
}100
}105
}@@ -150,9 +155,17 @@ pub fn start(150
transport: Arc<dyn Transport>,155
transport: Arc<dyn Transport>,151
ringable: bool,156
ringable: bool,152
activity: watch::Receiver<bool>,157
activity: watch::Receiver<bool>,158
guest_tenant: Option<String>,153
) -> mpsc::UnboundedReceiver<BackendEvent> {159
) -> mpsc::UnboundedReceiver<BackendEvent> {154
let (sender, receiver) = mpsc::unbounded_channel();160
let (sender, receiver) = mpsc::unbounded_channel();155
crate::runtime::handle().spawn(supervise(store, transport, ringable, activity, sender));161
crate::runtime::handle().spawn(supervise(162
store,163
transport,164
ringable,165
activity,166
guest_tenant,167
sender,168
));156
receiver169
receiver157
}170
}158
171
@@ -161,10 +174,11 @@ async fn supervise(161
transport: Arc<dyn Transport>,174
transport: Arc<dyn Transport>,162
ringable: bool,175
ringable: bool,163
activity: watch::Receiver<bool>,176
activity: watch::Receiver<bool>,177
guest_tenant: Option<String>,164
events: EventSender,178
events: EventSender,165
) {179
) {166
let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));180
let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));167
let session = loop {181
let home = loop {168
match Session::with_transport(transport.clone(), SessionConfig::for_app()).await {182
match Session::with_transport(transport.clone(), SessionConfig::for_app()).await {169
Ok(session) => break session,183
Ok(session) => break session,170
Err(error) => {184
Err(error) => {@@ -173,6 +187,12 @@ async fn supervise(173
}187
}174
}188
}175
};189
};190
tokio::spawn(org_list(home.clone(), guest_tenant.clone(), events.clone()));191
// Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.192
let session = match &guest_tenant {193
Some(tenant) => home.in_tenant(tenant),194
None => home,195
};176
let build = || {196
let build = || {177
SyncEngine::new(Graph::new(session.clone()), store.clone())197
SyncEngine::new(Graph::new(session.clone()), store.clone())178
.with_folder_source(Arc::new(ChatsvcFolderSource::new(&session)))198
.with_folder_source(Arc::new(ChatsvcFolderSource::new(&session)))@@ -217,6 +237,49 @@ async fn supervise(217
refresh_loop(engine, events, nudges).await;237
refresh_loop(engine, events, nudges).await;218
}238
}219
239
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) {243
for _ in 0..ORG_LIST_ATTEMPTS {244
match chatsvc::list_tenants(&home).await {245
Ok(tenants) => {246
let mut orgs = Vec::with_capacity(tenants.len());247
for tenant in tenants {248
let org = app_base::orgs::Org {249
id: tenant.id,250
name: tenant.name,251
guest: tenant.guest,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
}272
let _ = events.send(BackendEvent::Orgs(orgs));273
return;274
}275
Err(error) => {276
crate::diagnostics::record(format!("orgs: tenant list not loaded: {error}"));277
tokio::time::sleep(CONNECT_RETRY).await;278
}279
}280
}281
}282
220
async fn forward_core_events(engine: Arc<Engine>, events: EventSender) {283
async fn forward_core_events(engine: Arc<Engine>, events: EventSender) {221
let mut receiver = engine.subscribe();284
let mut receiver = engine.subscribe();222
loop {285
loop {@@ -39,6 +39,8 @@ pub mod manage_team;
39
39
pub mod message_actions;
40
40
pub mod notice;
41
41
pub mod notify;
42
mod org_actions;
43
pub mod org_watch;
42
44
pub mod outbox;
43
45
pub mod outgoing;
44
46
pub mod own_status;
@@ -39,6 +39,8 @@ pub mod manage_team;39
pub mod message_actions;39
pub mod message_actions;40
pub mod notice;40
pub mod notice;41
pub mod notify;41
pub mod notify;42
mod org_actions;43
pub mod org_watch;42
pub mod outbox;44
pub mod outbox;43
pub mod outgoing;45
pub mod outgoing;44
pub mod own_status;46
pub mod own_status;@@ -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.);@@ -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
201
impl ToastModel {203
impl 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_change240
&& !toast.status_change241
&& toast.org.is_none()239
&& !toast.dismissed242
&& !toast.dismissed240
&& !toast.is_leaving()243
&& !toast.is_leaving()241
&& toast.conversation_id == incoming.conversation_id244
&& 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_id328
self.next_id324
}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_id366
}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::Direct382
} 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_id404
self.next_id360
}405
}@@ -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
@@ -0,0 +1,113 @@
1
use app_base::orgs::{OPEN_CONVERSATION_FLAG, Org, Orgs};
2
use gpui_kit::Context;
3
4
use crate::app_state::AppState;
5
6
impl AppState {
7
pub(crate) fn take_org_list(&mut self, list: Vec<Org>) {
8
if self.orgs.list == list {
9
return;
10
}
11
self.orgs.replace_list(list);
12
self.save_orgs(&self.orgs);
13
}
14
15
/// Orgs to offer in the account menu; a single org needs no switcher, like Teams.
16
pub fn switchable_orgs(&self) -> &[Org] {
17
if self.orgs.list.len() > 1 {
18
&self.orgs.list
19
} else {
20
&[]
21
}
22
}
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
29
/// Restarts the app on `org`: its own cache opens at once and the backend signs in to its tenant.
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
) {
37
if self.orgs.is_active(org) {
38
return;
39
}
40
let mut next = self.orgs.clone();
41
next.activate(org);
42
if !self.save_orgs(&next) {
43
return;
44
}
45
self.orgs = next;
46
match std::env::current_exe().and_then(|exe| {
47
std::process::Command::new(exe)
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
)
56
.spawn()
57
}) {
58
Ok(_) => cx.quit(),
59
Err(error) => {
60
crate::diagnostics::record(format!("orgs: restart for the switch failed: {error}"))
61
}
62
}
63
}
64
65
fn save_orgs(&self, orgs: &Orgs) -> bool {
66
if self.mode.demo {
67
return false;
68
}
69
let saved = Orgs::path().map(|path| orgs.save(&path));
70
if let Some(Err(error)) = &saved {
71
crate::diagnostics::record(format!(
72
"orgs: {} not saved: {error}",
73
app_base::orgs::ORGS_FILE
74
));
75
}
76
matches!(saved, Some(Ok(())))
77
}
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
}
@@ -0,0 +1,113 @@1
use app_base::orgs::{OPEN_CONVERSATION_FLAG, Org, Orgs};2
use gpui_kit::Context;3
4
use crate::app_state::AppState;5
6
impl AppState {7
pub(crate) fn take_org_list(&mut self, list: Vec<Org>) {8
if self.orgs.list == list {9
return;10
}11
self.orgs.replace_list(list);12
self.save_orgs(&self.orgs);13
}14
15
/// Orgs to offer in the account menu; a single org needs no switcher, like Teams.16
pub fn switchable_orgs(&self) -> &[Org] {17
if self.orgs.list.len() > 1 {18
&self.orgs.list19
} else {20
&[]21
}22
}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
29
/// Restarts the app on `org`: its own cache opens at once and the backend signs in to its tenant.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
) {37
if self.orgs.is_active(org) {38
return;39
}40
let mut next = self.orgs.clone();41
next.activate(org);42
if !self.save_orgs(&next) {43
return;44
}45
self.orgs = next;46
match std::env::current_exe().and_then(|exe| {47
std::process::Command::new(exe)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
)56
.spawn()57
}) {58
Ok(_) => cx.quit(),59
Err(error) => {60
crate::diagnostics::record(format!("orgs: restart for the switch failed: {error}"))61
}62
}63
}64
65
fn save_orgs(&self, orgs: &Orgs) -> bool {66
if self.mode.demo {67
return false;68
}69
let saved = Orgs::path().map(|path| orgs.save(&path));70
if let Some(Err(error)) = &saved {71
crate::diagnostics::record(format!(72
"orgs: {} not saved: {error}",73
app_base::orgs::ORGS_FILE74
));75
}76
matches!(saved, Some(Ok(())))77
}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
arguments99
}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
}@@ -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.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().await58
{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) = parsed77
&& 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 = properties125
.and_then(|properties| properties["topic"].as_str())126
.map(str::trim)127
.filter(|topic| !topic.is_empty());128
let direct = properties129
.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
None183
);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
None188
);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
}@@ -49,7 +49,6 @@ const WINDOW_MIN_WIDTH: f32 = 640.;
49
49
const WINDOW_MIN_HEIGHT: f32 = 480.;
50
50
const ENDPOINT_UNREGISTER_TIMEOUT: Duration = Duration::from_millis(800);
51
51
const SINGLE_INSTANCE_NAME: &str = "rusty-teams";
52
const DATABASE_FILE: &str = "cache.sqlite3";
53
52
#[cfg(windows)]
54
53
const WEBVIEW_FOLDER: &str = "WebView2";
55
54
#[cfg(windows)]
@@ -108,6 +107,9 @@ fn parse_arguments() -> Arguments {
108
107
.and_then(|value| value.parse().ok())
109
108
.map(OpenTarget::Chat)
110
109
}
110
app_base::orgs::OPEN_CONVERSATION_FLAG => {
111
arguments.open_target = input.next().map(OpenTarget::Conversation)
112
}
111
113
"--open-channel" => {
112
114
arguments.open_target = input
113
115
.next()
@@ -234,6 +236,13 @@ fn main() {
234
236
if arguments.demo {
235
237
inline_video::configure(std::env::temp_dir().join(DEMO_WEBVIEW_FOLDER));
236
238
}
239
let orgs = if arguments.demo {
240
app_base::orgs::Orgs::default()
241
} else {
242
app_base::orgs::Orgs::path()
243
.map(|path| app_base::orgs::Orgs::load(&path))
244
.unwrap_or_default()
245
};
237
246
let store = if arguments.demo {
238
247
let store = Store::open_in_memory().expect("in-memory store");
239
248
demo::seed(&store);
@@ -242,7 +251,7 @@ fn main() {
242
251
let path = arguments
243
252
.database
244
253
.clone()
245
.unwrap_or_else(|| data_path(DATABASE_FILE));
254
.unwrap_or_else(|| data_path(&orgs.database_file()));
246
255
open_store(&path)
247
256
};
248
257
let store = Arc::new(store);
@@ -280,8 +289,14 @@ fn main() {
280
289
#[cfg(not(windows))]
281
290
let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
282
291
let activity = user_activity::track(user_input.clone());
283
let mut backend_events =
284
backend::start(store.clone(), transport, !arguments.read_only, activity);
292
let guest_tenant = orgs.active_guest().map(|org| org.id.clone());
293
let mut backend_events = backend::start(
294
store.clone(),
295
transport,
296
!arguments.read_only,
297
activity,
298
guest_tenant,
299
);
285
300
app_base::runtime::handle().spawn(async move {
286
301
while let Some(event) = backend_events.recv().await {
287
302
if ui_events.send(event).is_err() {
@@ -316,6 +331,7 @@ fn main() {
316
331
let state = cx.new(|_| {
317
332
let mut state = AppState::new(store, mode);
318
333
state.start_on_channels = arguments.channels_tab;
334
state.orgs = orgs;
319
335
state
320
336
});
321
337
views::shell::install_globals(&state, user_input, cx);
@@ -49,7 +49,6 @@ const WINDOW_MIN_WIDTH: f32 = 640.;49
const WINDOW_MIN_HEIGHT: f32 = 480.;49
const WINDOW_MIN_HEIGHT: f32 = 480.;50
const ENDPOINT_UNREGISTER_TIMEOUT: Duration = Duration::from_millis(800);50
const ENDPOINT_UNREGISTER_TIMEOUT: Duration = Duration::from_millis(800);51
const SINGLE_INSTANCE_NAME: &str = "rusty-teams";51
const SINGLE_INSTANCE_NAME: &str = "rusty-teams";52
const DATABASE_FILE: &str = "cache.sqlite3";53
#[cfg(windows)]52
#[cfg(windows)]54
const WEBVIEW_FOLDER: &str = "WebView2";53
const WEBVIEW_FOLDER: &str = "WebView2";55
#[cfg(windows)]54
#[cfg(windows)]@@ -108,6 +107,9 @@ fn parse_arguments() -> Arguments {108
.and_then(|value| value.parse().ok())107
.and_then(|value| value.parse().ok())109
.map(OpenTarget::Chat)108
.map(OpenTarget::Chat)110
}109
}110
app_base::orgs::OPEN_CONVERSATION_FLAG => {111
arguments.open_target = input.next().map(OpenTarget::Conversation)112
}111
"--open-channel" => {113
"--open-channel" => {112
arguments.open_target = input114
arguments.open_target = input113
.next()115
.next()@@ -234,6 +236,13 @@ fn main() {234
if arguments.demo {236
if arguments.demo {235
inline_video::configure(std::env::temp_dir().join(DEMO_WEBVIEW_FOLDER));237
inline_video::configure(std::env::temp_dir().join(DEMO_WEBVIEW_FOLDER));236
}238
}239
let orgs = if arguments.demo {240
app_base::orgs::Orgs::default()241
} else {242
app_base::orgs::Orgs::path()243
.map(|path| app_base::orgs::Orgs::load(&path))244
.unwrap_or_default()245
};237
let store = if arguments.demo {246
let store = if arguments.demo {238
let store = Store::open_in_memory().expect("in-memory store");247
let store = Store::open_in_memory().expect("in-memory store");239
demo::seed(&store);248
demo::seed(&store);@@ -242,7 +251,7 @@ fn main() {242
let path = arguments251
let path = arguments243
.database252
.database244
.clone()253
.clone()245
.unwrap_or_else(|| data_path(DATABASE_FILE));254
.unwrap_or_else(|| data_path(&orgs.database_file()));246
open_store(&path)255
open_store(&path)247
};256
};248
let store = Arc::new(store);257
let store = Arc::new(store);@@ -280,8 +289,14 @@ fn main() {280
#[cfg(not(windows))]289
#[cfg(not(windows))]281
let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());290
let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());282
let activity = user_activity::track(user_input.clone());291
let activity = user_activity::track(user_input.clone());283
let mut backend_events =292
let guest_tenant = orgs.active_guest().map(|org| org.id.clone());284
backend::start(store.clone(), transport, !arguments.read_only, activity);293
let mut backend_events = backend::start(294
store.clone(),295
transport,296
!arguments.read_only,297
activity,298
guest_tenant,299
);285
app_base::runtime::handle().spawn(async move {300
app_base::runtime::handle().spawn(async move {286
while let Some(event) = backend_events.recv().await {301
while let Some(event) = backend_events.recv().await {287
if ui_events.send(event).is_err() {302
if ui_events.send(event).is_err() {@@ -316,6 +331,7 @@ fn main() {316
let state = cx.new(|_| {331
let state = cx.new(|_| {317
let mut state = AppState::new(store, mode);332
let mut state = AppState::new(store, mode);318
state.start_on_channels = arguments.channels_tab;333
state.start_on_channels = arguments.channels_tab;334
state.orgs = orgs;319
state335
state320
});336
});321
views::shell::install_globals(&state, user_input, cx);337
views::shell::install_globals(&state, user_input, cx);@@ -47,6 +47,7 @@ use crate::appearance::AppIcon;
47
47
use crate::autostart::{self, StartupSettings};
48
48
use crate::call::DemoScene;
49
49
use crate::data::{self, Directory, PresenceKind};
50
use crate::org_watch::OrgMessage;
50
51
use crate::own_status;
51
52
use crate::runtime;
52
53
use crate::settings_section::SettingsSection;
@@ -461,6 +462,7 @@ impl NotificationCenter {
461
462
AppEvent::Call => self.sync_call_sounds(cx),
462
463
AppEvent::SoundSettings => self.on_account_sounds(cx),
463
464
AppEvent::ChatSettings => self.on_account_notifications(cx),
465
AppEvent::OrgMessage(message) => self.present_org_message(message, cx),
464
466
AppEvent::FollowedStatus { user_id, text } => {
465
467
self.present_status_change(user_id, text, cx)
466
468
}
@@ -602,6 +604,24 @@ impl NotificationCenter {
602
604
)
603
605
}
604
606
607
fn present_org_message(&mut self, message: &OrgMessage, cx: &mut Context<Self>) {
608
let decision = self.own_feature_decision(cx);
609
if !decision.toast {
610
return;
611
}
612
let now = Instant::now();
613
let id = self.stack.push_org_message(message, now);
614
if let Some(model) = self.stack.get_mut(id) {
615
model.time = chrono::Local::now()
616
.format(crate::format::clock_format())
617
.to_string();
618
}
619
if decision.sound && self.throttle.allow(&message.conversation_id, now) {
620
self.play_notification_sound(cx);
621
}
622
self.sync_windows(cx);
623
}
624
605
625
fn present_status_change(&mut self, user_id: &str, text: &str, cx: &mut Context<Self>) {
606
626
if !self.own_feature_decision(cx).toast {
607
627
return;
@@ -1746,6 +1766,17 @@ impl NotificationCenter {
1746
1766
if self.is_dismissed(id) {
1747
1767
return;
1748
1768
}
1769
if let Some((org, conversation_id)) = self
1770
.stack
1771
.get(id)
1772
.and_then(|toast| Some((toast.org.clone()?, toast.conversation_id.clone())))
1773
{
1774
self.drop_toast(id, cx);
1775
self.app.update(cx, |state, cx| {
1776
state.switch_org(&org, Some(&conversation_id), cx)
1777
});
1778
return;
1779
}
1749
1780
let Some((conversation_id, message_id, proposal_id)) = self.stack.get(id).map(|toast| {
1750
1781
(
1751
1782
toast.conversation_id.clone(),
@@ -47,6 +47,7 @@ use crate::appearance::AppIcon;47
use crate::autostart::{self, StartupSettings};47
use crate::autostart::{self, StartupSettings};48
use crate::call::DemoScene;48
use crate::call::DemoScene;49
use crate::data::{self, Directory, PresenceKind};49
use crate::data::{self, Directory, PresenceKind};50
use crate::org_watch::OrgMessage;50
use crate::own_status;51
use crate::own_status;51
use crate::runtime;52
use crate::runtime;52
use crate::settings_section::SettingsSection;53
use crate::settings_section::SettingsSection;@@ -461,6 +462,7 @@ impl NotificationCenter {461
AppEvent::Call => self.sync_call_sounds(cx),462
AppEvent::Call => self.sync_call_sounds(cx),462
AppEvent::SoundSettings => self.on_account_sounds(cx),463
AppEvent::SoundSettings => self.on_account_sounds(cx),463
AppEvent::ChatSettings => self.on_account_notifications(cx),464
AppEvent::ChatSettings => self.on_account_notifications(cx),465
AppEvent::OrgMessage(message) => self.present_org_message(message, cx),464
AppEvent::FollowedStatus { user_id, text } => {466
AppEvent::FollowedStatus { user_id, text } => {465
self.present_status_change(user_id, text, cx)467
self.present_status_change(user_id, text, cx)466
}468
}@@ -602,6 +604,24 @@ impl NotificationCenter {602
)604
)603
}605
}604
606
607
fn present_org_message(&mut self, message: &OrgMessage, cx: &mut Context<Self>) {608
let decision = self.own_feature_decision(cx);609
if !decision.toast {610
return;611
}612
let now = Instant::now();613
let id = self.stack.push_org_message(message, now);614
if let Some(model) = self.stack.get_mut(id) {615
model.time = chrono::Local::now()616
.format(crate::format::clock_format())617
.to_string();618
}619
if decision.sound && self.throttle.allow(&message.conversation_id, now) {620
self.play_notification_sound(cx);621
}622
self.sync_windows(cx);623
}624
605
fn present_status_change(&mut self, user_id: &str, text: &str, cx: &mut Context<Self>) {625
fn present_status_change(&mut self, user_id: &str, text: &str, cx: &mut Context<Self>) {606
if !self.own_feature_decision(cx).toast {626
if !self.own_feature_decision(cx).toast {607
return;627
return;@@ -1746,6 +1766,17 @@ impl NotificationCenter {1746
if self.is_dismissed(id) {1766
if self.is_dismissed(id) {1747
return;1767
return;1748
}1768
}1769
if let Some((org, conversation_id)) = self1770
.stack1771
.get(id)1772
.and_then(|toast| Some((toast.org.clone()?, toast.conversation_id.clone())))1773
{1774
self.drop_toast(id, cx);1775
self.app.update(cx, |state, cx| {1776
state.switch_org(&org, Some(&conversation_id), cx)1777
});1778
return;1779
}1749
let Some((conversation_id, message_id, proposal_id)) = self.stack.get(id).map(|toast| {1780
let Some((conversation_id, message_id, proposal_id)) = self.stack.get(id).map(|toast| {1750
(1781
(1751
toast.conversation_id.clone(),1782
toast.conversation_id.clone(),@@ -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
};@@ -867,6 +867,7 @@ impl ConversationView {
867
867
| AppEvent::CallTone(_)
868
868
| AppEvent::SoundSettings
869
869
| AppEvent::FollowedStatus { .. }
870
| AppEvent::OrgMessage(_)
870
871
| AppEvent::Call => {}
871
872
AppEvent::LiveMeeting => cx.notify(),
872
873
AppEvent::Saved => cx.notify(),
@@ -867,6 +867,7 @@ impl ConversationView {867
| AppEvent::CallTone(_)867
| AppEvent::CallTone(_)868
| AppEvent::SoundSettings868
| AppEvent::SoundSettings869
| AppEvent::FollowedStatus { .. }869
| AppEvent::FollowedStatus { .. }870
| AppEvent::OrgMessage(_)870
| AppEvent::Call => {}871
| AppEvent::Call => {}871
AppEvent::LiveMeeting => cx.notify(),872
AppEvent::LiveMeeting => cx.notify(),872
AppEvent::Saved => cx.notify(),873
AppEvent::Saved => cx.notify(),@@ -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)]
@@ -591,21 +593,22 @@ impl AppShell {
591
593
}
592
594
593
595
fn apply_open_target(&mut self, cx: &mut Context<Self>) {
594
let Some(target) = self.open_target else {
596
let Some(target) = &self.open_target else {
595
597
return;
596
598
};
597
599
let sidebar = &self.state.read(cx).sidebar;
598
600
let selection = match target {
599
601
OpenTarget::Chat(index) => sidebar
600
602
.chats
601
.get(index)
603
.get(*index)
602
604
.map(|chat| Selection::Chat(chat.id.clone())),
603
605
OpenTarget::Channel(index) => sidebar
604
606
.teams
605
607
.iter()
606
608
.flat_map(|team| team.channels.iter())
607
.nth(index)
609
.nth(*index)
608
610
.map(|channel| Selection::Channel(channel.id.clone())),
611
OpenTarget::Conversation(id) => crate::app_state::selection_for(sidebar, id),
609
612
};
610
613
if let Some(selection) = selection {
611
614
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)]73
pub enum OpenTarget {73
pub 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)]@@ -591,21 +593,22 @@ impl AppShell {591
}593
}592
594
593
fn apply_open_target(&mut self, cx: &mut Context<Self>) {595
fn apply_open_target(&mut self, cx: &mut Context<Self>) {594
let Some(target) = self.open_target else {596
let Some(target) = &self.open_target else {595
return;597
return;596
};598
};597
let sidebar = &self.state.read(cx).sidebar;599
let sidebar = &self.state.read(cx).sidebar;598
let selection = match target {600
let selection = match target {599
OpenTarget::Chat(index) => sidebar601
OpenTarget::Chat(index) => sidebar600
.chats602
.chats601
.get(index)603
.get(*index)602
.map(|chat| Selection::Chat(chat.id.clone())),604
.map(|chat| Selection::Chat(chat.id.clone())),603
OpenTarget::Channel(index) => sidebar605
OpenTarget::Channel(index) => sidebar604
.teams606
.teams605
.iter()607
.iter()606
.flat_map(|team| team.channels.iter())608
.flat_map(|team| team.channels.iter())607
.nth(index)609
.nth(*index)608
.map(|channel| Selection::Channel(channel.id.clone())),610
.map(|channel| Selection::Channel(channel.id.clone())),611
OpenTarget::Conversation(id) => crate::app_state::selection_for(sidebar, id),609
};612
};610
if let Some(selection) = selection {613
if let Some(selection) = selection {611
self.open_target = None;614
self.open_target = None;@@ -44,6 +44,7 @@ pub mod sounds;
44
44
pub mod substrate_search;
45
45
pub mod team_admin;
46
46
pub mod teams_cdn;
47
pub mod tenants;
47
48
pub mod thread_activity;
48
49
pub mod transcripts;
49
50
pub mod translate;
@@ -136,6 +137,7 @@ pub use substrate_search::{
136
137
pub use team_admin::{
137
138
ChannelEdit, ChannelPrivacy, ExistingChannel, Mailbox, NewChannel, TeamAdmin,
138
139
};
140
pub use tenants::{Tenant, list_tenants};
139
141
pub use thread_activity::{ThreadActivity, ThreadActivityKind};
140
142
pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};
141
143
pub use translate::{
@@ -44,6 +44,7 @@ pub mod sounds;44
pub mod substrate_search;44
pub mod substrate_search;45
pub mod team_admin;45
pub mod team_admin;46
pub mod teams_cdn;46
pub mod teams_cdn;47
pub mod tenants;47
pub mod thread_activity;48
pub mod thread_activity;48
pub mod transcripts;49
pub mod transcripts;49
pub mod translate;50
pub mod translate;@@ -136,6 +137,7 @@ pub use substrate_search::{136
pub use team_admin::{137
pub use team_admin::{137
ChannelEdit, ChannelPrivacy, ExistingChannel, Mailbox, NewChannel, TeamAdmin,138
ChannelEdit, ChannelPrivacy, ExistingChannel, Mailbox, NewChannel, TeamAdmin,138
};139
};140
pub use tenants::{Tenant, list_tenants};139
pub use thread_activity::{ThreadActivity, ThreadActivityKind};141
pub use thread_activity::{ThreadActivity, ThreadActivityKind};140
pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};142
pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};141
pub use translate::{143
pub use translate::{@@ -0,0 +1,79 @@
1
//! The organizations the signed-in account belongs to, as the Teams org switcher lists them.
2
use serde_json::Value;
3
use session::{Method, Session};
4
5
use crate::cards::{DEFAULT_MT_REGION, spaces_scope};
6
use crate::error::{Error, Result};
7
8
#[derive(Debug, Clone, PartialEq, Eq)]
9
pub struct Tenant {
10
pub id: String,
11
pub name: String,
12
/// The account is a guest here; its home tenant is the one with `guest == false`.
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>,
16
}
17
18
/// Every tenant of the account, home tenant first.
19
pub async fn list_tenants(session: &Session) -> Result<Vec<Tenant>> {
20
let url =
21
format!("https://teams.cloud.microsoft/api/mt/{DEFAULT_MT_REGION}/beta/users/tenants");
22
let answer = session
23
.request(Method::Get, &url, &spaces_scope(), None)
24
.await?;
25
parse_tenants(&answer.body)
26
.ok_or_else(|| Error::UnexpectedAnswer(format!("{url}: no tenant list")))
27
}
28
29
fn parse_tenants(body: &Value) -> Option<Vec<Tenant>> {
30
let mut tenants: Vec<Tenant> = body
31
.as_array()?
32
.iter()
33
.filter_map(|entry| {
34
Some(Tenant {
35
id: entry["tenantId"].as_str()?.to_ascii_lowercase(),
36
name: entry["tenantName"].as_str()?.to_owned(),
37
guest: entry["userType"]
38
.as_str()
39
.is_some_and(|kind| kind.eq_ignore_ascii_case("guest")),
40
user_id: entry["userId"].as_str().map(str::to_ascii_lowercase),
41
})
42
})
43
.collect();
44
tenants.sort_by_key(|tenant| tenant.guest);
45
Some(tenants)
46
}
47
48
#[cfg(test)]
49
mod tests {
50
use super::*;
51
use serde_json::json;
52
53
#[test]
54
fn lists_the_home_tenant_first_and_marks_guest_tenants() {
55
let body = json!([
56
{"tenantId": "BBBB-GUEST", "tenantName": "Guest Org", "userType": "guest", "userId": "AB-12"},
57
{"tenantId": "aaaa-home", "tenantName": "Home Org", "userType": "member"},
58
{"tenantName": "no id"},
59
]);
60
assert_eq!(
61
parse_tenants(&body).unwrap(),
62
vec![
63
Tenant {
64
id: "aaaa-home".into(),
65
name: "Home Org".into(),
66
guest: false,
67
user_id: None,
68
},
69
Tenant {
70
id: "bbbb-guest".into(),
71
name: "Guest Org".into(),
72
guest: true,
73
user_id: Some("ab-12".into()),
74
},
75
]
76
);
77
assert_eq!(parse_tenants(&json!({"error": 1})), None);
78
}
79
}
@@ -0,0 +1,79 @@1
//! The organizations the signed-in account belongs to, as the Teams org switcher lists them.2
use serde_json::Value;3
use session::{Method, Session};4
5
use crate::cards::{DEFAULT_MT_REGION, spaces_scope};6
use crate::error::{Error, Result};7
8
#[derive(Debug, Clone, PartialEq, Eq)]9
pub struct Tenant {10
pub id: String,11
pub name: String,12
/// The account is a guest here; its home tenant is the one with `guest == false`.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>,16
}17
18
/// Every tenant of the account, home tenant first.19
pub async fn list_tenants(session: &Session) -> Result<Vec<Tenant>> {20
let url =21
format!("https://teams.cloud.microsoft/api/mt/{DEFAULT_MT_REGION}/beta/users/tenants");22
let answer = session23
.request(Method::Get, &url, &spaces_scope(), None)24
.await?;25
parse_tenants(&answer.body)26
.ok_or_else(|| Error::UnexpectedAnswer(format!("{url}: no tenant list")))27
}28
29
fn parse_tenants(body: &Value) -> Option<Vec<Tenant>> {30
let mut tenants: Vec<Tenant> = body31
.as_array()?32
.iter()33
.filter_map(|entry| {34
Some(Tenant {35
id: entry["tenantId"].as_str()?.to_ascii_lowercase(),36
name: entry["tenantName"].as_str()?.to_owned(),37
guest: entry["userType"]38
.as_str()39
.is_some_and(|kind| kind.eq_ignore_ascii_case("guest")),40
user_id: entry["userId"].as_str().map(str::to_ascii_lowercase),41
})42
})43
.collect();44
tenants.sort_by_key(|tenant| tenant.guest);45
Some(tenants)46
}47
48
#[cfg(test)]49
mod tests {50
use super::*;51
use serde_json::json;52
53
#[test]54
fn lists_the_home_tenant_first_and_marks_guest_tenants() {55
let body = json!([56
{"tenantId": "BBBB-GUEST", "tenantName": "Guest Org", "userType": "guest", "userId": "AB-12"},57
{"tenantId": "aaaa-home", "tenantName": "Home Org", "userType": "member"},58
{"tenantName": "no id"},59
]);60
assert_eq!(61
parse_tenants(&body).unwrap(),62
vec![63
Tenant {64
id: "aaaa-home".into(),65
name: "Home Org".into(),66
guest: false,67
user_id: None,68
},69
Tenant {70
id: "bbbb-guest".into(),71
name: "Guest Org".into(),72
guest: true,73
user_id: Some("ab-12".into()),74
},75
]76
);77
assert_eq!(parse_tenants(&json!({"error": 1})), None);78
}79
}@@ -1,4 +1,4 @@
1
(async ({requests, resource, scope, marginMs, concurrency, maxBytes, forceRefresh, nestedApp}) => {
1
(async ({requests, resource, scope, marginMs, concurrency, maxBytes, forceRefresh, nestedApp, tenant}) => {
2
2
const fresh = (expires) => expires > Date.now() + marginMs;
3
3
const normalize = (value) => value.toLowerCase().replace(/\/\/+(?=[^/]*$)/, '/');
4
4
const covers = (value, name) => value === name || value === name + '.all';
@@ -54,6 +54,8 @@
54
54
if (sealed.length) await unseal();
55
55
const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome;
56
56
const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1];
57
// Without a tenant the account's home tenant; a guest tenant is reached with the same account's refresh token.
58
const inTenant = (entry) => tenant ? entry.realm === tenant : (!entry.realm || entry.realm === homeTenant(entry));
57
59
const cache = (window.__rustyTeamsTokens = window.__rustyTeamsTokens || {});
58
60
const acquire = async (resource, scope) => {
59
61
const base = resource.replace(/\/+$/, '');
@@ -62,12 +64,12 @@
62
64
const underResource = (name) => normalize(name).startsWith(base.toLowerCase() + '/');
63
65
const grants = (scopes) => scopes.some(s => (scope === '.default' ? underResource(s) : covers(normalize(s), wanted))
64
66
|| (base === 'https://graph.microsoft.com' && covers(s.toLowerCase(), short)));
65
const cacheKey = nestedApp ? base + '|' + nestedApp.clientId : base;
67
const cacheKey = [base, nestedApp ? nestedApp.clientId : '', tenant || ''].join('|');
66
68
let token = null, expiresOn = 0;
67
69
for (const entry of forceRefresh ? [] : entries) {
68
70
if (entry.credentialType !== 'AccessToken' || (entry.tokenType && entry.tokenType !== 'Bearer')) continue;
69
71
if (nestedApp && entry.clientId !== nestedApp.clientId) continue;
70
if (!ownAccount(entry) || (entry.realm && entry.realm !== homeTenant(entry))) continue;
72
if (!ownAccount(entry) || !inTenant(entry)) continue;
71
73
const expires = Number(entry.expiresOn) * 1000;
72
74
if (!grants((entry.target || '').split(' ')) || !fresh(expires) || expires <= expiresOn) continue;
73
75
token = entry.secret; expiresOn = expires;
@@ -94,7 +96,7 @@
94
96
form.set('brk_redirect_uri', nestedApp.brokerRedirectUri);
95
97
}
96
98
try {
97
const response = await fetch(`https://login.microsoftonline.com/${homeTenant(refreshToken) || 'organizations'}/oauth2/v2.0/token`,
99
const response = await fetch(`https://login.microsoftonline.com/${tenant || homeTenant(refreshToken) || 'organizations'}/oauth2/v2.0/token`,
98
100
{method: 'POST', body: form});
99
101
const answer = await response.json();
100
102
if (!response.ok) { refreshError = answer.error || `HTTP ${response.status}`; continue; }
@@ -1,4 +1,4 @@1
(async ({requests, resource, scope, marginMs, concurrency, maxBytes, forceRefresh, nestedApp}) => {1
(async ({requests, resource, scope, marginMs, concurrency, maxBytes, forceRefresh, nestedApp, tenant}) => {2
const fresh = (expires) => expires > Date.now() + marginMs;2
const fresh = (expires) => expires > Date.now() + marginMs;3
const normalize = (value) => value.toLowerCase().replace(/\/\/+(?=[^/]*$)/, '/');3
const normalize = (value) => value.toLowerCase().replace(/\/\/+(?=[^/]*$)/, '/');4
const covers = (value, name) => value === name || value === name + '.all';4
const covers = (value, name) => value === name || value === name + '.all';@@ -54,6 +54,8 @@54
if (sealed.length) await unseal();54
if (sealed.length) await unseal();55
const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome;55
const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome;56
const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1];56
const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1];57
// Without a tenant the account's home tenant; a guest tenant is reached with the same account's refresh token.58
const inTenant = (entry) => tenant ? entry.realm === tenant : (!entry.realm || entry.realm === homeTenant(entry));57
const cache = (window.__rustyTeamsTokens = window.__rustyTeamsTokens || {});59
const cache = (window.__rustyTeamsTokens = window.__rustyTeamsTokens || {});58
const acquire = async (resource, scope) => {60
const acquire = async (resource, scope) => {59
const base = resource.replace(/\/+$/, '');61
const base = resource.replace(/\/+$/, '');@@ -62,12 +64,12 @@62
const underResource = (name) => normalize(name).startsWith(base.toLowerCase() + '/');64
const underResource = (name) => normalize(name).startsWith(base.toLowerCase() + '/');63
const grants = (scopes) => scopes.some(s => (scope === '.default' ? underResource(s) : covers(normalize(s), wanted))65
const grants = (scopes) => scopes.some(s => (scope === '.default' ? underResource(s) : covers(normalize(s), wanted))64
|| (base === 'https://graph.microsoft.com' && covers(s.toLowerCase(), short)));66
|| (base === 'https://graph.microsoft.com' && covers(s.toLowerCase(), short)));65
const cacheKey = nestedApp ? base + '|' + nestedApp.clientId : base;67
const cacheKey = [base, nestedApp ? nestedApp.clientId : '', tenant || ''].join('|');66
let token = null, expiresOn = 0;68
let token = null, expiresOn = 0;67
for (const entry of forceRefresh ? [] : entries) {69
for (const entry of forceRefresh ? [] : entries) {68
if (entry.credentialType !== 'AccessToken' || (entry.tokenType && entry.tokenType !== 'Bearer')) continue;70
if (entry.credentialType !== 'AccessToken' || (entry.tokenType && entry.tokenType !== 'Bearer')) continue;69
if (nestedApp && entry.clientId !== nestedApp.clientId) continue;71
if (nestedApp && entry.clientId !== nestedApp.clientId) continue;70
if (!ownAccount(entry) || (entry.realm && entry.realm !== homeTenant(entry))) continue;72
if (!ownAccount(entry) || !inTenant(entry)) continue;71
const expires = Number(entry.expiresOn) * 1000;73
const expires = Number(entry.expiresOn) * 1000;72
if (!grants((entry.target || '').split(' ')) || !fresh(expires) || expires <= expiresOn) continue;74
if (!grants((entry.target || '').split(' ')) || !fresh(expires) || expires <= expiresOn) continue;73
token = entry.secret; expiresOn = expires;75
token = entry.secret; expiresOn = expires;@@ -94,7 +96,7 @@94
form.set('brk_redirect_uri', nestedApp.brokerRedirectUri);96
form.set('brk_redirect_uri', nestedApp.brokerRedirectUri);95
}97
}96
try {98
try {97
const response = await fetch(`https://login.microsoftonline.com/${homeTenant(refreshToken) || 'organizations'}/oauth2/v2.0/token`,99
const response = await fetch(`https://login.microsoftonline.com/${tenant || homeTenant(refreshToken) || 'organizations'}/oauth2/v2.0/token`,98
{method: 'POST', body: form});100
{method: 'POST', body: form});99
const answer = await response.json();101
const answer = await response.json();100
if (!response.ok) { refreshError = answer.error || `HTTP ${response.status}`; continue; }102
if (!response.ok) { refreshError = answer.error || `HTTP ${response.status}`; continue; }@@ -55,6 +55,7 @@ impl Session {
55
55
"concurrency": 1,
56
56
"maxBytes": 1,
57
57
"forceRefresh": force_refresh,
58
"tenant": self.tenant(),
58
59
});
59
60
let script = format!(
60
61
"{head}{TOKEN_MARKER}\nconst args = {args};\n{body}\n}})",
@@ -55,6 +55,7 @@ impl Session {55
"concurrency": 1,55
"concurrency": 1,56
"maxBytes": 1,56
"maxBytes": 1,57
"forceRefresh": force_refresh,57
"forceRefresh": force_refresh,58
"tenant": self.tenant(),58
});59
});59
let script = format!(60
let script = format!(60
"{head}{TOKEN_MARKER}\nconst args = {args};\n{body}\n}})",61
"{head}{TOKEN_MARKER}\nconst args = {args};\n{body}\n}})",@@ -74,6 +74,7 @@ pub struct Session {
74
74
tabs: Arc<HashMap<App, Mutex<Option<TabControl>>>>,
75
75
force_refresh: Arc<AtomicBool>,
76
76
native: Option<Arc<NativeHttp>>,
77
tenant: Option<Arc<str>>,
77
78
}
78
79
79
80
impl Session {
@@ -90,13 +91,9 @@ impl Session {
90
91
config: SessionConfig,
91
92
) -> Result<Self> {
92
93
transport.check().await?;
93
let native = config
94
.native_http
95
.then(|| NativeHttp::new(config.evaluate_timeout, MAX_DOWNLOAD_BYTES))
96
.flatten()
97
.map(Arc::new);
98
94
Ok(Session {
99
native,
95
native: native_http(&config),
96
tenant: None,
100
97
transport,
101
98
config,
102
99
tabs: Arc::new(
@@ -109,6 +106,22 @@ impl Session {
109
106
})
110
107
}
111
108
109
/// The same browser session with tokens for `tenant_id`, e.g. a tenant the account is a guest in.
110
/// Tokens are held apart from the home tenant's, so both can run side by side.
111
pub fn in_tenant(&self, tenant_id: &str) -> Session {
112
Session {
113
native: native_http(&self.config),
114
force_refresh: Arc::new(AtomicBool::new(false)),
115
tenant: Some(tenant_id.to_ascii_lowercase().into()),
116
..self.clone()
117
}
118
}
119
120
/// The tenant set with [`Session::in_tenant`]; `None` is the account's home tenant.
121
pub fn tenant(&self) -> Option<&str> {
122
self.tenant.as_deref()
123
}
124
112
125
pub async fn request(
113
126
&self,
114
127
method: Method,
@@ -314,6 +327,7 @@ impl Session {
314
327
"concurrency": DEFAULT_CONCURRENCY,
315
328
"maxBytes": MAX_DOWNLOAD_BYTES,
316
329
"forceRefresh": self.force_refresh.load(Ordering::SeqCst),
330
"tenant": self.tenant(),
317
331
})
318
332
.to_string()
319
333
}
@@ -364,6 +378,14 @@ impl Drop for TabHold {
364
378
}
365
379
}
366
380
381
fn native_http(config: &SessionConfig) -> Option<Arc<NativeHttp>> {
382
config
383
.native_http
384
.then(|| NativeHttp::new(config.evaluate_timeout, MAX_DOWNLOAD_BYTES))
385
.flatten()
386
.map(Arc::new)
387
}
388
367
389
pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
368
390
header
369
391
.and_then(|value| value.trim().parse::<f64>().ok())
@@ -420,6 +442,25 @@ mod tests {
420
442
);
421
443
}
422
444
445
#[tokio::test]
446
async fn a_tenant_session_asks_the_page_for_that_tenant_only() {
447
let home =
448
Session::with_transport(Arc::new(HoldRecorder::default()), SessionConfig::default())
449
.await
450
.unwrap();
451
let guest = home.in_tenant("AAAA-Guest");
452
let request = Request::get("https://graph.microsoft.com/v1.0/me");
453
let tenant_of = |session: &Session| {
454
let payload: Value =
455
serde_json::from_str(&session.payload(&[&request], &Scope::graph("User.Read")))
456
.unwrap();
457
payload["tenant"].clone()
458
};
459
assert_eq!(tenant_of(&home), Value::Null);
460
assert_eq!(tenant_of(&guest), json!("aaaa-guest"));
461
assert_eq!(home.tenant(), None);
462
}
463
423
464
#[test]
424
465
fn retry_after_seconds_parse() {
425
466
let default = Duration::from_secs(2);
@@ -74,6 +74,7 @@ pub struct Session {74
tabs: Arc<HashMap<App, Mutex<Option<TabControl>>>>,74
tabs: Arc<HashMap<App, Mutex<Option<TabControl>>>>,75
force_refresh: Arc<AtomicBool>,75
force_refresh: Arc<AtomicBool>,76
native: Option<Arc<NativeHttp>>,76
native: Option<Arc<NativeHttp>>,77
tenant: Option<Arc<str>>,77
}78
}78
79
79
impl Session {80
impl Session {@@ -90,13 +91,9 @@ impl Session {90
config: SessionConfig,91
config: SessionConfig,91
) -> Result<Self> {92
) -> Result<Self> {92
transport.check().await?;93
transport.check().await?;93
let native = config94
.native_http95
.then(|| NativeHttp::new(config.evaluate_timeout, MAX_DOWNLOAD_BYTES))96
.flatten()97
.map(Arc::new);98
Ok(Session {94
Ok(Session {99
native,95
native: native_http(&config),96
tenant: None,100
transport,97
transport,101
config,98
config,102
tabs: Arc::new(99
tabs: Arc::new(@@ -109,6 +106,22 @@ impl Session {109
})106
})110
}107
}111
108
109
/// The same browser session with tokens for `tenant_id`, e.g. a tenant the account is a guest in.110
/// Tokens are held apart from the home tenant's, so both can run side by side.111
pub fn in_tenant(&self, tenant_id: &str) -> Session {112
Session {113
native: native_http(&self.config),114
force_refresh: Arc::new(AtomicBool::new(false)),115
tenant: Some(tenant_id.to_ascii_lowercase().into()),116
..self.clone()117
}118
}119
120
/// The tenant set with [`Session::in_tenant`]; `None` is the account's home tenant.121
pub fn tenant(&self) -> Option<&str> {122
self.tenant.as_deref()123
}124
112
pub async fn request(125
pub async fn request(113
&self,126
&self,114
method: Method,127
method: Method,@@ -314,6 +327,7 @@ impl Session {314
"concurrency": DEFAULT_CONCURRENCY,327
"concurrency": DEFAULT_CONCURRENCY,315
"maxBytes": MAX_DOWNLOAD_BYTES,328
"maxBytes": MAX_DOWNLOAD_BYTES,316
"forceRefresh": self.force_refresh.load(Ordering::SeqCst),329
"forceRefresh": self.force_refresh.load(Ordering::SeqCst),330
"tenant": self.tenant(),317
})331
})318
.to_string()332
.to_string()319
}333
}@@ -364,6 +378,14 @@ impl Drop for TabHold {364
}378
}365
}379
}366
380
381
fn native_http(config: &SessionConfig) -> Option<Arc<NativeHttp>> {382
config383
.native_http384
.then(|| NativeHttp::new(config.evaluate_timeout, MAX_DOWNLOAD_BYTES))385
.flatten()386
.map(Arc::new)387
}388
367
pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {389
pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {368
header390
header369
.and_then(|value| value.trim().parse::<f64>().ok())391
.and_then(|value| value.trim().parse::<f64>().ok())@@ -420,6 +442,25 @@ mod tests {420
);442
);421
}443
}422
444
445
#[tokio::test]446
async fn a_tenant_session_asks_the_page_for_that_tenant_only() {447
let home =448
Session::with_transport(Arc::new(HoldRecorder::default()), SessionConfig::default())449
.await450
.unwrap();451
let guest = home.in_tenant("AAAA-Guest");452
let request = Request::get("https://graph.microsoft.com/v1.0/me");453
let tenant_of = |session: &Session| {454
let payload: Value =455
serde_json::from_str(&session.payload(&[&request], &Scope::graph("User.Read")))456
.unwrap();457
payload["tenant"].clone()458
};459
assert_eq!(tenant_of(&home), Value::Null);460
assert_eq!(tenant_of(&guest), json!("aaaa-guest"));461
assert_eq!(home.tenant(), None);462
}463
423
#[test]464
#[test]424
fn retry_after_seconds_parse() {465
fn retry_after_seconds_parse() {425
let default = Duration::from_secs(2);466
let default = Duration::from_secs(2);@@ -0,0 +1,29 @@
1
---
2
status: accepted
3
date: 2026-11-15
4
---
5
6
# ADR 0017: Guest orgs, one org per window, switch by restart
7
8
## Context
9
10
One account can be a member of its home tenant and a guest in other tenants. Teams lists these orgs in the account menu, shows one org at a time and keeps the others alive for notifications.
11
12
Rusty Teams took tokens of the home tenant only, so a guest org could not be opened at all. The app's store, engine and views assume one org for the lifetime of the process.
13
14
Options were: swap the store and engine under the running UI, run a second process per org, or restart on the chosen org.
15
16
## Decision
17
18
- Guest tenants use the same browser session. `Session::in_tenant` picks tokens of that tenant from the page and redeems the account's refresh token at that tenant's token endpoint, as Teams does. No second sign-in.
19
- The org list comes from `mt/{region}/beta/users/tenants` and is kept in `orgs.json` beside the caches, together with the org the window shows.
20
- Each org has its own cache: the home org keeps `cache.sqlite3`, a guest org gets `cache-<tenant id>.sqlite3`. Local settings stored in the cache are per org.
21
- The account menu lists the orgs when there is more than one. Picking another org saves it and restarts the app, which opens that org's cache at once. Teams switches without a restart; this is the deviation.
22
- Calls keep the home tenant's registration in every org.
23
24
## Consequences
25
26
- A guest org works with all features that go through the session, because every token request carries the tenant.
27
- Switching costs a restart of a second or two instead of an in-place swap. Swapping the store under the UI would touch every view that holds it.
28
- Calls inside a guest org and Outlook calendar for a guest (no mailbox there) are not covered.
29
- Every org that is not open keeps its own realtime socket through a tenant session. New chat messages from others show as toasts that name the org, without quick reply, and the menu counts chats with new messages. Clicking the toast restarts on that org with `--open-conversation`. Channel posts of other orgs do not notify.
@@ -0,0 +1,29 @@1
---2
status: accepted3
date: 2026-11-154
---5
6
# ADR 0017: Guest orgs, one org per window, switch by restart7
8
## Context9
10
One account can be a member of its home tenant and a guest in other tenants. Teams lists these orgs in the account menu, shows one org at a time and keeps the others alive for notifications.11
12
Rusty Teams took tokens of the home tenant only, so a guest org could not be opened at all. The app's store, engine and views assume one org for the lifetime of the process.13
14
Options were: swap the store and engine under the running UI, run a second process per org, or restart on the chosen org.15
16
## Decision17
18
- Guest tenants use the same browser session. `Session::in_tenant` picks tokens of that tenant from the page and redeems the account's refresh token at that tenant's token endpoint, as Teams does. No second sign-in.19
- The org list comes from `mt/{region}/beta/users/tenants` and is kept in `orgs.json` beside the caches, together with the org the window shows.20
- Each org has its own cache: the home org keeps `cache.sqlite3`, a guest org gets `cache-<tenant id>.sqlite3`. Local settings stored in the cache are per org.21
- The account menu lists the orgs when there is more than one. Picking another org saves it and restarts the app, which opens that org's cache at once. Teams switches without a restart; this is the deviation.22
- Calls keep the home tenant's registration in every org.23
24
## Consequences25
26
- A guest org works with all features that go through the session, because every token request carries the tenant.27
- Switching costs a restart of a second or two instead of an in-place swap. Swapping the store under the UI would touch every view that holds it.28
- Calls inside a guest org and Outlook calendar for a guest (no mailbox there) are not covered.29
- Every org that is not open keeps its own realtime socket through a tenant session. New chat messages from others show as toasts that name the org, without quick reply, and the menu counts chats with new messages. Clicking the toast restarts on that org with `--open-conversation`. Channel posts of other orgs do not notify.@@ -32,5 +32,6 @@ Statuses: `proposed`, `accepted`, `superseded`.
32
32
| [0014](0014-linux-installs-and-updates-itself.md) | The Linux binary installs and updates itself |
33
33
| [0015](0015-linux-desktop-toasts-use-freedesktop-notifications.md) | Linux desktop toasts use freedesktop Notifications |
34
34
| [0016](0016-calendar-week-start-and-time-scale-stay-local.md) | Calendar work hours go to the mailbox, week start and time scale stay local |
35
| [0017](0017-guest-orgs-switch-by-restart.md) | Guest orgs, one org per window, switch by restart |
35
36
36
Records `0001` to `0016` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
37
Records `0001` to `0017` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
@@ -32,5 +32,6 @@ Statuses: `proposed`, `accepted`, `superseded`.32
| [0014](0014-linux-installs-and-updates-itself.md) | The Linux binary installs and updates itself |32
| [0014](0014-linux-installs-and-updates-itself.md) | The Linux binary installs and updates itself |33
| [0015](0015-linux-desktop-toasts-use-freedesktop-notifications.md) | Linux desktop toasts use freedesktop Notifications |33
| [0015](0015-linux-desktop-toasts-use-freedesktop-notifications.md) | Linux desktop toasts use freedesktop Notifications |34
| [0016](0016-calendar-week-start-and-time-scale-stay-local.md) | Calendar work hours go to the mailbox, week start and time scale stay local |34
| [0016](0016-calendar-week-start-and-time-scale-stay-local.md) | Calendar work hours go to the mailbox, week start and time scale stay local |35
| [0017](0017-guest-orgs-switch-by-restart.md) | Guest orgs, one org per window, switch by restart |35
36
36
Records `0001` to `0016` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.37
Records `0001` to `0017` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.@@ -65,6 +65,7 @@ Token audiences (not requests): `crates/session/src/scope.rs` - `ic3.teams.offic
65
65
| `/beta/me/calendarEvents/privateMeeting/schedulingService/create` | POST | `crates/chatsvc/src/calendar.rs` | Meet now | W | partly - `/me/onlineMeetings`; no ad-hoc chat unhide |
66
66
| `/beta/chats/{id}/apps/chatentitlements` | GET | `crates/chatsvc/src/cards.rs` | apps entitled in a chat | R | partly - `/chats/{id}/installedApps` |
67
67
| `/beta/commands/com.microsoft.teamspace.inputextension.giphy/execute?version=1.0` | POST | `crates/chatsvc/src/gifs.rs` | GIF search and trending | R | no |
68
| `/beta/users/tenants` | GET | `crates/chatsvc/src/tenants.rs` | the account's home and guest tenants for the org switcher (`userType` member or guest) | R | no - Graph lists only the tenant of the token |
68
69
| `/beta/users/fetchShortProfile?...&includeBots=true` | POST | `crates/chatsvc/src/bot_profiles.rs` | bot names and images | R | no |
69
70
| `/beta/users/useraggregatesettings` | POST | `crates/chatsvc/src/language_settings.rs`, `crates/chatsvc/src/sound_settings.rs` | translation, voice and recording policy settings | R | no |
70
71
| `/beta/users/languageAccountSettings` | PATCH | `crates/chatsvc/src/language_settings.rs` | translation preferences | W | no |
@@ -65,6 +65,7 @@ Token audiences (not requests): `crates/session/src/scope.rs` - `ic3.teams.offic65
| `/beta/me/calendarEvents/privateMeeting/schedulingService/create` | POST | `crates/chatsvc/src/calendar.rs` | Meet now | W | partly - `/me/onlineMeetings`; no ad-hoc chat unhide |65
| `/beta/me/calendarEvents/privateMeeting/schedulingService/create` | POST | `crates/chatsvc/src/calendar.rs` | Meet now | W | partly - `/me/onlineMeetings`; no ad-hoc chat unhide |66
| `/beta/chats/{id}/apps/chatentitlements` | GET | `crates/chatsvc/src/cards.rs` | apps entitled in a chat | R | partly - `/chats/{id}/installedApps` |66
| `/beta/chats/{id}/apps/chatentitlements` | GET | `crates/chatsvc/src/cards.rs` | apps entitled in a chat | R | partly - `/chats/{id}/installedApps` |67
| `/beta/commands/com.microsoft.teamspace.inputextension.giphy/execute?version=1.0` | POST | `crates/chatsvc/src/gifs.rs` | GIF search and trending | R | no |67
| `/beta/commands/com.microsoft.teamspace.inputextension.giphy/execute?version=1.0` | POST | `crates/chatsvc/src/gifs.rs` | GIF search and trending | R | no |68
| `/beta/users/tenants` | GET | `crates/chatsvc/src/tenants.rs` | the account's home and guest tenants for the org switcher (`userType` member or guest) | R | no - Graph lists only the tenant of the token |68
| `/beta/users/fetchShortProfile?...&includeBots=true` | POST | `crates/chatsvc/src/bot_profiles.rs` | bot names and images | R | no |69
| `/beta/users/fetchShortProfile?...&includeBots=true` | POST | `crates/chatsvc/src/bot_profiles.rs` | bot names and images | R | no |69
| `/beta/users/useraggregatesettings` | POST | `crates/chatsvc/src/language_settings.rs`, `crates/chatsvc/src/sound_settings.rs` | translation, voice and recording policy settings | R | no |70
| `/beta/users/useraggregatesettings` | POST | `crates/chatsvc/src/language_settings.rs`, `crates/chatsvc/src/sound_settings.rs` | translation, voice and recording policy settings | R | no |70
| `/beta/users/languageAccountSettings` | PATCH | `crates/chatsvc/src/language_settings.rs` | translation preferences | W | no |71
| `/beta/users/languageAccountSettings` | PATCH | `crates/chatsvc/src/language_settings.rs` | translation preferences | W | no |