Skip to main content

agentmux_srv/server/app_api/
agent_reconcile.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One pane per agent, for the layouts that already hold more (task #5419). An older build, an import or a
5//! restore can leave two panes of one agent. The one that keeps the agent is the one running it, else the
6//! one it launched last ([`super::agent_block::agent_blocks_by_uid`]); every other becomes a closed pane
7//! that says where the agent is and offers Go there and Move here (`open_in_other_pane`, the recovery the
8//! duplicate-pane spec built), so what a person types there is never taken in silence.
9//!
10//! Runs once at startup and after a layout is opened. Each duplicate is one log line and one entry in
11//! Warden's Audit (`agent.reconcile_duplicate_pane`, by `agentmux`); a pane already closed this way for the
12//! same keeper is left alone, so a second run changes nothing.
13
14use super::agent_block::{agent_blocks_by_uid, blocks_in_tabs_or_parked, describe_tab, AgentBlock};
15use super::agent_attach::{set_desired, DESIRED_STOPPED};
16use crate::backend::blockcontroller;
17use crate::backend::obj::{self, Block};
18use crate::backend::rpc::action_record::{ActionRecord, Target};
19use crate::backend::rpc::actor::Actor;
20use crate::backend::storage::store::Store;
21use crate::server::AppState;
22use std::collections::BTreeSet;
23
24/// The command named in the audit.
25pub(crate) const AUDIT_COMMAND: &str = "agent.reconcile_duplicate_pane";
26
27/// An agent's pane that is not the agent's: `keeper` holds it.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub(crate) struct Duplicate {
30    pub agent: String,
31    pub block_id: String,
32    pub tab_id: Option<String>,
33    pub keeper: String,
34    pub keeper_tab_id: Option<String>,
35}
36
37/// The agents (by the id their blocks resolve to) that have a pane or a parked block.
38fn agents_with_blocks(mstore: &Store) -> Result<BTreeSet<String>, String> {
39    let mut agents = BTreeSet::new();
40    for (block, _) in blocks_in_tabs_or_parked(mstore)? {
41        if obj::meta_get_string(&block.meta, "view", "") != "agent" {
42            continue;
43        }
44        let bound = obj::meta_get_string(&block.meta, "agentInstanceId", "");
45        let id = if bound.is_empty() { obj::meta_get_string(&block.meta, "agentId", "") } else { bound };
46        if !id.is_empty() {
47            agents.insert(id);
48        }
49    }
50    Ok(agents)
51}
52
53/// Every pane that is a second (or later) pane of an agent. A template's id is skipped: the panes launched
54/// from it are different agents, told apart by their instance.
55pub(crate) fn find_duplicates(mstore: &Store) -> Result<Vec<Duplicate>, String> {
56    let mut out = Vec::new();
57    for agent in agents_with_blocks(mstore)? {
58        if mstore.instance_get(&agent).ok().flatten().is_none() {
59            continue;
60        }
61        let mut panes = agent_blocks_by_uid(mstore, &agent)?.into_iter();
62        let Some(AgentBlock { block: keeper, tab_id: keeper_tab_id }) = panes.next() else { continue };
63        for AgentBlock { block, tab_id } in panes {
64            out.push(Duplicate { agent: agent.clone(), block_id: block.oid, tab_id, keeper: keeper.oid.clone(), keeper_tab_id: keeper_tab_id.clone() });
65        }
66    }
67    Ok(out)
68}
69
70fn place(mstore: &Store, tab_id: &Option<String>) -> String {
71    match tab_id {
72        Some(tab) => describe_tab(mstore, tab),
73        None => "no tab (parked)".to_string(),
74    }
75}
76
77/// Whether the pane already says it is closed for `keeper`.
78fn already_closed_for(block: &Block, keeper: &str) -> bool {
79    block
80        .meta
81        .get(blockcontroller::core::META_LAST_FAILURE)
82        .is_some_and(|f| f.get("code").and_then(|c| c.as_str()) == Some("open_in_other_pane") && f.get("holderBlockId").and_then(|h| h.as_str()) == Some(keeper))
83}
84
85/// Close one duplicate: it says where the agent is, and the agent is not wanted running by it.
86fn close_duplicate(state: &AppState, d: &Duplicate) {
87    let mstore = &state.mstore;
88    let name = mstore.instance_get(&d.agent).ok().flatten().and_then(|_| mstore.agent_def_get(&d.agent).ok().flatten()).map(|def| def.name).unwrap_or_else(|| "This agent".to_string());
89    let (here, there) = (place(mstore, &d.tab_id), place(mstore, &d.keeper_tab_id));
90    tracing::warn!(
91        agent = %d.agent, block_id = %d.block_id, kept = %d.keeper,
92        "agent_panes.duplicate: {name} had a second pane in {here}; its pane in {there} is kept and this one is closed"
93    );
94    let mut failure = crate::agents::failure::classify(None, None, &crate::backend::blockcontroller::persistent::held_elsewhere_error(&d.keeper, false), None);
95    failure.title = format!("{name} moved to {there}");
96    failure.detail = format!(
97        "{name} is open in {there}, so this pane is closed. Go there to keep working in it, or move it here: the other pane stops and this one resumes the same conversation."
98    );
99    crate::server::agent_takeover::surface_classified_failure(state, &d.block_id, &failure);
100    set_desired(mstore, &d.block_id, DESIRED_STOPPED);
101    crate::backend::reactive::get_global_handler().audit_action(&ActionRecord {
102        actor: Actor::Srv,
103        command: AUDIT_COMMAND.to_string(),
104        target: Target { agent: Some(name), block_id: Some(d.block_id.clone()), subject: Some(d.keeper.clone()) },
105        request_id: String::new(),
106        error: None,
107    });
108}
109
110/// Close every duplicate pane there is. Returns how many it closed now.
111pub(crate) fn reconcile_duplicate_panes(state: &AppState) -> usize {
112    let duplicates = match find_duplicates(&state.mstore) {
113        Ok(d) => d,
114        Err(e) => {
115            tracing::warn!("agent_panes.duplicate: could not look for duplicate agent panes: {e}");
116            return 0;
117        }
118    };
119    let mut closed = 0;
120    for d in &duplicates {
121        let Ok(Some(block)) = state.mstore.get::<Block>(&d.block_id) else { continue };
122        if already_closed_for(&block, &d.keeper) {
123            continue;
124        }
125        close_duplicate(state, d);
126        closed += 1;
127    }
128    if closed > 0 {
129        tracing::warn!("agent_panes.duplicate: closed {closed} duplicate agent pane(s)");
130    }
131    closed
132}
133
134/// At startup, before any window shows the panes.
135pub(crate) fn install(state: &AppState) {
136    let state = state.clone();
137    tokio::task::spawn_blocking(move || {
138        reconcile_duplicate_panes(&state);
139    });
140}