Skip to main content

agentmux_srv/server/
http_naming.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Window, tab, pane and workspace naming.
5//! Split out of server/mod.rs unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.1).
6
7use super::*;
8
9/// `POST /api/v1/window/name` — set a window's display name
10/// (`window:displayname`), which the frontend turns into the OS/taskbar title.
11/// Defaults to the caller's own window (resolved from `block_id`). Routes
12/// through the same `object.UpdateObjectMeta` service path the InstancePanel
13/// rename uses, so persistence + live-title update are identical.
14/// agentmux-mcp's `SetWindowName` tool POSTs here.
15pub(super) async fn handle_window_name(
16    State(state): State<AppState>,
17    Json(req): Json<WindowNameRequest>,
18) -> impl IntoResponse {
19    // window:displayname is documented as ≤64 chars (window-title.ts).
20    let name: String = req.name.trim().chars().take(64).collect();
21    if name.is_empty() {
22        return ApiError::bad_request("name must not be empty").into_response();
23    }
24
25    let window_id = match req.window_id.filter(|w| !w.is_empty()) {
26        Some(w) => w,
27        None => {
28            let block_id = req.block_id.unwrap_or_default();
29            if block_id.is_empty() {
30                return ApiError::bad_request("provide window_id or block_id").into_response();
31            }
32            match service::resolve_agent_context(&state.mstore, &block_id) {
33                Ok(ctx) => match ctx.window_id {
34                    Some(w) => w,
35                    None => {
36                        return ApiError::not_found("no live window for this agent (tab not attached to a window)").into_response()
37                    }
38                },
39                Err(e) => return ApiError::not_found(e).into_response(),
40            }
41        }
42    };
43
44    let call = crate::backend::service::WebCallType {
45        service: "object".to_string(),
46        method: "UpdateObjectMeta".to_string(),
47        uicontext: None,
48        args: vec![
49            json!(format!("window:{window_id}")),
50            json!({ "window:displayname": name }),
51        ],
52    };
53    finish_name_call(
54        &state,
55        call,
56        json!({ "success": true, "window_id": window_id, "name": name }),
57    )
58    .await
59}
60
61/// Trim a user-supplied name and clamp to `max` chars; `None` if empty.
62pub(super) fn clean_name(raw: &str, max: usize) -> Option<String> {
63    let n: String = raw.trim().chars().take(max).collect();
64    if n.is_empty() {
65        None
66    } else {
67        Some(n)
68    }
69}
70
71/// `POST /api/v1/tab/name` — rename a tab. Defaults to the caller's own tab
72/// (resolved from `block_id`). Routes through `object.UpdateTabName`.
73pub(super) async fn handle_tab_name(
74    State(state): State<AppState>,
75    Json(req): Json<TabNameRequest>,
76) -> impl IntoResponse {
77    let name = match clean_name(&req.name, 128) {
78        Some(n) => n,
79        None => return ApiError::bad_request("name must not be empty").into_response(),
80    };
81    let tab_id = match req.tab_id.filter(|t| !t.is_empty()) {
82        Some(t) => t,
83        None => match resolve_own(&state, req.block_id, |c| Some(c.tab_id.clone())) {
84            Ok(t) => t,
85            Err(resp) => return resp,
86        },
87    };
88    let call = crate::backend::service::WebCallType {
89        service: "object".to_string(),
90        method: "UpdateTabName".to_string(),
91        uicontext: None,
92        args: vec![json!(tab_id), json!(name)],
93    };
94    finish_name_call(&state, call, json!({ "success": true, "tab_id": tab_id, "name": name })).await
95}
96
97/// `POST /api/v1/pane/title` — set a pane's display title (`frame:title`).
98/// Targets the caller's own pane (its `block_id`). Routes through
99/// `object.UpdateObjectMeta`.
100pub(super) async fn handle_pane_title(
101    State(state): State<AppState>,
102    Json(req): Json<PaneTitleRequest>,
103) -> impl IntoResponse {
104    let title = match clean_name(&req.title, 128) {
105        Some(t) => t,
106        None => return ApiError::bad_request("title must not be empty").into_response(),
107    };
108    let block_id = match req.block_id.filter(|b| !b.is_empty()) {
109        Some(b) => b,
110        None => return ApiError::bad_request("missing block_id").into_response(),
111    };
112    let call = crate::backend::service::WebCallType {
113        service: "object".to_string(),
114        method: "UpdateObjectMeta".to_string(),
115        uicontext: None,
116        args: vec![
117            json!(format!("block:{block_id}")),
118            json!({ "frame:title": title }),
119        ],
120    };
121    finish_name_call(&state, call, json!({ "success": true, "block_id": block_id, "title": title })).await
122}
123
124/// `POST /api/v1/workspace/name` — rename a workspace. Defaults to the
125/// caller's own workspace (resolved from `block_id`). Routes through
126/// `workspace.UpdateWorkspace`.
127pub(super) async fn handle_workspace_name(
128    State(state): State<AppState>,
129    Json(req): Json<WorkspaceNameRequest>,
130) -> impl IntoResponse {
131    let name = match clean_name(&req.name, 128) {
132        Some(n) => n,
133        None => return ApiError::bad_request("name must not be empty").into_response(),
134    };
135    let workspace_id = match req.workspace_id.filter(|w| !w.is_empty()) {
136        Some(w) => w,
137        None => match resolve_own(&state, req.block_id, |c| c.workspace_id.clone()) {
138            Ok(w) => w,
139            Err(resp) => return resp,
140        },
141    };
142    let call = crate::backend::service::WebCallType {
143        service: "workspace".to_string(),
144        method: "UpdateWorkspace".to_string(),
145        uicontext: None,
146        args: vec![json!(workspace_id), json!(name)],
147    };
148    finish_name_call(&state, call, json!({ "success": true, "workspace_id": workspace_id, "name": name })).await
149}
150
151/// Resolve a target id from the caller's own context (via `block_id`), using
152/// `pick` to select the field. Returns the route's error response on failure
153/// (missing block_id, unresolvable block, or the field is `None`).
154pub(super) fn resolve_own(
155    state: &AppState,
156    block_id: Option<String>,
157    pick: impl Fn(&service::AgentContext) -> Option<String>,
158) -> Result<String, Response> {
159    let block_id = block_id.unwrap_or_default();
160    if block_id.is_empty() {
161        return Err(ApiError::bad_request("provide an explicit target id or block_id").into_response());
162    }
163    let ctx = service::resolve_agent_context(&state.mstore, &block_id)
164        .map_err(|e| ApiError::not_found(e).into_response())?;
165    pick(&ctx).filter(|s| !s.is_empty()).ok_or_else(|| ApiError::not_found("no such target resolved for this agent").into_response())
166}
167
168/// Run a naming service call and map the result to a JSON HTTP response.
169pub(super) async fn finish_name_call(
170    state: &AppState,
171    call: crate::backend::service::WebCallType,
172    ok_body: serde_json::Value,
173) -> Response {
174    let result = service::run_service_call(state, &call).await;
175    if let Some(err) = result.error {
176        return ApiError::from(err).into_response();
177    }
178    Json(ok_body).into_response()
179}