1mod accounts;
36pub mod failover;
37mod login_expiry;
38mod login_recheck;
39mod fresh;
40mod key_account;
41mod machine;
42mod moves;
43mod resume;
44mod switch;
45mod switch_error;
46
47use std::collections::HashMap;
48use std::sync::{Arc, Mutex, OnceLock};
49use std::time::Duration;
50
51use serde::{Deserialize, Serialize};
52
53use crate::agents::failure::FailureClass;
54use crate::backend::agent_state::{self, failure_of_block, run_accounts_of_block, AgentState};
55use crate::backend::eventbus::EventBus;
56use crate::backend::mps::MuxEvent;
57use crate::backend::obj::{self, Block, Tab};
58use crate::backend::rpc::engine::WshRpcEngine;
59use crate::backend::rpc_types::{NoArgsReq, COMMAND_IDENTITY_ACCOUNT_AVAILABILITY, COMMAND_IDENTITY_ACCOUNT_USAGE, COMMAND_AGENT_ACCOUNT_SWITCH, COMMAND_IDENTITY_ACCOUNT_MOVE_AGENTS, COMMAND_IDENTITY_ACCOUNT_SET_FAILOVER, COMMAND_IDENTITY_ACCOUNT_SIGNED_IN};
60use crate::backend::storage::store::Store;
61use crate::server::AppState;
62
63use machine::{BlockedPane, Effect, Episode, Episodes};
64use resume::Failed;
65
66pub use crate::backend::account_availability::{
67 AccountAvailabilityEvent, AccountEpisodeAgent, AccountEpisodeTask,
68};
69
70const TICK: Duration = Duration::from_secs(15);
73const SETTLE: Duration = Duration::from_millis(1_500);
75
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
78#[ts(export, export_to = "../../../frontend/types/rpc/")]
79pub struct AccountMoveCandidate {
80 pub account_id: String,
81 pub label: String,
82 pub status: String,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
91#[ts(export, export_to = "../../../frontend/types/rpc/")]
92pub struct AccountAvailability {
93 pub account_id: String,
94 pub account_label: String,
95 pub provider: String,
96 #[ts(type = r#""limited" | "signed_out" | "ok""#)]
97 pub state: String,
98 #[ts(type = "number | null")]
100 pub resets_at_ms: Option<u64>,
101 pub limit_window: Option<String>,
103 #[ts(type = "number")]
105 pub since_ms: u64,
106 pub agents: Vec<AccountEpisodeAgent>,
107 pub tasks: Vec<AccountEpisodeTask>,
108 pub candidates: Vec<AccountMoveCandidate>,
110 pub agent_ids: Vec<String>,
114 pub block_ids: Vec<String>,
115}
116
117impl From<AccountAvailability> for AccountAvailabilityEvent {
118 fn from(a: AccountAvailability) -> Self {
119 AccountAvailabilityEvent { account_id: a.account_id, provider: a.provider, state: a.state, resets_at_ms: a.resets_at_ms, agents: a.agents, tasks: a.tasks }
120 }
121}
122
123#[derive(Debug, Clone, Serialize, ts_rs::TS)]
126#[ts(export, export_to = "../../../frontend/types/rpc/")]
127pub struct IdentityAccountAvailabilityResult {
128 pub episodes: Vec<AccountAvailability>,
129}
130
131#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
134#[ts(export, export_to = "../../../frontend/types/rpc/")]
135pub struct IdentityAccountSignedInReq {
136 pub account_id: String,
137}
138
139#[derive(Debug, Clone, Serialize, ts_rs::TS)]
142#[ts(export, export_to = "../../../frontend/types/rpc/")]
143pub struct IdentityAccountSignedInResult {
144 pub cleared: u32,
145}
146
147use failover::IdentityAccountSetFailoverReq;
148use moves::IdentityAccountMoveAgentsReq;
149pub(crate) use accounts::IdentityAccountsResult;
150pub(crate) use switch_error::{SwitchError, SwitchRefusal};
151pub(crate) use switch::{is_all_limited, AccountSwitchAllResult, AccountSwitchWhen, AgentAccountSwitchReq, AgentAccountSwitchResult};
152
153struct Runtime {
154 state: AppState,
155 episodes: Mutex<Episodes>,
156 wake: tokio::sync::Notify,
157}
158
159static RUNTIME: OnceLock<Runtime> = OnceLock::new();
160
161pub fn install(state: AppState) {
163 crate::identity::sign_in_hook::set_after_sign_in(after_sign_in);
164 crate::backend::account_availability::set_covers_block(covers_block);
165 let baseline = baseline(&state.mstore);
166 let broker = state.broker.clone();
167 let sign_in_watch = (state.fs_watch_pool.clone(), state.id_store.clone());
168 if RUNTIME.set(Runtime { state, episodes: Mutex::new(Episodes::new(baseline)), wake: tokio::sync::Notify::new() }).is_err() {
169 return;
170 }
171 broker.add_observer(Arc::new(|ev: &MuxEvent| {
173 if ev.event == crate::backend::mps::EVENT_AGENT_FAILURE || ev.event == crate::backend::mps::EVENT_AGENT_TURN {
174 refresh_soon();
175 }
176 }));
177 if tokio::runtime::Handle::try_current().is_err() {
178 return;
179 }
180 crate::identity::staged_watch::start(sign_in_watch.0.clone());
181 crate::identity::sign_in_watch::start(sign_in_watch.0, sign_in_watch.1);
182 tokio::spawn(async {
183 let Some(rt) = RUNTIME.get() else { return };
184 loop {
185 tokio::select! {
186 _ = tokio::time::sleep(TICK) => {}
187 _ = rt.wake.notified() => tokio::time::sleep(SETTLE).await,
188 }
189 let _ = tokio::task::spawn_blocking(refresh).await;
190 }
191 });
192}
193
194pub(crate) async fn switch_account(state: AppState, caller: String, req: AgentAccountSwitchReq) -> Result<AgentAccountSwitchResult, SwitchError> {
197 tokio::task::spawn_blocking(move || switch::switch(&state, &caller, &req)).await.map_err(|e| SwitchError::new(SwitchRefusal::Failed, e.to_string()))?
198}
199
200pub(crate) async fn switch_all_limited(state: AppState, caller: String, req: AgentAccountSwitchReq) -> Result<AccountSwitchAllResult, String> {
202 tokio::task::spawn_blocking(move || switch::switch_all_limited(&state, &caller, &req)).await.map_err(|e| e.to_string())?
203}
204
205pub(crate) async fn identity_accounts(state: AppState) -> Result<IdentityAccountsResult, String> {
207 tokio::task::spawn_blocking(move || accounts::accounts(&state, agentmux_common::time::now_ms_u64())).await.map_err(|e| e.to_string())?
208}
209
210pub(crate) fn refresh_soon() {
212 if let Some(rt) = RUNTIME.get() {
213 rt.wake.notify_one();
214 }
215}
216
217fn refresh() {
219 let Some(rt) = RUNTIME.get() else { return };
220 let now = agentmux_common::time::now_ms_u64();
221 let panes = scan(&rt.state, now);
222 let effects = rt.episodes.lock().unwrap_or_else(|e| e.into_inner()).update(panes.clone(), now);
223 for effect in effects {
224 apply(&rt.state, effect);
225 }
226 switch::apply_pending(&rt.state);
227 failover::run(&rt.state, &panes);
228 login_expiry::run(&rt.state, &panes);
229 login_recheck::run(&rt.state, &panes);
230 crate::identity::credential_watch::check(&rt.state.id_store, &rt.state.identity_store, Some(&rt.state.broker));
231}
232
233fn blocking_failure(block: &Block) -> Option<agent_state::StoredFailure> {
235 failure_of_block(block)
237 .filter(|f| matches!(f.code, FailureClass::UsageLimit | FailureClass::Auth) && f.title != crate::agents::failure::ROUTE_CREDITS_TITLE)
238}
239
240fn signature(f: &agent_state::StoredFailure) -> String {
241 format!("{:?}|{:?}|{}", f.code, f.resets_at_ms, f.title)
242}
243
244fn tab_blocks(mstore: &Store) -> Vec<Block> {
247 let Ok(tabs) = mstore.get_all::<Tab>() else {
248 return Vec::new();
249 };
250 let mut out: Vec<Block> = tabs.iter().flat_map(|t| t.blockids.iter()).filter_map(|id| mstore.get::<Block>(id).ok().flatten()).collect();
251 let parked = mstore.get_all::<Block>().unwrap_or_default().into_iter().filter(|b| obj::meta_get_bool(&b.meta, crate::persist_subscriber::parked::PARKED_META_KEY, false));
252 out.extend(parked);
253 out
254}
255
256fn baseline(mstore: &Store) -> HashMap<String, String> {
259 tab_blocks(mstore).into_iter().filter_map(|b| blocking_failure(&b).map(|f| (b.oid.clone(), signature(&f)))).collect()
260}
261
262fn canonical(provider: &str) -> String {
264 match crate::backend::providers::resolve_provider_alias(provider) {
265 "" => provider.to_lowercase(),
266 c => c.to_string(),
267 }
268}
269
270fn agent_name(mstore: &Store, block: &Block) -> String {
271 let name = obj::meta_get_string(&block.meta, "agentName", "");
272 if !name.trim().is_empty() {
273 return name;
274 }
275 let def_id = obj::meta_get_string(&block.meta, "agentId", "");
276 mstore
277 .agent_def_list()
278 .ok()
279 .and_then(|defs| defs.into_iter().find(|d| d.id == def_id))
280 .map(|d| d.name)
281 .unwrap_or(def_id)
282}
283
284fn membership(identity: &Store, block: &Block, failure: &agent_state::StoredFailure, now_ms: u64) -> Option<(String, AgentState)> {
291 let state = match failure.code {
292 FailureClass::UsageLimit if failure.resets_at_ms.is_none_or(|r| r > now_ms) => AgentState::Limited,
293 FailureClass::Auth => AgentState::SignedOut,
294 _ => return None,
295 };
296 let account = run_accounts_of_block(identity, block).into_iter().next()?;
297 if identity.identity_get(&account).ok().flatten().is_some_and(|a| key_account::is_key(&a)) {
300 return None;
301 }
302 Some((account, state))
303}
304
305fn scan(state: &AppState, now_ms: u64) -> Vec<BlockedPane> {
307 let accounts = state.id_store.identity_list(None).unwrap_or_default();
308 let mut out = Vec::new();
309 for block in tab_blocks(&state.mstore) {
310 let Some(failure) = blocking_failure(&block) else { continue };
311 let Some((account_id, pane_state)) = membership(&state.identity_store, &block, &failure, now_ms) else { continue };
312 let provider = accounts
313 .iter()
314 .find(|a| a.id == account_id)
315 .map(|a| a.provider.clone())
316 .unwrap_or_else(|| obj::meta_get_string(&block.meta, "agentProvider", ""));
317 let limit_window = block
318 .meta
319 .get(crate::backend::blockcontroller::core::META_LAST_FAILURE)
320 .and_then(|f| f.get("limitWindow"))
321 .and_then(|w| w.as_str())
322 .map(str::to_string);
323 out.push(BlockedPane {
324 agent_id: obj::meta_get_string(&block.meta, "agentId", ""),
325 agent_name: agent_name(&state.mstore, &block),
326 block_id: block.oid.clone(),
327 account_id,
328 provider: canonical(&provider),
329 state: pane_state,
330 resets_at_ms: failure.resets_at_ms,
331 limit_window,
332 signature: signature(&failure),
333 });
334 }
335 out
336}
337
338pub fn covers_block(block_id: &str) -> bool {
343 let Some(rt) = RUNTIME.get() else { return false };
344 covers(&rt.state.mstore, &rt.state.identity_store, block_id, agentmux_common::time::now_ms_u64())
345}
346
347fn covers(mstore: &Store, identity: &Store, block_id: &str, now_ms: u64) -> bool {
349 let Some(block) = mstore.get::<Block>(block_id).ok().flatten() else { return false };
350 blocking_failure(&block).is_some_and(|f| membership(identity, &block, &f, now_ms).is_some())
351}
352
353fn toast_key(account_id: &str) -> String {
356 format!("account:{}", crate::backend::notify::policy::tag_for(account_id))
357}
358
359fn apply(state: &AppState, effect: Effect) {
360 match effect {
361 Effect::Changed(ep) => {
362 tracing::info!(provider = %ep.provider, agents = ep.panes.len(), state = ep.state().as_str(), "account episode: changed");
363 publish(state, AccountAvailabilityEvent::from(view(state, &ep)));
364 }
365 Effect::Closed { account_id, provider } => {
366 tracing::info!(provider = %provider, "account episode: closed");
367 let ok = AccountAvailabilityEvent {
368 account_id: account_id.clone(),
369 provider,
370 state: "ok".to_string(),
371 resets_at_ms: None,
372 agents: Vec::new(),
373 tasks: Vec::new(),
374 };
375 publish(state, ok);
376 if let Some(router) = crate::backend::notify::router::get(&state.broker) {
377 router.resolve(&toast_key(&account_id), crate::backend::notify::policy::Family::Account);
378 }
379 }
380 Effect::Toast(ep) => match crate::backend::notify::router::get(&state.broker) {
381 Some(router) => router.account_unavailable(&toast_key(&ep.account_id), machine::toast_body(&ep)),
382 None => tracing::info!("account episode: no notification router yet (no window connected); the strip shows it"),
383 },
384 Effect::Announce { episode, panes } => announce(state, &episode.account_id, &panes),
385 }
386}
387
388fn publish(state: &AppState, payload: AccountAvailabilityEvent) {
389 state.broker.publish_event::<crate::backend::mps_events::AccountAvailability>(&payload, vec![], 0);
390}
391
392fn label_of(state: &AppState, account_id: &str) -> String {
393 let all = state.id_store.identity_list(None).unwrap_or_default();
394 all.iter()
395 .find(|a| a.id == account_id)
396 .map(|a| crate::server::app_api::agent_spawn::account_label_in(a, &all))
397 .unwrap_or_else(|| "an account no longer in AgentMux".to_string())
398}
399
400fn held_tasks(state: &AppState, block_ids: &[&str]) -> HashMap<String, Vec<(AccountEpisodeTask, String)>> {
403 use crate::backend::storage::work_board::requested;
404 use crate::backend::storage::work_queue::work_state;
405 let regs = state.reactive_handler.list_agents();
406 let now = agentmux_common::time::now_ms();
407 let tasks = state
408 .work_store
409 .work_board_list(now - crate::backend::kanban::FINISHED_WINDOW_MS, 500, now)
410 .unwrap_or_default();
411 let mut out: HashMap<String, Vec<(AccountEpisodeTask, String)>> = HashMap::new();
412 for t in tasks.iter().filter(|t| t.item.state == work_state::CLAIMED || t.item.state == work_state::BLOCKED) {
413 let holder = regs.iter().find(|r| {
414 if t.item.claimed_by_uid.is_empty() {
415 !t.item.claimed_by.is_empty() && r.agent_id.eq_ignore_ascii_case(&t.item.claimed_by)
416 } else {
417 r.uid.as_deref() == Some(t.item.claimed_by_uid.as_str())
418 }
419 });
420 let Some(holder) = holder.filter(|h| block_ids.contains(&h.block_id.as_str())) else { continue };
421 let requester = if t.card.requested_by_kind == requested::AGENT && !t.card.requested_by.eq_ignore_ascii_case(&holder.agent_id) {
422 t.card.requested_by.clone()
423 } else {
424 String::new()
425 };
426 let task = AccountEpisodeTask { id: t.item.id.clone(), number: t.card.num, task_ref: t.card.name(), title: t.item.title.clone() };
427 out.entry(holder.block_id.clone()).or_default().push((task, requester));
428 }
429 out
430}
431
432fn view(state: &AppState, ep: &Episode) -> AccountAvailability {
434 let ids: Vec<&str> = ep.panes.iter().map(|p| p.block_id.as_str()).collect();
435 let held = held_tasks(state, &ids);
436 let mut tasks: Vec<AccountEpisodeTask> = ids.iter().flat_map(|b| held.get(*b).into_iter().flatten().map(|(t, _)| t.clone())).collect();
437 tasks.sort_by_key(|t| t.number);
438 tasks.dedup_by(|a, b| a.id == b.id);
439 AccountAvailability {
440 account_id: ep.account_id.clone(),
441 account_label: label_of(state, &ep.account_id),
442 provider: ep.provider.clone(),
443 state: ep.state().as_str().to_string(),
444 resets_at_ms: ep.resets_at_ms(),
445 limit_window: ep.limit_window(),
446 since_ms: ep.opened_at_ms,
447 agents: ep
448 .panes
449 .iter()
450 .map(|p| AccountEpisodeAgent { block_id: p.block_id.clone(), agent_id: p.agent_id.clone(), agent_name: p.agent_name.clone() })
451 .collect(),
452 tasks,
453 candidates: moves::candidates(state, &ep.account_id, &ep.provider),
454 agent_ids: {
455 let mut ids: Vec<String> = ep.panes.iter().map(|p| p.agent_id.clone()).filter(|a| !a.is_empty()).collect();
456 ids.sort();
457 ids.dedup();
458 ids
459 },
460 block_ids: ep.panes.iter().map(|p| p.block_id.clone()).collect(),
461 }
462}
463
464fn requester_items(state: &AppState, panes: &[BlockedPane]) -> std::collections::BTreeMap<String, Vec<(BlockedPane, Vec<String>)>> {
467 let ids: Vec<&str> = panes.iter().map(|p| p.block_id.as_str()).collect();
468 let held = held_tasks(state, &ids);
469 let mut out: std::collections::BTreeMap<String, Vec<(BlockedPane, Vec<String>)>> = Default::default();
470 for pane in panes {
471 let mut by_requester: std::collections::BTreeMap<String, Vec<(i64, String)>> = Default::default();
472 for (task, requester) in held.get(&pane.block_id).into_iter().flatten() {
473 if !requester.is_empty() {
474 by_requester.entry(requester.clone()).or_default().push((task.number, task.task_ref.clone()));
475 }
476 }
477 for (requester, mut held) in by_requester {
478 held.sort_unstable();
479 out.entry(requester).or_default().push((pane.clone(), held.into_iter().map(|(_, r)| r).collect()));
480 }
481 }
482 out
483}
484
485fn requester_notes(state: &AppState, episodes: &Mutex<Episodes>, account_id: &str, panes: &[BlockedPane]) -> Vec<(String, String)> {
490 let items = requester_items(state, panes);
491 let fresh = episodes.lock().unwrap_or_else(|e| e.into_inner()).first_notes(account_id, items.keys().cloned());
492 items
493 .into_iter()
494 .filter(|(requester, _)| fresh.contains(requester))
495 .map(|(requester, items)| {
496 let refs: Vec<(&BlockedPane, &[String])> = items.iter().map(|(p, n)| (p, n.as_slice())).collect();
497 let text = format!("[AgentMux] {}", crate::backend::reactive::sanitize::quote_in_system_note(&machine::leader_note(&refs)));
498 (requester, text)
499 })
500 .collect()
501}
502
503fn announce(state: &AppState, account_id: &str, panes: &[BlockedPane]) {
504 let Some(rt) = RUNTIME.get() else { return };
505 for (requester, text) in requester_notes(state, &rt.episodes, account_id, panes) {
506 if let Err(e) = state.reactive_handler.deliver_system_note(&requester, &text) {
507 tracing::info!(requester = %requester, error = %e, "account episode: requester note not delivered");
508 }
509 }
510}
511
512fn availability(state: &AppState) -> IdentityAccountAvailabilityResult {
514 let open: Vec<Episode> = match RUNTIME.get() {
515 Some(rt) => rt.episodes.lock().unwrap_or_else(|e| e.into_inner()).list().cloned().collect(),
516 None => Vec::new(),
517 };
518 let shown: Vec<String> = open.iter().map(|ep| ep.account_id.clone()).collect();
519 let mut episodes: Vec<AccountAvailability> = open.iter().map(|ep| view(state, ep)).collect();
520 episodes.extend(login_expiry::rows(state, &shown));
521 IdentityAccountAvailabilityResult { episodes }
522}
523
524pub fn failed_panes(mstore: &Store, identity: &Store, agent_id: &str, provider: &str) -> Vec<(String, Vec<String>)> {
529 let provider = canonical(provider);
530 tab_blocks(mstore)
531 .into_iter()
532 .filter(|b| obj::meta_get_string(&b.meta, "agentId", "") == agent_id)
533 .filter(|b| canonical(&obj::meta_get_string(&b.meta, "agentProvider", "")) == provider)
534 .filter(|b| blocking_failure(b).is_some())
535 .map(|b| {
536 let accounts = run_accounts_of_block(identity, &b);
537 (b.oid, accounts)
538 })
539 .collect()
540}
541
542pub fn after_rebind(mstore: &Arc<Store>, event_bus: &Arc<EventBus>, before: Vec<(String, Vec<String>)>, account_id: &str) -> usize {
547 after_rebind_telling(mstore, event_bus, before, account_id, false)
548}
549
550pub fn after_rebind_telling(mstore: &Arc<Store>, event_bus: &Arc<EventBus>, before: Vec<(String, Vec<String>)>, account_id: &str, tell: bool) -> usize {
555 let (cleared, signed_out) = rebind_clearing(mstore, event_bus, before, account_id, tell);
556 resume::start(signed_out, agentmux_common::time::now_ms());
557 cleared
558}
559
560pub(super) fn rebind_clearing(mstore: &Arc<Store>, event_bus: &Arc<EventBus>, before: Vec<(String, Vec<String>)>, account_id: &str, tell: bool) -> (usize, Vec<Failed>) {
565 let mut cleared = 0;
566 let mut signed_out = Vec::new();
567 for (block_id, accounts) in before {
568 if accounts.iter().any(|a| a == account_id) {
569 continue;
570 }
571 if let Some(failure) = mstore.get::<Block>(&block_id).ok().flatten().and_then(|b| failure_of_block(&b)).filter(|f| tell && !account_id.is_empty() && f.code == FailureClass::Auth) {
573 signed_out.push(Failed { block_id: block_id.clone(), failed_at_ms: failure.at_ms });
574 }
575 crate::backend::blockcontroller::core::persist_last_failure(&block_id, None, &Some(mstore.clone()), &Some(event_bus.clone()));
576 cleared += 1;
577 }
578 if cleared > 0 {
579 tracing::info!(cleared, "account episode: a rebind cleared its old account's failures");
580 after_clearing();
581 }
582 (cleared, signed_out)
583}
584
585fn after_clearing() {
588 crate::backend::reactive::held_jekt_wake().notify_one();
589 refresh_soon();
590}
591
592pub fn after_sign_in(account_id: &str) {
599 let Some(rt) = RUNTIME.get() else { return };
600 let account_id = account_id.to_string();
601 let run = move || {
602 resume::start(clear_signed_out_panes(&rt.state.mstore, &rt.state.identity_store, &rt.state.event_bus, &account_id), agentmux_common::time::now_ms());
603 };
604 match tokio::runtime::Handle::try_current() {
605 Ok(handle) => drop(handle.spawn_blocking(run)),
606 Err(_) => run(),
607 }
608}
609
610pub(crate) fn clear_signed_out(mstore: &Arc<Store>, identity: &Store, event_bus: &Arc<EventBus>, account_id: &str) -> usize {
615 clear_signed_out_panes(mstore, identity, event_bus, account_id).len()
616}
617
618fn clear_signed_out_panes(mstore: &Arc<Store>, identity: &Store, event_bus: &Arc<EventBus>, account_id: &str) -> Vec<Failed> {
621 let mut cleared = Vec::new();
622 for block in tab_blocks(mstore) {
623 let Some(failure) = failure_of_block(&block).filter(|f| f.code == FailureClass::Auth) else { continue };
624 if !run_accounts_of_block(identity, &block).iter().any(|a| a == account_id) {
625 continue;
626 }
627 crate::backend::blockcontroller::core::persist_last_failure(&block.oid, None, &Some(mstore.clone()), &Some(event_bus.clone()));
628 cleared.push(Failed { block_id: block.oid.clone(), failed_at_ms: failure.at_ms });
629 }
630 if !cleared.is_empty() {
631 tracing::info!(cleared = cleared.len(), "account episode: a sign-in cleared its account's signed-out panes");
632 after_clearing();
633 }
634 cleared
635}
636
637pub(crate) fn restart_panes_of(state: &AppState, def_id: &str) -> (u32, u32, Vec<String>) {
642 let (mut restarted, mut next_turn, mut failed) = (0, 0, Vec::new());
643 for block in switch::open_panes(state, def_id) {
644 let one_shot = crate::backend::blockcontroller::get_controller(&block.oid)
646 .is_none_or(|c| c.controller_type() == crate::backend::blockcontroller::BLOCK_CONTROLLER_SUBPROCESS);
647 if one_shot {
648 next_turn += 1;
649 continue;
650 }
651 match moves::restart(state, &block) {
652 Ok(()) => restarted += 1,
653 Err(e) => failed.push(e),
654 }
655 }
656 (restarted, next_turn, failed)
657}
658
659pub(crate) fn panes_of(state: &AppState, def_id: &str) -> Vec<Block> {
661 switch::open_panes(state, def_id)
662}
663
664pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
671 let s = state.clone();
672 engine.register_typed(COMMAND_IDENTITY_ACCOUNT_SIGNED_IN, move |req: IdentityAccountSignedInReq, ctx| {
673 let s = s.clone();
674 async move {
675 ctx.operator_only("only the operator's window reports a sign-in")?;
676 if req.account_id.is_empty() {
677 return Err("identity.account.signed_in: account_id is required".to_string());
678 }
679 let cleared = tokio::task::spawn_blocking(move || clear_signed_out_panes(&s.mstore, &s.identity_store, &s.event_bus, &req.account_id))
680 .await
681 .map_err(|e| e.to_string())?;
682 let count = cleared.len();
683 resume::start(cleared, agentmux_common::time::now_ms());
684 Ok(IdentityAccountSignedInResult { cleared: u32::try_from(count).unwrap_or(u32::MAX) })
685 }
686 });
687 let s = state.clone();
690 engine.register_typed(COMMAND_IDENTITY_ACCOUNT_SET_FAILOVER, move |req: IdentityAccountSetFailoverReq, ctx| {
691 let s = s.clone();
692 async move {
693 if ctx.agent_id.is_empty() {
694 ctx.operator_only("only the AgentMux window or an agent marks an account never to fail over to")?;
695 }
696 tokio::task::spawn_blocking(move || failover::set_failover(&s, &req)).await.map_err(|e| e.to_string())?
697 }
698 });
699 let s = state.clone();
700 engine.register_typed(COMMAND_IDENTITY_ACCOUNT_AVAILABILITY, move |_req: Option<NoArgsReq>, ctx| {
701 let s = s.clone();
702 async move {
703 if ctx.agent_id.is_empty() {
705 ctx.operator_only("only the AgentMux window or an agent sees which accounts can't run")?;
706 }
707 tokio::task::spawn_blocking(move || availability(&s)).await.map_err(|e| e.to_string())
708 }
709 });
710 let s = state.clone();
712 engine.register_typed(COMMAND_IDENTITY_ACCOUNT_USAGE, move |_req: Option<NoArgsReq>, ctx| {
713 let s = s.clone();
714 async move {
715 if ctx.agent_id.is_empty() {
716 ctx.operator_only("only the AgentMux window or an agent sees how much of an account is used")?;
717 }
718 identity_accounts(s).await
719 }
720 });
721 let s = state.clone();
722 engine.register_typed(COMMAND_IDENTITY_ACCOUNT_MOVE_AGENTS, move |req: IdentityAccountMoveAgentsReq, ctx| {
723 let s = s.clone();
724 async move {
725 ctx.operator_only("only the operator moves agents to another account")?;
726 let result = tokio::task::spawn_blocking(move || moves::move_agents(&s, &req)).await.map_err(|e| e.to_string())??;
727 refresh_soon();
728 Ok(result)
729 }
730 });
731 let s = state.clone();
734 engine.register_typed(COMMAND_AGENT_ACCOUNT_SWITCH, move |req: AgentAccountSwitchReq, ctx| {
735 let s = s.clone();
736 async move {
737 let caller = ctx.agent_id.clone();
738 if caller.is_empty() {
740 ctx.operator_only("changing an agent's account is for the AgentMux window or an agent")?;
741 }
742 tokio::task::spawn_blocking(move || switch::switch(&s, &caller, &req)).await.map_err(|e| e.to_string())?.map_err(String::from)
743 }
744 });
745}
746
747#[cfg(test)]
748#[path = "tests.rs"]
749mod tests;