BlueGit

ict rusty-teams

feat(calendar): enter your own Google OAuth client in Settings (#151)

metis Joe Mild · pushed by metis

Authored 2026-11-29 · 2 days ago

Hash
6dd18f36e0bfb9710f2d2fdc8ba68227f71e86e3
Parent
e248a41c
22 files changed +611 −44
README.md +5 −7
@@ -143,19 +143,17 @@ cargo run --release -p app
143 143
144 144 ### Google Calendar (optional)
145 145
146 1. Create an OAuth Desktop client in Google Cloud Console with redirect `http://127.0.0.1:<port>/` (loopback; the app picks a free port).
147 2. Export before starting the app:
146 1. Settings > Calendar accounts > Connect Google.
147 2. Finish sign-in in the browser (if Google says the app is not verified, choose Advanced, then continue).
148 3. Choose the home calendar and optional dual-write targets.
149
150 Release builds bake in the project OAuth Desktop client, so those steps are enough when the client fields are empty. To use your own Desktop client, paste the client ID and client secret on that same page (the page has the short Google Cloud Console guide) and save. A saved pair is used instead of the built-in client and instead of `TEAMS_GOOGLE_CLIENT_ID` / `TEAMS_GOOGLE_CLIENT_SECRET`. Local builds without a built-in client stay Outlook-only until you save a pair or export those variables before `cargo run`:
148 151
149 152 ```bash
150 153 export TEAMS_GOOGLE_CLIENT_ID="….apps.googleusercontent.com"
151 # only if the client has a secret:
152 154 export TEAMS_GOOGLE_CLIENT_SECRET="…"
153 155 ```
154 156
155 3. Settings > Calendar > Connect Google, then choose home calendar and optional dual-write targets.
156
157 Without these env vars the calendar stays Outlook-only.
158
159 157 | Task | Command |
160 158 |---|---|
161 159 | Linux build needs clang 21+ (libwebrtc's hermetic libc++) + mold (set in `.cargo/config.toml`); sccache shares compiled deps across worktrees | `sudo apt install clang mold sccache`, clang from [apt.llvm.org](https://apt.llvm.org) if the distro one is older than 21 |
@@ -143,19 +143,17 @@ cargo run --release -p app
143
143
144### Google Calendar (optional)
144### Google Calendar (optional)
145
145
1461. Create an OAuth Desktop client in Google Cloud Console with redirect `http://127.0.0.1:<port>/` (loopback; the app picks a free port).
1461. Settings > Calendar accounts > Connect Google.
1472. Export before starting the app:
1472. Finish sign-in in the browser (if Google says the app is not verified, choose Advanced, then continue).
1483. Choose the home calendar and optional dual-write targets.
149
150Release builds bake in the project OAuth Desktop client, so those steps are enough when the client fields are empty. To use your own Desktop client, paste the client ID and client secret on that same page (the page has the short Google Cloud Console guide) and save. A saved pair is used instead of the built-in client and instead of `TEAMS_GOOGLE_CLIENT_ID` / `TEAMS_GOOGLE_CLIENT_SECRET`. Local builds without a built-in client stay Outlook-only until you save a pair or export those variables before `cargo run`:
148
151
149```bash
152```bash
150export TEAMS_GOOGLE_CLIENT_ID="….apps.googleusercontent.com"
153export TEAMS_GOOGLE_CLIENT_ID="….apps.googleusercontent.com"
151# only if the client has a secret:
152export TEAMS_GOOGLE_CLIENT_SECRET="…"
154export TEAMS_GOOGLE_CLIENT_SECRET="…"
153```
155```
154
156
1553. Settings > Calendar > Connect Google, then choose home calendar and optional dual-write targets.
156
157Without these env vars the calendar stays Outlook-only.
158
159| Task | Command |
157| Task | Command |
160|---|---|
158|---|---|
161| Linux build needs clang 21+ (libwebrtc's hermetic libc++) + mold (set in `.cargo/config.toml`); sccache shares compiled deps across worktrees | `sudo apt install clang mold sccache`, clang from [apt.llvm.org](https://apt.llvm.org) if the distro one is older than 21 |
159| Linux build needs clang 21+ (libwebrtc's hermetic libc++) + mold (set in `.cargo/config.toml`); sccache shares compiled deps across worktrees | `sudo apt install clang mold sccache`, clang from [apt.llvm.org](https://apt.llvm.org) if the distro one is older than 21 |
crates/app-base/locales/app.yml +62 −2
@@ -178,7 +178,7 @@ settings:
178 178 de: Schreibt ausführliche Logs in diagnostics.log - danach wieder ausschalten
179 179 debug_logging_off_detail:
180 180 en: Off by default - enable before reproducing a bug
181 de: Standardmäßig aus - vor der Fehlerreproduktion einschalten
181 de: Standardmässig aus - vor der Fehlerreproduktion einschalten
182 182 clear_logs:
183 183 en: Clear logs
184 184 de: Logs leeren
@@ -280,6 +280,66 @@ settings:
280 280 google_title:
281 281 en: Google Calendar
282 282 de: Google Kalender
283 google_client_status_title:
284 en: OAuth client
285 de: OAuth-Client
286 google_client_status_own:
287 en: Your client
288 de: Eigener Client
289 google_client_status_builtin:
290 en: Built-in client, or TEAMS_GOOGLE_CLIENT_ID when set
291 de: Eingebauter Client, oder TEAMS_GOOGLE_CLIENT_ID, wenn gesetzt
292 google_client_status_missing:
293 en: No client yet. Save one here, or use a build that includes one.
294 de: Noch kein Client. Hier einen speichern, oder einen Build mit eingebautem Client verwenden.
295 google_client_id:
296 en: Client ID
297 de: Client-ID
298 google_client_secret:
299 en: Client secret
300 de: Clientschlüssel
301 google_client_secret_kept:
302 en: A secret is saved. Leave this empty to keep it.
303 de: Ein Schlüssel ist gespeichert. Leer lassen behält ihn.
304 google_client_save:
305 en: Save
306 de: Speichern
307 google_client_reset:
308 en: Use built-in client
309 de: Eingebauten Client verwenden
310 google_client_saved:
311 en: Saved. Connect Google uses this client.
312 de: Gespeichert. «Google verbinden» nutzt diesen Client.
313 google_client_saved_reconnect:
314 en: Saved. Connect Google again. Existing tokens belong to the previous client.
315 de: Gespeichert. Google erneut verbinden. Bestehende Tokens gehören zum vorherigen Client.
316 google_client_cleared:
317 en: Cleared. Connect uses the built-in client again.
318 de: Zurückgesetzt. Verbinden nutzt wieder den eingebauten Client.
319 google_client_cleared_reconnect:
320 en: Cleared. Connect Google again. Existing tokens belong to the previous client.
321 de: Zurückgesetzt. Google erneut verbinden. Bestehende Tokens gehören zum vorherigen Client.
322 google_client_secret_required:
323 en: Enter the client secret. A saved secret can be left blank.
324 de: Clientschlüssel eintragen. Ein gespeicherter Schlüssel darf leer bleiben.
325 google_client_save_failed:
326 en: The Google client could not be saved.
327 de: Der Google-Client konnte nicht gespeichert werden.
328 google_client_guide_1:
329 en: "1. Open https://console.cloud.google.com/ and choose a project."
330 de: "1. https://console.cloud.google.com/ öffnen und ein Projekt wählen."
331 google_client_guide_2:
332 en: "2. Enable the Google Calendar API."
333 de: "2. Google Calendar API aktivieren."
334 google_client_guide_3:
335 en: "3. Google Auth Platform (OAuth consent screen): External. Add the calendar and userinfo.email scopes. Under Audience, add your Google account as a test user, or publish the app."
336 de: "3. Google Auth Platform (OAuth-Zustimmungsbildschirm): Extern. Bereiche calendar und userinfo.email hinzufügen. Unter «Zielgruppe» das eigene Google-Konto als Testnutzer eintragen oder die App veröffentlichen."
337 google_client_guide_4:
338 en: "4. Clients, then Create client (older consoles: Credentials, OAuth client ID), application type Desktop. Do not set a redirect URI. The app uses http://127.0.0.1 on a free port."
339 de: "4. Clients, dann Client erstellen (ältere Konsolen: Anmeldedaten, OAuth-Client-ID), Anwendungstyp Desktop. Keine Redirect-URI setzen. Die App nutzt http://127.0.0.1 mit einem freien Port."
340 google_client_guide_5:
341 en: "5. Paste the client ID and client secret here, save, then choose Connect Google."
342 de: "5. Client-ID und Clientschlüssel hier eintragen, speichern, dann «Google verbinden»."
283 343 caldav_title:
284 344 en: CalDAV calendar
285 345 de: CalDAV-Kalender
@@ -1898,7 +1958,7 @@ sidebar:
1898 1958 de: Abschnitt löschen
1899 1959 delete_section_title:
1900 1960 en: 'Delete section "%{name}"?'
1901 de: 'Abschnitt „%{name}" löschen?'
1961 de: 'Abschnitt «%{name}» löschen?'
1902 1962 delete_section_detail:
1903 1963 en: Chats in it move back to Chats.
1904 1964 de: Chats darin werden zurück zu Chats verschoben.
@@ -178,7 +178,7 @@ settings:
178 de: Schreibt ausführliche Logs in diagnostics.log - danach wieder ausschalten
178 de: Schreibt ausführliche Logs in diagnostics.log - danach wieder ausschalten
179 debug_logging_off_detail:
179 debug_logging_off_detail:
180 en: Off by default - enable before reproducing a bug
180 en: Off by default - enable before reproducing a bug
181 de: Standardmäßig aus - vor der Fehlerreproduktion einschalten
181 de: Standardmässig aus - vor der Fehlerreproduktion einschalten
182 clear_logs:
182 clear_logs:
183 en: Clear logs
183 en: Clear logs
184 de: Logs leeren
184 de: Logs leeren
@@ -280,6 +280,66 @@ settings:
280 google_title:
280 google_title:
281 en: Google Calendar
281 en: Google Calendar
282 de: Google Kalender
282 de: Google Kalender
283 google_client_status_title:
284 en: OAuth client
285 de: OAuth-Client
286 google_client_status_own:
287 en: Your client
288 de: Eigener Client
289 google_client_status_builtin:
290 en: Built-in client, or TEAMS_GOOGLE_CLIENT_ID when set
291 de: Eingebauter Client, oder TEAMS_GOOGLE_CLIENT_ID, wenn gesetzt
292 google_client_status_missing:
293 en: No client yet. Save one here, or use a build that includes one.
294 de: Noch kein Client. Hier einen speichern, oder einen Build mit eingebautem Client verwenden.
295 google_client_id:
296 en: Client ID
297 de: Client-ID
298 google_client_secret:
299 en: Client secret
300 de: Clientschlüssel
301 google_client_secret_kept:
302 en: A secret is saved. Leave this empty to keep it.
303 de: Ein Schlüssel ist gespeichert. Leer lassen behält ihn.
304 google_client_save:
305 en: Save
306 de: Speichern
307 google_client_reset:
308 en: Use built-in client
309 de: Eingebauten Client verwenden
310 google_client_saved:
311 en: Saved. Connect Google uses this client.
312 de: Gespeichert. «Google verbinden» nutzt diesen Client.
313 google_client_saved_reconnect:
314 en: Saved. Connect Google again. Existing tokens belong to the previous client.
315 de: Gespeichert. Google erneut verbinden. Bestehende Tokens gehören zum vorherigen Client.
316 google_client_cleared:
317 en: Cleared. Connect uses the built-in client again.
318 de: Zurückgesetzt. Verbinden nutzt wieder den eingebauten Client.
319 google_client_cleared_reconnect:
320 en: Cleared. Connect Google again. Existing tokens belong to the previous client.
321 de: Zurückgesetzt. Google erneut verbinden. Bestehende Tokens gehören zum vorherigen Client.
322 google_client_secret_required:
323 en: Enter the client secret. A saved secret can be left blank.
324 de: Clientschlüssel eintragen. Ein gespeicherter Schlüssel darf leer bleiben.
325 google_client_save_failed:
326 en: The Google client could not be saved.
327 de: Der Google-Client konnte nicht gespeichert werden.
328 google_client_guide_1:
329 en: "1. Open https://console.cloud.google.com/ and choose a project."
330 de: "1. https://console.cloud.google.com/ öffnen und ein Projekt wählen."
331 google_client_guide_2:
332 en: "2. Enable the Google Calendar API."
333 de: "2. Google Calendar API aktivieren."
334 google_client_guide_3:
335 en: "3. Google Auth Platform (OAuth consent screen): External. Add the calendar and userinfo.email scopes. Under Audience, add your Google account as a test user, or publish the app."
336 de: "3. Google Auth Platform (OAuth-Zustimmungsbildschirm): Extern. Bereiche calendar und userinfo.email hinzufügen. Unter «Zielgruppe» das eigene Google-Konto als Testnutzer eintragen oder die App veröffentlichen."
337 google_client_guide_4:
338 en: "4. Clients, then Create client (older consoles: Credentials, OAuth client ID), application type Desktop. Do not set a redirect URI. The app uses http://127.0.0.1 on a free port."
339 de: "4. Clients, dann Client erstellen (ältere Konsolen: Anmeldedaten, OAuth-Client-ID), Anwendungstyp Desktop. Keine Redirect-URI setzen. Die App nutzt http://127.0.0.1 mit einem freien Port."
340 google_client_guide_5:
341 en: "5. Paste the client ID and client secret here, save, then choose Connect Google."
342 de: "5. Client-ID und Clientschlüssel hier eintragen, speichern, dann «Google verbinden»."
283 caldav_title:
343 caldav_title:
284 en: CalDAV calendar
344 en: CalDAV calendar
285 de: CalDAV-Kalender
345 de: CalDAV-Kalender
@@ -1898,7 +1958,7 @@ sidebar:
1898 de: Abschnitt löschen
1958 de: Abschnitt löschen
1899 delete_section_title:
1959 delete_section_title:
1900 en: 'Delete section "%{name}"?'
1960 en: 'Delete section "%{name}"?'
1901 de: 'Abschnitt „%{name}" löschen?'
1961 de: 'Abschnitt «%{name}» löschen?'
1902 delete_section_detail:
1962 delete_section_detail:
1903 en: Chats in it move back to Chats.
1963 en: Chats in it move back to Chats.
1904 de: Chats darin werden zurück zu Chats verschoben.
1964 de: Chats darin werden zurück zu Chats verschoben.
crates/app-state/src/backend.rs +7 −2
@@ -614,8 +614,13 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
614 614 }
615 615 }
616 616 }
617 match crate::google_calendar_sync::fetch_google_events(&mut fetched_accounts, start, end)
618 .await
617 match crate::google_calendar_sync::fetch_google_events(
618 &store,
619 &mut fetched_accounts,
620 start,
621 end,
622 )
623 .await
619 624 {
620 625 Ok((google_events, account_errors)) => {
621 626 // Only refreshed tokens: a calendar toggle made during the fetch stays.
@@ -614,8 +614,13 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
614 }
614 }
615 }
615 }
616 }
616 }
617 match crate::google_calendar_sync::fetch_google_events(&mut fetched_accounts, start, end)
617 match crate::google_calendar_sync::fetch_google_events(
618 .await
618 &store,
619 &mut fetched_accounts,
620 start,
621 end,
622 )
623 .await
619 {
624 {
620 Ok((google_events, account_errors)) => {
625 Ok((google_events, account_errors)) => {
621 // Only refreshed tokens: a calendar toggle made during the fetch stays.
626 // Only refreshed tokens: a calendar toggle made during the fetch stays.
crates/app-state/src/calendar_accounts_actions.rs +6 −7
@@ -8,8 +8,8 @@ use store::{
8 8 use uuid::Uuid;
9 9
10 10 use chatsvc::{
11 GoogleCalendar, GoogleOAuth, allocate_redirect_uri, client_id_from_env, exchange_code,
12 parse_calendar_list, wait_for_code,
11 GoogleCalendar, GoogleOAuth, allocate_redirect_uri, exchange_code, parse_calendar_list,
12 wait_for_code,
13 13 };
14 14
15 15 use crate::app_state::AppState;
@@ -264,17 +264,16 @@ impl AppState {
264 264 self.reopen_google_connect(cx);
265 265 return;
266 266 }
267 let Some(oauth) = client_id_from_env() else {
268 self.raise_notice(tr("settings.calendar.not_in_build"), None, cx);
269 return;
270 };
271 267 let store = self.store.clone();
272 268 self.google_connect_generation = self.google_connect_generation.wrapping_add(1);
273 269 let generation = self.google_connect_generation;
274 270 cx.spawn(async move |this, cx| {
275 271 let prepared = runtime::spawn({
276 let oauth = oauth.clone();
272 let store = store.clone();
277 273 async move {
274 let oauth = crate::google_oauth_client::resolve(&store)
275 .await
276 .ok_or_else(|| tr("settings.calendar.not_in_build"))?;
278 277 let (redirect_uri, listener) = allocate_redirect_uri()
279 278 .await
280 279 .map_err(|error| error.to_string())?;
@@ -8,8 +8,8 @@ use store::{
8use uuid::Uuid;
8use uuid::Uuid;
9
9
10use chatsvc::{
10use chatsvc::{
11 GoogleCalendar, GoogleOAuth, allocate_redirect_uri, client_id_from_env, exchange_code,
11 GoogleCalendar, GoogleOAuth, allocate_redirect_uri, exchange_code, parse_calendar_list,
12 parse_calendar_list, wait_for_code,
12 wait_for_code,
13};
13};
14
14
15use crate::app_state::AppState;
15use crate::app_state::AppState;
@@ -264,17 +264,16 @@ impl AppState {
264 self.reopen_google_connect(cx);
264 self.reopen_google_connect(cx);
265 return;
265 return;
266 }
266 }
267 let Some(oauth) = client_id_from_env() else {
268 self.raise_notice(tr("settings.calendar.not_in_build"), None, cx);
269 return;
270 };
271 let store = self.store.clone();
267 let store = self.store.clone();
272 self.google_connect_generation = self.google_connect_generation.wrapping_add(1);
268 self.google_connect_generation = self.google_connect_generation.wrapping_add(1);
273 let generation = self.google_connect_generation;
269 let generation = self.google_connect_generation;
274 cx.spawn(async move |this, cx| {
270 cx.spawn(async move |this, cx| {
275 let prepared = runtime::spawn({
271 let prepared = runtime::spawn({
276 let oauth = oauth.clone();
272 let store = store.clone();
277 async move {
273 async move {
274 let oauth = crate::google_oauth_client::resolve(&store)
275 .await
276 .ok_or_else(|| tr("settings.calendar.not_in_build"))?;
278 let (redirect_uri, listener) = allocate_redirect_uri()
277 let (redirect_uri, listener) = allocate_redirect_uri()
279 .await
278 .await
280 .map_err(|error| error.to_string())?;
279 .map_err(|error| error.to_string())?;
crates/app-state/src/call/meeting_create.rs +3 −0
@@ -47,6 +47,7 @@ pub async fn create_across_targets(
47 47 for target in targets {
48 48 match write_target(
49 49 launcher.as_ref(),
50 store.as_ref(),
50 51 &mut accounts,
51 52 &target,
52 53 &event,
@@ -82,6 +83,7 @@ pub async fn create_across_targets(
82 83
83 84 async fn write_target(
84 85 launcher: &CallLauncher,
86 store: &Store,
85 87 accounts: &mut CalendarAccounts,
86 88 target: &CalendarRef,
87 89 event: &NewEvent,
@@ -102,6 +104,7 @@ async fn write_target(
102 104 let mut draft = GoogleEventDraft::from(event);
103 105 draft.join_url = Some(join_url.to_owned());
104 106 crate::google_calendar_sync::insert_google_event(
107 store,
105 108 accounts,
106 109 &target.account_id,
107 110 calendar_id,
@@ -47,6 +47,7 @@ pub async fn create_across_targets(
47 for target in targets {
47 for target in targets {
48 match write_target(
48 match write_target(
49 launcher.as_ref(),
49 launcher.as_ref(),
50 store.as_ref(),
50 &mut accounts,
51 &mut accounts,
51 &target,
52 &target,
52 &event,
53 &event,
@@ -82,6 +83,7 @@ pub async fn create_across_targets(
82
83
83async fn write_target(
84async fn write_target(
84 launcher: &CallLauncher,
85 launcher: &CallLauncher,
86 store: &Store,
85 accounts: &mut CalendarAccounts,
87 accounts: &mut CalendarAccounts,
86 target: &CalendarRef,
88 target: &CalendarRef,
87 event: &NewEvent,
89 event: &NewEvent,
@@ -102,6 +104,7 @@ async fn write_target(
102 let mut draft = GoogleEventDraft::from(event);
104 let mut draft = GoogleEventDraft::from(event);
103 draft.join_url = Some(join_url.to_owned());
105 draft.join_url = Some(join_url.to_owned());
104 crate::google_calendar_sync::insert_google_event(
106 crate::google_calendar_sync::insert_google_event(
107 store,
105 accounts,
108 accounts,
106 &target.account_id,
109 &target.account_id,
107 calendar_id,
110 calendar_id,
crates/app-state/src/call/schedule.rs +2 −0
@@ -309,6 +309,7 @@ impl AppState {
309 309 account_id.ok_or_else(|| "Google account missing".to_owned())?;
310 310 let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());
311 311 let result = crate::google_calendar_sync::delete_google_event(
312 &store,
312 313 &mut accounts,
313 314 &account,
314 315 &calendar,
@@ -554,6 +555,7 @@ impl AppState {
554 555 account_id.ok_or_else(|| "Google account missing".to_owned())?;
555 556 let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());
556 557 let result = crate::google_calendar_sync::respond_google_event(
558 &store,
557 559 &mut accounts,
558 560 &account,
559 561 &calendar,
@@ -309,6 +309,7 @@ impl AppState {
309 account_id.ok_or_else(|| "Google account missing".to_owned())?;
309 account_id.ok_or_else(|| "Google account missing".to_owned())?;
310 let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());
310 let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());
311 let result = crate::google_calendar_sync::delete_google_event(
311 let result = crate::google_calendar_sync::delete_google_event(
312 &store,
312 &mut accounts,
313 &mut accounts,
313 &account,
314 &account,
314 &calendar,
315 &calendar,
@@ -554,6 +555,7 @@ impl AppState {
554 account_id.ok_or_else(|| "Google account missing".to_owned())?;
555 account_id.ok_or_else(|| "Google account missing".to_owned())?;
555 let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());
556 let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());
556 let result = crate::google_calendar_sync::respond_google_event(
557 let result = crate::google_calendar_sync::respond_google_event(
558 &store,
557 &mut accounts,
559 &mut accounts,
558 &account,
560 &account,
559 &calendar,
561 &calendar,
crates/app-state/src/call/week.rs +1 −0
@@ -265,6 +265,7 @@ impl AppState {
265 265 let mut google_count = None;
266 266 if accounts.has_google() {
267 267 match crate::google_calendar_sync::fetch_google_events(
268 &store,
268 269 &mut fetched_accounts,
269 270 from,
270 271 to,
@@ -265,6 +265,7 @@ impl AppState {
265 let mut google_count = None;
265 let mut google_count = None;
266 if accounts.has_google() {
266 if accounts.has_google() {
267 match crate::google_calendar_sync::fetch_google_events(
267 match crate::google_calendar_sync::fetch_google_events(
268 &store,
268 &mut fetched_accounts,
269 &mut fetched_accounts,
269 from,
270 from,
270 to,
271 to,
crates/app-state/src/google_calendar_sync.rs +17 −7
@@ -1,18 +1,19 @@
1 1 use chrono::{DateTime, Utc};
2 use store::{CalendarAccounts, GoogleTokenSet};
2 use store::{CalendarAccounts, GoogleTokenSet, Store};
3 3
4 4 use chatsvc::{
5 CalendarEvent, GoogleCalendar, GoogleEventDraft, GoogleOAuth, Reply, client_id_from_env,
6 google_rsvp_status, refresh_access_token,
5 CalendarEvent, GoogleCalendar, GoogleEventDraft, GoogleOAuth, Reply, google_rsvp_status,
6 refresh_access_token,
7 7 };
8 8
9 9 /// Refresh tokens when needed and load events from every selected Google calendar.
10 10 pub async fn fetch_google_events(
11 store: &Store,
11 12 accounts: &mut CalendarAccounts,
12 13 start: DateTime<Utc>,
13 14 end: DateTime<Utc>,
14 15 ) -> Result<(Vec<CalendarEvent>, Vec<String>), String> {
15 let Some(oauth) = client_id_from_env() else {
16 let Some(oauth) = crate::google_oauth_client::resolve(store).await else {
16 17 // Connected accounts but no client id compiled in: say so instead of an empty week.
17 18 if accounts.has_google() {
18 19 return Err(missing_client_id());
@@ -86,12 +87,15 @@ fn remember_account_error(errors: &mut Vec<String>, error: String) {
86 87 }
87 88
88 89 pub async fn insert_google_event(
90 store: &Store,
89 91 accounts: &mut CalendarAccounts,
90 92 account_id: &str,
91 93 calendar_id: &str,
92 94 draft: &GoogleEventDraft,
93 95 ) -> Result<(), String> {
94 let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
96 let oauth = crate::google_oauth_client::resolve(store)
97 .await
98 .ok_or_else(|| missing_client_id())?;
95 99 let index = accounts
96 100 .google_accounts
97 101 .iter()
@@ -109,6 +113,7 @@ pub async fn insert_google_event(
109 113 }
110 114
111 115 pub async fn respond_google_event(
116 store: &Store,
112 117 accounts: &mut CalendarAccounts,
113 118 account_id: &str,
114 119 calendar_id: &str,
@@ -116,7 +121,9 @@ pub async fn respond_google_event(
116 121 reply: Reply,
117 122 send_updates: bool,
118 123 ) -> Result<(), String> {
119 let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
124 let oauth = crate::google_oauth_client::resolve(store)
125 .await
126 .ok_or_else(|| missing_client_id())?;
120 127 let index = accounts
121 128 .google_accounts
122 129 .iter()
@@ -138,13 +145,16 @@ pub async fn respond_google_event(
138 145 }
139 146
140 147 pub async fn delete_google_event(
148 store: &Store,
141 149 accounts: &mut CalendarAccounts,
142 150 account_id: &str,
143 151 calendar_id: &str,
144 152 event_id: &str,
145 153 send_updates: bool,
146 154 ) -> Result<(), String> {
147 let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
155 let oauth = crate::google_oauth_client::resolve(store)
156 .await
157 .ok_or_else(|| missing_client_id())?;
148 158 let index = accounts
149 159 .google_accounts
150 160 .iter()
@@ -1,18 +1,19 @@
1use chrono::{DateTime, Utc};
1use chrono::{DateTime, Utc};
2use store::{CalendarAccounts, GoogleTokenSet};
2use store::{CalendarAccounts, GoogleTokenSet, Store};
3
3
4use chatsvc::{
4use chatsvc::{
5 CalendarEvent, GoogleCalendar, GoogleEventDraft, GoogleOAuth, Reply, client_id_from_env,
5 CalendarEvent, GoogleCalendar, GoogleEventDraft, GoogleOAuth, Reply, google_rsvp_status,
6 google_rsvp_status, refresh_access_token,
6 refresh_access_token,
7};
7};
8
8
9/// Refresh tokens when needed and load events from every selected Google calendar.
9/// Refresh tokens when needed and load events from every selected Google calendar.
10pub async fn fetch_google_events(
10pub async fn fetch_google_events(
11 store: &Store,
11 accounts: &mut CalendarAccounts,
12 accounts: &mut CalendarAccounts,
12 start: DateTime<Utc>,
13 start: DateTime<Utc>,
13 end: DateTime<Utc>,
14 end: DateTime<Utc>,
14) -> Result<(Vec<CalendarEvent>, Vec<String>), String> {
15) -> Result<(Vec<CalendarEvent>, Vec<String>), String> {
15 let Some(oauth) = client_id_from_env() else {
16 let Some(oauth) = crate::google_oauth_client::resolve(store).await else {
16 // Connected accounts but no client id compiled in: say so instead of an empty week.
17 // Connected accounts but no client id compiled in: say so instead of an empty week.
17 if accounts.has_google() {
18 if accounts.has_google() {
18 return Err(missing_client_id());
19 return Err(missing_client_id());
@@ -86,12 +87,15 @@ fn remember_account_error(errors: &mut Vec<String>, error: String) {
86}
87}
87
88
88pub async fn insert_google_event(
89pub async fn insert_google_event(
90 store: &Store,
89 accounts: &mut CalendarAccounts,
91 accounts: &mut CalendarAccounts,
90 account_id: &str,
92 account_id: &str,
91 calendar_id: &str,
93 calendar_id: &str,
92 draft: &GoogleEventDraft,
94 draft: &GoogleEventDraft,
93) -> Result<(), String> {
95) -> Result<(), String> {
94 let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
96 let oauth = crate::google_oauth_client::resolve(store)
97 .await
98 .ok_or_else(|| missing_client_id())?;
95 let index = accounts
99 let index = accounts
96 .google_accounts
100 .google_accounts
97 .iter()
101 .iter()
@@ -109,6 +113,7 @@ pub async fn insert_google_event(
109}
113}
110
114
111pub async fn respond_google_event(
115pub async fn respond_google_event(
116 store: &Store,
112 accounts: &mut CalendarAccounts,
117 accounts: &mut CalendarAccounts,
113 account_id: &str,
118 account_id: &str,
114 calendar_id: &str,
119 calendar_id: &str,
@@ -116,7 +121,9 @@ pub async fn respond_google_event(
116 reply: Reply,
121 reply: Reply,
117 send_updates: bool,
122 send_updates: bool,
118) -> Result<(), String> {
123) -> Result<(), String> {
119 let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
124 let oauth = crate::google_oauth_client::resolve(store)
125 .await
126 .ok_or_else(|| missing_client_id())?;
120 let index = accounts
127 let index = accounts
121 .google_accounts
128 .google_accounts
122 .iter()
129 .iter()
@@ -138,13 +145,16 @@ pub async fn respond_google_event(
138}
145}
139
146
140pub async fn delete_google_event(
147pub async fn delete_google_event(
148 store: &Store,
141 accounts: &mut CalendarAccounts,
149 accounts: &mut CalendarAccounts,
142 account_id: &str,
150 account_id: &str,
143 calendar_id: &str,
151 calendar_id: &str,
144 event_id: &str,
152 event_id: &str,
145 send_updates: bool,
153 send_updates: bool,
146) -> Result<(), String> {
154) -> Result<(), String> {
147 let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
155 let oauth = crate::google_oauth_client::resolve(store)
156 .await
157 .ok_or_else(|| missing_client_id())?;
148 let index = accounts
158 let index = accounts
149 .google_accounts
159 .google_accounts
150 .iter()
160 .iter()
crates/app-state/src/google_oauth_client.rs added +135 −0
@@ -0,0 +1,135 @@
1 //! Saved Google OAuth Desktop client (ADR 0024).
2 //!
3 //! The client id lives in store meta. The secret lives in the OS keyring and is
4 //! never written to the calendar account document or to logs.
5
6 use store::Store;
7
8 use chatsvc::GoogleOAuth;
9
10 pub const CLIENT_ID_KEY: &str = "calendar.google_client_id";
11 const SERVICE: &str = "rusty-teams.google-oauth";
12 const ACCOUNT: &str = "desktop";
13
14 pub enum GoogleClientSave {
15 Saved,
16 Cleared,
17 }
18
19 pub enum GoogleClientSaveError {
20 /// An id was given without a secret, and no secret is stored for that id.
21 SecretRequired,
22 Failed,
23 }
24
25 pub fn load_client_id(store: &Store) -> String {
26 store
27 .meta(CLIENT_ID_KEY)
28 .ok()
29 .flatten()
30 .map(|value| value.trim().to_owned())
31 .filter(|value| !value.is_empty())
32 .unwrap_or_default()
33 }
34
35 pub async fn secret_is_stored() -> bool {
36 load_secret()
37 .await
38 .map(|value| !value.trim().is_empty())
39 .unwrap_or(false)
40 }
41
42 /// Saved pair, then the environment, then the client compiled into the build.
43 pub async fn resolve(store: &Store) -> Option<GoogleOAuth> {
44 let stored_id = load_client_id(store);
45 // Without a saved id the keyring is never asked, so Secret Service stays out of every fetch.
46 let stored_secret = if stored_id.is_empty() {
47 String::new()
48 } else {
49 match load_secret().await {
50 Ok(secret) => secret,
51 Err(_) => {
52 log::warn!("saved Google client secret not read from the keyring");
53 String::new()
54 }
55 }
56 };
57 chatsvc::client_from_stored(Some(stored_id.as_str()), Some(stored_secret.as_str()))
58 }
59
60 pub async fn save(
61 store: &Store,
62 client_id: &str,
63 secret: &str,
64 ) -> Result<GoogleClientSave, GoogleClientSaveError> {
65 let id = client_id.trim();
66 let secret = secret.trim();
67 if id.is_empty() {
68 store
69 .set_meta(CLIENT_ID_KEY, "")
70 .map_err(|_| GoogleClientSaveError::Failed)?;
71 delete_secret().await?;
72 return Ok(GoogleClientSave::Cleared);
73 }
74 if secret.is_empty() {
75 // The kept secret belongs to the saved id; a new id needs its own secret.
76 if load_client_id(store) != id {
77 return Err(GoogleClientSaveError::SecretRequired);
78 }
79 return match load_secret().await {
80 Ok(existing) if !existing.trim().is_empty() => Ok(GoogleClientSave::Saved),
81 _ => Err(GoogleClientSaveError::SecretRequired),
82 };
83 }
84 // Secret before id: a failed keyring write must not leave a new id beside the old secret.
85 store_secret(secret).await?;
86 store
87 .set_meta(CLIENT_ID_KEY, id)
88 .map_err(|_| GoogleClientSaveError::Failed)?;
89 Ok(GoogleClientSave::Saved)
90 }
91
92 async fn load_secret() -> Result<String, GoogleClientSaveError> {
93 spawn_blocking(move || {
94 let entry =
95 keyring::Entry::new(SERVICE, ACCOUNT).map_err(|_| GoogleClientSaveError::Failed)?;
96 entry
97 .get_password()
98 .map_err(|_| GoogleClientSaveError::Failed)
99 })
100 .await
101 }
102
103 async fn store_secret(secret: &str) -> Result<(), GoogleClientSaveError> {
104 let secret = secret.to_owned();
105 spawn_blocking(move || {
106 let entry =
107 keyring::Entry::new(SERVICE, ACCOUNT).map_err(|_| GoogleClientSaveError::Failed)?;
108 entry
109 .set_password(&secret)
110 .map_err(|_| GoogleClientSaveError::Failed)
111 })
112 .await
113 }
114
115 async fn delete_secret() -> Result<(), GoogleClientSaveError> {
116 spawn_blocking(move || {
117 let entry =
118 keyring::Entry::new(SERVICE, ACCOUNT).map_err(|_| GoogleClientSaveError::Failed)?;
119 match entry.delete_credential() {
120 Ok(()) => Ok(()),
121 Err(keyring::Error::NoEntry) => Ok(()),
122 Err(_) => Err(GoogleClientSaveError::Failed),
123 }
124 })
125 .await
126 }
127
128 async fn spawn_blocking<T: Send + 'static>(
129 work: impl FnOnce() -> Result<T, GoogleClientSaveError> + Send + 'static,
130 ) -> Result<T, GoogleClientSaveError> {
131 match tokio::task::spawn_blocking(work).await {
132 Ok(result) => result,
133 Err(_) => Err(GoogleClientSaveError::Failed),
134 }
135 }
@@ -0,0 +1,135 @@
1//! Saved Google OAuth Desktop client (ADR 0024).
2//!
3//! The client id lives in store meta. The secret lives in the OS keyring and is
4//! never written to the calendar account document or to logs.
5
6use store::Store;
7
8use chatsvc::GoogleOAuth;
9
10pub const CLIENT_ID_KEY: &str = "calendar.google_client_id";
11const SERVICE: &str = "rusty-teams.google-oauth";
12const ACCOUNT: &str = "desktop";
13
14pub enum GoogleClientSave {
15 Saved,
16 Cleared,
17}
18
19pub enum GoogleClientSaveError {
20 /// An id was given without a secret, and no secret is stored for that id.
21 SecretRequired,
22 Failed,
23}
24
25pub fn load_client_id(store: &Store) -> String {
26 store
27 .meta(CLIENT_ID_KEY)
28 .ok()
29 .flatten()
30 .map(|value| value.trim().to_owned())
31 .filter(|value| !value.is_empty())
32 .unwrap_or_default()
33}
34
35pub async fn secret_is_stored() -> bool {
36 load_secret()
37 .await
38 .map(|value| !value.trim().is_empty())
39 .unwrap_or(false)
40}
41
42/// Saved pair, then the environment, then the client compiled into the build.
43pub async fn resolve(store: &Store) -> Option<GoogleOAuth> {
44 let stored_id = load_client_id(store);
45 // Without a saved id the keyring is never asked, so Secret Service stays out of every fetch.
46 let stored_secret = if stored_id.is_empty() {
47 String::new()
48 } else {
49 match load_secret().await {
50 Ok(secret) => secret,
51 Err(_) => {
52 log::warn!("saved Google client secret not read from the keyring");
53 String::new()
54 }
55 }
56 };
57 chatsvc::client_from_stored(Some(stored_id.as_str()), Some(stored_secret.as_str()))
58}
59
60pub async fn save(
61 store: &Store,
62 client_id: &str,
63 secret: &str,
64) -> Result<GoogleClientSave, GoogleClientSaveError> {
65 let id = client_id.trim();
66 let secret = secret.trim();
67 if id.is_empty() {
68 store
69 .set_meta(CLIENT_ID_KEY, "")
70 .map_err(|_| GoogleClientSaveError::Failed)?;
71 delete_secret().await?;
72 return Ok(GoogleClientSave::Cleared);
73 }
74 if secret.is_empty() {
75 // The kept secret belongs to the saved id; a new id needs its own secret.
76 if load_client_id(store) != id {
77 return Err(GoogleClientSaveError::SecretRequired);
78 }
79 return match load_secret().await {
80 Ok(existing) if !existing.trim().is_empty() => Ok(GoogleClientSave::Saved),
81 _ => Err(GoogleClientSaveError::SecretRequired),
82 };
83 }
84 // Secret before id: a failed keyring write must not leave a new id beside the old secret.
85 store_secret(secret).await?;
86 store
87 .set_meta(CLIENT_ID_KEY, id)
88 .map_err(|_| GoogleClientSaveError::Failed)?;
89 Ok(GoogleClientSave::Saved)
90}
91
92async fn load_secret() -> Result<String, GoogleClientSaveError> {
93 spawn_blocking(move || {
94 let entry =
95 keyring::Entry::new(SERVICE, ACCOUNT).map_err(|_| GoogleClientSaveError::Failed)?;
96 entry
97 .get_password()
98 .map_err(|_| GoogleClientSaveError::Failed)
99 })
100 .await
101}
102
103async fn store_secret(secret: &str) -> Result<(), GoogleClientSaveError> {
104 let secret = secret.to_owned();
105 spawn_blocking(move || {
106 let entry =
107 keyring::Entry::new(SERVICE, ACCOUNT).map_err(|_| GoogleClientSaveError::Failed)?;
108 entry
109 .set_password(&secret)
110 .map_err(|_| GoogleClientSaveError::Failed)
111 })
112 .await
113}
114
115async fn delete_secret() -> Result<(), GoogleClientSaveError> {
116 spawn_blocking(move || {
117 let entry =
118 keyring::Entry::new(SERVICE, ACCOUNT).map_err(|_| GoogleClientSaveError::Failed)?;
119 match entry.delete_credential() {
120 Ok(()) => Ok(()),
121 Err(keyring::Error::NoEntry) => Ok(()),
122 Err(_) => Err(GoogleClientSaveError::Failed),
123 }
124 })
125 .await
126}
127
128async fn spawn_blocking<T: Send + 'static>(
129 work: impl FnOnce() -> Result<T, GoogleClientSaveError> + Send + 'static,
130) -> Result<T, GoogleClientSaveError> {
131 match tokio::task::spawn_blocking(work).await {
132 Ok(result) => result,
133 Err(_) => Err(GoogleClientSaveError::Failed),
134 }
135}
crates/app-state/src/lib.rs +1 −0
@@ -34,6 +34,7 @@ pub mod find_in_chat;
34 34 pub mod forward_selection;
35 35 pub mod gifs;
36 36 pub mod google_calendar_sync;
37 pub mod google_oauth_client;
37 38 pub mod ics_sync;
38 39 pub mod image_view_gallery;
39 40 pub mod importance;
@@ -34,6 +34,7 @@ pub mod find_in_chat;
34pub mod forward_selection;
34pub mod forward_selection;
35pub mod gifs;
35pub mod gifs;
36pub mod google_calendar_sync;
36pub mod google_calendar_sync;
37pub mod google_oauth_client;
37pub mod ics_sync;
38pub mod ics_sync;
38pub mod image_view_gallery;
39pub mod image_view_gallery;
39pub mod importance;
40pub mod importance;
crates/app/src/i18n.rs +5 −0
@@ -143,5 +143,10 @@ mod tests {
143 143 tr("settings.calendar.not_in_build"),
144 144 "Google Kalender ist in diesem Build nicht enthalten."
145 145 );
146 assert_eq!(
147 tr("settings.calendar.google_client_status_own"),
148 "Eigener Client"
149 );
150 assert!(tr("settings.calendar.google_client_guide_5").contains("«Google verbinden»"));
146 151 }
147 152 }
@@ -143,5 +143,10 @@ mod tests {
143 tr("settings.calendar.not_in_build"),
143 tr("settings.calendar.not_in_build"),
144 "Google Kalender ist in diesem Build nicht enthalten."
144 "Google Kalender ist in diesem Build nicht enthalten."
145 );
145 );
146 assert_eq!(
147 tr("settings.calendar.google_client_status_own"),
148 "Eigener Client"
149 );
150 assert!(tr("settings.calendar.google_client_guide_5").contains("«Google verbinden»"));
146 }
151 }
147}
152}
crates/app/src/settings/calendar.rs +6 −2
@@ -32,6 +32,7 @@ pub fn render_view(app: &Entity<AppState>, cx: &App) -> Div {
32 32
33 33 pub fn render_accounts(
34 34 app: &Entity<AppState>,
35 google_client: Option<&Entity<super::google_client_form::GoogleClientForm>>,
35 36 caldav: Option<&Entity<super::caldav_form::CalDavForm>>,
36 37 ics: Option<&Entity<super::caldav_form::IcsForm>>,
37 38 cx: &App,
@@ -40,8 +41,11 @@ pub fn render_accounts(
40 41 let pending = app.read(cx).google_connect_pending().is_some();
41 42 let mut body = v_flex()
42 43 .w_full()
43 .child(caption(tr("settings.calendar.section_google")))
44 .child(connect_row(app, accounts.has_google(), pending));
44 .child(caption(tr("settings.calendar.section_google")));
45 if let Some(form) = google_client {
46 body = body.child(form.clone());
47 }
48 body = body.child(connect_row(app, accounts.has_google(), pending));
45 49 for account in &accounts.google_accounts {
46 50 body = body.child(account_block(app, account, &accounts));
47 51 }
@@ -32,6 +32,7 @@ pub fn render_view(app: &Entity<AppState>, cx: &App) -> Div {
32
32
33pub fn render_accounts(
33pub fn render_accounts(
34 app: &Entity<AppState>,
34 app: &Entity<AppState>,
35 google_client: Option<&Entity<super::google_client_form::GoogleClientForm>>,
35 caldav: Option<&Entity<super::caldav_form::CalDavForm>>,
36 caldav: Option<&Entity<super::caldav_form::CalDavForm>>,
36 ics: Option<&Entity<super::caldav_form::IcsForm>>,
37 ics: Option<&Entity<super::caldav_form::IcsForm>>,
37 cx: &App,
38 cx: &App,
@@ -40,8 +41,11 @@ pub fn render_accounts(
40 let pending = app.read(cx).google_connect_pending().is_some();
41 let pending = app.read(cx).google_connect_pending().is_some();
41 let mut body = v_flex()
42 let mut body = v_flex()
42 .w_full()
43 .w_full()
43 .child(caption(tr("settings.calendar.section_google")))
44 .child(caption(tr("settings.calendar.section_google")));
44 .child(connect_row(app, accounts.has_google(), pending));
45 if let Some(form) = google_client {
46 body = body.child(form.clone());
47 }
48 body = body.child(connect_row(app, accounts.has_google(), pending));
45 for account in &accounts.google_accounts {
49 for account in &accounts.google_accounts {
46 body = body.child(account_block(app, account, &accounts));
50 body = body.child(account_block(app, account, &accounts));
47 }
51 }
crates/app/src/settings/dialog.rs +15 −4
@@ -8,6 +8,7 @@ use gpui_kit::*;
8 8
9 9 use super::caldav_form::{CalDavForm, IcsForm};
10 10 use super::devices::DevicesView;
11 use super::google_client_form::GoogleClientForm;
11 12 use super::help::HelpView;
12 13 use super::mcp::McpView;
13 14 use super::nav::{NavLayout, NavSearch, first_match, label, matches, render_nav};
@@ -69,6 +70,7 @@ pub struct SettingsDialog {
69 70 help: Option<Entity<HelpView>>,
70 71 mcp: Option<Entity<McpView>>,
71 72 agents: Option<Entity<AgentsSettings>>,
73 google_client: Option<Entity<GoogleClientForm>>,
72 74 caldav: Option<Entity<CalDavForm>>,
73 75 ics: Option<Entity<IcsForm>>,
74 76 body_scroll: ScrollHandle,
@@ -111,6 +113,7 @@ impl SettingsDialog {
111 113 help: None,
112 114 mcp: None,
113 115 agents: None,
116 google_client: None,
114 117 caldav: None,
115 118 ics: None,
116 119 body_scroll: ScrollHandle::new(),
@@ -158,6 +161,10 @@ impl SettingsDialog {
158 161 .map(|runs| cx.new(|cx| AgentsSettings::new(runs, cx)));
159 162 }
160 163 if section == SettingsSection::CalendarAccounts {
164 if self.google_client.is_none() {
165 let app = self.app.clone();
166 self.google_client = Some(cx.new(|cx| GoogleClientForm::new(app, window, cx)));
167 }
161 168 if self.caldav.is_none() {
162 169 let app = self.app.clone();
163 170 self.caldav = Some(cx.new(|cx| CalDavForm::new(app, window, cx)));
@@ -219,10 +226,14 @@ impl SettingsDialog {
219 226 SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),
220 227 SettingsSection::Calls => calls::render(&self.center, cx).into_any_element(),
221 228 SettingsSection::Calendar => calendar::render_view(&self.app, cx).into_any_element(),
222 SettingsSection::CalendarAccounts => {
223 calendar::render_accounts(&self.app, self.caldav.as_ref(), self.ics.as_ref(), cx)
224 .into_any_element()
225 }
229 SettingsSection::CalendarAccounts => calendar::render_accounts(
230 &self.app,
231 self.google_client.as_ref(),
232 self.caldav.as_ref(),
233 self.ics.as_ref(),
234 cx,
235 )
236 .into_any_element(),
226 237 SettingsSection::Devices => self
227 238 .devices
228 239 .clone()
@@ -8,6 +8,7 @@ use gpui_kit::*;
8
8
9use super::caldav_form::{CalDavForm, IcsForm};
9use super::caldav_form::{CalDavForm, IcsForm};
10use super::devices::DevicesView;
10use super::devices::DevicesView;
11use super::google_client_form::GoogleClientForm;
11use super::help::HelpView;
12use super::help::HelpView;
12use super::mcp::McpView;
13use super::mcp::McpView;
13use super::nav::{NavLayout, NavSearch, first_match, label, matches, render_nav};
14use super::nav::{NavLayout, NavSearch, first_match, label, matches, render_nav};
@@ -69,6 +70,7 @@ pub struct SettingsDialog {
69 help: Option<Entity<HelpView>>,
70 help: Option<Entity<HelpView>>,
70 mcp: Option<Entity<McpView>>,
71 mcp: Option<Entity<McpView>>,
71 agents: Option<Entity<AgentsSettings>>,
72 agents: Option<Entity<AgentsSettings>>,
73 google_client: Option<Entity<GoogleClientForm>>,
72 caldav: Option<Entity<CalDavForm>>,
74 caldav: Option<Entity<CalDavForm>>,
73 ics: Option<Entity<IcsForm>>,
75 ics: Option<Entity<IcsForm>>,
74 body_scroll: ScrollHandle,
76 body_scroll: ScrollHandle,
@@ -111,6 +113,7 @@ impl SettingsDialog {
111 help: None,
113 help: None,
112 mcp: None,
114 mcp: None,
113 agents: None,
115 agents: None,
116 google_client: None,
114 caldav: None,
117 caldav: None,
115 ics: None,
118 ics: None,
116 body_scroll: ScrollHandle::new(),
119 body_scroll: ScrollHandle::new(),
@@ -158,6 +161,10 @@ impl SettingsDialog {
158 .map(|runs| cx.new(|cx| AgentsSettings::new(runs, cx)));
161 .map(|runs| cx.new(|cx| AgentsSettings::new(runs, cx)));
159 }
162 }
160 if section == SettingsSection::CalendarAccounts {
163 if section == SettingsSection::CalendarAccounts {
164 if self.google_client.is_none() {
165 let app = self.app.clone();
166 self.google_client = Some(cx.new(|cx| GoogleClientForm::new(app, window, cx)));
167 }
161 if self.caldav.is_none() {
168 if self.caldav.is_none() {
162 let app = self.app.clone();
169 let app = self.app.clone();
163 self.caldav = Some(cx.new(|cx| CalDavForm::new(app, window, cx)));
170 self.caldav = Some(cx.new(|cx| CalDavForm::new(app, window, cx)));
@@ -219,10 +226,14 @@ impl SettingsDialog {
219 SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),
226 SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),
220 SettingsSection::Calls => calls::render(&self.center, cx).into_any_element(),
227 SettingsSection::Calls => calls::render(&self.center, cx).into_any_element(),
221 SettingsSection::Calendar => calendar::render_view(&self.app, cx).into_any_element(),
228 SettingsSection::Calendar => calendar::render_view(&self.app, cx).into_any_element(),
222 SettingsSection::CalendarAccounts => {
229 SettingsSection::CalendarAccounts => calendar::render_accounts(
223 calendar::render_accounts(&self.app, self.caldav.as_ref(), self.ics.as_ref(), cx)
230 &self.app,
224 .into_any_element()
231 self.google_client.as_ref(),
225 }
232 self.caldav.as_ref(),
233 self.ics.as_ref(),
234 cx,
235 )
236 .into_any_element(),
226 SettingsSection::Devices => self
237 SettingsSection::Devices => self
227 .devices
238 .devices
228 .clone()
239 .clone()
crates/app/src/settings/google_client_form.rs added +224 −0
@@ -0,0 +1,224 @@
1 use gpui_kit::component::input::{Input, InputContentType, InputState};
2 use gpui_kit::component::{h_flex, v_flex};
3 use gpui_kit::*;
4
5 use super::rows::{ROW_INSET, control_row, stacked_field, text_button};
6 use crate::app_state::AppState;
7 use crate::i18n::tr;
8 use crate::theme;
9
10 pub struct GoogleClientForm {
11 app: Entity<AppState>,
12 client_id: Entity<InputState>,
13 secret: Entity<InputState>,
14 saved_id: String,
15 secret_present: bool,
16 submits: u64,
17 saving: bool,
18 }
19
20 impl GoogleClientForm {
21 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
22 let saved_id = crate::google_oauth_client::load_client_id(&app.read(cx).store);
23 let client_id =
24 cx.new(|cx| InputState::new(window, cx).placeholder("….apps.googleusercontent.com"));
25 if !saved_id.is_empty() {
26 let text = saved_id.clone();
27 client_id.update(cx, |input, cx| input.set_value(text, window, cx));
28 }
29 let secret = cx.new(|cx| InputState::new(window, cx));
30 secret.update(cx, |input, cx| input.toggle_masked(window, cx));
31 if !saved_id.is_empty() {
32 cx.spawn_in(window, async move |form, cx| {
33 let present =
34 crate::runtime::spawn(crate::google_oauth_client::secret_is_stored()).await;
35 if !matches!(present, Ok(true)) {
36 return;
37 }
38 form.update_in(cx, |form, window, cx| {
39 if form.submits > 0 {
40 return;
41 }
42 form.secret_present = true;
43 form.secret.update(cx, |input, cx| {
44 input.set_placeholder(
45 tr("settings.calendar.google_client_secret_kept"),
46 window,
47 cx,
48 );
49 });
50 cx.notify();
51 })
52 .ok();
53 })
54 .detach();
55 }
56 GoogleClientForm {
57 app,
58 client_id,
59 secret,
60 saved_id,
61 secret_present: false,
62 submits: 0,
63 saving: false,
64 }
65 }
66
67 fn status_detail(&self) -> String {
68 if !self.saved_id.is_empty() && self.secret_present {
69 tr("settings.calendar.google_client_status_own")
70 } else if chatsvc::client_id_from_env().is_some() {
71 tr("settings.calendar.google_client_status_builtin")
72 } else {
73 tr("settings.calendar.google_client_status_missing")
74 }
75 }
76
77 fn submit(&mut self, clear: bool, window: &mut Window, cx: &mut Context<Self>) {
78 if self.saving {
79 return;
80 }
81 self.saving = true;
82 self.submits += 1;
83 let client_id = if clear {
84 String::new()
85 } else {
86 self.client_id.read(cx).value().to_string()
87 };
88 let secret = if clear {
89 String::new()
90 } else {
91 self.secret.read(cx).value().to_string()
92 };
93 let store = self.app.read(cx).store.clone();
94 let connected = self.app.read(cx).calendar_accounts().has_google();
95 let app = self.app.clone();
96 let id_field = self.client_id.clone();
97 let secret_field = self.secret.clone();
98 let saved_label = client_id.trim().to_owned();
99 cx.spawn_in(window, async move |form, cx| {
100 let result = crate::runtime::spawn(async move {
101 crate::google_oauth_client::save(&store, &client_id, &secret).await
102 })
103 .await;
104 form.update_in(cx, |form, window, cx| {
105 form.saving = false;
106 let notice = match result {
107 Ok(Ok(crate::google_oauth_client::GoogleClientSave::Saved)) => {
108 form.saved_id = saved_label;
109 form.secret_present = true;
110 secret_field.update(cx, |input, cx| input.set_value("", window, cx));
111 if connected {
112 tr("settings.calendar.google_client_saved_reconnect")
113 } else {
114 tr("settings.calendar.google_client_saved")
115 }
116 }
117 Ok(Ok(crate::google_oauth_client::GoogleClientSave::Cleared)) => {
118 form.saved_id.clear();
119 form.secret_present = false;
120 id_field.update(cx, |input, cx| input.set_value("", window, cx));
121 secret_field.update(cx, |input, cx| {
122 input.set_value("", window, cx);
123 input.set_placeholder("", window, cx);
124 });
125 if connected {
126 tr("settings.calendar.google_client_cleared_reconnect")
127 } else {
128 tr("settings.calendar.google_client_cleared")
129 }
130 }
131 Ok(Err(crate::google_oauth_client::GoogleClientSaveError::SecretRequired)) => {
132 tr("settings.calendar.google_client_secret_required")
133 }
134 _ => tr("settings.calendar.google_client_save_failed"),
135 };
136 if form.secret_present {
137 secret_field.update(cx, |input, cx| {
138 input.set_placeholder(
139 tr("settings.calendar.google_client_secret_kept"),
140 window,
141 cx,
142 );
143 });
144 }
145 app.update(cx, |state, cx| state.raise_notice(notice, None, cx));
146 cx.notify();
147 })
148 .ok();
149 })
150 .detach();
151 }
152 }
153
154 impl Render for GoogleClientForm {
155 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
156 let save = cx.entity().clone();
157 let reset = cx.entity().clone();
158 v_flex()
159 .w_full()
160 .gap(px(8.))
161 .child(control_row(
162 tr("settings.calendar.google_client_status_title"),
163 self.status_detail(),
164 div(),
165 ))
166 .child(stacked_field(
167 tr("settings.calendar.google_client_id"),
168 "",
169 Input::new(&self.client_id),
170 ))
171 .child(stacked_field(
172 tr("settings.calendar.google_client_secret"),
173 "",
174 Input::new(&self.secret)
175 .content_type(InputContentType::Password)
176 .mask_toggle(),
177 ))
178 .child(guide())
179 .child(control_row(
180 tr("settings.calendar.google_client_save"),
181 "",
182 h_flex()
183 .gap_2()
184 .child(
185 text_button(
186 "settings-google-client-save",
187 tr("settings.calendar.google_client_save"),
188 )
189 .on_click(move |_, window, cx| {
190 save.update(cx, |form, cx| form.submit(false, window, cx))
191 }),
192 )
193 .child(
194 text_button(
195 "settings-google-client-reset",
196 tr("settings.calendar.google_client_reset"),
197 )
198 .on_click(move |_, window, cx| {
199 reset.update(cx, |form, cx| form.submit(true, window, cx))
200 }),
201 ),
202 ))
203 }
204 }
205
206 fn guide() -> Div {
207 v_flex()
208 .w_full()
209 .px(px(ROW_INSET))
210 .child(guide_line(tr("settings.calendar.google_client_guide_1")))
211 .child(guide_line(tr("settings.calendar.google_client_guide_2")))
212 .child(guide_line(tr("settings.calendar.google_client_guide_3")))
213 .child(guide_line(tr("settings.calendar.google_client_guide_4")))
214 .child(guide_line(tr("settings.calendar.google_client_guide_5")))
215 }
216
217 fn guide_line(text: String) -> Div {
218 div()
219 .w_full()
220 .text_size(px(12.))
221 .line_height(px(16.))
222 .text_color(theme::text_muted())
223 .child(text)
224 }
@@ -0,0 +1,224 @@
1use gpui_kit::component::input::{Input, InputContentType, InputState};
2use gpui_kit::component::{h_flex, v_flex};
3use gpui_kit::*;
4
5use super::rows::{ROW_INSET, control_row, stacked_field, text_button};
6use crate::app_state::AppState;
7use crate::i18n::tr;
8use crate::theme;
9
10pub struct GoogleClientForm {
11 app: Entity<AppState>,
12 client_id: Entity<InputState>,
13 secret: Entity<InputState>,
14 saved_id: String,
15 secret_present: bool,
16 submits: u64,
17 saving: bool,
18}
19
20impl GoogleClientForm {
21 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
22 let saved_id = crate::google_oauth_client::load_client_id(&app.read(cx).store);
23 let client_id =
24 cx.new(|cx| InputState::new(window, cx).placeholder("….apps.googleusercontent.com"));
25 if !saved_id.is_empty() {
26 let text = saved_id.clone();
27 client_id.update(cx, |input, cx| input.set_value(text, window, cx));
28 }
29 let secret = cx.new(|cx| InputState::new(window, cx));
30 secret.update(cx, |input, cx| input.toggle_masked(window, cx));
31 if !saved_id.is_empty() {
32 cx.spawn_in(window, async move |form, cx| {
33 let present =
34 crate::runtime::spawn(crate::google_oauth_client::secret_is_stored()).await;
35 if !matches!(present, Ok(true)) {
36 return;
37 }
38 form.update_in(cx, |form, window, cx| {
39 if form.submits > 0 {
40 return;
41 }
42 form.secret_present = true;
43 form.secret.update(cx, |input, cx| {
44 input.set_placeholder(
45 tr("settings.calendar.google_client_secret_kept"),
46 window,
47 cx,
48 );
49 });
50 cx.notify();
51 })
52 .ok();
53 })
54 .detach();
55 }
56 GoogleClientForm {
57 app,
58 client_id,
59 secret,
60 saved_id,
61 secret_present: false,
62 submits: 0,
63 saving: false,
64 }
65 }
66
67 fn status_detail(&self) -> String {
68 if !self.saved_id.is_empty() && self.secret_present {
69 tr("settings.calendar.google_client_status_own")
70 } else if chatsvc::client_id_from_env().is_some() {
71 tr("settings.calendar.google_client_status_builtin")
72 } else {
73 tr("settings.calendar.google_client_status_missing")
74 }
75 }
76
77 fn submit(&mut self, clear: bool, window: &mut Window, cx: &mut Context<Self>) {
78 if self.saving {
79 return;
80 }
81 self.saving = true;
82 self.submits += 1;
83 let client_id = if clear {
84 String::new()
85 } else {
86 self.client_id.read(cx).value().to_string()
87 };
88 let secret = if clear {
89 String::new()
90 } else {
91 self.secret.read(cx).value().to_string()
92 };
93 let store = self.app.read(cx).store.clone();
94 let connected = self.app.read(cx).calendar_accounts().has_google();
95 let app = self.app.clone();
96 let id_field = self.client_id.clone();
97 let secret_field = self.secret.clone();
98 let saved_label = client_id.trim().to_owned();
99 cx.spawn_in(window, async move |form, cx| {
100 let result = crate::runtime::spawn(async move {
101 crate::google_oauth_client::save(&store, &client_id, &secret).await
102 })
103 .await;
104 form.update_in(cx, |form, window, cx| {
105 form.saving = false;
106 let notice = match result {
107 Ok(Ok(crate::google_oauth_client::GoogleClientSave::Saved)) => {
108 form.saved_id = saved_label;
109 form.secret_present = true;
110 secret_field.update(cx, |input, cx| input.set_value("", window, cx));
111 if connected {
112 tr("settings.calendar.google_client_saved_reconnect")
113 } else {
114 tr("settings.calendar.google_client_saved")
115 }
116 }
117 Ok(Ok(crate::google_oauth_client::GoogleClientSave::Cleared)) => {
118 form.saved_id.clear();
119 form.secret_present = false;
120 id_field.update(cx, |input, cx| input.set_value("", window, cx));
121 secret_field.update(cx, |input, cx| {
122 input.set_value("", window, cx);
123 input.set_placeholder("", window, cx);
124 });
125 if connected {
126 tr("settings.calendar.google_client_cleared_reconnect")
127 } else {
128 tr("settings.calendar.google_client_cleared")
129 }
130 }
131 Ok(Err(crate::google_oauth_client::GoogleClientSaveError::SecretRequired)) => {
132 tr("settings.calendar.google_client_secret_required")
133 }
134 _ => tr("settings.calendar.google_client_save_failed"),
135 };
136 if form.secret_present {
137 secret_field.update(cx, |input, cx| {
138 input.set_placeholder(
139 tr("settings.calendar.google_client_secret_kept"),
140 window,
141 cx,
142 );
143 });
144 }
145 app.update(cx, |state, cx| state.raise_notice(notice, None, cx));
146 cx.notify();
147 })
148 .ok();
149 })
150 .detach();
151 }
152}
153
154impl Render for GoogleClientForm {
155 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
156 let save = cx.entity().clone();
157 let reset = cx.entity().clone();
158 v_flex()
159 .w_full()
160 .gap(px(8.))
161 .child(control_row(
162 tr("settings.calendar.google_client_status_title"),
163 self.status_detail(),
164 div(),
165 ))
166 .child(stacked_field(
167 tr("settings.calendar.google_client_id"),
168 "",
169 Input::new(&self.client_id),
170 ))
171 .child(stacked_field(
172 tr("settings.calendar.google_client_secret"),
173 "",
174 Input::new(&self.secret)
175 .content_type(InputContentType::Password)
176 .mask_toggle(),
177 ))
178 .child(guide())
179 .child(control_row(
180 tr("settings.calendar.google_client_save"),
181 "",
182 h_flex()
183 .gap_2()
184 .child(
185 text_button(
186 "settings-google-client-save",
187 tr("settings.calendar.google_client_save"),
188 )
189 .on_click(move |_, window, cx| {
190 save.update(cx, |form, cx| form.submit(false, window, cx))
191 }),
192 )
193 .child(
194 text_button(
195 "settings-google-client-reset",
196 tr("settings.calendar.google_client_reset"),
197 )
198 .on_click(move |_, window, cx| {
199 reset.update(cx, |form, cx| form.submit(true, window, cx))
200 }),
201 ),
202 ))
203 }
204}
205
206fn guide() -> Div {
207 v_flex()
208 .w_full()
209 .px(px(ROW_INSET))
210 .child(guide_line(tr("settings.calendar.google_client_guide_1")))
211 .child(guide_line(tr("settings.calendar.google_client_guide_2")))
212 .child(guide_line(tr("settings.calendar.google_client_guide_3")))
213 .child(guide_line(tr("settings.calendar.google_client_guide_4")))
214 .child(guide_line(tr("settings.calendar.google_client_guide_5")))
215}
216
217fn guide_line(text: String) -> Div {
218 div()
219 .w_full()
220 .text_size(px(12.))
221 .line_height(px(16.))
222 .text_color(theme::text_muted())
223 .child(text)
224}
crates/app/src/settings/mod.rs +1 −0
@@ -8,6 +8,7 @@ mod chats;
8 8 mod devices;
9 9 mod dialog;
10 10 mod general;
11 mod google_client_form;
11 12 mod help;
12 13 mod mcp;
13 14 mod nav;
@@ -8,6 +8,7 @@ mod chats;
8mod devices;
8mod devices;
9mod dialog;
9mod dialog;
10mod general;
10mod general;
11mod google_client_form;
11mod help;
12mod help;
12mod mcp;
13mod mcp;
13mod nav;
14mod nav;
crates/app/src/settings/nav.rs +6 −1
@@ -36,8 +36,11 @@ const CALENDAR_VIEW_TERMS: [&str; 5] = [
36 36 "settings.calendar.weekend",
37 37 ];
38 38
39 const CALENDAR_ACCOUNTS_TERMS: [&str; 9] = [
39 const CALENDAR_ACCOUNTS_TERMS: [&str; 12] = [
40 40 "settings.calendar.google_title",
41 "settings.calendar.google_client_id",
42 "settings.calendar.google_client_secret",
43 "settings.calendar.google_client_guide_1",
41 44 "settings.calendar.connect_button",
42 45 "settings.calendar.caldav_title",
43 46 "settings.calendar.caldav_connect",
@@ -454,6 +457,8 @@ mod tests {
454 457 include_str!("calendar.rs"),
455 458 "\n",
456 459 include_str!("caldav_form.rs"),
460 "\n",
461 include_str!("google_client_form.rs"),
457 462 );
458 463 let pages = [
459 464 (SettingsSection::General, include_str!("general.rs")),
@@ -36,8 +36,11 @@ const CALENDAR_VIEW_TERMS: [&str; 5] = [
36 "settings.calendar.weekend",
36 "settings.calendar.weekend",
37];
37];
38
38
39const CALENDAR_ACCOUNTS_TERMS: [&str; 9] = [
39const CALENDAR_ACCOUNTS_TERMS: [&str; 12] = [
40 "settings.calendar.google_title",
40 "settings.calendar.google_title",
41 "settings.calendar.google_client_id",
42 "settings.calendar.google_client_secret",
43 "settings.calendar.google_client_guide_1",
41 "settings.calendar.connect_button",
44 "settings.calendar.connect_button",
42 "settings.calendar.caldav_title",
45 "settings.calendar.caldav_title",
43 "settings.calendar.caldav_connect",
46 "settings.calendar.caldav_connect",
@@ -454,6 +457,8 @@ mod tests {
454 include_str!("calendar.rs"),
457 include_str!("calendar.rs"),
455 "\n",
458 "\n",
456 include_str!("caldav_form.rs"),
459 include_str!("caldav_form.rs"),
460 "\n",
461 include_str!("google_client_form.rs"),
457 );
462 );
458 let pages = [
463 let pages = [
459 (SettingsSection::General, include_str!("general.rs")),
464 (SettingsSection::General, include_str!("general.rs")),
crates/chatsvc/src/google_calendar/mod.rs +2 −1
@@ -9,7 +9,8 @@ mod write;
9 9 pub use loopback::{allocate_redirect_uri, wait_for_code};
10 10 pub use merge::{merge_calendar_events, normalize_join_url};
11 11 pub use oauth::{
12 AuthPending, GoogleOAuth, TokenBundle, client_id_from_env, exchange_code, refresh_access_token,
12 AuthPending, GoogleOAuth, TokenBundle, client_from_stored, client_id_from_env, exchange_code,
13 refresh_access_token,
13 14 };
14 15 pub use parse::{parse_calendar_list, parse_google_events};
15 16 pub use write::{
@@ -9,7 +9,8 @@ mod write;
9pub use loopback::{allocate_redirect_uri, wait_for_code};
9pub use loopback::{allocate_redirect_uri, wait_for_code};
10pub use merge::{merge_calendar_events, normalize_join_url};
10pub use merge::{merge_calendar_events, normalize_join_url};
11pub use oauth::{
11pub use oauth::{
12 AuthPending, GoogleOAuth, TokenBundle, client_id_from_env, exchange_code, refresh_access_token,
12 AuthPending, GoogleOAuth, TokenBundle, client_from_stored, client_id_from_env, exchange_code,
13 refresh_access_token,
13};
14};
14pub use parse::{parse_calendar_list, parse_google_events};
15pub use parse::{parse_calendar_list, parse_google_events};
15pub use write::{
16pub use write::{
crates/chatsvc/src/google_calendar/oauth.rs +81 −6
@@ -39,9 +39,20 @@ pub struct TokenBundle {
39 39 }
40 40
41 41 /// Runtime env wins; otherwise the value baked in at compile time (`option_env!`).
42 /// Empty strings count as missing. Used by Connect and token refresh.
42 /// Empty strings count as missing. Used when Settings has no saved pair.
43 43 pub fn client_id_from_env() -> Option<GoogleOAuth> {
44 client_from_stored(None, None)
45 }
46
47 /// A saved id and secret win only together. Otherwise the same order as
48 /// [`client_id_from_env`]: runtime env, then the compiled client.
49 pub fn client_from_stored(
50 stored_id: Option<&str>,
51 stored_secret: Option<&str>,
52 ) -> Option<GoogleOAuth> {
44 53 resolve_oauth(
54 stored_id,
55 stored_secret,
45 56 std::env::var(GOOGLE_CLIENT_ID_ENV).ok().as_deref(),
46 57 std::env::var(GOOGLE_CLIENT_SECRET_ENV).ok().as_deref(),
47 58 option_env!("TEAMS_GOOGLE_CLIENT_ID"),
@@ -50,11 +61,21 @@ pub fn client_id_from_env() -> Option<GoogleOAuth> {
50 61 }
51 62
52 63 fn resolve_oauth(
64 stored_id: Option<&str>,
65 stored_secret: Option<&str>,
53 66 runtime_id: Option<&str>,
54 67 runtime_secret: Option<&str>,
55 68 compile_id: Option<&str>,
56 69 compile_secret: Option<&str>,
57 70 ) -> Option<GoogleOAuth> {
71 if let (Some(client_id), Some(client_secret)) =
72 (first_non_empty(stored_id), first_non_empty(stored_secret))
73 {
74 return Some(GoogleOAuth {
75 client_id,
76 client_secret,
77 });
78 }
58 79 let client_id = first_non_empty(runtime_id).or_else(|| first_non_empty(compile_id))?;
59 80 let client_secret = first_non_empty(runtime_secret)
60 81 .or_else(|| first_non_empty(compile_secret))
@@ -208,6 +229,8 @@ mod tests {
208 229 #[test]
209 230 fn resolve_prefers_runtime_over_compile() {
210 231 let oauth = resolve_oauth(
232 None,
233 None,
211 234 Some("runtime-id"),
212 235 Some("runtime-secret"),
213 236 Some("compile-id"),
@@ -220,22 +243,74 @@ mod tests {
220 243
221 244 #[test]
222 245 fn resolve_falls_back_to_compile_when_runtime_empty() {
223 let oauth =
224 resolve_oauth(Some(" "), None, Some("compile-id"), Some("compile-secret")).unwrap();
246 let oauth = resolve_oauth(
247 None,
248 None,
249 Some(" "),
250 None,
251 Some("compile-id"),
252 Some("compile-secret"),
253 )
254 .unwrap();
225 255 assert_eq!(oauth.client_id, "compile-id");
226 256 assert_eq!(oauth.client_secret, "compile-secret");
227 257 }
228 258
229 259 #[test]
230 260 fn resolve_returns_none_when_both_missing() {
231 assert!(resolve_oauth(None, None, None, None).is_none());
232 assert!(resolve_oauth(Some(""), None, Some(" "), None).is_none());
261 assert!(resolve_oauth(None, None, None, None, None, None).is_none());
262 assert!(resolve_oauth(None, None, Some(""), None, Some(" "), None).is_none());
233 263 }
234 264
235 265 #[test]
236 266 fn resolve_allows_missing_secret() {
237 let oauth = resolve_oauth(Some("cid"), None, None, None).unwrap();
267 let oauth = resolve_oauth(None, None, Some("cid"), None, None, None).unwrap();
238 268 assert_eq!(oauth.client_id, "cid");
239 269 assert!(oauth.client_secret.is_empty());
240 270 }
271
272 #[test]
273 fn stored_pair_wins_over_runtime_and_compile() {
274 let oauth = resolve_oauth(
275 Some(" stored-id "),
276 Some(" stored-secret "),
277 Some("runtime-id"),
278 Some("runtime-secret"),
279 Some("compile-id"),
280 Some("compile-secret"),
281 )
282 .unwrap();
283 assert_eq!(oauth.client_id, "stored-id");
284 assert_eq!(oauth.client_secret, "stored-secret");
285 }
286
287 #[test]
288 fn stored_id_without_secret_does_not_override() {
289 let oauth = resolve_oauth(
290 Some("stored-id"),
291 Some(" "),
292 Some("runtime-id"),
293 Some("runtime-secret"),
294 None,
295 None,
296 )
297 .unwrap();
298 assert_eq!(oauth.client_id, "runtime-id");
299 assert_eq!(oauth.client_secret, "runtime-secret");
300 }
301
302 #[test]
303 fn stored_secret_without_id_does_not_override() {
304 let oauth = resolve_oauth(
305 Some(""),
306 Some("stored-secret"),
307 None,
308 None,
309 Some("compile-id"),
310 Some("compile-secret"),
311 )
312 .unwrap();
313 assert_eq!(oauth.client_id, "compile-id");
314 assert_eq!(oauth.client_secret, "compile-secret");
315 }
241 316 }
@@ -39,9 +39,20 @@ pub struct TokenBundle {
39}
39}
40
40
41/// Runtime env wins; otherwise the value baked in at compile time (`option_env!`).
41/// Runtime env wins; otherwise the value baked in at compile time (`option_env!`).
42/// Empty strings count as missing. Used by Connect and token refresh.
42/// Empty strings count as missing. Used when Settings has no saved pair.
43pub fn client_id_from_env() -> Option<GoogleOAuth> {
43pub fn client_id_from_env() -> Option<GoogleOAuth> {
44 client_from_stored(None, None)
45}
46
47/// A saved id and secret win only together. Otherwise the same order as
48/// [`client_id_from_env`]: runtime env, then the compiled client.
49pub fn client_from_stored(
50 stored_id: Option<&str>,
51 stored_secret: Option<&str>,
52) -> Option<GoogleOAuth> {
44 resolve_oauth(
53 resolve_oauth(
54 stored_id,
55 stored_secret,
45 std::env::var(GOOGLE_CLIENT_ID_ENV).ok().as_deref(),
56 std::env::var(GOOGLE_CLIENT_ID_ENV).ok().as_deref(),
46 std::env::var(GOOGLE_CLIENT_SECRET_ENV).ok().as_deref(),
57 std::env::var(GOOGLE_CLIENT_SECRET_ENV).ok().as_deref(),
47 option_env!("TEAMS_GOOGLE_CLIENT_ID"),
58 option_env!("TEAMS_GOOGLE_CLIENT_ID"),
@@ -50,11 +61,21 @@ pub fn client_id_from_env() -> Option<GoogleOAuth> {
50}
61}
51
62
52fn resolve_oauth(
63fn resolve_oauth(
64 stored_id: Option<&str>,
65 stored_secret: Option<&str>,
53 runtime_id: Option<&str>,
66 runtime_id: Option<&str>,
54 runtime_secret: Option<&str>,
67 runtime_secret: Option<&str>,
55 compile_id: Option<&str>,
68 compile_id: Option<&str>,
56 compile_secret: Option<&str>,
69 compile_secret: Option<&str>,
57) -> Option<GoogleOAuth> {
70) -> Option<GoogleOAuth> {
71 if let (Some(client_id), Some(client_secret)) =
72 (first_non_empty(stored_id), first_non_empty(stored_secret))
73 {
74 return Some(GoogleOAuth {
75 client_id,
76 client_secret,
77 });
78 }
58 let client_id = first_non_empty(runtime_id).or_else(|| first_non_empty(compile_id))?;
79 let client_id = first_non_empty(runtime_id).or_else(|| first_non_empty(compile_id))?;
59 let client_secret = first_non_empty(runtime_secret)
80 let client_secret = first_non_empty(runtime_secret)
60 .or_else(|| first_non_empty(compile_secret))
81 .or_else(|| first_non_empty(compile_secret))
@@ -208,6 +229,8 @@ mod tests {
208 #[test]
229 #[test]
209 fn resolve_prefers_runtime_over_compile() {
230 fn resolve_prefers_runtime_over_compile() {
210 let oauth = resolve_oauth(
231 let oauth = resolve_oauth(
232 None,
233 None,
211 Some("runtime-id"),
234 Some("runtime-id"),
212 Some("runtime-secret"),
235 Some("runtime-secret"),
213 Some("compile-id"),
236 Some("compile-id"),
@@ -220,22 +243,74 @@ mod tests {
220
243
221 #[test]
244 #[test]
222 fn resolve_falls_back_to_compile_when_runtime_empty() {
245 fn resolve_falls_back_to_compile_when_runtime_empty() {
223 let oauth =
246 let oauth = resolve_oauth(
224 resolve_oauth(Some(" "), None, Some("compile-id"), Some("compile-secret")).unwrap();
247 None,
248 None,
249 Some(" "),
250 None,
251 Some("compile-id"),
252 Some("compile-secret"),
253 )
254 .unwrap();
225 assert_eq!(oauth.client_id, "compile-id");
255 assert_eq!(oauth.client_id, "compile-id");
226 assert_eq!(oauth.client_secret, "compile-secret");
256 assert_eq!(oauth.client_secret, "compile-secret");
227 }
257 }
228
258
229 #[test]
259 #[test]
230 fn resolve_returns_none_when_both_missing() {
260 fn resolve_returns_none_when_both_missing() {
231 assert!(resolve_oauth(None, None, None, None).is_none());
261 assert!(resolve_oauth(None, None, None, None, None, None).is_none());
232 assert!(resolve_oauth(Some(""), None, Some(" "), None).is_none());
262 assert!(resolve_oauth(None, None, Some(""), None, Some(" "), None).is_none());
233 }
263 }
234
264
235 #[test]
265 #[test]
236 fn resolve_allows_missing_secret() {
266 fn resolve_allows_missing_secret() {
237 let oauth = resolve_oauth(Some("cid"), None, None, None).unwrap();
267 let oauth = resolve_oauth(None, None, Some("cid"), None, None, None).unwrap();
238 assert_eq!(oauth.client_id, "cid");
268 assert_eq!(oauth.client_id, "cid");
239 assert!(oauth.client_secret.is_empty());
269 assert!(oauth.client_secret.is_empty());
240 }
270 }
271
272 #[test]
273 fn stored_pair_wins_over_runtime_and_compile() {
274 let oauth = resolve_oauth(
275 Some(" stored-id "),
276 Some(" stored-secret "),
277 Some("runtime-id"),
278 Some("runtime-secret"),
279 Some("compile-id"),
280 Some("compile-secret"),
281 )
282 .unwrap();
283 assert_eq!(oauth.client_id, "stored-id");
284 assert_eq!(oauth.client_secret, "stored-secret");
285 }
286
287 #[test]
288 fn stored_id_without_secret_does_not_override() {
289 let oauth = resolve_oauth(
290 Some("stored-id"),
291 Some(" "),
292 Some("runtime-id"),
293 Some("runtime-secret"),
294 None,
295 None,
296 )
297 .unwrap();
298 assert_eq!(oauth.client_id, "runtime-id");
299 assert_eq!(oauth.client_secret, "runtime-secret");
300 }
301
302 #[test]
303 fn stored_secret_without_id_does_not_override() {
304 let oauth = resolve_oauth(
305 Some(""),
306 Some("stored-secret"),
307 None,
308 None,
309 Some("compile-id"),
310 Some("compile-secret"),
311 )
312 .unwrap();
313 assert_eq!(oauth.client_id, "compile-id");
314 assert_eq!(oauth.client_secret, "compile-secret");
315 }
241}
316}
crates/chatsvc/src/lib.rs +3 −3
@@ -90,9 +90,9 @@ pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
90 90 pub use gifs::{Gif, Gifs};
91 91 pub use google_calendar::{
92 92 AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,
93 client_id_from_env, exchange_code, google_event_body, google_rsvp_query, google_rsvp_status,
94 parse_calendar_list, parse_google_events, refresh_access_token, rrule_for_repeat,
95 wait_for_code,
93 client_from_stored, client_id_from_env, exchange_code, google_event_body, google_rsvp_query,
94 google_rsvp_status, parse_calendar_list, parse_google_events, refresh_access_token,
95 rrule_for_repeat, wait_for_code,
96 96 };
97 97 pub use ical::{
98 98 CalDavEventDraft, build_vevent, exclude_occurrence_from_ics, expand_events, parse_calendar,
@@ -90,9 +90,9 @@ pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
90pub use gifs::{Gif, Gifs};
90pub use gifs::{Gif, Gifs};
91pub use google_calendar::{
91pub use google_calendar::{
92 AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,
92 AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,
93 client_id_from_env, exchange_code, google_event_body, google_rsvp_query, google_rsvp_status,
93 client_from_stored, client_id_from_env, exchange_code, google_event_body, google_rsvp_query,
94 parse_calendar_list, parse_google_events, refresh_access_token, rrule_for_repeat,
94 google_rsvp_status, parse_calendar_list, parse_google_events, refresh_access_token,
95 wait_for_code,
95 rrule_for_repeat, wait_for_code,
96};
96};
97pub use ical::{
97pub use ical::{
98 CalDavEventDraft, build_vevent, exclude_occurrence_from_ics, expand_events, parse_calendar,
98 CalDavEventDraft, build_vevent, exclude_occurrence_from_ics, expand_events, parse_calendar,
docs/decisions/0009-bundled-google-oauth-client.md +3 −1
@@ -15,9 +15,11 @@ Options were: env vars only, a settings field for the client id, or one project
15 15
16 16 Official release builds compile in the project Desktop client id (and optional secret) via `option_env!`. Runtime env vars still override for developers. Users only click Connect Google; tokens stay on the device (see ADR 0002). Release CI must supply the client id at compile time so Dock and Start Menu launches are not Outlook-only by accident.
17 17
18 A client id and secret saved in Settings override both the environment and this compiled client (ADR 0024). When those fields are empty, this decision still applies.
19
18 20 ## Consequences
19 21
20 22 - Connect works from a Dock-started macOS `.app` and from Windows/Linux installers without a terminal.
21 23 - The project owns the Google Cloud consent screen and verification path for the sensitive `calendar` scope.
22 24 - Local `cargo run` without the secret stays Outlook-only unless the developer exports the env vars.
23 - The client id is visible in the binary; the secret must never appear in UI, logs, or the store.
25 - The client id is visible in the binary; the secret must never appear in UI, logs, or the store. A secret the user types is stored in the OS keyring (ADR 0024) and is not shown again after save.
@@ -15,9 +15,11 @@ Options were: env vars only, a settings field for the client id, or one project
15
15
16Official release builds compile in the project Desktop client id (and optional secret) via `option_env!`. Runtime env vars still override for developers. Users only click Connect Google; tokens stay on the device (see ADR 0002). Release CI must supply the client id at compile time so Dock and Start Menu launches are not Outlook-only by accident.
16Official release builds compile in the project Desktop client id (and optional secret) via `option_env!`. Runtime env vars still override for developers. Users only click Connect Google; tokens stay on the device (see ADR 0002). Release CI must supply the client id at compile time so Dock and Start Menu launches are not Outlook-only by accident.
17
17
18A client id and secret saved in Settings override both the environment and this compiled client (ADR 0024). When those fields are empty, this decision still applies.
19
18## Consequences
20## Consequences
19
21
20- Connect works from a Dock-started macOS `.app` and from Windows/Linux installers without a terminal.
22- Connect works from a Dock-started macOS `.app` and from Windows/Linux installers without a terminal.
21- The project owns the Google Cloud consent screen and verification path for the sensitive `calendar` scope.
23- The project owns the Google Cloud consent screen and verification path for the sensitive `calendar` scope.
22- Local `cargo run` without the secret stays Outlook-only unless the developer exports the env vars.
24- Local `cargo run` without the secret stays Outlook-only unless the developer exports the env vars.
23- The client id is visible in the binary; the secret must never appear in UI, logs, or the store.
25- The client id is visible in the binary; the secret must never appear in UI, logs, or the store. A secret the user types is stored in the OS keyring (ADR 0024) and is not shown again after save.
docs/decisions/0024-google-oauth-client-in-settings.md added +24 −0
@@ -0,0 +1,24 @@
1 ---
2 status: proposed
3 date: 2026-11-27
4 superseded-by:
5 ---
6
7 # ADR 0024: Google OAuth client in Settings
8
9 ## Context
10
11 ADR 0009 compiles one Desktop client into release builds so Connect Google works from a Dock or Start Menu launch. That still leaves anyone who wants their own Google Cloud client rebuilding the app or exporting shell variables. A settings field was rejected in 0009 because it would have been the only path.
12
13 ## Decision
14
15 Settings › Calendar accounts accepts a client id and client secret, with a short guide for a Desktop client. The pair is used for Connect and token refresh only when both are saved. The id is store metadata. The secret is in the OS keyring under `rusty-teams.google-oauth`, never in the calendar account document, never in logs, and never put back into the field. Clearing the id removes the pair.
16
17 Empty settings keep ADR 0009: runtime environment, then the compiled client. Release builds stay unchanged.
18
19 ## Consequences
20
21 - A person can use their own Google Cloud project without a rebuild.
22 - Official builds still connect with one click when the fields are empty.
23 - Tokens issued for the previous client do not refresh after a switch. The save notice says to connect again; the app does not disconnect on its own.
24 - The compiled client id remains visible in release binaries, as in ADR 0009.
@@ -0,0 +1,24 @@
1---
2status: proposed
3date: 2026-11-27
4superseded-by:
5---
6
7# ADR 0024: Google OAuth client in Settings
8
9## Context
10
11ADR 0009 compiles one Desktop client into release builds so Connect Google works from a Dock or Start Menu launch. That still leaves anyone who wants their own Google Cloud client rebuilding the app or exporting shell variables. A settings field was rejected in 0009 because it would have been the only path.
12
13## Decision
14
15Settings › Calendar accounts accepts a client id and client secret, with a short guide for a Desktop client. The pair is used for Connect and token refresh only when both are saved. The id is store metadata. The secret is in the OS keyring under `rusty-teams.google-oauth`, never in the calendar account document, never in logs, and never put back into the field. Clearing the id removes the pair.
16
17Empty settings keep ADR 0009: runtime environment, then the compiled client. Release builds stay unchanged.
18
19## Consequences
20
21- A person can use their own Google Cloud project without a rebuild.
22- Official builds still connect with one click when the fields are empty.
23- Tokens issued for the previous client do not refresh after a switch. The save notice says to connect again; the app does not disconnect on its own.
24- The compiled client id remains visible in release binaries, as in ADR 0009.
docs/decisions/README.md +2 −1
@@ -39,5 +39,6 @@ Statuses: `proposed`, `accepted`, `superseded`.
39 39 | [0021](0021-linux-packages.md) | Linux releases also ship an AppImage, a deb and an rpm |
40 40 | [0022](0022-linux-parks-the-idle-teams-tab.md) | Linux parks the idle Teams tab in a Chromium browser |
41 41 | [0023](0023-calendar-slot-selection-for-new-meetings.md) | Picking empty calendar slots for a new meeting |
42 | [0024](0024-google-oauth-client-in-settings.md) | A saved Google OAuth client in Settings overrides the built-in client |
42 43
43 Records `0001` to `0021` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
44 Records `0001` to `0021` are the decisions already shipped. `0024` is proposed. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
@@ -39,5 +39,6 @@ Statuses: `proposed`, `accepted`, `superseded`.
39| [0021](0021-linux-packages.md) | Linux releases also ship an AppImage, a deb and an rpm |
39| [0021](0021-linux-packages.md) | Linux releases also ship an AppImage, a deb and an rpm |
40| [0022](0022-linux-parks-the-idle-teams-tab.md) | Linux parks the idle Teams tab in a Chromium browser |
40| [0022](0022-linux-parks-the-idle-teams-tab.md) | Linux parks the idle Teams tab in a Chromium browser |
41| [0023](0023-calendar-slot-selection-for-new-meetings.md) | Picking empty calendar slots for a new meeting |
41| [0023](0023-calendar-slot-selection-for-new-meetings.md) | Picking empty calendar slots for a new meeting |
42| [0024](0024-google-oauth-client-in-settings.md) | A saved Google OAuth client in Settings overrides the built-in client |
42
43
43Records `0001` to `0021` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
44Records `0001` to `0021` are the decisions already shipped. `0024` is proposed. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.