Skip to main content

agentmux_srv/server/app_api/
pane.rs

1use super::*;
2use super::pane_open_steps as steps;
3use agentmux_common::AUTH_KEY_HEADER;
4
5pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
6    register_pane_open(engine, state);
7    register_pane_move_tab(engine, state);
8    register_pane_move_tabs(engine, state);
9    register_pane_tab_edits(engine, state);
10    register_pane_float_placed(engine);
11}
12
13/// `pane.floatplaced`: the window an agent's floating open went to says where it put the pane, which the
14/// open is waiting for (`floater_place`).
15fn register_pane_float_placed(engine: &Arc<WshRpcEngine>) {
16    engine.register_typed("pane.floatplaced", move |cmd: crate::backend::rpc_types::CommandPaneFloatPlacedData, _ctx| async move {
17        // The answer to `measurepanes` (`Pane layout`'s docked sizes) comes back the same way.
18        if let Some(sizes) = cmd.sizes {
19            return Ok(crate::backend::rpc_types::PaneFloatPlacedResult { delivered: crate::server::pane_measure::answered(&cmd.request_id, sizes) });
20        }
21        let answer = match (cmd.placed, cmd.error) {
22            (Some(placed), _) => Ok(placed),
23            (None, why) => Err(why.unwrap_or_else(|| "the window gave no reason".to_string())),
24        };
25        Ok(crate::backend::rpc_types::PaneFloatPlacedResult { delivered: super::floater_place::answered(&cmd.request_id, answer) })
26    });
27}
28
29fn register_pane_open(engine: &Arc<WshRpcEngine>, state: &AppState) {
30    let state = state.clone();
31    engine.register_typed(COMMAND_PANE_OPEN, move |mut cmd: CommandPaneOpenData, ctx| {
32        let state = state.clone();
33        async move {
34            if ctx.operator_proven_now() {
35                super::pane_open_tab::window_open_names_a_tab(&cmd)?;
36            }
37            if let Some(meta) = cmd.meta.as_mut() {
38                crate::server::browser_owner::strip_srv_only_keys(meta);
39                // A browser tab's jar: checked here, where new tabs arrive.
40                crate::server::browser_identity::check_new_tab(&state, meta)?;
41                // An agent browses as a named profile only if the user lets it.
42                if !ctx.agent_id.is_empty() {
43                    let owner = crate::server::browser_identity::profile_owner(&state, &ctx.agent_id);
44                    crate::server::browser_identity::check_agent_may_use(meta, &owner)?;
45                }
46            }
47            open_pane(&state, cmd).await
48        }
49    });
50}
51
52/// SPEC_PANE_TAB_DRAG_AND_DROP_2026_09_19.md §4.1, Phase 3.
53fn register_pane_move_tab(engine: &Arc<WshRpcEngine>, state: &AppState) {
54    let state = state.clone();
55    engine.register_typed(COMMAND_PANE_MOVE_TAB, move |cmd: CommandPaneMoveTabData, _ctx| {
56        let state = state.clone();
57        async move { super::move_tab(&state, cmd).await }
58    });
59}
60
61/// SPEC_PANE_TAB_MULTI_SELECT_MOVE_AND_COLLAPSED_EXPAND_2026_10_24.md §5.
62fn register_pane_move_tabs(engine: &Arc<WshRpcEngine>, state: &AppState) {
63    let state = state.clone();
64    engine.register_typed(COMMAND_PANE_MOVE_TABS, move |cmd: CommandPaneMoveTabsData, _ctx| {
65        let state = state.clone();
66        async move { super::move_tabs(&state, cmd).await }
67    });
68}
69
70/// SPEC_PANE_TABS_REDUCER_COMMANDS_2026_09_18.md §3.3: a tab switch and a tab
71/// close, as reducer commands the frontend sends beside its own local edit.
72fn register_pane_tab_edits(engine: &Arc<WshRpcEngine>, state: &AppState) {
73    let st = state.clone();
74    engine.register_typed(COMMAND_PANE_ACTIVATE_TAB, move |cmd: CommandPaneTabData, _ctx| {
75        let state = st.clone();
76        async move { activate_tab(&state, cmd).await }
77    });
78    let st = state.clone();
79    engine.register_typed(COMMAND_PANE_REMOVE_TAB, move |cmd: CommandPaneTabData, _ctx| {
80        let state = st.clone();
81        async move { remove_tab(&state, cmd).await }
82    });
83}
84
85/// Floating-pane branch of `open_pane`. The block already exists in
86/// `source_tab_id`'s blockids (created by the caller, with no layout node).
87/// This moves it into a fresh floating workspace via the `tear_off_block`
88/// saga, sets up the new tab's layout, broadcasts the new MuxObjs, and asks
89/// the source window's frontend to materialize the chromeless floating OS
90/// window via the host `open_floating_pane_window` command (srv cannot open
91/// windows itself). See docs/specs/SPEC_OPENEDITOR_FLOATING_AND_COLLAPSED_TREE_2026_06_16.md.
92pub(super) async fn open_pane_floating(
93    state: &AppState,
94    mstore: &Store,
95    event_bus: &crate::backend::eventbus::EventBus,
96    cmd: &CommandPaneOpenData,
97    source_tab_id: String,
98    meta: MetaMapType,
99) -> Result<PaneOpenResult, String> {
100    let view = cmd.view.clone();
101    let open_already = floaters_under_the_cap(state, cmd).await?;
102
103    // Source workspace from the reducer's canonical tab→workspace map.
104    let source_ws_id = {
105        let s = state.srv_state.lock().await;
106        s.tabs
107            .get(&source_tab_id)
108            .map(|t| t.workspace_id.clone())
109            .ok_or_else(|| format!("pane.open: floating: tab {source_tab_id} not in reducer state"))?
110    };
111
112    let block_id = create_floater_block(state, &source_tab_id, &meta).await?;
113    let (new_ws_id, new_tab_id) = tear_off_into_floater(state, &block_id, &source_tab_id, &source_ws_id).await?;
114
115    // Make the moved block the new tab's single root node so it renders.
116    if let Err(e) =
117        crate::server::service::setup_torn_off_block_layout(state, &new_tab_id, &block_id).await
118    {
119        tracing::warn!(
120            new_tab = %new_tab_id,
121            "pane.open: floating: layout setup failed: {e} (block moved but layout malformed)"
122        );
123    }
124    super::open_updates::broadcast_new_floater(mstore, event_bus, &new_ws_id, &new_tab_id, &block_id);
125
126    // Ask the source window's frontend to open the floating OS window — scoped
127    // to that window (mirrors the window-scoped `userinput` event) so exactly
128    // one window acts. The frontend handler calls the host
129    // `open_floating_pane_window` command.
130    if let Some(agent) = cmd.opener.as_deref() {
131        crate::server::browser_sessions::note_opened(state, &block_id, agent, cmd);
132    }
133    let mut result = PaneOpenResult::docked(block_id.clone(), new_tab_id, view, true);
134    announce_floater(state, &source_ws_id, &new_ws_id, cmd, &mut result, open_already.len()).await;
135    Ok(result)
136}
137
138/// An agent has at most `MAX_FLOATERS` floating panes open: checked before anything is made. Returns the ones
139/// it has open now.
140async fn floaters_under_the_cap(state: &AppState, cmd: &CommandPaneOpenData) -> Result<Vec<String>, String> {
141    let open_already = match cmd.opener.as_deref() {
142        Some(agent) => super::floater_place::live_floaters(state, agent).await,
143        None => Vec::new(),
144    };
145    if open_already.len() >= super::floater_place::MAX_FLOATERS {
146        return Err(super::floater_place::limit_text(&open_already));
147    }
148    Ok(open_already)
149}
150
151/// Create the block through the reducer (NOT wcore-direct) so it lands in
152/// `state.blocks` — the `tear_off_block` saga's pre-condition checks the
153/// reducer-canonical block map. The `BlockCreated` event also carries the
154/// meta, which `persist_subscriber::apply_block_created` writes into the
155/// mstore Block so the editor renders with its file + tree state. We skip
156/// layout placement, so the block never renders docked before the saga
157/// moves it into the floating workspace (no flash).
158async fn create_floater_block(state: &AppState, source_tab_id: &str, meta: &MetaMapType) -> Result<String, String> {
159    let meta_val = serde_json::to_value(meta)
160        .map_err(|e| format!("pane.open: floating: meta serialize: {e}"))?;
161    crate::server::service::create_block_in_tab(state, source_tab_id, meta_val, "pane.open: floating").await
162}
163
164/// Tear the block off into a fresh floating workspace + tab (reuses the
165/// exact saga the drag tear-off uses: CreateWorkspace → CreateTab → MoveBlock).
166/// Returns the new workspace's and tab's ids.
167async fn tear_off_into_floater(state: &AppState, block_id: &str, source_tab_id: &str, source_ws_id: &str) -> Result<(String, String), String> {
168    let saga_val = crate::sagas::tear_off_block::run(
169        state,
170        block_id.to_string(),
171        source_tab_id.to_string(),
172        source_ws_id.to_string(),
173    )
174    .await?;
175    let id_of = |key: &str| saga_val.get(key).and_then(|v| v.as_str()).unwrap_or_default().to_string();
176    let (new_ws_id, new_tab_id) = (id_of("new_workspace_id"), id_of("new_tab_id"));
177    if new_ws_id.is_empty() || new_tab_id.is_empty() {
178        return Err("pane.open: floating: tear_off_block returned empty ids".to_string());
179    }
180    Ok((new_ws_id, new_tab_id))
181}
182
183/// Tell the source window to open the floater. For an agent's open the event carries what it asked for, and
184/// the open waits for the window to say where the pane went (`placed`), or says `queued` when it does not
185/// answer in time.
186pub(crate) async fn announce_floater(
187    state: &AppState,
188    source_ws_id: &str,
189    new_ws_id: &str,
190    cmd: &CommandPaneOpenData,
191    result: &mut PaneOpenResult,
192    already_open: usize,
193) {
194    let window_id = {
195        let s = state.srv_state.lock().await;
196        s.windows.iter().find(|(_, w)| w.workspace_id == source_ws_id).map(|(id, _)| id.clone())
197    };
198    let Some(win) = window_id else {
199        tracing::warn!(source_ws = %source_ws_id, "pane.open: floating: no window mapped to source workspace — floater not opened");
200        return;
201    };
202    let (place, waiting) = match cmd.opener {
203        Some(_) => {
204            let id = uuid::Uuid::new_v4().to_string();
205            let max_share = cmd.floater_max_share;
206            // Registered before the window is told, so an answer cannot beat the waiter.
207            let rx = super::floater_place::expect(&id);
208            (Some(super::floater_place::place_for(cmd, id.clone(), already_open, max_share)), Some((id, rx)))
209        }
210        None => (None, None),
211    };
212    let open = crate::backend::mps_events::OpenFloatingPaneEvent { block_id: result.block_id.clone(), workspace_id: new_ws_id.to_string(), place };
213    state.broker.publish_event::<crate::backend::mps_events::OpenFloatingPane>(&open, vec![win], 0);
214    let Some((id, rx)) = waiting else { return };
215    match tokio::time::timeout(super::floater_place::WAIT, rx).await {
216        Ok(Ok(Ok(placed))) => result.placed = Some(placed),
217        Ok(Ok(Err(why))) => tracing::warn!(block = %result.block_id, "pane.open: floating: the window could not open it: {why}"),
218        _ => {
219            super::floater_place::forget(&id);
220            result.queued = true;
221        }
222    }
223}
224
225/// The title the opener gave the pane. A browser pane also records the address it was opened at, so it keeps
226/// the title only while it stays on that site (frontend/app/view/browser/given-title.ts).
227fn add_title(meta: &mut MetaMapType, cmd: &CommandPaneOpenData) {
228    let Some(title) = cmd.title.as_deref().filter(|s| !s.is_empty()) else { return };
229    meta.insert("frame:title".to_string(), json!(title));
230    if let Some(url) = cmd.url.as_deref().filter(|s| !s.is_empty()).filter(|_| cmd.view == "browser") {
231        meta.insert("frame:title_url".to_string(), json!(url));
232    }
233}
234
235/// The `file` an editor or media pane opens, refused when the request names none.
236fn required_file<'a>(cmd: &'a CommandPaneOpenData, view: &str) -> Result<&'a str, String> {
237    cmd.file.as_deref().filter(|s| !s.is_empty()).ok_or_else(|| format!("MISSING_ARG: view={view} requires 'file'"))
238}
239
240/// The Editor: the file, then what only an explicit caller value writes. Tree state: without one the Editor decides
241/// (collapsed for a pane opened on a file, which this always is).
242fn editor_meta(meta: &mut MetaMapType, cmd: &CommandPaneOpenData) -> Result<(), String> {
243    let file = required_file(cmd, "editor")?;
244    meta.insert("view".to_string(), json!("editor"));
245    meta.insert("file".to_string(), json!(file));
246    if let Some(expanded) = cmd.tree_expanded {
247        meta.insert("editor:tree_expanded".to_string(), json!(expanded));
248    }
249    let at = OpenAt::of(cmd);
250    if let Some(line) = at.line {
251        meta.insert("editor:line".to_string(), json!(line));
252    }
253    if let Some(offset) = at.offset {
254        meta.insert(META_OFFSET.to_string(), json!(offset));
255    }
256    if let Some(page) = at.page {
257        meta.insert(META_PAGE.to_string(), json!(page));
258    }
259    if cmd.follow_folder == Some(true) {
260        meta.insert(META_FOLLOW_FOLDER.to_string(), json!(true));
261    }
262    if let Some(viewer) = requested_viewer(cmd)? {
263        meta.insert(META_VIEWER.to_string(), json!(viewer));
264    }
265    Ok(())
266}
267
268/// The Files pane. The folder comes from `file`, else `cwd`, else home; `select` becomes a one-shot `files:select`
269/// the view applies after its first listing and then clears. SPEC_FILE_BROWSER_PANE_2026_10_01.md §6.2, §8.1.
270fn files_meta(meta: &mut MetaMapType, cmd: &CommandPaneOpenData) -> Result<(), String> {
271    let path = cmd
272        .file
273        .as_deref()
274        .filter(|s| !s.is_empty())
275        .or_else(|| cmd.cwd.as_deref().filter(|s| !s.is_empty()))
276        .map(str::to_string)
277        .or_else(|| dirs::home_dir().map(|h| h.to_string_lossy().into_owned()))
278        .ok_or_else(|| "MISSING_ARG: view=files requires 'file' (no home directory to default to)".to_string())?;
279    meta.insert("view".to_string(), json!("files"));
280    meta.insert("files:path".to_string(), json!(path));
281    if let Some(select) = cmd.select.as_ref().filter(|s| !s.is_empty()) {
282        meta.insert("files:select".to_string(), json!(select));
283    }
284    Ok(())
285}
286
287/// The connection the pane works on, for the views that have one; media reads this computer's files only.
288fn add_connection(meta: &mut MetaMapType, cmd: &CommandPaneOpenData) -> Result<(), String> {
289    let Some(conn) = cmd.connection.as_deref().map(str::trim).filter(|c| !c.is_empty() && *c != "local") else { return Ok(()) };
290    match cmd.view.as_str() {
291        "editor" | "term" | "files" => {
292            meta.insert("connection".to_string(), json!(conn));
293        }
294        "media" if crate::backend::fs_ops::remote::ssh_connection(Some(conn)).is_some() => {
295            return Err(format!("INVALID_ARG: media files on {conn} can't be shown yet"));
296        }
297        _ => {}
298    }
299    Ok(())
300}
301
302/// Build the metadata map for a pane.open request, validating required args.
303pub(crate) fn build_pane_meta(cmd: &CommandPaneOpenData) -> Result<MetaMapType, String> {
304    let mut meta = MetaMapType::new();
305
306    match cmd.view.as_str() {
307        "editor" => editor_meta(&mut meta, cmd)?,
308        "term" => {
309            meta.insert("view".to_string(), json!("term"));
310            meta.insert("controller".to_string(), json!("shell"));
311            if let Some(cwd) = cmd.cwd.as_deref().filter(|s| !s.is_empty()) {
312                meta.insert("cmd:cwd".to_string(), json!(cwd));
313            }
314        }
315        "browser" => {
316            let url = cmd.url.as_deref().filter(|s| !s.is_empty())
317                .ok_or_else(|| "MISSING_ARG: view=browser requires 'url'".to_string())?;
318            meta.insert("view".to_string(), json!("browser"));
319            meta.insert("url".to_string(), json!(url));
320        }
321        // Tower, the read-only task manager. Opening one is harmless: its data
322        // goes only to the window (`tower.*` refuses agents).
323        "sysinfo" | "help" | "tower" => {
324            meta.insert("view".to_string(), json!(cmd.view));
325        }
326        // The Media pane is folded into the Editor: a media request opens an
327        // Editor whose tab follows newer files in the folder, as Media did.
328        // SPEC_EDITOR_REVAMP_UNIFIED_VIEWERS_2026_10_15.md §4.11.
329        "media" => {
330            let file = required_file(cmd, "media")?;
331            meta.insert("view".to_string(), json!("editor"));
332            meta.insert("file".to_string(), json!(file));
333            meta.insert(META_FOLLOW_FOLDER.to_string(), json!(true));
334        }
335        "files" => files_meta(&mut meta, cmd)?,
336        other => {
337            return Err(format!(
338                "INVALID_VIEW: unsupported view '{other}' (expected editor/term/browser/sysinfo/help/media/files/tower)"
339            ));
340        }
341    }
342
343    add_title(&mut meta, cmd);
344    add_connection(&mut meta, cmd)?;
345    Ok(meta)
346}
347
348/// Block-meta key carrying an ARRAY of files the reused pane should open —
349/// the sole delivery path (see below for why an earlier version's second,
350/// "live MPS event" path was removed). Drained (all entries, in order)
351/// reactively by `EditorViewModel`'s `createEffect` over its own block meta,
352/// then cleared immediately after — covers both "not yet mounted when this
353/// was written" and "already mounted, reacts as soon as the write lands"
354/// uniformly through the same MuxObj sync path the pane already depends on
355/// for everything else.
356///
357/// **Array, not a single scalar** (codex P1 on PR #2404): if 2+ `OpenEditor`
358/// reuse calls arrive before the target pane ever mounts, a single-value key
359/// would have each call overwrite the last, silently losing every request
360/// but the final one. Appending to an array and draining all of them at
361/// once fixes that.
362///
363/// **Sole delivery path — no separate live MPS event** (codex P1 on PR
364/// #2404, found twice): an earlier version ALSO fired a direct MPS event
365/// (`persist: 0`) alongside this meta write, for immediate delivery when the
366/// pane was already mounted. First finding: the frontend's live handler
367/// didn't clear its own entry from this array, so it could be reprocessed
368/// on a later, unrelated remount. Second, deeper finding after fixing that:
369/// the MPS event is a direct WS push and arrives essentially synchronously,
370/// while THIS meta write only reaches the frontend's `blockAtom` after an
371/// async MuxObj DB-refetch — so the live handler's own dequeue attempt
372/// could run and read stale data (this exact write not yet reflected)
373/// before it landed, no-op, and strand the entry anyway. Removing the
374/// separate live path entirely (rather than patching a second-order race in
375/// its own race-fix) leaves one delivery mechanism and one reactive
376/// consumer — nothing to race. Trades a small amount of latency for the
377/// already-mounted case (a real MuxObj round-trip instead of a direct
378/// push) for not being racy.
379///
380/// **Superseded relying on MPS `persist > 0` for durability** (codex P1 on
381/// PR #2404, earliest finding on this function): a just-created Editor
382/// block may not have finished mounting its `EditorViewModel` by the time a
383/// second back-to-back `OpenEditor` call reuses it. `persist: N` closes that
384/// race but opens a *worse* one: `Broker::unsubscribe_all` clears a route's
385/// replay marker on disconnect (`crates/srv-core/src/backend/mps.rs`),
386/// so any later, unrelated reconnect would replay the *entire* persisted
387/// history again — reopening files the user has since closed. The broker
388/// has no ack/consume concept, so nothing marks a persisted event "already
389/// delivered." Block meta does have exactly that shape (write once, drain
390/// once, clear after reading) — reusing it avoids inventing new broker
391/// machinery.
392const META_PENDING_OPEN_FILES: &str = "editor:pending_open_files";
393
394/// Block-meta key: the Editor's initial `file` opens following newer files
395/// in its folder (an image or video tab). An entry of
396/// `editor:pending_open_files` says the same per file, as
397/// `{"path": ..., "follow_folder": true}`.
398const META_FOLLOW_FOLDER: &str = "editor:follow_folder";
399
400/// Block-meta key: the viewer the Editor's initial `file` opens in (pane.open's
401/// `viewer`, so `muxsh edit` shows any file as text). An entry of
402/// `editor:pending_open_files` says the same per file, as
403/// `{"path": ..., "viewer": "text"}`.
404const META_VIEWER: &str = "editor:viewer";
405
406/// Block-meta keys: where a new Editor pane's initial `file` opens, once: the hex viewer's byte offset and the PDF
407/// viewer's page (`editor:line`, the text viewer's, is `open-at-line.ts`'s). An entry of `editor:pending_open_files`
408/// says the same per file, as `{"path": ..., "line": ..., "offset": ..., "page": ...}`.
409const META_OFFSET: &str = "editor:offset";
410const META_PAGE: &str = "editor:page";
411
412/// The viewers the Editor opens a file in (frontend `VIEWER_IDS`).
413const VIEWERS: [&str; 7] = ["text", "large", "image", "media", "pdf", "hex", "info"];
414
415/// pane.open's `viewer`, checked against the Editor's viewers.
416pub(crate) fn requested_viewer(cmd: &CommandPaneOpenData) -> Result<Option<&'static str>, String> {
417    let Some(asked) = cmd.viewer.as_deref() else { return Ok(None) };
418    let viewer = VIEWERS.iter().find(|v| **v == asked).ok_or_else(|| {
419        format!("INVALID_ARG: viewer {asked:?} isn't one the editor opens a file in (one of {})", VIEWERS.join(", "))
420    })?;
421    // The other viewers read this computer's files; a file on an SSH host reaches the Editor as text only.
422    let on_host = cmd.connection.as_deref().map(str::trim).is_some_and(|c| !c.is_empty() && c != "local" && crate::backend::fs_ops::remote::ssh_connection(Some(c)).is_some());
423    if on_host && *viewer != "text" {
424        return Err(format!("INVALID_ARG: viewer {asked:?} can't show a file on an SSH host yet; only \"text\" opens there"));
425    }
426    Ok(Some(*viewer))
427}
428
429/// Where in the file pane.open asks to land: a text line, a hex byte offset, a PDF page. Each is read by its own viewer
430/// and ignored by the others; a line or page of 0 counts as absent.
431#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
432pub(crate) struct OpenAt {
433    pub line: Option<u32>,
434    pub offset: Option<u64>,
435    pub page: Option<u32>,
436}
437
438impl OpenAt {
439    pub(crate) fn of(cmd: &CommandPaneOpenData) -> Self {
440        Self { line: cmd.line.filter(|&n| n > 0), offset: cmd.offset, page: cmd.page.filter(|&n| n > 0) }
441    }
442
443    fn is_empty(&self) -> bool {
444        *self == Self::default()
445    }
446}
447
448/// An `editor:pending_open_files` entry: the path, or `{path, ...}` with how
449/// it opens.
450fn pending_open_entry(file: &str, follow_folder: bool, viewer: Option<&str>, at: OpenAt) -> serde_json::Value {
451    if !follow_folder && viewer.is_none() && at.is_empty() {
452        return json!(file);
453    }
454    let mut entry = serde_json::Map::new();
455    entry.insert("path".into(), json!(file));
456    if follow_folder {
457        entry.insert("follow_folder".into(), json!(true));
458    }
459    if let Some(viewer) = viewer {
460        entry.insert("viewer".into(), json!(viewer));
461    }
462    if let Some(line) = at.line {
463        entry.insert("line".into(), json!(line));
464    }
465    if let Some(offset) = at.offset {
466        entry.insert("offset".into(), json!(offset));
467    }
468    if let Some(page) = at.page {
469        entry.insert("page".into(), json!(page));
470    }
471    serde_json::Value::Object(entry)
472}
473
474/// If the calling agent (identified by its own block id, `caller_block_id`)
475/// already has an Editor pane open in its own tab, push `file` into that
476/// pane as a new tab instead of creating another Editor pane. Returns
477/// `Ok(None)` when there's no existing Editor pane to reuse (or the caller's
478/// tab can't be resolved) — the normal create-new-block path handles that
479/// case unchanged.
480///
481/// **Known, accepted limitation: does not apply layout focus.** An earlier
482/// version of this function resolved the reused block's layout leaf id and
483/// dispatched `Command::SetFocusedNode` — reagent (PR #2404) confirmed the
484/// leaf-id resolution itself was correct, then found a deeper problem:
485/// the frontend's `onBackendUpdate` (`frontend/layout/lib/layoutPersistence.ts`)
486/// only re-derives `focusedNodeId` at initial model construction or via a
487/// `pendingBackendActions`-driven tree action — a bare `focusednodeid`
488/// MuxObj push to an ALREADY-MOUNTED `LayoutModel` (confirmed by reading
489/// the function directly: no branch reads `muxObj.focusednodeid` outside
490/// those two triggers) is silently never applied to the live `treeState`.
491/// Making that work would mean changing `onBackendUpdate`'s reactivity —
492/// shared code this file's own comments show has deliberately been kept
493/// narrow/non-reactive before (see the dangling-leaf-prune history right
494/// above it) — a real, separate piece of work, not a one-line fix. Shipping
495/// a backend dispatch that compiles and passes a reducer-internal test but
496/// has no visible frontend effect would be worse than not attempting it: it
497/// would look done without being done. The reused pane's new tab still
498/// becomes its *own* active tab via `openFile()`; only the cross-pane
499/// layout-focus indicator is unaffected, same as before this feature
500/// existed.
501pub(super) async fn maybe_reuse_editor_pane(
502    state: &AppState,
503    caller_block_id: Option<&str>,
504    target_block_id: Option<&str>,
505    file: &str,
506    connection: &str,
507    follow_folder: bool,
508    viewer: Option<&str>,
509    at: OpenAt,
510) -> Result<Option<PaneOpenResult>, String> {
511    let mstore = &state.mstore;
512    // A named Editor is in its own tab; otherwise the caller's tab is searched.
513    let Some(tab_of) = target_block_id.or(caller_block_id) else { return Ok(None) };
514    let tab_id = match super::resolve_tab_id_for_block(mstore, tab_of) {
515        Ok(id) => id,
516        Err(_) if target_block_id.is_some() => {
517            return Err(format!("INVALID_ARG: {tab_of} is not a pane in any tab; target_id takes a block_id from layout"))
518        }
519        Err(_) => return Ok(None), // caller's own block isn't in any known tab — fall through
520    };
521
522    // Only an editor on the file's own connection: one on a host reads and
523    // saves there, so a local file pushed into it would be read there.
524    let found = match target_block_id {
525        Some(target) => super::editor_block_named(mstore, &tab_id, target, connection)?,
526        None => match super::find_editor_block(mstore, &tab_id, connection, caller_block_id)? {
527            Some(found) => found,
528            None => return Ok(None),
529        },
530    };
531    tracing::info!(block_id = %found.block.oid, tab_id = %tab_id, why = found.why, "pane.open: chose the Editor pane for the file");
532    let (existing, needs_activation) = (found.block, found.needs_activation);
533    // A background tab of a pane stack isn't mounted, so it would never take the file: bring it to
534    // the front first, the way a click on its tab does.
535    if needs_activation {
536        if let Err(e) = super::activate_tab(
537            state,
538            crate::backend::rpc_types::CommandPaneTabData { block_id: existing.oid.clone(), action_id: None },
539        )
540        .await
541        {
542            tracing::warn!(block_id = %existing.oid, "pane.open: reuse: couldn't bring the editor tab to the front: {e}");
543        }
544    }
545
546    // Durable delivery path: append to any already-pending queue (read then
547    // write — a small race window under truly concurrent reuse calls is
548    // accepted, matching this codebase's general best-effort meta-patch
549    // posture elsewhere) so a not-yet-mounted (or remounting)
550    // EditorViewModel drains every pending file once at construction, then
551    // clears the queue — see META_PENDING_OPEN_FILES's doc comment for why
552    // this replaces relying on MPS persist/replay for correctness.
553    // Entries are paths, or `{path, follow_folder, viewer}` for a media or
554    // text open.
555    let mut pending: Vec<serde_json::Value> = existing
556        .meta
557        .get(META_PENDING_OPEN_FILES)
558        .and_then(|v| v.as_array())
559        .map(|arr| arr.iter().filter(|v| v.is_string() || v.is_object()).cloned().collect())
560        .unwrap_or_default();
561    pending.push(pending_open_entry(file, follow_folder, viewer, at));
562
563    let meta_events = crate::server::service::dispatch_to_reducer(
564        state,
565        agentmux_common::ipc::Command::UpdateBlockMeta {
566            block_id: existing.oid.clone(),
567            meta_patch: json!({ META_PENDING_OPEN_FILES: pending }),
568        },
569    )
570    .await;
571    for ev in &meta_events {
572        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, mstore) {
573            tracing::warn!("pane.open: reuse: UpdateBlockMeta mstore apply failed: {e}");
574        }
575    }
576    crate::server::service::publish_events(state, &meta_events);
577
578    tracing::info!(
579        block_id = %existing.oid,
580        tab_id = %tab_id,
581        "pane.open: reused existing editor pane instead of creating a new one"
582    );
583
584    Ok(Some(PaneOpenResult::docked(existing.oid, tab_id, "editor".to_string(), false)))
585}
586
587/// Translate `split_direction` + `split_reference_block_id` into a placement:
588/// a split of the reference block's pane, or the first free slot when either
589/// is missing. A direction ending in `:half` (`down:half`) gives the new pane exactly half of the
590/// reference pane's space; without it the new pane takes the layout's default size.
591pub(crate) fn resolve_placement(
592    direction: Option<&str>,
593    reference: Option<&str>,
594    focused: bool,
595) -> crate::server::service::layout_intents::Placement {
596    use crate::server::service::layout_intents::Placement;
597    use agentmux_common::SplitPosition::{After, Before};
598    let Some(reference) = reference.filter(|s| !s.is_empty()) else {
599        return Placement::Append { focused };
600    };
601    let (direction, half) = match direction.and_then(|d| d.strip_suffix(":half")) {
602        Some(base) => (Some(base), true),
603        None => (direction, false),
604    };
605    let (horizontal, position) = match direction {
606        Some("right") => (true, After),
607        Some("left") => (true, Before),
608        Some("down") | Some("below") => (false, After),
609        Some("up") | Some("above") => (false, Before),
610        _ => return Placement::Append { focused },
611    };
612    Placement::Split { target_block_id: reference.to_string(), horizontal, position, size_fraction: half.then_some(0.5), focused }
613}
614
615/// `POST /api/v1/agent/pane/close` — backs the `ClosePane` MCP tool.
616/// See docs/specs/SPEC_AGENT_PANE_LIFECYCLE_CONTROL_2026_09_10.md.
617///
618/// Identity is always verified first via the same `verified_block_id`
619/// mechanism `UIClick`/`UIQuery`/`UIScreenshot` use (§5.0 of that spec) —
620/// this both resolves the caller's OWN pane when `req.block_id` is absent,
621/// and supplies a real, checked `source_agent` for the audit log when
622/// `req.block_id` targets another agent's pane (fleet tier, §5.1/§5.2): no
623/// ownership check on the TARGET (closing another agent's stuck pane without
624/// needing its cooperation is this spec's whole motivation), but the CALLER
625/// is never anonymous the way `FleetBulkStop`'s existing calls are today.
626/// `POST /api/v1/agent/self/quit` — the `QuitSelf` tool
627/// (docs/specs/SPEC_AGENT_SELF_QUIT_2026_09_24.md §6). Always the caller's
628/// own block (from the signed `auth`); there is no target. Proceeds only
629/// when the user started the current turn, nothing else got in, and the
630/// quote is theirs (§6.3). The quit then waits for the turn to end (§4.2):
631/// 202 now, the tab closes after. Anything else is an external shutdown: 202
632/// `pending_user_override`, and the user has 15 s to keep the agent (§6.5).
633pub(crate) async fn handle_quit_self(
634    axum::extract::State(state): axum::extract::State<AppState>,
635    caller: Option<axum::Extension<crate::server::caller::Caller>>,
636    axum::Json(req): axum::Json<agentmux_common::api_types::QuitSelfRequest>,
637) -> impl axum::response::IntoResponse {
638    use axum::http::StatusCode;
639    use axum::response::IntoResponse;
640    use axum::Json;
641
642    let block_id = match crate::server::ui_handlers::verified_block_id(&state, caller.as_deref(), &req.auth) {
643        Ok(b) => b,
644        Err(e) => return (StatusCode::UNAUTHORIZED, Json(json!({ "error": e }))).into_response(),
645    };
646    quit_self(&state, &block_id, &req.auth.agent_id, "QuitSelf", req.reason.trim(), &req.user_instruction)
647}
648
649/// An agent ending its own session — `QuitSelf`, or `ClosePane` with no
650/// arguments (§7), which has no quote and so always asks the user. A
651/// user-started, untainted turn with the user's quote quits when the turn
652/// ends; anything else waits 15 s for the user to keep it (§6.5).
653fn quit_self(
654    state: &AppState,
655    block_id: &str,
656    agent: &str,
657    via: &str,
658    reason: &str,
659    user_instruction: &str,
660) -> axum::response::Response {
661    use crate::sagas::self_quit;
662    use axum::http::StatusCode;
663    use axum::response::IntoResponse;
664    use axum::Json;
665
666    let detail = format!("{reason} | user said: {user_instruction:?}");
667    // Scheduled, closing, or a user-override window that already ran out.
668    let under_way = crate::sagas::pending_shutdown::active_for(block_id).is_some_and(|v| v.status == "proceeding");
669    if self_quit::is_quitting(block_id) || under_way {
670        return (StatusCode::OK, Json(json!({ "status": "already_quitting" }))).into_response();
671    }
672    let provenance = crate::backend::blockcontroller::get_controller(block_id).and_then(|c| c.turn_provenance());
673    if let Err(refusal) = self_quit::gate(provenance.as_ref(), user_instruction) {
674        // Not the user's own ask: the user decides, within 15 s (§6.5). Audited
675        // with why the gate didn't pass (§4.4); the outcome is audited too.
676        let pending = crate::sagas::pending_shutdown::request(
677            state,
678            block_id,
679            agent,
680            via,
681            reason,
682            crate::sagas::pending_shutdown::Action::SelfQuit { detail: detail.clone() },
683        );
684        state.reactive_handler.log_fleet_action_audit(
685            Some(agent),
686            agent,
687            block_id,
688            "agent.quit_self",
689            true,
690            Some(refusal.as_str()),
691            &pending.request_id,
692            Some(&format!("{} ({via}): {detail}", crate::sagas::pending_shutdown::audit_note(state, &pending, agent, via))),
693        );
694        return (StatusCode::ACCEPTED, Json(pending_body(&pending))).into_response();
695    }
696    if !self_quit::schedule_after_turn(state, block_id, detail) {
697        return (StatusCode::OK, Json(json!({ "status": "already_quitting" }))).into_response();
698    }
699    (StatusCode::ACCEPTED, Json(json!({ "status": "scheduled" }))).into_response()
700}
701
702/// The 202 answer for a shutdown waiting on the user (§6.5).
703pub(crate) fn pending_body(p: &crate::sagas::pending_shutdown::PendingView) -> serde_json::Value {
704    json!({
705        "status": "pending_user_override",
706        "request_id": p.request_id,
707        // Whose request this is: a caller who finds someone else here joined it.
708        "by": p.by,
709        "via": p.via,
710        "deadline_ms": p.deadline_ms,
711        "wait_at_least_ms": crate::sagas::pending_shutdown::wait_at_least_ms(p.deadline_ms),
712    })
713}
714
715/// `GET /api/v1/agent/shutdown/{request_id}` — where a shutdown waiting on the
716/// user's override stands (§6.5): `pending`, `kept_by_user`, `proceeding`,
717/// `shut_down`, `superseded` or `failed`.
718pub(crate) async fn handle_shutdown_status(
719    axum::extract::State(state): axum::extract::State<AppState>,
720    axum::extract::Path(request_id): axum::extract::Path<String>,
721) -> impl axum::response::IntoResponse {
722    use axum::http::StatusCode;
723    use axum::response::IntoResponse;
724    use axum::Json;
725    if let Some(v) = crate::sagas::pending_shutdown::status(&request_id) {
726        return (StatusCode::OK, Json(serde_json::to_value(v).unwrap_or_default())).into_response();
727    }
728    // Asked on another instance on this machine (a cross-channel
729    // FleetBulkStop target): that instance holds the answer.
730    if let Some(remote) = crate::sagas::pending_shutdown::remote_for(&request_id) {
731        let url = format!("{}/api/v1/agent/shutdown/{request_id}", remote.local_url.trim_end_matches('/'));
732        let mut req = state.http_client.get(&url);
733        if !remote.auth_key.is_empty() {
734            req = req.header(AUTH_KEY_HEADER, &remote.auth_key);
735        }
736        return match req.send().await {
737            Ok(r) => {
738                let code = StatusCode::from_u16(r.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
739                let body: serde_json::Value = r.json().await.unwrap_or_default();
740                (code, Json(body)).into_response()
741            }
742            Err(e) => (StatusCode::BAD_GATEWAY, Json(json!({ "error": format!("its AgentMux instance: {e}") }))).into_response(),
743        };
744    }
745    (StatusCode::NOT_FOUND, Json(json!({ "error": "no such shutdown request" }))).into_response()
746}
747
748pub(crate) async fn handle_close_pane(
749    axum::extract::State(state): axum::extract::State<AppState>,
750    caller: Option<axum::Extension<crate::server::caller::Caller>>,
751    axum::Json(req): axum::Json<agentmux_common::api_types::ClosePaneRequest>,
752) -> impl axum::response::IntoResponse {
753    use axum::http::StatusCode;
754    use axum::response::IntoResponse;
755    use axum::Json;
756
757    let caller_agent_id = req.auth.agent_id.clone();
758    let verified_own_block_id = match crate::server::ui_handlers::verified_block_id(&state, caller.as_deref(), &req.auth) {
759        Ok(b) => b,
760        Err(e) => return (StatusCode::UNAUTHORIZED, Json(json!({ "error": e }))).into_response(),
761    };
762
763    // No arguments: the agent closing itself. That is `QuitSelf` without its
764    // quote (§7): its own tab only, siblings keep running, and only after the
765    // user's 15 s window. An explicit block_id closes that tab, and the pane with it only when it was the last.
766    if req.block_id.is_none() {
767        let reason = req.reason.clone().unwrap_or_default();
768        return quit_self(&state, &verified_own_block_id, &caller_agent_id, "ClosePane", reason.trim(), "");
769    }
770
771    let target = req.block_id.clone().unwrap_or_else(|| verified_own_block_id.clone());
772    let (code, body) = close_pane_as(&state, &caller_agent_id, &target, req.reason.as_deref(), "ClosePane").await;
773    (code, Json(body)).into_response()
774}
775
776/// Whether closing `target` takes its pane with it (nothing else is left in it); `None` when there is no such block.
777async fn closes_its_pane(state: &AppState, target: &str) -> Option<bool> {
778    let s = state.srv_state.lock().await;
779    let b = s.blocks.get(target)?;
780    let stack = s
781        .tabs
782        .get(&b.tab_id)
783        .and_then(|t| t.rootnode.as_ref())
784        .and_then(|root| crate::backend::layout::find_leaf_containing_block(root, target))
785        .and_then(|leaf| leaf.data.as_ref())
786        .map(crate::backend::layout::leaf_members)
787        .unwrap_or_default();
788    Some(stack.iter().all(|m| m == target || !s.blocks.contains_key(m)))
789}
790
791/// Close the tab `target_block_id` on behalf of `caller_agent_id`: it waits 30 s for its
792/// user to keep it (§6.5) and answers 202 with the pending request, which names the tab and
793/// says whether the pane closes with it (`pane_closes`: it was the pane's last tab). The
794/// pane's other tabs stay. That includes a tab the caller is in: closing it ends the caller
795/// (which only `QuitSelf` may do without the user's window). Audited as `pane.close`. Shared by ClosePane
796/// and RunCommand's `pane:close` (`server/ui_shortcuts.rs`), so both carry the
797/// same protection. `via` names the tool in the pending request and the audit.
798pub(crate) async fn close_pane_as(
799    state: &AppState,
800    caller_agent_id: &str,
801    target_block_id: &str,
802    reason: Option<&str>,
803    via: &str,
804) -> (axum::http::StatusCode, serde_json::Value) {
805    use axum::http::StatusCode;
806    let target_block_id = target_block_id.to_string();
807    let caller_agent_id = caller_agent_id.to_string();
808
809    // codex P2 on PR #3193: resolve the target's agent name BEFORE deleting
810    // the block, not after. `delete_block::run` stops the block's
811    // controller, and a running agent's own exit-triggered
812    // `unregister_block` can race ahead of this lookup once it does — a
813    // post-delete lookup would then fall back to the bare block UUID
814    // instead of the real agent name, making attribution timing-dependent.
815    let target_agent = state
816        .reactive_handler
817        .get_agent_by_block(&target_block_id)
818        .map(|a| a.agent_id)
819        .unwrap_or_else(|| target_block_id.clone());
820
821    // The target alone closes, and its pane goes with it only when nothing else is left in it (the
822    // close saga prunes just the closed tab otherwise).
823    let Some(pane_closes) = closes_its_pane(state, &target_block_id).await else {
824        let err = format!("block not found: {target_block_id}");
825        let request_id = uuid::Uuid::new_v4().to_string();
826        state.reactive_handler.log_fleet_action_audit(
827            Some(&caller_agent_id), &target_agent, &target_block_id,
828            "pane.close", false, Some(&err), &request_id, reason,
829        );
830        return (StatusCode::NOT_FOUND, json!({ "error": err }));
831    };
832    let pane_block_ids = vec![target_block_id.clone()];
833
834    // A tab that is an agent is closed by closing the agent, with `Stop
835    // agents`: one way to stop an agent, and only that agent's tab goes
836    // (docs/specs/SPEC_STOP_AN_AGENT_ONE_WAY_AND_SHUTDOWN_TOAST_2026_10_23.md
837    // §3.2). Refused here, not in the tool, so `UI run_command pane:close` has
838    // no way round it. A non-agent tab beside an agent closes without it.
839    let agents: Vec<&String> =
840        pane_block_ids.iter().filter(|b| crate::sagas::orphan_reaper::is_agent_block(state, b)).collect();
841    if !agents.is_empty() {
842        let names = agents.iter().map(|b| b.as_str()).collect::<Vec<_>>().join(", ");
843        let err = format!(
844            "not a tab to close this way: it is an agent (block {names}). Use Stop with action \"agents\" and targets [{names}], which closes the agent's tab and leaves the others in the pane running"
845        );
846        let request_id = uuid::Uuid::new_v4().to_string();
847        state.reactive_handler.log_fleet_action_audit(
848            Some(&caller_agent_id), &target_agent, &target_block_id,
849            "pane.close", false, Some(&err), &request_id, reason,
850        );
851        return (StatusCode::CONFLICT, json!({ "error": err }));
852    }
853
854    // Its user has 30 s to keep it (§6.5; 10 s for a browser pane, which holds no conversation), whoever's tab it
855    // is. A tab the caller is in is no exception: closing it would end the caller without QuitSelf's check.
856    let reason = reason.unwrap_or_default().to_string();
857    let window = crate::sagas::pending_shutdown::close_window(state, &pane_block_ids);
858    let pending = crate::sagas::pending_shutdown::request_within(
859        state,
860        &target_block_id,
861        &caller_agent_id,
862        via,
863        &reason,
864        crate::sagas::pending_shutdown::Action::ClosePane { block_ids: pane_block_ids },
865        window,
866    );
867    // `Stop pane` doesn't wait for the window: it is told by a note if the user keeps the pane.
868    if via == "ClosePane" {
869        crate::sagas::pending_shutdown::tell_when_settled(state, &pending.request_id, &caller_agent_id, via);
870    }
871    state.reactive_handler.log_fleet_action_audit(
872        Some(&caller_agent_id),
873        &target_agent,
874        &target_block_id,
875        "pane.close",
876        true,
877        None,
878        &pending.request_id,
879        Some(&format!("{}: {reason}", crate::sagas::pending_shutdown::audit_note(state, &pending, &caller_agent_id, via))),
880    );
881    let mut body = pending_body(&pending);
882    body["tab"] = json!(target_block_id);
883    body["pane_closes"] = json!(pane_closes);
884    (StatusCode::ACCEPTED, body)
885}
886
887#[cfg(test)]
888mod close_pane_tests {
889    use super::*;
890    use axum::response::IntoResponse;
891    use crate::server::tests::{dispatch_apply, test_state};
892    use agentmux_common::api_types::{ClosePaneRequest, UiAutomationAuth};
893    use agentmux_common::ipc::{Command, Event};
894
895    /// Seed a workspace + tab + block, same shape as
896    /// `sagas::delete_block::tests::seed` — duplicated rather than shared
897    /// across modules (both are small, private `#[cfg(test)]` helpers).
898    async fn seed(state: &AppState) -> (String, String) {
899        seed_with(state, serde_json::Value::Null).await
900    }
901
902    async fn seed_with(state: &AppState, meta: serde_json::Value) -> (String, String) {
903        let ws_evs = dispatch_apply(state, Command::CreateWorkspace { name: "w".into() }).await;
904        let ws_id = ws_evs
905            .iter()
906            .find_map(|e| match e {
907                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
908                _ => None,
909            })
910            .unwrap();
911        let tab_evs = dispatch_apply(
912            state,
913            Command::CreateTab { workspace_id: ws_id, name: "t".into() },
914        )
915        .await;
916        let tab_id = tab_evs
917            .iter()
918            .find_map(|e| match e {
919                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
920                _ => None,
921            })
922            .unwrap();
923        let blk_evs = dispatch_apply(
924            state,
925            Command::CreateBlock { tab_id: tab_id.clone(), meta },
926        )
927        .await;
928        let block_id = blk_evs
929            .iter()
930            .find_map(|e| match e {
931                Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
932                _ => None,
933            })
934            .unwrap();
935        (tab_id, block_id)
936    }
937
938    /// Mint a real signing key for `agent_id` (same store call
939    /// `agent_open`/spawn use) and sign a fresh `UiAutomationAuth` for it —
940    /// the exact mechanism `agentmux-mcp`'s `sign_ui_automation_auth` uses,
941    /// reproduced here since this is a different crate.
942    fn sign_auth(state: &AppState, agent_id: &str) -> UiAutomationAuth {
943        let key = state.mstore.agent_jekt_key_ensure(agent_id).unwrap();
944        let ts_secs = agentmux_common::time::now_secs();
945        let sig = agentmux_common::jekt_sign::sign_jekt(
946            &key, "ui-automation-identity", agent_id, "__srv__", ts_secs, "",
947        );
948        UiAutomationAuth { agent_id: agent_id.to_string(), ts_secs, sig }
949    }
950
951    /// §7: with no arguments, ClosePane is the agent quitting itself — no
952    /// quote, so always the user's 15 s window, then its own tab only.
953    #[tokio::test]
954    async fn no_argument_close_is_a_self_quit_behind_the_user_s_window() {
955        let state = test_state();
956        let (tab_id, block_id) = seed(&state).await;
957        let sibling = dispatch_apply(&state, Command::CreateBlock { tab_id: tab_id.clone(), meta: serde_json::Value::Null })
958            .await
959            .iter()
960            .find_map(|e| match e {
961                Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
962                _ => None,
963            })
964            .unwrap();
965        let agent_id = format!("close-own-{}", uuid::Uuid::new_v4());
966        state.reactive_handler.register_agent(&agent_id, &block_id, Some(&tab_id)).unwrap();
967        let auth = sign_auth(&state, &agent_id);
968
969        let resp = handle_close_pane(
970            axum::extract::State(state.clone()),
971            None,
972            axum::Json(ClosePaneRequest { auth, block_id: None, reason: Some("done".into()) }),
973        )
974        .await
975        .into_response();
976        assert_eq!(resp.status(), axum::http::StatusCode::ACCEPTED);
977        let body = body_json(resp).await;
978        assert_eq!(body["status"], "pending_user_override", "no quote: the user is asked");
979        let request_id = body["request_id"].as_str().unwrap().to_string();
980        let pending = crate::sagas::pending_shutdown::status(&request_id).unwrap();
981        assert_eq!((pending.via.as_str(), pending.by.as_str()), ("ClosePane", agent_id.as_str()));
982        assert!(state.srv_state.lock().await.blocks.contains_key(&block_id), "still running during the window");
983
984        crate::sagas::pending_shutdown::expire_now(&request_id);
985        assert_eq!(crate::sagas::pending_shutdown::settled(&request_id).await.status, "shut_down");
986        let s = state.srv_state.lock().await;
987        assert!(!s.blocks.contains_key(&block_id), "its own tab is gone");
988        assert!(s.blocks.contains_key(&sibling), "a sibling tab keeps running");
989    }
990
991    #[tokio::test]
992    async fn cross_pane_close_removes_the_target_and_logs_the_verified_caller() {
993        let state = test_state();
994        // Caller: registered with its OWN pane, but acts on someone else's.
995        let (caller_tab, caller_block) = seed(&state).await;
996        let caller_id = format!("close-caller-{}", uuid::Uuid::new_v4());
997        state.reactive_handler.register_agent(&caller_id, &caller_block, Some(&caller_tab)).unwrap();
998        let auth = sign_auth(&state, &caller_id);
999
1000        // Target: a different agent's pane, entirely unrelated to the caller.
1001        let (target_tab, target_block) = seed(&state).await;
1002        let target_id = format!("close-target-{}", uuid::Uuid::new_v4());
1003        state.reactive_handler.register_agent(&target_id, &target_block, Some(&target_tab)).unwrap();
1004
1005        let resp = handle_close_pane(
1006            axum::extract::State(state.clone()),
1007            None,
1008            axum::Json(ClosePaneRequest {
1009                auth,
1010                block_id: Some(target_block.clone()),
1011                reason: Some("verifying the fix".to_string()),
1012            }),
1013        )
1014        .await
1015        .into_response();
1016        assert_eq!(resp.status(), axum::http::StatusCode::ACCEPTED, "another agent's pane waits for its user");
1017        let request_id = body_json(resp).await["request_id"].as_str().unwrap().to_string();
1018        assert!(state.srv_state.lock().await.blocks.contains_key(&target_block), "still running during the window");
1019        crate::sagas::pending_shutdown::expire_now(&request_id);
1020        assert_eq!(crate::sagas::pending_shutdown::settled(&request_id).await.status, "shut_down");
1021
1022        // Target pane gone; caller's own pane untouched.
1023        {
1024            let s = state.srv_state.lock().await;
1025            assert!(!s.blocks.contains_key(&target_block), "target pane must be closed");
1026            assert!(s.blocks.contains_key(&caller_block), "caller's own pane must be untouched");
1027        }
1028
1029        // Audit entry carries the CALLER's verified identity as source_agent —
1030        // not None, the gap this spec's §5.2 fixed (FleetBulkStop still has
1031        // it; this new call site must not repeat it).
1032        // get_audit_log returns most-recent-first (its own doc comment) — no
1033        // extra .rev() needed; the closed-block entry is naturally first.
1034        let entries = state.reactive_handler.get_audit_log(50);
1035        let entry = entries
1036            .iter()
1037            .find(|e| e.block_id == target_block)
1038            .expect("expected an audit entry for the closed target block");
1039        assert_eq!(entry.source_agent.as_deref(), Some(caller_id.as_str()));
1040        assert_eq!(entry.target_agent, target_id);
1041        assert!(entry.success);
1042        let reason = entry.reason.as_deref().unwrap_or_default();
1043        assert!(reason.starts_with("shut_down") && reason.contains("verifying the fix"), "{reason}");
1044    }
1045
1046    /// A browser pane has no conversation to lose: its user has 10 s to keep it, an agent's or any other pane 30 s.
1047    #[tokio::test]
1048    async fn a_browser_pane_close_gives_its_user_ten_seconds() {
1049        let state = test_state();
1050        let (caller_tab, caller_block) = seed(&state).await;
1051        let caller_id = format!("close-browser-caller-{}", uuid::Uuid::new_v4());
1052        state.reactive_handler.register_agent(&caller_id, &caller_block, Some(&caller_tab)).unwrap();
1053        let (_, browser) = seed_with(&state, json!({ "view": "browser" })).await;
1054        let resp = handle_close_pane(
1055            axum::extract::State(state.clone()),
1056            None,
1057            axum::Json(ClosePaneRequest { auth: sign_auth(&state, &caller_id), block_id: Some(browser.clone()), reason: None }),
1058        )
1059        .await
1060        .into_response();
1061        assert_eq!(resp.status(), axum::http::StatusCode::ACCEPTED);
1062        let body = body_json(resp).await;
1063        assert!((9_000..=10_000).contains(&body["wait_at_least_ms"].as_u64().unwrap()), "{body}");
1064        let request_id = body["request_id"].as_str().unwrap().to_string();
1065        assert_eq!(crate::sagas::pending_shutdown::keep(&state, &browser, &request_id), "kept_by_user");
1066    }
1067
1068    #[tokio::test]
1069    async fn keep_running_leaves_another_agent_s_pane_open() {
1070        let state = test_state();
1071        let (caller_tab, caller_block) = seed(&state).await;
1072        let caller_id = format!("close-keep-caller-{}", uuid::Uuid::new_v4());
1073        state.reactive_handler.register_agent(&caller_id, &caller_block, Some(&caller_tab)).unwrap();
1074        let (_, target_block) = seed(&state).await;
1075
1076        let resp = handle_close_pane(
1077            axum::extract::State(state.clone()),
1078            None,
1079            axum::Json(ClosePaneRequest {
1080                auth: sign_auth(&state, &caller_id),
1081                block_id: Some(target_block.clone()),
1082                reason: None,
1083            }),
1084        )
1085        .await
1086        .into_response();
1087        assert_eq!(resp.status(), axum::http::StatusCode::ACCEPTED);
1088        let body = body_json(resp).await;
1089        assert_eq!(body["status"], "pending_user_override");
1090        assert!((29_000..=30_000).contains(&body["wait_at_least_ms"].as_u64().unwrap()), "{body}");
1091        let request_id = body["request_id"].as_str().unwrap().to_string();
1092
1093        assert_eq!(crate::sagas::pending_shutdown::keep(&state, &target_block, &request_id), "kept_by_user");
1094        assert_eq!(crate::sagas::pending_shutdown::settled(&request_id).await.status, "kept_by_user");
1095        assert!(state.srv_state.lock().await.blocks.contains_key(&target_block), "the user kept it");
1096    }
1097
1098    async fn body_json(resp: axum::response::Response) -> serde_json::Value {
1099        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
1100        serde_json::from_slice(&bytes).unwrap()
1101    }
1102
1103    /// Stop pane names a tab: that tab closes, even when it is a background one, and the pane's
1104    /// other tab stays. The pane goes only with its last tab.
1105    #[tokio::test]
1106    async fn close_closes_just_the_named_tab_and_the_pane_with_its_last() {
1107        let state = test_state();
1108        let (caller_tab, caller_block) = seed(&state).await;
1109        let caller_id = format!("close-stack-caller-{}", uuid::Uuid::new_v4());
1110        state.reactive_handler.register_agent(&caller_id, &caller_block, Some(&caller_tab)).unwrap();
1111        let auth = sign_auth(&state, &caller_id);
1112
1113        let (tab_id, visible) = seed(&state).await;
1114        let background = dispatch_apply(
1115            &state,
1116            Command::CreateBlock { tab_id: tab_id.clone(), meta: serde_json::Value::Null },
1117        )
1118        .await
1119        .iter()
1120        .find_map(|e| match e {
1121            Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
1122            _ => None,
1123        })
1124        .unwrap();
1125        dispatch_apply(
1126            &state,
1127            Command::LayoutSetTree {
1128                tab_id: tab_id.clone(),
1129                new_tree: Some(agentmux_common::LayoutNode {
1130                    id: "leaf".into(),
1131                    data: Some(agentmux_common::LayoutNodeData {
1132                        block_id: visible.clone(),
1133                        block_stack: vec![visible.clone(), background.clone()],
1134                        active_block_id: visible.clone(),
1135                        ..Default::default()
1136                    }),
1137                    ..Default::default()
1138                }),
1139                correlation_id: String::new(),
1140                slices: None,
1141            },
1142        )
1143        .await;
1144
1145        let close = |block: String| {
1146            let (state, auth) = (state.clone(), auth.clone());
1147            async move {
1148                let resp = handle_close_pane(
1149                    axum::extract::State(state),
1150                    None,
1151                    axum::Json(ClosePaneRequest { auth, block_id: Some(block), reason: None }),
1152                )
1153                .await
1154                .into_response();
1155                assert_eq!(resp.status(), axum::http::StatusCode::ACCEPTED);
1156                let body = body_json(resp).await;
1157                let request_id = body["request_id"].as_str().unwrap().to_string();
1158                crate::sagas::pending_shutdown::expire_now(&request_id);
1159                crate::sagas::pending_shutdown::settled(&request_id).await;
1160                body
1161            }
1162        };
1163
1164        let queued = |state: &AppState| {
1165            let tab = state.mstore.must_get::<crate::backend::obj::Tab>(&tab_id).unwrap();
1166            let layout = state.mstore.must_get::<crate::backend::obj::LayoutState>(&tab.layoutstate).unwrap();
1167            layout.pendingbackendactions.unwrap_or_default().into_iter().filter(|a| a.actiontype == "delete").map(|a| a.blockid).collect::<Vec<_>>()
1168        };
1169        let first = close(background.clone()).await;
1170        assert_eq!(queued(&state), vec![background.clone()], "the window is told to drop the closed tab of the kept pane");
1171        assert_eq!((first["tab"].as_str(), first["pane_closes"].as_bool()), (Some(background.as_str()), Some(false)));
1172        {
1173            let s = state.srv_state.lock().await;
1174            assert!(!s.blocks.contains_key(&background), "the named tab closed");
1175            assert!(s.blocks.contains_key(&visible), "the pane's other tab stays");
1176            assert!(s.tabs[&tab_id].rootnode.is_some(), "and so does the pane");
1177        }
1178
1179        let last = close(visible.clone()).await;
1180        assert_eq!(last["pane_closes"].as_bool(), Some(true), "the last tab says the pane goes with it");
1181        let s = state.srv_state.lock().await;
1182        assert!(!s.blocks.contains_key(&visible));
1183        assert!(s.tabs[&tab_id].block_ids.is_empty());
1184        assert!(s.tabs[&tab_id].rootnode.is_none(), "pane removed with its last tab");
1185        assert!(s.blocks.contains_key(&caller_block), "caller untouched");
1186    }
1187
1188    #[tokio::test]
1189    async fn rejects_an_invalid_signature() {
1190        let state = test_state();
1191        let (tab_id, block_id) = seed(&state).await;
1192        let agent_id = format!("close-bad-sig-{}", uuid::Uuid::new_v4());
1193        state.reactive_handler.register_agent(&agent_id, &block_id, Some(&tab_id)).unwrap();
1194        // A signature signed with the WRONG key — this agent's real key was
1195        // never used, simulating a forged/corrupted signature.
1196        let bogus_key = vec![0u8; 32];
1197        let ts_secs = agentmux_common::time::now_secs();
1198        let sig = agentmux_common::jekt_sign::sign_jekt(
1199            &bogus_key, "ui-automation-identity", &agent_id, "__srv__", ts_secs, "",
1200        );
1201        let auth = UiAutomationAuth { agent_id, ts_secs, sig };
1202
1203        let resp = handle_close_pane(
1204            axum::extract::State(state.clone()),
1205            None,
1206            axum::Json(ClosePaneRequest { auth, block_id: None, reason: None }),
1207        )
1208        .await
1209        .into_response();
1210        assert_eq!(resp.status(), axum::http::StatusCode::UNAUTHORIZED);
1211
1212        // Nothing was touched.
1213        let s = state.srv_state.lock().await;
1214        assert!(s.blocks.contains_key(&block_id));
1215    }
1216}
1217
1218/// Core `pane.open` logic, shared by the WebSocket RPC handler
1219/// (`register_pane_open`) and the HTTP route `POST /api/v1/pane/open`
1220/// (`agentmux-mcp`'s `OpenEditor` tool). Creates a block for the requested
1221/// view, enqueues a layout action (split or insert), and broadcasts the
1222/// block/tab/layout updates so the frontend renders the new pane.
1223pub async fn open_pane(state: &AppState, mut cmd: CommandPaneOpenData) -> Result<PaneOpenResult, String> {
1224    steps::fold_media_into_editor(&mut cmd)?;
1225    steps::fold_reviews_into_kanban(&mut cmd);
1226    // A file of a container agent's folder opens as a read-only copy, which goes with the pane it opened in.
1227    let copy = crate::server::agent_folder_open::bind(state, &mut cmd).await?;
1228    let opened = open_checked(state, cmd).await;
1229    if let Some(copy) = &copy {
1230        match &opened {
1231            Ok(pane) => copy.opened(&pane.block_id),
1232            Err(_) => copy.discard(),
1233        }
1234    }
1235    opened
1236}
1237
1238/// [`open_pane`], once what it opens is settled.
1239async fn open_checked(state: &AppState, mut cmd: CommandPaneOpenData) -> Result<PaneOpenResult, String> {
1240    let viewer = pane::requested_viewer(&cmd)?;
1241    let bring_back = super::pane_singleton::wants_existing(&cmd);
1242    let _one_at_a_time = if bring_back { Some(super::pane_singleton::OPENING.lock().await) } else { None };
1243    let mstore = state.mstore.clone();
1244    let event_bus = state.event_bus.clone();
1245
1246    tracing::info!(view = %cmd.view, "pane.open");
1247
1248    // Use caller-supplied meta when present (widget bar path: full blockdef.meta
1249    // already known); otherwise derive from view + args via build_pane_meta.
1250    let meta = match cmd.meta.take() {
1251        Some(m) => m,
1252        None => pane::build_pane_meta(&cmd)?,
1253    };
1254
1255    // Reuse of an open Editor pane (`reuse_editor_pane`), or the one a `target_id` names.
1256    let named = steps::named_editor_target(&cmd)?;
1257    if let Some(result) = steps::reuse_editor_pane(state, &cmd, named, viewer).await? {
1258        return Ok(result);
1259    }
1260
1261    // Resolve tab: explicit tab_id wins; otherwise, if the caller told us
1262    // which block to place this pane relative to (split_reference_block_id),
1263    // resolve THAT block's own tab rather than falling back to "whichever
1264    // tab happens to be globally active" — a caller specifying a relative
1265    // block virtually always means "my own tab" (codex P2 on PR #2404: the
1266    // editor-reuse check above already resolves this correctly-scoped tab
1267    // for its own lookup, but previously discarded it whenever reuse didn't
1268    // apply — e.g. a floating request, or no existing Editor pane yet —
1269    // silently falling through to the flakier "first workspace's active
1270    // tab" heuristic for the actual block creation/placement below, which
1271    // can place a pane in the wrong tab entirely in a multi-tab setup).
1272    let tab_id = super::pane_open_tab::resolve_open_tab(
1273        &mstore,
1274        cmd.tab_id.as_deref(),
1275        cmd.split_reference_block_id.as_deref(),
1276        cmd.origin_tab_id.as_deref(),
1277    )?;
1278
1279    // A management pane the window already has is returned, not opened again.
1280    if bring_back {
1281        if let Some((block_id, tab_id)) = super::pane_singleton::in_window(&mstore, &tab_id, &cmd.view) {
1282            tracing::info!(block_id = %block_id, view = %cmd.view, "pane.open: the window already has this pane");
1283            super::pane_singleton::apply_to_existing(state, &block_id, &cmd.view, &meta).await;
1284            return Ok(PaneOpenResult::docked(block_id, tab_id, cmd.view, false));
1285        }
1286    }
1287
1288    // Floating path (SPEC_OPENEDITOR_FLOATING_AND_COLLAPSED_TREE_2026_06_16):
1289    // create the block in a fresh floating workspace (via reducer CreateBlock +
1290    // the existing tear_off_block saga) and signal the source window's frontend
1291    // to materialize the chromeless OS window — srv can't open windows itself.
1292    if cmd.floating == Some(true) {
1293        return pane::open_pane_floating(state, &mstore, &event_bus, &cmd, tab_id, meta).await;
1294    }
1295
1296    if let Some(target) = cmd.stack_onto_block_id.clone().filter(|t| !t.is_empty()) {
1297        return steps::open_stacked(state, &cmd, target, meta).await;
1298    }
1299
1300    if cmd.skip_placement == Some(true) {
1301        return steps::open_unplaced(state, cmd.view, tab_id, meta).await;
1302    }
1303
1304    steps::open_docked(state, &cmd, tab_id, meta).await
1305}