Skip to main content

agentmux_srv/server/agent_handlers/
seat.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `agent.setSeat`: the operator sets or clears an agent's seat
5//! (`SPEC_AGENT_SEATS_IN_THE_UI_2026_10_23.md` §3). A connection registered
6//! as an agent is refused here; an agent sets seats through MuxAPI's `Agents
7//! set_seat` (`app_api/agent_seats.rs`), which shares the checks below
8//! ([`plan_seats`]) and records the agent as the one who set them.
9
10use std::sync::Arc;
11
12use crate::backend::rpc::engine::WshRpcEngine;
13use crate::backend::rpc_types::{AgentSetSeatResult, CommandAgentSetSeatData, RpcContext, SeatInput, COMMAND_AGENT_SET_SEAT};
14use crate::backend::storage::store::Store;
15use crate::backend::storage::AgentDefinition;
16use crate::registry::AgentSeat;
17
18use super::super::AppState;
19
20pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
21    let state = state.clone();
22    engine.register_typed(COMMAND_AGENT_SET_SEAT, move |cmd: CommandAgentSetSeatData, ctx| {
23        let state = state.clone();
24        async move {
25            operator_only(&ctx)?;
26            let mstore = state.mstore.clone();
27            let result = tokio::task::spawn_blocking(move || set_seat(&mstore, cmd))
28                .await
29                .map_err(|e| format!("agent.setSeat: {e}"))??;
30            state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
31            refresh_pane_seats(&state).await;
32            Ok(result)
33        }
34    });
35}
36
37/// Bring the `agent:seat` of every open agent pane up to date, so the pane
38/// header's tooltip shows the seat just set, or a lead's new name after a
39/// rename (§4). Best-effort: a pane that
40/// can't be patched shows the old seat until it's opened again.
41pub(crate) async fn refresh_pane_seats(state: &AppState) {
42    use crate::backend::agent_seat::{stale_seat_meta, summary_in, SEAT_META_KEY};
43    let mstore = state.mstore.clone();
44    let stale = tokio::task::spawn_blocking(move || {
45        let blocks = mstore.get_all::<crate::backend::obj::Block>().unwrap_or_default();
46        // Listed once: the overlaid definitions name each lead (#5382).
47        let defs = mstore.agent_def_list().unwrap_or_default();
48        stale_seat_meta(&blocks, |id| summary_in(&mstore, &defs, id))
49    })
50    .await
51    .unwrap_or_default();
52    for (block_id, value) in stale {
53        let patch = serde_json::json!({ SEAT_META_KEY: value });
54        let events = crate::server::service::dispatch_to_reducer(
55            state,
56            agentmux_common::ipc::Command::UpdateBlockMeta { block_id, meta_patch: patch },
57        )
58        .await;
59        for ev in &events {
60            if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore) {
61                tracing::warn!("agent.setSeat: pane seat refresh failed: {e}");
62            }
63        }
64        crate::server::service::publish_events(state, &events);
65    }
66}
67
68/// Refuse a connection registered as an agent (`bus:register`), the same
69/// rule as Tower's and the browser profiles' RPCs: only the operator's own
70/// client sets a seat, an agent's own included.
71fn operator_only(ctx: &RpcContext) -> Result<(), String> {
72    ctx.operator_only("only the operator sets an agent's seat")
73}
74
75/// One seat to set (`Some`) or clear (`None`) on the agent whose uid is `agent_id`.
76pub(crate) struct SeatChange {
77    pub agent_id: String,
78    pub seat: Option<SeatInput>,
79}
80
81/// A seat change that passed every check, ready to write.
82#[derive(Debug, Clone, PartialEq)]
83pub(crate) struct PlannedSeat {
84    pub agent_id: String,
85    pub name: String,
86    pub slug: String,
87    pub seat: Option<AgentSeat>,
88}
89
90/// Who made a seat change, for the log: the operator's window, or an agent.
91pub(crate) enum SeatActor<'a> {
92    Operator,
93    Agent { uid: &'a str, name: &'a str },
94}
95
96/// Check every change as it will stand once all of them are written: a lead
97/// may be an agent set in the same call, and a cycle through two changes of one
98/// call is a cycle. Nothing is written. `refuse` starts the message of the
99/// two "no such agent" refusals, so each caller names itself. `remote` are the leads on other
100/// machines (`Name@host`) the caller checked against the LAN directory and accepts in this call.
101pub(crate) fn plan_seats(
102    mstore: &Store,
103    defs: &[AgentDefinition],
104    changes: &[SeatChange],
105    refuse: &str,
106    remote: &[String],
107) -> Result<Vec<PlannedSeat>, String> {
108    use std::collections::HashMap;
109    let now = agentmux_common::time::now_ms();
110    // The lead each changed agent will have once every change is written.
111    let mut pending: HashMap<String, Option<String>> = HashMap::new();
112    // Each seat is checked on its own first (a lead is an agent here, it isn't
113    // itself); cycles are checked below against the whole call, so the answer
114    // doesn't depend on the order of the changes.
115    let alone = |_: &str| None;
116    let mut planned = Vec::with_capacity(changes.len());
117    for change in changes {
118        let agent_id = change.agent_id.trim().to_string();
119        let Some(def) = defs.iter().find(|d| d.id == agent_id) else {
120            return Err(format!("{refuse}agent {agent_id} not found"));
121        };
122        if def.is_seeded != 0 {
123            return Err(format!("{refuse}{} is a template; only an agent has a seat", def.name));
124        }
125        let (seat, lead_after) = match &change.seat {
126            None => {
127                // A spawned worker's leader becomes its lead again (#5378).
128                let leader = crate::server::app_api::agent_spawn::worker_of(mstore, &agent_id);
129                (None, leader)
130            }
131            Some(input) => {
132                let seat = crate::backend::agent_seat::validate(
133                    &agent_id,
134                    input,
135                    now,
136                    |id| defs.iter().any(|d| d.id == id && d.is_seeded == 0) || remote.iter().any(|r| r == id),
137                    alone,
138                )?;
139                let lead = seat.lead.clone();
140                (Some(seat), lead)
141            }
142        };
143        pending.insert(agent_id.clone(), lead_after);
144        planned.push(PlannedSeat { agent_id, name: def.name.clone(), slug: def.slug.clone(), seat });
145    }
146    // The graph as it will stand: a changed agent has the lead of its change,
147    // any other the lead it has now.
148    let lead_of = |id: &str| match pending.get(id) {
149        Some(lead) => lead.clone(),
150        None => defs
151            .iter()
152            .find(|d| d.id == id)
153            .and_then(|d| crate::backend::agent_seat::effective_seat(mstore, d))
154            .and_then(|s| s.lead),
155    };
156    for p in &planned {
157        if let Some(Some(lead)) = pending.get(&p.agent_id) {
158            crate::backend::agent_seat::no_cycle(&p.agent_id, lead, lead_of)?;
159        }
160    }
161    one_super_agent(mstore, defs, &mut planned, refuse)?;
162    Ok(planned)
163}
164
165/// At most one agent holds the `super` seat: naming a second one moves it. The
166/// agent that held it goes back to the role it had (`prior_role`, else
167/// worker), keeping its qualifier, lead and area. An agent made super
168/// remembers the role it had.
169fn one_super_agent(mstore: &Store, defs: &[AgentDefinition], planned: &mut Vec<PlannedSeat>, refuse: &str) -> Result<(), String> {
170    use crate::backend::agent_seat::{super_holder, SUPER_ROLE};
171    let is_super = |p: &PlannedSeat| p.seat.as_ref().is_some_and(|s| s.role == SUPER_ROLE);
172    let mut new_supers = planned.iter().filter(|p| is_super(p));
173    let Some(new_super) = new_supers.next().map(|p| p.agent_id.clone()) else {
174        return Ok(());
175    };
176    if new_supers.next().is_some() {
177        return Err(format!("{refuse}only one agent can be the super agent"));
178    }
179    for p in planned.iter_mut().filter(|p| is_super(p)) {
180        let was = mstore.agent_seat_get(&p.agent_id);
181        let seat = p.seat.as_mut().expect("a super seat");
182        seat.prior_role = match was {
183            Some(w) if w.role == SUPER_ROLE => w.prior_role,
184            Some(w) => Some(w.role),
185            None => None,
186        };
187    }
188    let Some(holder) = super_holder(mstore, defs).filter(|h| *h != new_super) else {
189        return Ok(());
190    };
191    // The holder may be in the same call, set to something else: that stands.
192    if planned.iter().any(|p| p.agent_id == holder) {
193        return Ok(());
194    }
195    let (Some(def), Some(mut seat)) = (defs.iter().find(|d| d.id == holder), mstore.agent_seat_get(&holder)) else {
196        return Ok(());
197    };
198    seat.role = seat.prior_role.take().filter(|r| crate::backend::agent_seat::is_role(r) && r != SUPER_ROLE).unwrap_or_else(|| "worker".to_string());
199    seat.set_at_ms = agentmux_common::time::now_ms();
200    planned.push(PlannedSeat { agent_id: holder, name: def.name.clone(), slug: def.slug.clone(), seat: Some(seat) });
201    Ok(())
202}
203
204/// Write planned seats and log each as an identity change by `actor`. The
205/// caller holds the seat lock from the check to here.
206pub(crate) fn write_seats(mstore: &Store, planned: &[PlannedSeat], actor: &SeatActor<'_>) -> Result<(), String> {
207    // Each seat as it was, so a store error part-way puts the earlier ones back.
208    let mut before: Vec<(&str, Option<crate::registry::AgentSeat>)> = Vec::new();
209    for p in planned {
210        let was = mstore.agent_seat_get(&p.agent_id);
211        if let Err(e) = mstore.agent_seat_set(&p.agent_id, p.seat.as_ref()) {
212            for (id, seat) in before.iter().rev() {
213                if let Err(undo) = mstore.agent_seat_set(id, seat.as_ref()) {
214                    tracing::warn!(target: "identity", agent_id = %id, "agent.setSeat: could not put the seat back: {undo}");
215                }
216            }
217            return Err(format!("agent.setSeat: {e}"));
218        }
219        before.push((&p.agent_id, was));
220        let (by, by_uid) = match actor {
221            SeatActor::Operator => ("the operator", ""),
222            SeatActor::Agent { uid, name } => (*name, *uid),
223        };
224        match &p.seat {
225            Some(s) => tracing::info!(
226                target: "identity",
227                agent_id = %p.agent_id,
228                agent = %p.name,
229                role = %s.role,
230                lead = %s.lead.as_deref().unwrap_or("the operator"),
231                by_agent_id = %by_uid,
232                "agent.setSeat: {by} set the seat"
233            ),
234            None => tracing::info!(
235                target: "identity",
236                agent_id = %p.agent_id,
237                agent = %p.name,
238                by_agent_id = %by_uid,
239                "agent.setSeat: {by} cleared the seat"
240            ),
241        }
242    }
243    Ok(())
244}
245
246/// Validate and store (or clear) the seat, and log it as an identity change.
247pub(super) fn set_seat(mstore: &Store, cmd: CommandAgentSetSeatData) -> Result<AgentSetSeatResult, String> {
248    // Held from reading every seat to writing this one, across channels and
249    // instances, so two writes can't each pass the cycle check (#5378).
250    let _seats = mstore.agent_seat_lock().map_err(|e| format!("agent.setSeat: {e}"))?;
251    let defs = mstore.agent_def_list().map_err(|e| format!("agent.setSeat: {e}"))?;
252    let change = SeatChange { agent_id: cmd.agent_id, seat: cmd.seat };
253    // A lead on another machine, set through MuxAPI, stays when the operator edits the seat's other fields:
254    // the window sends the stored lead back. A new one is set with `Agents set_seat`, which checks the LAN.
255    let kept_remote: Vec<String> = defs
256        .iter()
257        .find(|d| d.id == change.agent_id.trim())
258        .and_then(|d| crate::backend::agent_seat::effective_seat(mstore, d))
259        .and_then(|s| s.lead)
260        .filter(|lead| crate::backend::agent_seat::is_remote_lead(lead))
261        .into_iter()
262        .collect();
263    let planned = plan_seats(mstore, &defs, std::slice::from_ref(&change), "agent.setSeat: ", &kept_remote)?;
264    write_seats(mstore, &planned, &SeatActor::Operator)?;
265    Ok(AgentSetSeatResult { seat: planned.into_iter().next().and_then(|p| p.seat) })
266}
267
268#[cfg(test)]
269#[path = "seat_tests.rs"]
270mod tests;