feat(orgs): open a guest org from the account menu
The account menu lists the account's orgs like Teams, the open one checked. Picking another saves it in orgs.json and restarts the app on it: a guest org opens its own cache-<tenant>.sqlite3 and the backend syncs through a tenant session, the home org keeps cache.sqlite3. Deviation from Teams: switching restarts the app instead of swapping in place (ADR 0015). Calls keep the home tenant's registration. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -1413,6 +1413,9 @@ shell:
1413
1413
en: Settings and more
1414
1414
de: Einstellungen und mehr
1415
1415
status_menu:
1416
guest_org:
1417
en: "%{name} (Guest)"
1418
de: "%{name} (Gast)"
1416
1419
view_account:
1417
1420
en: View account
1418
1421
de: Konto anzeigen
@@ -1413,6 +1413,9 @@ shell:1413
en: Settings and more1413
en: Settings and more1414
de: Einstellungen und mehr1414
de: Einstellungen und mehr1415
status_menu:1415
status_menu:1416
guest_org:1417
en: "%{name} (Guest)"1418
de: "%{name} (Gast)"1416
view_account:1419
view_account:1417
en: View account1420
en: View account1418
de: Konto anzeigen1421
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,122 @@
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
const HOME_DATABASE: &str = "cache.sqlite3";
11
12
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13
pub struct Org {
14
pub id: String,
15
pub name: String,
16
pub guest: bool,
17
}
18
19
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
20
pub struct Orgs {
21
/// Tenant id of the org the window shows; `None` is the home tenant.
22
pub active: Option<String>,
23
pub list: Vec<Org>,
24
}
25
26
impl Orgs {
27
pub fn path() -> Option<PathBuf> {
28
crate::support::local_data_dir().map(|root| root.join(ORGS_FILE))
29
}
30
31
/// A missing or unreadable file is the home tenant with no known orgs.
32
pub fn load(path: &Path) -> Orgs {
33
std::fs::read(path)
34
.ok()
35
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
36
.unwrap_or_default()
37
}
38
39
pub fn save(&self, path: &Path) -> std::io::Result<()> {
40
let bytes = serde_json::to_vec_pretty(self).map_err(std::io::Error::other)?;
41
std::fs::write(path, bytes)
42
}
43
44
/// The active org when it is a guest tenant, the only case that needs its own tokens and cache.
45
pub fn active_guest(&self) -> Option<&Org> {
46
let active = self.active.as_deref()?;
47
self.list
48
.iter()
49
.find(|org| org.guest && org.id == active && is_tenant_id(&org.id))
50
}
51
52
pub fn is_active(&self, org: &Org) -> bool {
53
match self.active_guest() {
54
Some(active) => active.id == org.id,
55
None => !org.guest,
56
}
57
}
58
59
pub fn database_file(&self) -> String {
60
match self.active_guest() {
61
Some(org) => format!("cache-{}.sqlite3", org.id),
62
None => HOME_DATABASE.to_owned(),
63
}
64
}
65
66
/// Takes the account's current org list; an active org that is gone falls back to home.
67
pub fn replace_list(&mut self, list: Vec<Org>) {
68
self.list = list;
69
if self.active_guest().is_none() {
70
self.active = None;
71
}
72
}
73
74
pub fn activate(&mut self, org: &Org) {
75
self.active = org.guest.then(|| org.id.clone());
76
}
77
}
78
79
/// Tenant ids are GUIDs; anything else must not end up in a file name.
80
fn is_tenant_id(id: &str) -> bool {
81
!id.is_empty() && id.chars().all(|character| character.is_ascii_hexdigit() || character == '-')
82
}
83
84
#[cfg(test)]
85
mod tests {
86
use super::*;
87
88
fn org(id: &str, guest: bool) -> Org {
89
Org {
90
id: id.into(),
91
name: id.into(),
92
guest,
93
}
94
}
95
96
#[test]
97
fn a_guest_org_gets_its_own_cache_and_home_keeps_the_old_one() {
98
let mut orgs = Orgs {
99
active: None,
100
list: vec![org("aaaa-01", false), org("bbbb-02", true)],
101
};
102
assert_eq!(orgs.database_file(), "cache.sqlite3");
103
assert!(orgs.is_active(&orgs.list[0].clone()));
104
orgs.activate(&orgs.list[1].clone());
105
assert_eq!(orgs.database_file(), "cache-bbbb-02.sqlite3");
106
assert!(orgs.is_active(&orgs.list[1].clone()));
107
orgs.activate(&orgs.list[0].clone());
108
assert_eq!(orgs.active, None);
109
}
110
111
#[test]
112
fn an_unknown_or_unsafe_active_org_is_the_home_tenant() {
113
let mut orgs = Orgs {
114
active: Some("../evil".into()),
115
list: vec![org("../evil", true)],
116
};
117
assert_eq!(orgs.database_file(), "cache.sqlite3");
118
orgs.active = Some("bbbb-02".into());
119
orgs.replace_list(vec![org("aaaa-01", false)]);
120
assert_eq!(orgs.active, None);
121
}
122
}
@@ -0,0 +1,122 @@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
const HOME_DATABASE: &str = "cache.sqlite3";11
12
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]13
pub struct Org {14
pub id: String,15
pub name: String,16
pub guest: bool,17
}18
19
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]20
pub struct Orgs {21
/// Tenant id of the org the window shows; `None` is the home tenant.22
pub active: Option<String>,23
pub list: Vec<Org>,24
}25
26
impl Orgs {27
pub fn path() -> Option<PathBuf> {28
crate::support::local_data_dir().map(|root| root.join(ORGS_FILE))29
}30
31
/// A missing or unreadable file is the home tenant with no known orgs.32
pub fn load(path: &Path) -> Orgs {33
std::fs::read(path)34
.ok()35
.and_then(|bytes| serde_json::from_slice(&bytes).ok())36
.unwrap_or_default()37
}38
39
pub fn save(&self, path: &Path) -> std::io::Result<()> {40
let bytes = serde_json::to_vec_pretty(self).map_err(std::io::Error::other)?;41
std::fs::write(path, bytes)42
}43
44
/// The active org when it is a guest tenant, the only case that needs its own tokens and cache.45
pub fn active_guest(&self) -> Option<&Org> {46
let active = self.active.as_deref()?;47
self.list48
.iter()49
.find(|org| org.guest && org.id == active && is_tenant_id(&org.id))50
}51
52
pub fn is_active(&self, org: &Org) -> bool {53
match self.active_guest() {54
Some(active) => active.id == org.id,55
None => !org.guest,56
}57
}58
59
pub fn database_file(&self) -> String {60
match self.active_guest() {61
Some(org) => format!("cache-{}.sqlite3", org.id),62
None => HOME_DATABASE.to_owned(),63
}64
}65
66
/// Takes the account's current org list; an active org that is gone falls back to home.67
pub fn replace_list(&mut self, list: Vec<Org>) {68
self.list = list;69
if self.active_guest().is_none() {70
self.active = None;71
}72
}73
74
pub fn activate(&mut self, org: &Org) {75
self.active = org.guest.then(|| org.id.clone());76
}77
}78
79
/// Tenant ids are GUIDs; anything else must not end up in a file name.80
fn is_tenant_id(id: &str) -> bool {81
!id.is_empty() && id.chars().all(|character| character.is_ascii_hexdigit() || character == '-')82
}83
84
#[cfg(test)]85
mod tests {86
use super::*;87
88
fn org(id: &str, guest: bool) -> Org {89
Org {90
id: id.into(),91
name: id.into(),92
guest,93
}94
}95
96
#[test]97
fn a_guest_org_gets_its_own_cache_and_home_keeps_the_old_one() {98
let mut orgs = Orgs {99
active: None,100
list: vec![org("aaaa-01", false), org("bbbb-02", true)],101
};102
assert_eq!(orgs.database_file(), "cache.sqlite3");103
assert!(orgs.is_active(&orgs.list[0].clone()));104
orgs.activate(&orgs.list[1].clone());105
assert_eq!(orgs.database_file(), "cache-bbbb-02.sqlite3");106
assert!(orgs.is_active(&orgs.list[1].clone()));107
orgs.activate(&orgs.list[0].clone());108
assert_eq!(orgs.active, None);109
}110
111
#[test]112
fn an_unknown_or_unsafe_active_org_is_the_home_tenant() {113
let mut orgs = Orgs {114
active: Some("../evil".into()),115
list: vec![org("../evil", true)],116
};117
assert_eq!(orgs.database_file(), "cache.sqlite3");118
orgs.active = Some("bbbb-02".into());119
orgs.replace_list(vec![org("aaaa-01", false)]);120
assert_eq!(orgs.active, None);121
}122
}@@ -133,6 +133,8 @@ pub struct AppState {
133
133
pub collapsed: HashSet<String>,
134
134
pub expanded_lists: HashSet<String>,
135
135
pub start_on_channels: bool,
136
/// The account's organizations and the one this window shows.
137
pub orgs: app_base::orgs::Orgs,
136
138
pub pending_jump: Option<(String, String)>,
137
139
pub cards: CardState,
138
140
pub task_dialog: Option<TaskDialogState>,
@@ -300,6 +302,7 @@ impl AppState {
300
302
collapsed: HashSet::new(),
301
303
expanded_lists: HashSet::new(),
302
304
start_on_channels: false,
305
orgs: app_base::orgs::Orgs::default(),
303
306
pending_jump: None,
304
307
cards: CardState::default(),
305
308
task_dialog: None,
@@ -1247,6 +1250,10 @@ impl AppState {
1247
1250
self.refresh_connection_banner(cx);
1248
1251
cx.emit(AppEvent::Status);
1249
1252
}
1253
BackendEvent::Orgs(list) => {
1254
self.take_org_list(list);
1255
cx.notify();
1256
}
1250
1257
BackendEvent::Favorites(ids) => {
1251
1258
self.favorite_ids = ids;
1252
1259
if !self.mode.demo {
@@ -133,6 +133,8 @@ pub struct AppState {133
pub collapsed: HashSet<String>,133
pub collapsed: HashSet<String>,134
pub expanded_lists: HashSet<String>,134
pub expanded_lists: HashSet<String>,135
pub start_on_channels: bool,135
pub start_on_channels: bool,136
/// The account's organizations and the one this window shows.137
pub orgs: app_base::orgs::Orgs,136
pub pending_jump: Option<(String, String)>,138
pub pending_jump: Option<(String, String)>,137
pub cards: CardState,139
pub cards: CardState,138
pub task_dialog: Option<TaskDialogState>,140
pub task_dialog: Option<TaskDialogState>,@@ -300,6 +302,7 @@ impl AppState {300
collapsed: HashSet::new(),302
collapsed: HashSet::new(),301
expanded_lists: HashSet::new(),303
expanded_lists: HashSet::new(),302
start_on_channels: false,304
start_on_channels: false,305
orgs: app_base::orgs::Orgs::default(),303
pending_jump: None,306
pending_jump: None,304
cards: CardState::default(),307
cards: CardState::default(),305
task_dialog: None,308
task_dialog: None,@@ -1247,6 +1250,10 @@ impl AppState {1247
self.refresh_connection_banner(cx);1250
self.refresh_connection_banner(cx);1248
cx.emit(AppEvent::Status);1251
cx.emit(AppEvent::Status);1249
}1252
}1253
BackendEvent::Orgs(list) => {1254
self.take_org_list(list);1255
cx.notify();1256
}1250
BackendEvent::Favorites(ids) => {1257
BackendEvent::Favorites(ids) => {1251
self.favorite_ids = ids;1258
self.favorite_ids = ids;1252
if !self.mode.demo {1259
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,7 @@ 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>),
75
77
}
76
78
77
79
impl BackendEvent {
@@ -95,6 +97,7 @@ impl BackendEvent {
95
97
BackendEvent::Favorites(_) => "Favorites".into(),
96
98
BackendEvent::Synced(_) => "Synced".into(),
97
99
BackendEvent::LiveRetry(_) => "LiveRetry".into(),
100
BackendEvent::Orgs(_) => "Orgs".into(),
98
101
}
99
102
}
100
103
}
@@ -150,9 +153,17 @@ pub fn start(
150
153
transport: Arc<dyn Transport>,
151
154
ringable: bool,
152
155
activity: watch::Receiver<bool>,
156
guest_tenant: Option<String>,
153
157
) -> mpsc::UnboundedReceiver<BackendEvent> {
154
158
let (sender, receiver) = mpsc::unbounded_channel();
155
crate::runtime::handle().spawn(supervise(store, transport, ringable, activity, sender));
159
crate::runtime::handle().spawn(supervise(
160
store,
161
transport,
162
ringable,
163
activity,
164
guest_tenant,
165
sender,
166
));
156
167
receiver
157
168
}
158
169
@@ -161,10 +172,11 @@ async fn supervise(
161
172
transport: Arc<dyn Transport>,
162
173
ringable: bool,
163
174
activity: watch::Receiver<bool>,
175
guest_tenant: Option<String>,
164
176
events: EventSender,
165
177
) {
166
178
let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));
167
let session = loop {
179
let home = loop {
168
180
match Session::with_transport(transport.clone(), SessionConfig::for_app()).await {
169
181
Ok(session) => break session,
170
182
Err(error) => {
@@ -173,6 +185,12 @@ async fn supervise(
173
185
}
174
186
}
175
187
};
188
tokio::spawn(org_list(home.clone(), events.clone()));
189
// Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.
190
let session = match &guest_tenant {
191
Some(tenant) => home.in_tenant(tenant),
192
None => home,
193
};
176
194
let build = || {
177
195
SyncEngine::new(Graph::new(session.clone()), store.clone())
178
196
.with_folder_source(Arc::new(ChatsvcFolderSource::new(&session)))
@@ -217,6 +235,30 @@ async fn supervise(
217
235
refresh_loop(engine, events, nudges).await;
218
236
}
219
237
238
/// Fetches the account's organizations once per start; retried a few times while sign-in settles.
239
async fn org_list(home: Session, events: EventSender) {
240
for _ in 0..ORG_LIST_ATTEMPTS {
241
match chatsvc::list_tenants(&home).await {
242
Ok(tenants) => {
243
let orgs = tenants
244
.into_iter()
245
.map(|tenant| app_base::orgs::Org {
246
id: tenant.id,
247
name: tenant.name,
248
guest: tenant.guest,
249
})
250
.collect();
251
let _ = events.send(BackendEvent::Orgs(orgs));
252
return;
253
}
254
Err(error) => {
255
crate::diagnostics::record(format!("orgs: tenant list not loaded: {error}"));
256
tokio::time::sleep(CONNECT_RETRY).await;
257
}
258
}
259
}
260
}
261
220
262
async fn forward_core_events(engine: Arc<Engine>, events: EventSender) {
221
263
let mut receiver = engine.subscribe();
222
264
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,7 @@ 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>),75
}77
}76
78
77
impl BackendEvent {79
impl BackendEvent {@@ -95,6 +97,7 @@ impl BackendEvent {95
BackendEvent::Favorites(_) => "Favorites".into(),97
BackendEvent::Favorites(_) => "Favorites".into(),96
BackendEvent::Synced(_) => "Synced".into(),98
BackendEvent::Synced(_) => "Synced".into(),97
BackendEvent::LiveRetry(_) => "LiveRetry".into(),99
BackendEvent::LiveRetry(_) => "LiveRetry".into(),100
BackendEvent::Orgs(_) => "Orgs".into(),98
}101
}99
}102
}100
}103
}@@ -150,9 +153,17 @@ pub fn start(150
transport: Arc<dyn Transport>,153
transport: Arc<dyn Transport>,151
ringable: bool,154
ringable: bool,152
activity: watch::Receiver<bool>,155
activity: watch::Receiver<bool>,156
guest_tenant: Option<String>,153
) -> mpsc::UnboundedReceiver<BackendEvent> {157
) -> mpsc::UnboundedReceiver<BackendEvent> {154
let (sender, receiver) = mpsc::unbounded_channel();158
let (sender, receiver) = mpsc::unbounded_channel();155
crate::runtime::handle().spawn(supervise(store, transport, ringable, activity, sender));159
crate::runtime::handle().spawn(supervise(160
store,161
transport,162
ringable,163
activity,164
guest_tenant,165
sender,166
));156
receiver167
receiver157
}168
}158
169
@@ -161,10 +172,11 @@ async fn supervise(161
transport: Arc<dyn Transport>,172
transport: Arc<dyn Transport>,162
ringable: bool,173
ringable: bool,163
activity: watch::Receiver<bool>,174
activity: watch::Receiver<bool>,175
guest_tenant: Option<String>,164
events: EventSender,176
events: EventSender,165
) {177
) {166
let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));178
let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));167
let session = loop {179
let home = loop {168
match Session::with_transport(transport.clone(), SessionConfig::for_app()).await {180
match Session::with_transport(transport.clone(), SessionConfig::for_app()).await {169
Ok(session) => break session,181
Ok(session) => break session,170
Err(error) => {182
Err(error) => {@@ -173,6 +185,12 @@ async fn supervise(173
}185
}174
}186
}175
};187
};188
tokio::spawn(org_list(home.clone(), events.clone()));189
// Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.190
let session = match &guest_tenant {191
Some(tenant) => home.in_tenant(tenant),192
None => home,193
};176
let build = || {194
let build = || {177
SyncEngine::new(Graph::new(session.clone()), store.clone())195
SyncEngine::new(Graph::new(session.clone()), store.clone())178
.with_folder_source(Arc::new(ChatsvcFolderSource::new(&session)))196
.with_folder_source(Arc::new(ChatsvcFolderSource::new(&session)))@@ -217,6 +235,30 @@ async fn supervise(217
refresh_loop(engine, events, nudges).await;235
refresh_loop(engine, events, nudges).await;218
}236
}219
237
238
/// Fetches the account's organizations once per start; retried a few times while sign-in settles.239
async fn org_list(home: Session, events: EventSender) {240
for _ in 0..ORG_LIST_ATTEMPTS {241
match chatsvc::list_tenants(&home).await {242
Ok(tenants) => {243
let orgs = tenants244
.into_iter()245
.map(|tenant| app_base::orgs::Org {246
id: tenant.id,247
name: tenant.name,248
guest: tenant.guest,249
})250
.collect();251
let _ = events.send(BackendEvent::Orgs(orgs));252
return;253
}254
Err(error) => {255
crate::diagnostics::record(format!("orgs: tenant list not loaded: {error}"));256
tokio::time::sleep(CONNECT_RETRY).await;257
}258
}259
}260
}261
220
async fn forward_core_events(engine: Arc<Engine>, events: EventSender) {262
async fn forward_core_events(engine: Arc<Engine>, events: EventSender) {221
let mut receiver = engine.subscribe();263
let mut receiver = engine.subscribe();222
loop {264
loop {@@ -39,6 +39,7 @@ pub mod manage_team;
39
39
pub mod message_actions;
40
40
pub mod notice;
41
41
pub mod notify;
42
mod org_actions;
42
43
pub mod outbox;
43
44
pub mod outgoing;
44
45
pub mod own_status;
@@ -39,6 +39,7 @@ 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;42
pub mod outbox;43
pub mod outbox;43
pub mod outgoing;44
pub mod outgoing;44
pub mod own_status;45
pub mod own_status;@@ -0,0 +1,58 @@
1
use app_base::orgs::{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
/// Restarts the app on `org`: its own cache opens at once and the backend signs in to its tenant.
25
pub fn switch_org(&mut self, org: &Org, cx: &mut Context<Self>) {
26
if self.orgs.is_active(org) {
27
return;
28
}
29
let mut next = self.orgs.clone();
30
next.activate(org);
31
if !self.save_orgs(&next) {
32
return;
33
}
34
self.orgs = next;
35
match std::env::current_exe().and_then(|exe| {
36
std::process::Command::new(exe)
37
.args(std::env::args_os().skip(1))
38
.env(app_base::updater::RELAUNCH_ENV, std::process::id().to_string())
39
.spawn()
40
}) {
41
Ok(_) => cx.quit(),
42
Err(error) => {
43
crate::diagnostics::record(format!("orgs: restart for the switch failed: {error}"))
44
}
45
}
46
}
47
48
fn save_orgs(&self, orgs: &Orgs) -> bool {
49
if self.mode.demo {
50
return false;
51
}
52
let saved = Orgs::path().map(|path| orgs.save(&path));
53
if let Some(Err(error)) = &saved {
54
crate::diagnostics::record(format!("orgs: {} not saved: {error}", app_base::orgs::ORGS_FILE));
55
}
56
matches!(saved, Some(Ok(())))
57
}
58
}
@@ -0,0 +1,58 @@1
use app_base::orgs::{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
/// Restarts the app on `org`: its own cache opens at once and the backend signs in to its tenant.25
pub fn switch_org(&mut self, org: &Org, cx: &mut Context<Self>) {26
if self.orgs.is_active(org) {27
return;28
}29
let mut next = self.orgs.clone();30
next.activate(org);31
if !self.save_orgs(&next) {32
return;33
}34
self.orgs = next;35
match std::env::current_exe().and_then(|exe| {36
std::process::Command::new(exe)37
.args(std::env::args_os().skip(1))38
.env(app_base::updater::RELAUNCH_ENV, std::process::id().to_string())39
.spawn()40
}) {41
Ok(_) => cx.quit(),42
Err(error) => {43
crate::diagnostics::record(format!("orgs: restart for the switch failed: {error}"))44
}45
}46
}47
48
fn save_orgs(&self, orgs: &Orgs) -> bool {49
if self.mode.demo {50
return false;51
}52
let saved = Orgs::path().map(|path| orgs.save(&path));53
if let Some(Err(error)) = &saved {54
crate::diagnostics::record(format!("orgs: {} not saved: {error}", app_base::orgs::ORGS_FILE));55
}56
matches!(saved, Some(Ok(())))57
}58
}@@ -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)]
@@ -233,6 +232,13 @@ fn main() {
233
232
if arguments.demo {
234
233
inline_video::configure(std::env::temp_dir().join(DEMO_WEBVIEW_FOLDER));
235
234
}
235
let orgs = if arguments.demo {
236
app_base::orgs::Orgs::default()
237
} else {
238
app_base::orgs::Orgs::path()
239
.map(|path| app_base::orgs::Orgs::load(&path))
240
.unwrap_or_default()
241
};
236
242
let store = if arguments.demo {
237
243
let store = Store::open_in_memory().expect("in-memory store");
238
244
demo::seed(&store);
@@ -241,7 +247,7 @@ fn main() {
241
247
let path = arguments
242
248
.database
243
249
.clone()
244
.unwrap_or_else(|| data_path(DATABASE_FILE));
250
.unwrap_or_else(|| data_path(&orgs.database_file()));
245
251
open_store(&path)
246
252
};
247
253
let store = Arc::new(store);
@@ -279,8 +285,14 @@ fn main() {
279
285
#[cfg(not(windows))]
280
286
let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
281
287
let activity = user_activity::track(user_input.clone());
282
let mut backend_events =
283
backend::start(store.clone(), transport, !arguments.read_only, activity);
288
let guest_tenant = orgs.active_guest().map(|org| org.id.clone());
289
let mut backend_events = backend::start(
290
store.clone(),
291
transport,
292
!arguments.read_only,
293
activity,
294
guest_tenant,
295
);
284
296
app_base::runtime::handle().spawn(async move {
285
297
while let Some(event) = backend_events.recv().await {
286
298
if ui_events.send(event).is_err() {
@@ -315,6 +327,7 @@ fn main() {
315
327
let state = cx.new(|_| {
316
328
let mut state = AppState::new(store, mode);
317
329
state.start_on_channels = arguments.channels_tab;
330
state.orgs = orgs;
318
331
state
319
332
});
320
333
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)]@@ -233,6 +232,13 @@ fn main() {233
if arguments.demo {232
if arguments.demo {234
inline_video::configure(std::env::temp_dir().join(DEMO_WEBVIEW_FOLDER));233
inline_video::configure(std::env::temp_dir().join(DEMO_WEBVIEW_FOLDER));235
}234
}235
let orgs = if arguments.demo {236
app_base::orgs::Orgs::default()237
} else {238
app_base::orgs::Orgs::path()239
.map(|path| app_base::orgs::Orgs::load(&path))240
.unwrap_or_default()241
};236
let store = if arguments.demo {242
let store = if arguments.demo {237
let store = Store::open_in_memory().expect("in-memory store");243
let store = Store::open_in_memory().expect("in-memory store");238
demo::seed(&store);244
demo::seed(&store);@@ -241,7 +247,7 @@ fn main() {241
let path = arguments247
let path = arguments242
.database248
.database243
.clone()249
.clone()244
.unwrap_or_else(|| data_path(DATABASE_FILE));250
.unwrap_or_else(|| data_path(&orgs.database_file()));245
open_store(&path)251
open_store(&path)246
};252
};247
let store = Arc::new(store);253
let store = Arc::new(store);@@ -279,8 +285,14 @@ fn main() {279
#[cfg(not(windows))]285
#[cfg(not(windows))]280
let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());286
let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());281
let activity = user_activity::track(user_input.clone());287
let activity = user_activity::track(user_input.clone());282
let mut backend_events =288
let guest_tenant = orgs.active_guest().map(|org| org.id.clone());283
backend::start(store.clone(), transport, !arguments.read_only, activity);289
let mut backend_events = backend::start(290
store.clone(),291
transport,292
!arguments.read_only,293
activity,294
guest_tenant,295
);284
app_base::runtime::handle().spawn(async move {296
app_base::runtime::handle().spawn(async move {285
while let Some(event) = backend_events.recv().await {297
while let Some(event) = backend_events.recv().await {286
if ui_events.send(event).is_err() {298
if ui_events.send(event).is_err() {@@ -315,6 +327,7 @@ fn main() {315
let state = cx.new(|_| {327
let state = cx.new(|_| {316
let mut state = AppState::new(store, mode);328
let mut state = AppState::new(store, mode);317
state.start_on_channels = arguments.channels_tab;329
state.start_on_channels = arguments.channels_tab;330
state.orgs = orgs;318
state331
state319
});332
});320
views::shell::install_globals(&state, user_input, cx);333
views::shell::install_globals(&state, user_input, cx);@@ -0,0 +1,29 @@
1
---
2
status: accepted
3
date: 2026-11-15
4
---
5
6
# ADR 0015: 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
- Notifications and unread badges for the org that is not open are a separate step.
@@ -0,0 +1,29 @@1
---2
status: accepted3
date: 2026-11-154
---5
6
# ADR 0015: 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
- Notifications and unread badges for the org that is not open are a separate step.@@ -30,5 +30,6 @@ Statuses: `proposed`, `accepted`, `superseded`.
30
30
| [0012](0012-linux-close-to-tray-closes-the-window.md) | On Linux, close to tray closes the main window |
31
31
| [0013](0013-local-diagnostic-data-and-upstream-issues.md) | Local diagnostic data layout and upstream issues |
32
32
| [0014](0014-linux-installs-and-updates-itself.md) | The Linux binary installs and updates itself |
33
| [0015](0015-guest-orgs-switch-by-restart.md) | Guest orgs, one org per window, switch by restart |
33
34
34
35
Records `0001` to `0014` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
@@ -30,5 +30,6 @@ Statuses: `proposed`, `accepted`, `superseded`.30
| [0012](0012-linux-close-to-tray-closes-the-window.md) | On Linux, close to tray closes the main window |30
| [0012](0012-linux-close-to-tray-closes-the-window.md) | On Linux, close to tray closes the main window |31
| [0013](0013-local-diagnostic-data-and-upstream-issues.md) | Local diagnostic data layout and upstream issues |31
| [0013](0013-local-diagnostic-data-and-upstream-issues.md) | Local diagnostic data layout and upstream issues |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-guest-orgs-switch-by-restart.md) | Guest orgs, one org per window, switch by restart |33
34
34
Records `0001` to `0014` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.35
Records `0001` to `0014` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.