1use std::sync::Arc;
6
7use serde_json::json;
8
9use crate::backend::rpc::engine::WshRpcEngine;
10use crate::backend::rpc_types::{
11 COMMAND_LIST_IDENTITY_ACCOUNTS, COMMAND_GET_IDENTITY_ACCOUNT,
12 COMMAND_UPSERT_IDENTITY_ACCOUNT, COMMAND_DELETE_IDENTITY_ACCOUNT,
13 COMMAND_ACCOUNT_KEY_VERIFY,
14 COMMAND_ACCOUNT_OAUTH_START, COMMAND_ACCOUNT_OAUTH_POLL, COMMAND_ACCOUNT_OAUTH_CANCEL,
15 COMMAND_ACCOUNT_OAUTH_CLIENT_GET, COMMAND_ACCOUNT_OAUTH_CLIENT_CLEAR, COMMAND_GITHUB_CONNECTION, COMMAND_GITHUB_INSTALLATIONS,
16 COMMAND_LINK_AGENT_IDENTITY, COMMAND_UNLINK_AGENT_IDENTITY,
17 COMMAND_LIST_AGENT_IDENTITIES, COMMAND_LIST_ALL_AGENT_IDENTITIES,
18 COMMAND_LIST_NAMED_AGENTS, COMMAND_HIDE_NAMED_AGENT,
19 CommandHideNamedAgentData,
20 CommandListIdentityAccountsData, CommandGetIdentityAccountData,
21 CommandDeleteIdentityAccountData,
22 CommandLinkAgentIdentityData, CommandUnlinkAgentIdentityData,
23 CommandListAgentIdentitiesData, CommandListAllAgentIdentitiesData,
24};
25use crate::backend::storage::store::{
26 IdentityAccount, SecretRef,
27};
28
29use super::super::AppState;
30
31mod accounts;
32mod links;
33mod named_agents;
34mod oauth;
35
36fn reject_ambient_home_dir_binding(account: &IdentityAccount) -> Result<(), String> {
45 let SecretRef::OAuthConfigDir { dir } = &account.secret_ref else {
46 return Ok(());
47 };
48 let Some(provider_cfg) = crate::backend::providers::get_provider(
49 &crate::backend::providers::resolve_provider_alias(&account.provider),
50 ) else {
51 return Ok(());
52 };
53 if crate::backend::providers::is_provider_ambient_home_dir(provider_cfg, dir) {
54 return Err(format!(
55 "upsertidentityaccount: refusing to bind {} identity to its \
56 ambient home directory ({dir}) — this would let a spawned \
57 agent silently share your personal CLI login/session state \
58 instead of using an isolated AgentMux account. Use an \
59 isolated config dir for this account instead.",
60 account.provider,
61 ));
62 }
63 Ok(())
64}
65
66#[derive(serde::Deserialize)]
69#[serde(rename_all = "camelCase")]
70struct VerifyKeyReq {
71 provider: String,
73 name: String,
75 #[serde(default)]
76 display_name: String,
77 #[serde(default)]
79 kind: String,
80 api_key: String,
83 #[serde(default)]
87 validate: bool,
88 #[serde(default)]
90 account_id: String,
91 #[serde(default)]
95 context: serde_json::Value,
96}
97
98#[derive(serde::Deserialize)]
102#[serde(rename_all = "camelCase")]
103struct OAuthStartReq {
104 provider: String,
105 #[serde(default)]
107 name: String,
108 #[serde(default)]
109 client_id: Option<String>,
110 #[serde(default)]
111 client_secret: Option<String>,
112 #[serde(default)]
114 client_mode: Option<String>,
115 #[serde(default)]
118 save_client: Option<bool>,
119 #[serde(default)]
121 scopes: Vec<String>,
122 #[serde(default)]
125 account_id: Option<String>,
126 #[serde(default)]
129 replace_github_user: bool,
130 #[serde(default)]
133 use_builtin_client: bool,
134}
135
136#[derive(serde::Deserialize, serde::Serialize, ts_rs::TS)]
137#[ts(export, export_to = "../../../frontend/types/rpc/")]
138#[serde(rename_all = "camelCase")]
139pub struct OAuthSessionReq {
140 pub session_id: String,
141}
142
143#[derive(Default, serde::Deserialize, serde::Serialize, ts_rs::TS)]
145#[ts(export, export_to = "../../../frontend/types/rpc/")]
146#[serde(rename_all = "camelCase")]
147pub struct GithubConnectionReq {}
148
149#[derive(serde::Deserialize, serde::Serialize, ts_rs::TS)]
151#[ts(export, export_to = "../../../frontend/types/rpc/")]
152#[serde(rename_all = "camelCase")]
153pub struct OAuthClientReq {
154 pub provider: String,
155}
156
157#[derive(serde::Serialize, ts_rs::TS)]
160#[ts(export, export_to = "../../../frontend/types/rpc/")]
161#[serde(rename_all = "camelCase")]
162pub struct AccountOAuthClientInfo {
163 saved: bool,
164 #[serde(skip_serializing_if = "Option::is_none")]
165 #[ts(optional)]
166 client_id: Option<String>,
167 has_secret: bool,
168 #[serde(skip_serializing_if = "Option::is_none")]
169 #[ts(optional, type = "\"byo\" | \"workspace\"")]
170 mode: Option<String>,
171 builtin_available: bool,
174 offered_services: Vec<String>,
177}
178
179#[derive(serde::Serialize, ts_rs::TS)]
181#[ts(export, export_to = "../../../frontend/types/rpc/")]
182#[serde(rename_all = "camelCase")]
183pub struct AccountOAuthClientClearResult {
184 cleared: bool,
185}
186
187fn builtin_client_of(provider: &str) -> Result<(bool, Vec<String>), String> {
189 let cfg = crate::identity::oauth_client::config_for(provider)
190 .ok_or_else(|| format!("account.oauth.client.get: unknown OAuth provider: {provider}"))?;
191 let offered = if provider == "google" { crate::identity::google_offered::offered() } else { Vec::new() };
192 Ok((crate::identity::oauth_client::builtin_client_available(&cfg), offered))
193}
194
195fn byo_from_req(req: &OAuthStartReq) -> Result<Option<crate::identity::oauth_client::ByoCredentials>, String> {
198 let Some(client_id) = req.client_id.as_deref().map(str::trim).filter(|s| !s.is_empty()) else {
199 return Ok(None);
200 };
201 let mode = crate::identity::oauth_tokens::ClientMode::parse_user(req.client_mode.as_deref())?;
202 Ok(Some(crate::identity::oauth_client::ByoCredentials {
203 client_id: client_id.to_string(),
204 client_secret: req.client_secret.clone().filter(|s| !s.is_empty()),
205 mode,
206 }))
207}
208
209fn reads_saved_client(req: &OAuthStartReq, byo: &Option<crate::identity::oauth_client::ByoCredentials>) -> bool {
212 byo.is_none() && !req.use_builtin_client
213}
214
215fn panel_start_options(
219 req: &OAuthStartReq,
220 target: crate::identity::oauth_client::FlowTarget,
221 byo: Option<crate::identity::oauth_client::ByoCredentials>,
222 saved: Option<crate::identity::oauth_tokens::SavedClient>,
223 cloud_signed_in: bool,
224) -> crate::identity::oauth_client::StartOptions {
225 crate::identity::oauth_client::StartOptions {
226 target,
227 byo,
228 saved,
229 extra_scopes: req.scopes.clone(),
230 save_client: req.save_client.unwrap_or(true),
231 cloud_signed_in,
232 replace_user: req.replace_github_user,
233 open_system_browser: true,
234 login_hint: None,
235 }
236}
237
238fn oauth_status_wire(s: &crate::identity::oauth_client::OAuthStatus) -> serde_json::Value {
239 use crate::identity::oauth_client::OAuthStatus;
240 match s {
241 OAuthStatus::Pending => serde_json::json!({ "status": "pending" }),
242 OAuthStatus::UrlAvailable { auth_url } => {
243 serde_json::json!({ "status": "url-available", "authUrl": auth_url })
244 }
245 OAuthStatus::CodeEmitted { user_code, verification_uri } => serde_json::json!({
246 "status": "code-emitted",
247 "userCode": user_code,
248 "verificationUri": verification_uri,
249 }),
250 OAuthStatus::Success { account_id, granted_scopes, missing_scopes, email } => serde_json::json!({
251 "status": "success",
252 "accountId": account_id,
253 "grantedScopes": granted_scopes,
254 "missingScopes": missing_scopes,
255 "email": email,
256 }),
257 OAuthStatus::Failed { error } => serde_json::json!({ "status": "failed", "error": error }),
258 OAuthStatus::Picked { account_id, file_ids } => {
259 serde_json::json!({ "status": "picked", "accountId": account_id, "fileIds": file_ids })
260 }
261 OAuthStatus::ConfirmUser { current_login, current_id, new_login, new_id } => serde_json::json!({
262 "status": "confirm-user",
263 "currentLogin": current_login,
264 "currentId": current_id,
265 "newLogin": new_login,
266 "newId": new_id,
267 }),
268 }
269}
270
271pub(super) fn revoke_keeps_account(revoke_report: &serde_json::Value, require_revoke: bool) -> bool {
274 require_revoke && revoke_report.get("outcome").and_then(|v| v.as_str()) == Some("failed")
275}
276
277fn merge_json_object(base: &mut serde_json::Value, overlay: &serde_json::Value) {
279 if let (Some(b), Some(o)) = (base.as_object_mut(), overlay.as_object()) {
280 for (k, v) in o {
281 b.insert(k.clone(), v.clone());
282 }
283 }
284}
285
286#[derive(serde::Serialize, ts_rs::TS)]
288#[ts(export, export_to = "../../../frontend/types/rpc/")]
289#[serde(rename_all = "camelCase")]
290pub struct DeleteIdentityAccountResult {
291 pub(crate) deleted: bool,
292 pub(crate) affected_agents: Vec<String>,
294 #[ts(type = "{ outcome: \"removed\" | \"absent\" | \"skipped\" | \"failed\" | \"none\"; path?: string; detail?: string; historyKept?: boolean; historyPath?: string } | null")]
296 pub(crate) cleanup: serde_json::Value,
297 #[ts(type = "{ outcome: \"revoked\" | \"failed\"; detail?: string } | null")]
303 pub(crate) revoke: serde_json::Value,
304}
305
306#[derive(serde::Serialize, ts_rs::TS)]
309#[ts(export, export_to = "../../../frontend/types/rpc/")]
310#[serde(rename_all = "camelCase")]
311pub struct AccountKeyVerifyResult {
312 valid: bool,
313 #[serde(skip_serializing_if = "Option::is_none")]
314 #[ts(optional)]
315 error: Option<String>,
316 #[serde(skip_serializing_if = "Option::is_none")]
317 #[ts(optional)]
318 account_id: Option<String>,
319 #[serde(skip_serializing_if = "Option::is_none")]
320 #[ts(optional, type = "string")]
321 masked_tail: Option<serde_json::Value>,
322 #[serde(skip_serializing_if = "Option::is_none")]
323 #[ts(optional)]
324 status: Option<String>,
325 #[serde(skip_serializing_if = "Option::is_none")]
326 #[ts(optional, type = "Record<string, unknown>")]
327 metadata: Option<serde_json::Value>,
328}
329
330#[derive(serde::Serialize, ts_rs::TS)]
332#[ts(export, export_to = "../../../frontend/types/rpc/")]
333#[serde(rename_all = "camelCase")]
334pub struct AccountOAuthStartResult {
335 #[serde(skip_serializing_if = "Option::is_none")]
336 #[ts(optional)]
337 session_id: Option<String>,
338 #[serde(skip_serializing_if = "Option::is_none")]
340 #[ts(optional, type = "import(\"@/app/store/rpc-api/types\").OAuthFlowStatus")]
341 status: Option<serde_json::Value>,
342 #[serde(skip_serializing_if = "Option::is_none")]
343 #[ts(optional)]
344 error: Option<String>,
345}
346
347fn register_github_installations(engine: &Arc<WshRpcEngine>, state: &AppState) {
349 let mstore = state.id_store.clone();
350 let identity_store = state.identity_store.clone();
351 engine.register_typed(
352 COMMAND_GITHUB_INSTALLATIONS,
353 move |req: crate::identity::github_installs::GithubInstallationsReq, _ctx| {
354 let mstore = mstore.clone();
355 let identity_store = identity_store.clone();
356 async move { Ok(crate::identity::github_installs::run(&mstore, &identity_store, req).await) }
357 },
358 );
359}
360
361pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
362 register_accounts(engine, state);
363 register_oauth(engine, state);
364 register_agent_links(engine, state);
365 register_named_agents(engine, state);
366}
367
368fn register_accounts(engine: &Arc<WshRpcEngine>, state: &AppState) {
371 let (mstore, identity_store, broker) = (state.id_store.clone(), state.identity_store.clone(), state.broker.clone());
372 {
373 let (mstore, identity_store) = (mstore.clone(), identity_store.clone());
374 engine.register_typed(COMMAND_LIST_IDENTITY_ACCOUNTS, move |cmd: CommandListIdentityAccountsData, _ctx| {
375 accounts::list_identity_accounts(mstore.clone(), identity_store.clone(), cmd.provider)
376 });
377 }
378 {
379 let mstore = mstore.clone();
380 engine.register_typed(COMMAND_GET_IDENTITY_ACCOUNT, move |cmd: CommandGetIdentityAccountData, _ctx| {
381 let mstore = mstore.clone();
382 async move { accounts::get_identity_account(&mstore, &cmd.id) }
383 });
384 }
385 {
388 let (mstore, identity_store, broker) = (mstore.clone(), identity_store.clone(), broker.clone());
389 engine.register_typed(COMMAND_UPSERT_IDENTITY_ACCOUNT, move |data: serde_json::Value, _ctx| {
390 let (mstore, identity_store, broker) = (mstore.clone(), identity_store.clone(), broker.clone());
391 async move { accounts::upsert_identity_account(&mstore, &identity_store, &broker, data) }
392 });
393 }
394 {
396 let (mstore, identity_store, broker) = (mstore.clone(), identity_store.clone(), broker.clone());
397 engine.register_typed(COMMAND_ACCOUNT_KEY_VERIFY, move |data: serde_json::Value, _ctx| {
398 accounts::verify_account_key(mstore.clone(), identity_store.clone(), broker.clone(), data)
399 });
400 }
401 engine.register_typed(COMMAND_DELETE_IDENTITY_ACCOUNT, move |cmd: CommandDeleteIdentityAccountData, _ctx| {
402 let (mstore, identity_store, broker) = (mstore.clone(), identity_store.clone(), broker.clone());
403 async move { super::identity_delete::delete_identity_account(&mstore, &identity_store, &broker, &cmd.id, cmd.require_revoke).await }
404 });
405}
406
407fn register_oauth(engine: &Arc<WshRpcEngine>, state: &AppState) {
409 let (mstore, identity_store) = (state.id_store.clone(), state.identity_store.clone());
410 {
411 let (mstore, identity_store) = (mstore.clone(), identity_store.clone());
412 engine.register_typed(COMMAND_ACCOUNT_OAUTH_START, move |data: serde_json::Value, _ctx| {
414 oauth::start_oauth(mstore.clone(), identity_store.clone(), data)
415 });
416 }
417 engine.register_typed(COMMAND_ACCOUNT_OAUTH_CLIENT_GET, move |req: OAuthClientReq, _ctx| oauth::oauth_client_info(req));
418 engine.register_typed(COMMAND_ACCOUNT_OAUTH_CLIENT_CLEAR, move |req: OAuthClientReq, _ctx| oauth::clear_oauth_client(req));
419 engine.register_typed(COMMAND_ACCOUNT_OAUTH_POLL, move |req: OAuthSessionReq, _ctx| async move { oauth::poll_oauth(&req) });
420 engine.register_typed(COMMAND_ACCOUNT_OAUTH_CANCEL, move |req: OAuthSessionReq, _ctx| async move { Ok(oauth::cancel_oauth(&req)) });
421 engine.register_typed(COMMAND_GITHUB_CONNECTION, move |_req: GithubConnectionReq, _ctx| {
424 let (mstore, identity_store) = (mstore.clone(), identity_store.clone());
425 async move { Ok(crate::identity::github_connect::sync_connection(&mstore, &identity_store).await) }
426 });
427 register_github_installations(engine, state);
428}
429
430fn register_agent_links(engine: &Arc<WshRpcEngine>, state: &AppState) {
432 let deps = Arc::new(links::LinkDeps {
433 identity_store: state.identity_store.clone(),
434 broker: state.broker.clone(),
435 panes: state.mstore.clone(),
436 event_bus: state.event_bus.clone(),
437 });
438 {
439 let deps = deps.clone();
440 engine.register_typed(COMMAND_LINK_AGENT_IDENTITY, move |cmd: CommandLinkAgentIdentityData, _ctx| {
441 let deps = deps.clone();
442 async move { links::link_agent_identity(&deps, &cmd) }
443 });
444 }
445 {
446 let deps = deps.clone();
447 engine.register_typed(COMMAND_UNLINK_AGENT_IDENTITY, move |cmd: CommandUnlinkAgentIdentityData, _ctx| {
448 let deps = deps.clone();
449 async move { links::unlink_agent_identity(&deps, &cmd) }
450 });
451 }
452 {
453 let deps = deps.clone();
454 engine.register_typed(COMMAND_LIST_AGENT_IDENTITIES, move |cmd: CommandListAgentIdentitiesData, _ctx| {
455 let deps = deps.clone();
456 async move {
457 deps.identity_store.agent_identity_list_for_agent(&cmd.agent_id).map_err(|e| format!("listagentidentities: {e}"))
458 }
459 });
460 }
461 engine.register_typed(COMMAND_LIST_ALL_AGENT_IDENTITIES, move |_req: CommandListAllAgentIdentitiesData, _ctx| {
463 let deps = deps.clone();
464 async move { deps.identity_store.agent_identity_list_all().map_err(|e| format!("listallagentidentities: {e}")) }
465 });
466}
467
468fn register_named_agents(engine: &Arc<WshRpcEngine>, state: &AppState) {
470 let (mstore, id_store, identity_store) = (state.mstore.clone(), state.id_store.clone(), state.identity_store.clone());
471 let broker = state.broker.clone();
472 {
473 let mstore = mstore.clone();
474 engine.register_typed(COMMAND_LIST_NAMED_AGENTS, move |data: serde_json::Value, _ctx| {
475 let (mstore, id_store, identity_store) = (mstore.clone(), id_store.clone(), identity_store.clone());
476 async move { named_agents::list_named_agents(&mstore, &id_store, &identity_store, data) }
477 });
478 }
479 engine.register_typed(COMMAND_HIDE_NAMED_AGENT, move |cmd: CommandHideNamedAgentData, _ctx| {
480 let (mstore, broker) = (mstore.clone(), broker.clone());
481 async move { named_agents::hide_named_agent(&mstore, &broker, &cmd.id) }
482 });
483}
484
485#[cfg(test)]
486mod oauth_rpc_tests {
487 use super::*;
488 use crate::identity::oauth_client::OAuthStatus;
489 use crate::identity::oauth_tokens::ClientMode;
490
491 #[test]
492 fn a_start_reads_the_saved_client_unless_it_brings_one_or_asks_for_agentmuxs_own() {
493 let plain: OAuthStartReq = serde_json::from_value(json!({ "provider": "github" })).unwrap();
494 let builtin: OAuthStartReq = serde_json::from_value(json!({ "provider": "github", "useBuiltinClient": true })).unwrap();
495 let with_client: OAuthStartReq = serde_json::from_value(json!({ "provider": "github", "clientId": "Iv1.mine" })).unwrap();
496 let none = byo_from_req(&plain).unwrap();
497 let some = byo_from_req(&with_client).unwrap();
498 assert!(reads_saved_client(&plain, &none), "a request with no client uses the saved one, as before");
499 assert!(!reads_saved_client(&builtin, &none), "the App choice must not run with a saved client of the person's own");
500 assert!(!reads_saved_client(&with_client, &some), "a client sent with the request is the one used");
501 }
502
503 #[test]
504 fn a_start_request_without_the_new_fields_still_parses() {
505 let old: OAuthStartReq =
506 serde_json::from_value(json!({ "provider": "google", "name": "Work", "clientId": "cid" })).unwrap();
507 assert!(old.scopes.is_empty() && old.account_id.is_none() && old.save_client.is_none());
508 let byo = byo_from_req(&old).unwrap().unwrap();
509 assert_eq!((byo.client_id.as_str(), byo.mode, byo.client_secret), ("cid", ClientMode::Byo, None));
510 }
511
512 #[test]
513 fn a_start_request_can_turn_a_service_on_for_an_existing_account() {
514 let req: OAuthStartReq = serde_json::from_value(json!({
515 "provider": "google",
516 "accountId": "acc-1",
517 "scopes": ["https://www.googleapis.com/auth/calendar.events.readonly"],
518 "clientId": " cid ", "clientSecret": "", "clientMode": "workspace", "saveClient": false,
519 }))
520 .unwrap();
521 assert_eq!(req.account_id.as_deref(), Some("acc-1"));
522 assert_eq!(req.scopes.len(), 1);
523 assert_eq!(req.save_client, Some(false));
524 let byo = byo_from_req(&req).unwrap().unwrap();
525 assert_eq!((byo.client_id.as_str(), byo.mode, byo.client_secret), ("cid", ClientMode::Workspace, None));
526 let blank: OAuthStartReq = serde_json::from_value(json!({ "provider": "google", "clientId": " " })).unwrap();
528 assert!(byo_from_req(&blank).unwrap().is_none());
529 let bad: OAuthStartReq =
530 serde_json::from_value(json!({ "provider": "google", "clientId": "c", "clientMode": "builtin" })).unwrap();
531 assert!(byo_from_req(&bad).is_err());
532 }
533
534 #[test]
535 fn success_reports_the_granted_and_missing_scopes_and_email() {
536 let wire = oauth_status_wire(&OAuthStatus::Success {
537 account_id: "acc-1".into(),
538 granted_scopes: vec!["openid".into()],
539 missing_scopes: vec!["https://www.googleapis.com/auth/calendar.events".into()],
540 email: Some("me@example.com".into()),
541 });
542 assert_eq!(
543 wire,
544 json!({
545 "status": "success", "accountId": "acc-1", "grantedScopes": ["openid"],
546 "missingScopes": ["https://www.googleapis.com/auth/calendar.events"], "email": "me@example.com",
547 })
548 );
549 }
550
551 #[test]
552 fn only_a_failed_revoke_with_require_revoke_keeps_the_account() {
553 let failed = json!({ "outcome": "failed", "detail": "offline" });
554 assert!(revoke_keeps_account(&failed, true));
555 assert!(!revoke_keeps_account(&failed, false), "by default the account is deleted anyway");
556 assert!(!revoke_keeps_account(&json!({ "outcome": "revoked" }), true));
557 assert!(!revoke_keeps_account(&serde_json::Value::Null, true));
558 let old: CommandDeleteIdentityAccountData = serde_json::from_value(json!({ "id": "acc-1" })).unwrap();
560 assert!(!old.require_revoke);
561 }
562
563 #[test]
564 fn the_delete_result_carries_the_revoke_outcome() {
565 let r = DeleteIdentityAccountResult {
566 deleted: true,
567 affected_agents: vec![],
568 cleanup: json!({ "outcome": "removed" }),
569 revoke: json!({ "outcome": "revoked" }),
570 };
571 let v = serde_json::to_value(r).unwrap();
572 assert_eq!(v["revoke"]["outcome"], "revoked");
573 assert_eq!(v["cleanup"]["outcome"], "removed");
574 }
575
576 #[tokio::test]
577 async fn the_saved_client_commands_are_registered_typed() {
578 let state = crate::server::tests::test_state();
579 let (engine, _rx) = crate::backend::rpc::engine::WshRpcEngine::new();
580 register(&engine, &state);
581 let schema = engine.schema_json();
582 let rows = schema.as_array().unwrap();
583 let row = |c: &str| rows.iter().find(|r| r["command"] == c).unwrap_or_else(|| panic!("{c} missing")).clone();
584 assert_eq!(row(COMMAND_ACCOUNT_OAUTH_CLIENT_GET)["responseName"], "AccountOAuthClientInfo");
585 assert_eq!(row(COMMAND_ACCOUNT_OAUTH_CLIENT_CLEAR)["responseName"], "AccountOAuthClientClearResult");
586 assert_eq!(row(COMMAND_ACCOUNT_OAUTH_CLIENT_CLEAR)["requestName"], "OAuthClientReq");
587 }
588}
589
590#[cfg(test)]
591mod ambient_home_dir_binding_tests {
592 use super::*;
593 use crate::server::tests::test_state;
594
595 fn make_account(provider: &str, secret_ref: SecretRef) -> IdentityAccount {
596 IdentityAccount {
597 id: "acct-1".to_string(),
598 name: "test".to_string(),
599 provider: provider.to_string(),
600 kind: "pat".to_string(),
601 display_name: String::new(),
602 secret_ref,
603 context: serde_json::json!({}),
604 status: "unknown".to_string(),
605 created_at: 0,
606 updated_at: 0,
607 }
608 }
609
610 #[test]
615 fn refuses_oauth_config_dir_pointed_at_the_ambient_home() {
616 let ambient = crate::backend::base::get_home_dir()
617 .join(".claude")
618 .to_string_lossy()
619 .into_owned();
620 let account = make_account("claude", SecretRef::OAuthConfigDir { dir: ambient.clone() });
621
622 let err = reject_ambient_home_dir_binding(&account)
623 .expect_err("must refuse an account bound to the ambient home dir");
624 assert!(err.contains(&ambient), "error should name the offending dir: {err}");
625 assert!(err.contains("claude"), "error should name the provider: {err}");
626 }
627
628 #[test]
629 fn allows_oauth_config_dir_pointed_at_an_isolated_dir() {
630 let isolated = crate::backend::base::get_home_dir()
631 .join(".agentmux")
632 .join("shared")
633 .join("identities")
634 .join("some-id")
635 .join("claude")
636 .to_string_lossy()
637 .into_owned();
638 let account = make_account("claude", SecretRef::OAuthConfigDir { dir: isolated });
639
640 assert!(reject_ambient_home_dir_binding(&account).is_ok());
641 }
642
643 #[test]
644 fn allows_non_oauth_secret_refs_unconditionally() {
645 let account = make_account("github", SecretRef::Env { env_var: "GITHUB_TOKEN".to_string() });
646 assert!(reject_ambient_home_dir_binding(&account).is_ok());
647 }
648
649 #[test]
650 fn allows_an_unknown_provider_id_unconditionally() {
651 let account = make_account(
656 "not-a-real-provider",
657 SecretRef::OAuthConfigDir { dir: "/tmp/whatever".to_string() },
658 );
659 assert!(reject_ambient_home_dir_binding(&account).is_ok());
660 }
661
662 #[tokio::test]
667 async fn register_typed_records_hidenamedagent() {
668 let state = test_state();
669 let (engine, _rx) = crate::backend::rpc::engine::WshRpcEngine::new();
670 register(&engine, &state);
671 let schema = engine.schema_json();
672 let rows = schema.as_array().unwrap();
673 let row = rows
674 .iter()
675 .find(|r| r["command"] == COMMAND_HIDE_NAMED_AGENT)
676 .expect("hidenamedagent missing from the schema");
677 assert_eq!(row["requestName"], "CommandHideNamedAgentData");
678 assert_eq!(row["responseName"], "HideNamedAgentResult");
679 let list = rows
682 .iter()
683 .find(|r| r["command"] == COMMAND_LIST_NAMED_AGENTS)
684 .expect("listnamedagents missing from the schema");
685 assert_eq!(list["requestName"], "Value");
686 assert_eq!(list["responseTs"]["name"], "Array<NamedAgentRow>");
687 }
688}