Skip to main content

agentmux_srv/server/agent_handlers/
rename.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Renaming an agent's displayed name: the one path the window's `renameagentdefinitiontitle` and
5//! an agent's `Agents rename` both take, so every place that shows or addresses the agent follows.
6//!
7//! Deliberately separate from `updateagent`, which preserves `branch_label` unconditionally
8//! (`core.rs`: "parent_id + branch_label describe provenance and are immutable post-insert"). That
9//! stays true for every other caller of `updateagent`; this is the one narrow, explicit path that
10//! may change it, and only the field the tab strip's `titleOf()` displays: `branch_label` when the
11//! row already has one (a fork), else `name` (a lineage root).
12//! See SPEC_PANE_TAB_STRIP_COMPACT_SIZING_AND_RENAME_2026_07_22.md ยง4.
13
14use crate::backend::storage::store::Store;
15use crate::backend::storage::AgentDefinition;
16use agentmux_common::slug::agent_route_name;
17
18use super::super::AppState;
19use super::template::{former_name_of_another, renamed_note};
20
21/// Why a rename did not happen.
22#[derive(Debug)]
23pub(crate) enum RenameError {
24    /// No such agent.
25    NotFound(String),
26    /// The name is not one an agent can have.
27    Invalid(String),
28    /// Another agent has, or answers to, the name.
29    Taken(String),
30    /// The store failed.
31    Failed(String),
32}
33
34impl std::fmt::Display for RenameError {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        let (Self::NotFound(m) | Self::Invalid(m) | Self::Taken(m) | Self::Failed(m)) = self;
37        f.write_str(m)
38    }
39}
40
41impl From<crate::backend::storage::error::StoreError> for RenameError {
42    fn from(e: crate::backend::storage::error::StoreError) -> Self {
43        Self::Failed(e.to_string())
44    }
45}
46
47/// Give agent `id` the displayed name `title`. Its slug, id, signing keys and workspace folder stay
48/// as they are; the old name still reaches it as a former name (`display_rename`), and no other agent
49/// may take a name it still answers to. `refuse_taken` also refuses a name another agent answers to now (its
50/// name, slug or display name, or a slug it was renamed from): an agent renaming an agent must not make two
51/// agents answer to one name. Returns the renamed definition and the displayed name it replaced.
52pub(crate) async fn rename_title(state: &AppState, id: &str, title: &str, refuse_taken: bool) -> Result<(AgentDefinition, String), RenameError> {
53    let (mstore, broker, event_bus, local_url) = (&state.mstore, &state.broker, &state.event_bus, &state.local_web_url);
54    let title = title.trim();
55    if title.is_empty() {
56        return Err(RenameError::Invalid("title must not be empty".to_string()));
57    }
58
59    let all = mstore.agent_def_list()?;
60    let old = all.iter().find(|a| a.id == id).ok_or_else(|| RenameError::NotFound(format!("agent {id} not found")))?;
61
62    if former_name_of_another(mstore, title, id) {
63        return Err(RenameError::Taken(format!("{title:?} still addresses another agent")));
64    }
65    if refuse_taken {
66        refuse_if_taken(mstore, &all, id, title)?;
67    }
68    let old_title = shown_name(old).to_string();
69    // An agent that already has such a name may be given it again; a new name must not be reserved.
70    if title != old_title {
71        crate::backend::reserved_names::check_all(&[title]).map_err(RenameError::Invalid)?;
72    }
73    let mut updated = old.clone();
74    if !updated.branch_label.is_empty() {
75        updated.branch_label = title.to_string();
76    } else {
77        updated.name = title.to_string();
78    }
79
80    let found = mstore.agent_def_update(&mut updated)?;
81    if !found {
82        return Err(RenameError::NotFound(format!("agent {id} not found")));
83    }
84
85    // "My Agents" rows render `instance_name`, not these fields, so without this the picker redisplays the
86    // old name (#3262). Best-effort: the rename already landed, and a failed mirror is not a failed rename.
87    if let Err(e) = mstore.instance_rename(id, title) {
88        tracing::warn!(
89            agent_id = %id, error = %e,
90            "rename: display name not updated; the picker row may keep showing the old name"
91        );
92    }
93
94    // The running pane answers to the new name now; the old one still reaches it as a former name.
95    crate::backend::reactive::handler::renamed(id, &old_title, title, local_url);
96    broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
97    // Its reports' panes name their lead in `agent:seat` (#5382).
98    super::seat::refresh_pane_seats(state).await;
99    // The agent's open pane shows the new name (an earlier pane title outranks the name, so it is
100    // cleared), whichever UI the rename came from, and the running agent, which otherwise keeps its old
101    // name until it is launched again, is told.
102    if let Some(block_id) = crate::backend::reactive::get_global_handler().block_for_uid(id) {
103        show_new_name(mstore, event_bus, &block_id, title);
104        if old_title.as_str() != title {
105            let note = renamed_note(&old_title, title);
106            crate::backend::blockcontroller::system_note_into_turn_or_hold(&block_id, &format!("renamed:{title}"), &note);
107        }
108    }
109    Ok((updated, old_title))
110}
111
112/// Refuse `title` when another agent answers to it, as typed or as a message addressed to it is routed
113/// (`Zed Bot` and `Zed-Bot` are one route), or when it is a name another agent was renamed from.
114fn refuse_if_taken(mstore: &Store, all: &[AgentDefinition], id: &str, title: &str) -> Result<(), RenameError> {
115    let route = agent_route_name(title);
116    for spelling in [title, route.as_str()] {
117        let answering = mstore.agents_matching_name(spelling)?;
118        if let Some(other) = answering.iter().find(|m| m.id != id) {
119            return Err(RenameError::Taken(format!("{title:?} is already the name of another agent ({}); pick a different name", other.id)));
120        }
121        if answering.is_empty() && mstore.former_name_reserved(spelling) && !kept_for_it_alone(mstore, spelling, id)? {
122            return Err(RenameError::Taken(format!("{title:?} is a name another agent was renamed from and stays reserved for it")));
123        }
124    }
125    let routes_like_title = |name: &str| !name.trim().is_empty() && agent_route_name(name).eq_ignore_ascii_case(&route);
126    let other = all
127        .iter()
128        .filter(|a| a.id != id && a.is_seeded == 0 && a.user_hidden == 0)
129        .find(|a| routes_like_title(&a.name) || routes_like_title(&a.branch_label) || routes_like_title(&a.slug));
130    match other {
131        Some(a) => Err(RenameError::Taken(format!("{title:?} is already the name of another agent ({}); pick a different name", a.id))),
132        None => Ok(()),
133    }
134}
135
136/// Whether `id` is the only agent `name` is kept for, so it may take the name back.
137fn kept_for_it_alone(mstore: &Store, name: &str, id: &str) -> Result<bool, RenameError> {
138    let listers = mstore.former_name_listers(name)?;
139    Ok(!listers.is_empty() && listers.iter().all(|l| l == id))
140}
141
142/// What the tab strip shows for the agent: its fork label, else its name.
143fn shown_name(a: &AgentDefinition) -> &str {
144    if a.branch_label.is_empty() {
145        &a.name
146    } else {
147        &a.branch_label
148    }
149}
150
151/// Set the pane's `agentName` to `title` and clear an earlier `frame:title`.
152fn show_new_name(mstore: &Store, event_bus: &crate::backend::eventbus::EventBus, block_id: &str, title: &str) {
153    let mut meta = crate::backend::obj::MetaMapType::new();
154    meta.insert("agentName".to_string(), serde_json::json!(title));
155    meta.insert("frame:title".to_string(), serde_json::Value::Null);
156    match crate::server::service::update_object_meta(mstore, &format!("block:{block_id}"), &meta) {
157        Ok(_) => crate::backend::blockcontroller::core::broadcast_block_update(mstore, event_bus, block_id),
158        Err(e) => tracing::warn!(block_id, error = %e, "rename: the pane keeps its old title until relaunch"),
159    }
160}