Skip to main content

agentmux_srv/server/
pane_caller.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Whose pane a window command acts on, for a connection registered as an agent.
5//!
6//! An agent acts as itself: on its own pane (or a sub-block of it) a window command runs, and the action record names
7//! the agent. It does not act as the person, and it does not act as another agent: a pane another agent runs, or one
8//! no agent runs (the person's terminal), is refused with what to do instead. A connection that is not registered as
9//! an agent (the window, or one nothing proved) is not affected.
10
11use crate::backend::obj::Block;
12use crate::backend::rpc_types::RpcContext;
13use crate::backend::storage::store::Store;
14
15/// The slug of the agent that runs `block_id`: the agent on the pane, or on the pane a sub-block hangs from.
16fn pane_agent(mstore: &Store, block_id: &str) -> Option<String> {
17    let direct = |id: &str| crate::backend::spawn_env::identity::block_agent_slug(mstore, id);
18    direct(block_id).or_else(|| {
19        let block: Block = mstore.get(block_id).ok().flatten()?;
20        direct(block.parentoref.strip_prefix("block:")?)
21    })
22}
23
24/// Whether the connection `ctx` may `doing` on `block_id`: always, unless it is registered as an agent and the pane is
25/// not the one that agent runs. `Err` is the refusal, saying what the agent can do instead.
26pub(crate) fn agent_acts_on_own_pane(mstore: &Store, ctx: &RpcContext, block_id: &str, doing: &str) -> Result<(), String> {
27    if ctx.agent_id.is_empty() {
28        return Ok(());
29    }
30    match pane_agent(mstore, block_id) {
31        Some(owner) if owner.eq_ignore_ascii_case(&ctx.agent_id) => Ok(()),
32        Some(_) => Err(format!(
33            "FORBIDDEN: {doing} on another agent's pane is that agent's own act; do it on your own pane, or ask that agent with Message send"
34        )),
35        None => Err(format!(
36            "FORBIDDEN: {doing} on a pane no agent runs is the person's act; do it on your own pane, or ask the person"
37        )),
38    }
39}
40
41/// Whether the connection `ctx` may delete the block `block_id` as a sub-block: always, unless it is registered as an agent
42/// and the block is not a sub-block of the pane that agent runs. The pane itself is not a sub-block of anything, so an agent
43/// never deletes its own pane this way.
44pub(crate) fn agent_deletes_own_sub_block(mstore: &Store, ctx: &RpcContext, block_id: &str) -> Result<(), String> {
45    agent_acts_on_own_pane(mstore, ctx, block_id, "deleting a sub-block")?;
46    if ctx.agent_id.is_empty() {
47        return Ok(());
48    }
49    let hangs_from_a_pane = mstore.get::<Block>(block_id).ok().flatten().is_some_and(|b| b.parentoref.starts_with("block:"));
50    if hangs_from_a_pane {
51        Ok(())
52    } else {
53        Err("FORBIDDEN: deleting a pane is the person's act; an agent releases its shell drawer with Terminal close and closes a pane it opened with Pane close".to_string())
54    }
55}
56
57/// Whether the connection `ctx` may write the meta of `oref` (`block:<id>`, `tab:<id>`, ...): always, unless it is registered
58/// as an agent. An agent writes the meta of its own pane; a tab, window, workspace or any other object holds the person's
59/// layout, names and settings, so it is refused with what to do instead.
60pub(crate) fn agent_writes_meta_of(mstore: &Store, ctx: &RpcContext, oref: &str) -> Result<(), String> {
61    if ctx.agent_id.is_empty() {
62        return Ok(());
63    }
64    match oref.split_once(':') {
65        Some(("block", block_id)) => agent_acts_on_own_pane(mstore, ctx, block_id, "writing pane meta"),
66        Some((kind, _)) => Err(format!(
67            "FORBIDDEN: writing a {kind}'s meta is the person's act (the layout, names and settings of their window); an agent changes its own pane with the Pane and UI tools; to change this, ask the person"
68        )),
69        None => Err("FORBIDDEN: writing this object's meta is the person's act; an agent changes its own pane with the Pane and UI tools; to change this, ask the person".to_string()),
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76    use crate::backend::storage::agents::test_agent_def;
77
78    /// Two agents with a pane each, and a sub-block under the first one's pane, in a fresh store.
79    fn fleet() -> Store {
80        let store = Store::open_in_memory().unwrap();
81        for id in ["pane-agent-a", "pane-agent-b"] {
82            let mut def = test_agent_def(id, id, "claude", "agent", 1, "");
83            def.slug = id.to_string();
84            store.agent_def_insert(&mut def).unwrap();
85        }
86        let mut block = |oid: &str, agent: Option<&str>, parent: &str| {
87            let mut b = Block { oid: oid.to_string(), parentoref: parent.to_string(), ..Default::default() };
88            if let Some(agent) = agent {
89                b.meta.insert("agentId".to_string(), serde_json::json!(agent));
90            }
91            store.insert(&mut b).unwrap();
92        };
93        block("pane-a", Some("pane-agent-a"), "");
94        block("pane-b", Some("pane-agent-b"), "");
95        block("pane-a-shell", None, "block:pane-a");
96        block("persons-terminal", None, "");
97        store
98    }
99
100    fn agent(slug: &str) -> RpcContext {
101        RpcContext { agent_id: slug.to_string(), ..Default::default() }
102    }
103
104    #[test]
105    fn an_agent_acts_on_its_own_pane_and_on_a_sub_block_of_it() {
106        let store = fleet();
107        for block in ["pane-a", "pane-a-shell"] {
108            assert_eq!(agent_acts_on_own_pane(&store, &agent("pane-agent-a"), block, "x"), Ok(()), "{block}");
109        }
110        assert_eq!(agent_acts_on_own_pane(&store, &agent("PANE-AGENT-A"), "pane-a", "x"), Ok(()), "the slug is read without case");
111    }
112
113    #[test]
114    fn an_agent_is_refused_on_another_agents_pane_and_on_one_no_agent_runs_and_told_what_to_do() {
115        let store = fleet();
116        let other = agent_acts_on_own_pane(&store, &agent("pane-agent-a"), "pane-b", "restart a controller").unwrap_err();
117        assert!(other.starts_with("FORBIDDEN") && other.contains("another agent's pane") && other.contains("Message send"), "{other}");
118        for block in ["persons-terminal", "no-such-pane"] {
119            let refused = agent_acts_on_own_pane(&store, &agent("pane-agent-a"), block, "restart a controller").unwrap_err();
120            assert!(refused.starts_with("FORBIDDEN") && refused.contains("no agent runs") && refused.contains("ask the person"), "{refused}");
121        }
122    }
123
124    #[test]
125    fn the_window_and_an_unproven_connection_are_not_affected() {
126        let store = fleet();
127        for ctx in [RpcContext::operator_for_tests(), RpcContext::default()] {
128            for block in ["pane-a", "pane-b", "persons-terminal"] {
129                assert_eq!(agent_acts_on_own_pane(&store, &ctx, block, "x"), Ok(()), "{block}");
130            }
131        }
132    }
133}
134
135#[cfg(test)]
136#[path = "tests/pane_caller_tests.rs"]
137mod handler_tests;