Skip to main content

agentmux_srv/server/account_episodes/
switch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//! `agent.account.switch`: change which account an agent runs on
4//! (`docs/specs/SPEC_ACCOUNT_SWITCH_FROM_THE_COMPOSER_NO_BIND_2026_10_26.md` §3.1, §3.2, §3.4).
5//!
6//! The one door for the composer's login email, the failure row, and agents
7//! (`Identity` `switch`). It does what `bindAccountToAgent` did in the window
8//! (replace the link, clear the old account's limits, restart the panes with
9//! `--resume`), in srv, so every caller gets the same result and the same audit
10//! row. An agent in a turn is not restarted under it: the choice waits on its
11//! panes (`agent:pending_account`) and is applied when none of them is in a turn.
12
13use serde::{Deserialize, Serialize};
14
15use crate::backend::agent_resolve::resolve_agent_id;
16use crate::backend::blockcontroller;
17use crate::backend::obj::{self, Block};
18use crate::backend::storage::identities::{IdentityAccount, SecretRef};
19use crate::server::app_api::agent_spawn::account_label_in;
20use crate::server::AppState;
21
22use super::accounts::pick;
23use super::key_account::{can_take_a_key, is_key, is_link_of, serves};
24use super::switch_error::{SwitchError, SwitchRefusal};
25use super::moves::{busy, can_receive, relink, restart, signed_in};
26use super::{agent_name, canonical, tab_blocks};
27
28/// A pane's pending switch: the account id the agent moves to once none of its
29/// panes is in a turn. The pane's meta carries it, so the composer chip shows it
30/// live and it survives a restart.
31pub const META_PENDING_ACCOUNT: &str = "agent:pending_account";
32/// Who asked for it, for the audit row written when it is applied.
33const META_PENDING_BY: &str = "agent:pending_account_by";
34
35#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, ts_rs::TS)]
36#[serde(rename_all = "snake_case")]
37#[ts(export, export_to = "../../../frontend/types/rpc/")]
38pub enum AccountSwitchWhen {
39    /// Restart the agent's panes now, ending a turn in progress.
40    Now,
41    /// Apply when none of its panes is in a turn (at once when none is).
42    #[default]
43    AfterTurn,
44}
45
46/// `agent.account.switch`.
47#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
48#[ts(export, export_to = "../../../frontend/types/rpc/")]
49pub struct AgentAccountSwitchReq {
50    /// The agent (slug or definition id). An agent connection may leave it out for itself.
51    #[serde(default)]
52    pub agent_id: Option<String>,
53    /// The account: its stable or local id, the label the pane shows (`email ·2`), an email
54    /// that names exactly one account with quota, or `any with quota` (another account of the
55    /// agent's provider that can run now).
56    pub account: String,
57    #[serde(default)]
58    pub when: AccountSwitchWhen,
59}
60
61/// What `agent.account.switch` did.
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
63#[serde(rename_all = "snake_case")]
64#[ts(export, export_to = "../../../frontend/types/rpc/")]
65pub enum AccountSwitchStatus {
66    /// Linked, and the open panes restarted on it.
67    Switched,
68    /// An agent's pane is in a turn: the switch waits for the turn to end.
69    Queued,
70    /// The agent was asked to reach a safe point and leave a handoff first
71    /// (`server::prep`); the switch runs when it has, or when its window ends.
72    Preparing,
73    /// The agent is already on that account (a queued switch is cancelled).
74    Unchanged,
75}
76
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
78#[ts(export, export_to = "../../../frontend/types/rpc/")]
79pub struct AgentAccountSwitchResult {
80    pub status: AccountSwitchStatus,
81    pub account_id: String,
82    pub account_label: String,
83    /// Panes restarted on the new account.
84    pub restarted: u32,
85    /// Panes linked but not restarted, with why.
86    pub failed: Vec<String>,
87}
88
89pub(super) fn open_panes(state: &AppState, def_id: &str) -> Vec<Block> {
90    tab_blocks(&state.mstore).into_iter().filter(|b| obj::meta_get_string(&b.meta, "agentId", "") == def_id).collect()
91}
92
93fn set_pending(state: &AppState, blocks: &[Block], pending: Option<(&str, &str)>) {
94    // Clearing touches only the panes that carry one.
95    let ids: Vec<&str> =
96        blocks.iter().filter(|b| pending.is_some() || b.meta.get(META_PENDING_ACCOUNT).is_some_and(|v| !v.is_null())).map(|b| b.oid.as_str()).collect();
97    let null = serde_json::Value::Null;
98    let updates = [
99        (META_PENDING_ACCOUNT, pending.map_or(null.clone(), |(a, _)| serde_json::json!(a))),
100        (META_PENDING_BY, pending.map_or(null, |(_, by)| serde_json::json!(by))),
101    ];
102    crate::server::prep::set_block_meta(state, &ids, &updates);
103}
104
105/// Point the pane's own `cmd:env` config-dir variable at `to`. The spawn injects the linked
106/// account over it, but the window's auth re-check and login recovery read `cmd:env` as it is.
107fn refresh_auth_env(state: &AppState, block: &Block, to: &IdentityAccount, provider: &str) {
108    let SecretRef::OAuthConfigDir { dir } = &to.secret_ref else { return };
109    let Some(var) = crate::backend::providers::get_provider(provider).map(|p| p.auth_config_dir_env_var).filter(|v| !v.is_empty()) else { return };
110    let mut env = blockcontroller::cmd_env_of(&block.meta);
111    env.insert(var.to_string(), dir.clone());
112    let mut update = obj::MetaMapType::new();
113    update.insert("cmd:env".to_string(), serde_json::json!(env));
114    match crate::server::service::update_object_meta(&state.mstore, &format!("block:{}", block.oid), &update) {
115        Ok(()) => blockcontroller::core::broadcast_block_update(&state.mstore, &state.event_bus, &block.oid),
116        Err(e) => tracing::warn!(block_id = %block.oid, error = %e, "agent.account.switch: the pane's auth env was not updated"),
117    }
118}
119
120/// End the pane's turn by replacing its process. A forced resync of a persistent pane in a turn
121/// only defers the restart to the turn's end, which is `after_turn`, not `now`.
122fn stop_turn(block: &Block) {
123    if let Some(ctrl) = blockcontroller::take_controller(&block.oid) {
124        let _ = crate::sagas::agent_teardown::replace_now(ctrl.as_ref());
125    }
126}
127
128/// Link `agent` to `to` and restart each of `blocks` on it. `actor` is recorded. `now` ends a
129/// turn in progress; otherwise the caller has seen that no pane is in one.
130fn apply(state: &AppState, actor: &str, def_id: &str, to: &IdentityAccount, provider: &str, blocks: &[Block], all: &[IdentityAccount], now: bool) -> AgentAccountSwitchResult {
131    set_pending(state, blocks, None);
132    // Before the relink clears it: the panes whose turn died on the login that expired.
133    let interrupted = if actor == super::failover::ACTOR_EXPIRED { super::login_expiry::interrupted(blocks) } else { Vec::new() };
134    let label = account_label_in(to, all);
135    let mut result = AgentAccountSwitchResult { status: AccountSwitchStatus::Switched, account_id: to.id.clone(), account_label: label.clone(), restarted: 0, failed: Vec::new() };
136    let linked = relink(state, def_id, to, provider);
137    let signed_out = linked.clone().unwrap_or_default();
138    let mut restarted_ok: Vec<&str> = Vec::new();
139    let request_id = uuid::Uuid::new_v4().to_string();
140    let reason = format!("switched to {label}");
141    for block in blocks {
142        let outcome = linked.clone().and_then(|_| {
143            refresh_auth_env(state, block, to, provider);
144            if now && busy(state, &block.oid) {
145                stop_turn(block);
146            }
147            restart(state, block).map_err(|e| format!("linked, but its pane didn't restart ({e}); it uses the new account when it next starts"))
148        });
149        state.reactive_handler.log_fleet_action_audit(
150            Some(actor),
151            &agent_name(&state.mstore, block),
152            &block.oid,
153            "agent.account.switch",
154            outcome.is_ok(),
155            outcome.as_ref().err().map(String::as_str),
156            &request_id,
157            Some(&reason),
158        );
159        match outcome {
160            Ok(()) => {
161                result.restarted += 1;
162                restarted_ok.push(&block.oid);
163            }
164            Err(e) => result.failed.push(e),
165        }
166    }
167    tell_signed_out(actor, signed_out, &restarted_ok);
168    // A pane whose controller has no spawn step reading the handoff gets it as a held note.
169    crate::server::prep::hold_for_other_panes(def_id, &restarted_ok);
170    if blocks.is_empty() {
171        if let Err(e) = linked {
172            result.failed.push(e);
173        }
174    }
175    if super::failover::is_actor(actor) && result.restarted > 0 {
176        super::failover::notify(state, def_id, &label, blocks, actor == super::failover::ACTOR_EXPIRED, &interrupted);
177        super::login_expiry::resume(&interrupted, &label);
178    }
179    tracing::info!(agent = %actor, def_id = %def_id, restarted = result.restarted, failed = result.failed.len(), "agent.account.switch: switched an agent's account");
180    super::refresh_soon();
181    result
182}
183
184/// Tell the panes of `signed_out` (whose last turn failed on the login the move left) that they are signed in, now
185/// that each has restarted on the new account: before the restart the note would reach the old process, still on the
186/// expired login, and mark a turn active that defers or kills the restart. A pane that didn't restart is not told: it
187/// keeps its failure's notice and runs on the new account when it next starts. The login-expiry failover tells its own
188/// interrupted panes ([`super::login_expiry::resume`]).
189fn tell_signed_out(actor: &str, signed_out: Vec<super::resume::Failed>, restarted: &[&str]) {
190    super::resume::start(panes_to_tell(actor, signed_out, restarted), agentmux_common::time::now_ms());
191}
192
193/// The panes of `signed_out` to tell: those in `restarted`, and none when `actor` is the login-expiry failover.
194pub(super) fn panes_to_tell(actor: &str, signed_out: Vec<super::resume::Failed>, restarted: &[&str]) -> Vec<super::resume::Failed> {
195    if actor == super::failover::ACTOR_EXPIRED {
196        return Vec::new();
197    }
198    signed_out.into_iter().filter(|f| restarted.contains(&f.block_id.as_str())).collect()
199}
200
201/// One agent's outcome in an `all limited` switch.
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
203#[ts(export, export_to = "../../../frontend/types/rpc/")]
204pub struct AccountSwitchAllEntry {
205    pub agent_id: String,
206    pub agent_name: String,
207    #[serde(skip_serializing_if = "Option::is_none")]
208    #[ts(optional)]
209    pub result: Option<AgentAccountSwitchResult>,
210    #[serde(skip_serializing_if = "Option::is_none")]
211    #[ts(optional)]
212    pub error: Option<String>,
213}
214
215/// `Identity` `switch` with the agent `all limited`: every agent with a pane out of quota.
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
217#[ts(export, export_to = "../../../frontend/types/rpc/")]
218pub struct AccountSwitchAllResult {
219    pub agents: Vec<AccountSwitchAllEntry>,
220}
221
222/// Whether `agent` is the target `all limited`, in the words an agent may type.
223pub fn is_all_limited(agent: &str) -> bool {
224    agent.trim().to_lowercase().replace(['_', '-'], " ") == "all limited"
225}
226
227/// Move every agent that has a pane out of quota (a usage limit that hasn't reset) to `req.account`
228/// (`any with quota` is chosen per agent, so each lands on an account that can run). One agent that
229/// can't move doesn't stop the others. `req.agent_id` is ignored. BLOCKING.
230pub(super) fn switch_all_limited(state: &AppState, caller: &str, req: &AgentAccountSwitchReq) -> Result<AccountSwitchAllResult, String> {
231    let now = agentmux_common::time::now_ms_u64();
232    let mut limited: Vec<(String, String)> = Vec::new();
233    for pane in super::scan(state, now).into_iter().filter(|p| p.state == crate::backend::agent_state::AgentState::Limited) {
234        if !pane.agent_id.is_empty() && !limited.iter().any(|(id, _)| *id == pane.agent_id) {
235            limited.push((pane.agent_id, pane.agent_name));
236        }
237    }
238    let mut agents = Vec::new();
239    for (agent_id, agent_name) in limited {
240        let one = AgentAccountSwitchReq { agent_id: Some(agent_id.clone()), account: req.account.clone(), when: req.when };
241        let (result, error) = match switch(state, caller, &one) {
242            Ok(r) => (Some(r), None),
243            Err(e) => (None, Some(e.to_string())),
244        };
245        agents.push(AccountSwitchAllEntry { agent_id, agent_name, result, error });
246    }
247    Ok(AccountSwitchAllResult { agents })
248}
249
250/// The agent a person or agent named: by id or slug, else by the display name the panes show
251/// ("Camper-2") when exactly one agent has it.
252fn resolve_named(store: &crate::backend::storage::store::Store, named: &str) -> Result<String, SwitchError> {
253    let err = match resolve_agent_id(store, named) {
254        Ok(id) => return Ok(id),
255        Err(e) => e,
256    };
257    let defs = store.agent_def_list().map_err(|e| e.to_string())?;
258    let mut by_name = defs.iter().filter(|d| d.name.trim().eq_ignore_ascii_case(named));
259    match (by_name.next(), by_name.next()) {
260        (Some(d), None) => Ok(d.id.clone()),
261        (Some(_), Some(_)) => Err(SwitchError::new(SwitchRefusal::AgentNameShared, format!("more than one agent is named '{named}'; use its agent_id"))),
262        // The resolver's store failure is AgentMux failing, not a name nobody has.
263        _ if err.starts_with("resolve_agent_id: store:") => Err(SwitchError::from(err)),
264        _ => Err(SwitchError::new(SwitchRefusal::UnknownAgent, err)),
265    }
266}
267
268/// How a switch names who asked: the person for the window, else the agent with its prefix, so no agent id can
269/// read as the person or as AgentMux's own failover.
270fn actor_named(caller: &str) -> String {
271    if caller.is_empty() { "operator".to_string() } else { crate::backend::rpc::actor::Actor::Agent(caller.to_string()).label() }
272}
273
274
275/// `agent.account.switch`. `caller` is the connection's agent slug, empty for the window.
276/// BLOCKING (store reads, link writes, restarts).
277pub(super) fn switch(state: &AppState, caller: &str, req: &AgentAccountSwitchReq) -> Result<AgentAccountSwitchResult, SwitchError> {
278    let named = req.agent_id.as_deref().map(str::trim).filter(|a| !a.is_empty()).unwrap_or(caller);
279    if named.is_empty() {
280        return Err(SwitchError::new(SwitchRefusal::NoAgentNamed, "agent.account.switch: say which agent"));
281    }
282    let def_id = resolve_named(&state.mstore, named).map_err(|e| e.under("agent.account.switch"))?;
283    let provider = agent_provider(state, &def_id).ok_or_else(|| SwitchError::new(SwitchRefusal::UnknownAgent, "agent.account.switch: no such agent"))?;
284    let accounts: Vec<IdentityAccount> = super::fresh::identity_list(state)
285        .map_err(|e| format!("agent.account.switch: accounts: {e}"))?
286        .into_iter()
287        .filter(|a| serves(&provider, a))
288        .collect();
289    // `any with quota` doesn't pick the account the agent is on already.
290    let on: Vec<String> = state
291        .identity_store
292        .agent_identity_list_for_agent(&def_id)
293        .map_err(|e| format!("agent.account.switch: {e}"))?
294        .into_iter()
295        .filter(|l| is_link_of(&provider, &l.provider))
296        .map(|l| l.account_id)
297        .collect();
298    let to = pick(state, &accounts, req.account.trim(), &on, &provider)?;
299    if is_key(to) {
300        can_take_a_key(state, &def_id).map_err(|e| SwitchError::new(SwitchRefusal::CantRun, e))?;
301    }
302    if !(signed_in(&to.status) || (is_key(to) && can_receive(&to.status))) {
303        let why = match to.status.as_str() {
304            _ if is_key(to) => "its key was rejected; replace it in Connectors > Accounts",
305            "expired" => "its access token has lapsed and AgentMux cannot tell that it will renew; sign in to it again",
306            _ => "it is not signed in; sign in to it first",
307        };
308        return Err(SwitchError::new(SwitchRefusal::CantRun, format!("ACCOUNT_CANT_RUN: {}: {why}", account_label_in(to, &accounts))));
309    }
310    let actor = actor_named(caller);
311    switch_to(state, &actor, &def_id, to, &provider, &accounts, req.when)
312}
313
314/// Move the agent `def_id` to `to` (a signed-in account of `provider`; `accounts` are all of the
315/// provider's, for the labels): at once, or queued while a pane of it is in a turn. Also the door
316/// for the account strip's move of a whole episode (`moves::move_agents`).
317pub(super) fn switch_to(state: &AppState, actor: &str, def_id: &str, to: &IdentityAccount, provider: &str, accounts: &[IdentityAccount], when: AccountSwitchWhen) -> Result<AgentAccountSwitchResult, SwitchError> {
318    if is_key(to) && provider != "claude" {
319        return Err(SwitchError::new(SwitchRefusal::KeyNotForThisAgent, "agent.account.switch: an API key is chosen from a Claude agent's own account menu"));
320    }
321    let blocks = open_panes(state, def_id);
322    // Every link stored for the provider, an alias row (`claude-code`) included. Only when all of
323    // them are the target is there nothing to do: a stale alias row to another account would
324    // otherwise win at the next spawn, and the relink is what removes it.
325    let links: Vec<String> = state
326        .identity_store
327        .agent_identity_list_for_agent(def_id)
328        .map_err(|e| format!("agent.account.switch: {e}"))?
329        .into_iter()
330        .filter(|l| is_link_of(provider, &l.provider))
331        .map(|l| l.account_id)
332        .collect();
333    let label = account_label_in(to, accounts);
334    let result = |status| AgentAccountSwitchResult { status, account_id: to.id.clone(), account_label: label.clone(), restarted: 0, failed: Vec::new() };
335    if !links.is_empty() && links.iter().all(|a| *a == to.id) {
336        set_pending(state, &blocks, None);
337        // The change the agent was asked to prepare for isn't going to happen.
338        crate::server::prep::cancel(state, def_id);
339        return Ok(result(AccountSwitchStatus::Unchanged));
340    }
341    if is_asked(state, actor, def_id, &blocks, to, &label, when) {
342        let prep = prep_of(state, actor, def_id, &blocks, to, &label, when);
343        let (s, actor_c, def, to_id) = (state.clone(), actor.to_string(), def_id.to_string(), to.id.clone());
344        let now = when == AccountSwitchWhen::Now;
345        // The window first, then the choice it waits on: `apply_pending` skips an agent in a window, so
346        // a refresh between the two can't apply the choice before the agent was asked. The choice is
347        // written inside `open_with`, before the window can end: written after, it could outlive a window
348        // that had already settled and be applied a second time.
349        crate::server::prep::open_with(state, prep, Box::new(move |how| settle(&s, &actor_c, &def, &to_id, now || how == crate::server::prep::How::PersonSaidNow)), || {
350            set_pending(state, &blocks, Some((&to.id, actor)));
351        });
352        return Ok(result(AccountSwitchStatus::Preparing));
353    }
354    if when == AccountSwitchWhen::AfterTurn && blocks.iter().any(|b| busy(state, &b.oid)) {
355        set_pending(state, &blocks, Some((&to.id, actor)));
356        return Ok(result(AccountSwitchStatus::Queued));
357    }
358    Ok(apply(state, actor, def_id, to, provider, &blocks, accounts, when == AccountSwitchWhen::Now))
359}
360
361/// Whether the agent is asked to prepare before this switch (`server::prep`): a switch already waiting on
362/// its window is the window's, a failover never asks (AgentMux acts because the account failed, and the
363/// agent can seldom answer), and any other agent is asked when it has something to lose.
364fn is_asked(state: &AppState, actor: &str, def_id: &str, blocks: &[Block], to: &IdentityAccount, label: &str, when: AccountSwitchWhen) -> bool {
365    if super::failover::is_actor(actor) || blocks.is_empty() {
366        return false;
367    }
368    crate::server::prep::is_open(def_id) || crate::server::prep::decide(state, &prep_of(state, actor, def_id, blocks, to, label, when)) == crate::server::prep::Decision::Ask
369}
370
371fn prep_of(state: &AppState, actor: &str, def_id: &str, blocks: &[Block], to: &IdentityAccount, label: &str, when: AccountSwitchWhen) -> crate::server::prep::Prep {
372    crate::server::prep::Prep {
373        def_id: def_id.to_string(),
374        agent_name: blocks.first().map(|b| agent_name(&state.mstore, b)).unwrap_or_default(),
375        blocks: blocks.iter().map(|b| b.oid.clone()).collect(),
376        action: "account_switch",
377        target: to.id.clone(),
378        what: format!("move you to the account {label}"),
379        actor: actor.to_string(),
380        cuts_turn: when == AccountSwitchWhen::Now,
381    }
382}
383
384/// What a switch does when its window ends: as it would have without one. A turn still running waits for
385/// its end, unless the switch ends turns (`now`: the caller said `when: now`, or the person pressed
386/// "Switch now"). BLOCKING.
387fn settle(state: &AppState, actor: &str, def_id: &str, account_id: &str, now: bool) {
388    let blocks = open_panes(state, def_id);
389    // The account is read again: it may have signed out or gone in the window.
390    let Some((to, provider, accounts)) = receiving(state, def_id, account_id) else {
391        tracing::info!(def_id = %def_id, "agent.account.switch: a prepared switch was dropped, its account is gone or signed out");
392        set_pending(state, &blocks, None);
393        return;
394    };
395    if !now && blocks.iter().any(|b| busy(state, &b.oid)) {
396        // Still queued in the panes' meta: `apply_pending` runs it when the turn ends.
397        set_pending(state, &blocks, Some((&to.id, actor)));
398        return;
399    }
400    apply(state, actor, def_id, &to, &provider, &blocks, &accounts, now);
401}
402
403/// The account `account_id` as it is now, when it can take an agent: it, its provider and the provider's accounts.
404pub(super) fn receiving(state: &AppState, def_id: &str, account_id: &str) -> Option<(IdentityAccount, String, Vec<IdentityAccount>)> {
405    let provider = agent_provider(state, def_id)?;
406    let all: Vec<IdentityAccount> = super::fresh::identity_list(state).unwrap_or_default();
407    let to = all.iter().find(|a| a.id == account_id && can_receive(&a.status) && serves(&provider, a))?.clone();
408    // A switch that waited for a turn or a window to end meets the rules of a key again: the agent may have moved since.
409    if super::key_account::is_key(&to) && super::key_account::can_take_a_key(state, def_id).is_err() {
410        return None;
411    }
412    let same_provider = all.into_iter().filter(|a| serves(&provider, a)).collect();
413    Some((to, provider, same_provider))
414}
415
416/// The provider the agent `def_id` launches on: its own, or its bundle's when it has none.
417fn agent_provider(state: &AppState, def_id: &str) -> Option<String> {
418    let defs = state.mstore.agent_def_list().ok()?;
419    defs.into_iter().find(|d| d.id == def_id).map(|d| canonical(&state.mstore.resolve_effective_provider_id(&d)))
420}
421
422/// Clear the chip's countdown from panes whose window is gone: srv restarted in it, so the choice it
423/// waited on is applied by `apply_pending` from the pane's own meta, without a window.
424fn clear_stale_prep(state: &AppState) {
425    for pane in tab_blocks(&state.mstore).iter().filter(|b| b.meta.get(crate::server::prep::META_PREP).is_some_and(|v| !v.is_null())) {
426        if !crate::server::prep::is_open(&obj::meta_get_string(&pane.meta, "agentId", "")) {
427            crate::server::prep::set_block_meta(state, &[pane.oid.as_str()], &[(crate::server::prep::META_PREP, serde_json::Value::Null)]);
428        }
429    }
430}
431
432/// Apply each queued switch whose agent has no pane in a turn. Runs with every
433/// episode refresh (a turn ending pokes it). BLOCKING.
434pub(super) fn apply_pending(state: &AppState) {
435    clear_stale_prep(state);
436    let panes: Vec<Block> = tab_blocks(&state.mstore).into_iter().filter(|b| b.meta.get(META_PENDING_ACCOUNT).is_some_and(|v| v.is_string())).collect();
437    let mut done = std::collections::HashSet::new();
438    for first in &panes {
439        let def_id = obj::meta_get_string(&first.meta, "agentId", "");
440        let account_id = obj::meta_get_string(&first.meta, META_PENDING_ACCOUNT, "");
441        let by = obj::meta_get_string(&first.meta, META_PENDING_BY, "operator");
442        // An agent in its window is applied by the window, which also carries what it left.
443        if def_id.is_empty() || crate::server::prep::is_open(&def_id) || !done.insert(def_id.clone()) {
444            continue;
445        }
446        let blocks = open_panes(state, &def_id);
447        if blocks.iter().any(|b| busy(state, &b.oid)) {
448            continue;
449        }
450        let Some((to, provider, accounts)) = receiving(state, &def_id, &account_id) else {
451            tracing::info!(def_id = %def_id, "agent.account.switch: a queued switch was dropped, its account is gone or signed out");
452            set_pending(state, &blocks, None);
453            continue;
454        };
455        apply(state, &by, &def_id, &to, &provider, &blocks, &accounts, false);
456    }
457}
458
459#[cfg(test)]
460mod actor_tests {
461    use super::actor_named;
462
463    #[test]
464    fn an_agent_is_named_with_its_prefix_whatever_it_is_called() {
465        assert_eq!(actor_named(""), "operator");
466        assert_eq!(actor_named("wren"), "agent:wren");
467        assert_eq!(actor_named("operator"), "agent:operator");
468        assert_eq!(actor_named("failover"), "agent:failover");
469        assert_ne!(actor_named("operator"), actor_named(""));
470    }
471}