Skip to main content

agentmux_srv/server/app_api/
folder_overlap.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A host agent that shares a folder with a container agent: which container agents, and the person going ahead
5//! with one (`backend::folder_overlap`). Anyone may ask which; only the AgentMux window goes ahead or says no to an
6//! agent's ask for the go-ahead (`folder_overlap_ask`). A caller that is not the window, an agent's connection or one
7//! that has not proven it is the window, is refused with what to do instead. Each answer is recorded as the person's.
8
9use super::*;
10use crate::backend::folder_overlap as overlap;
11use crate::backend::folder_overlap_asks::{asks, FolderAsk};
12
13/// What a caller is told when it is not the window.
14pub(crate) const ONLY_THE_PERSON_GOES_AHEAD: &str = "only the person goes ahead with a host agent sharing a folder with a container agent, from the AgentMux window: give the agents separate workspaces, or bind the shared folder read-only into the container agent (a volume ending in :ro)";
15
16fn check(state: &AppState, cmd: CommandFolderOverlapCheckData) -> Result<FolderOverlapCheckResult, String> {
17    let def = state
18        .mstore
19        .agent_def_get(&cmd.agent_id)
20        .map_err(|e| format!("folderoverlapcheck: {e}"))?
21        .ok_or_else(|| format!("folderoverlapcheck: agent {} not found", cmd.agent_id))?;
22    let folder = cmd.folder.as_deref().map(str::trim).filter(|dir| !dir.is_empty()).map(crate::backend::base::expand_home_dir_safe);
23    // No folder named: the one `agent.open` runs the agent in, so the window asks about what srv would refuse.
24    let folder = folder.unwrap_or_else(|| overlap::open_folder(&def));
25    let overlaps = overlap::unchosen(overlap::of(&state.mstore, &def, Some(&folder)));
26    Ok(FolderOverlapCheckResult { overlaps })
27}
28
29/// Tells every window the asks now waiting.
30pub(crate) fn publish_asks(state: &AppState) {
31    let event = crate::backend::mps_events::FolderOverlapAsksEvent { asks: asks().list(agentmux_common::time::now_ms_u64()) };
32    state.broker.publish_event::<crate::backend::mps_events::FolderOverlapAsks>(&event, vec![], 0);
33}
34
35/// Restart resume left host agent `agent_id` (its parked block `block_id`) stopped for want of the person's go-ahead: one
36/// ask per pair it shares a folder with, with no asking agent, which the window shows as a card for the agent's block.
37pub(crate) fn ask_for_resumed(state: &AppState, agent_id: &str, block_id: &str) {
38    let Ok(Some(host)) = state.mstore.agent_def_get(agent_id) else { return };
39    let now = agentmux_common::time::now_ms_u64();
40    for o in overlap::unchosen(overlap::of(&state.mstore, &host, Some(&overlap::open_folder(&host)))) {
41        let ask = FolderAsk {
42            host_id: o.host_id,
43            host_name: o.host_name,
44            container_id: o.container_id,
45            container_name: o.container_name,
46            agent: String::new(),
47            block_id: block_id.to_string(),
48            requested_ms: now,
49        };
50        asks().ask(ask, now);
51    }
52    publish_asks(state);
53}
54
55/// An agent is deleted: what it asked, and what was asked about it, goes with it.
56pub(crate) fn forget_asks_of(state: &AppState, id: &str) {
57    asks().forget_agent(id);
58    publish_asks(state);
59}
60
61/// The name of agent `id`, or its id when it has none on record.
62fn name_of(state: &AppState, id: &str) -> String {
63    state.mstore.agent_def_get(id).ok().flatten().map(|def| def.name).unwrap_or_else(|| id.to_string())
64}
65
66/// Records what the person declined, or what an agent asked, in the audit log: `by` is the asking agent's slug, and
67/// `None` for the person's own window. The go-ahead is recorded by `backend::folder_overlap::accept_as`, which writes
68/// its row before the choice it records.
69pub(crate) fn audit(state: &AppState, by: Option<&str>, action: &str, host_id: &str, container_id: &str, block_id: &str) {
70    let (host, container) = (name_of(state, host_id), name_of(state, container_id));
71    let note = overlap::row_note(action, (host_id, &host), (container_id, &container));
72    tracing::info!(action, "{note}");
73    let request_id = uuid::Uuid::new_v4().to_string();
74    state.reactive_handler.log_fleet_action_audit(by, &host, block_id, action, true, None, &request_id, Some(&note));
75}
76
77fn accept(state: &AppState, cmd: CommandFolderOverlapAcceptData) -> Result<FolderOverlapAcceptResult, String> {
78    if !overlap::is_a_pair(&state.mstore, &cmd.host_id, &cmd.container_id) {
79        return Err("folderoverlapaccept: needs a host agent and a container agent".to_string());
80    }
81    // The go-ahead is the window's: its audit row is written first, then the choice it records.
82    overlap::accept_as((&cmd.host_id, &name_of(state, &cmd.host_id)), (&cmd.container_id, &name_of(state, &cmd.container_id)))?;
83    // An agent's ask for this pair is answered, whichever pane or window the person went ahead in.
84    let now = agentmux_common::time::now_ms_u64();
85    let left_stopped_in = asks().list(now).into_iter().find(|a| a.agent.is_empty() && a.host_id == cmd.host_id && a.container_id == cmd.container_id).map(|a| a.block_id);
86    asks().answer(&cmd.host_id, &cmd.container_id, true, now);
87    publish_asks(state);
88    if let Some(block_id) = left_stopped_in {
89        resume_when_nothing_waits(state, &cmd.host_id, block_id);
90    }
91    Ok(FolderOverlapAcceptResult { chosen: true })
92}
93
94/// Restart resume left the host agent stopped for the pair just gone ahead with: once no pair holds it, it comes back.
95fn resume_when_nothing_waits(state: &AppState, host_id: &str, block_id: String) {
96    let waits = state.mstore.agent_def_get(host_id).ok().flatten().and_then(|def| overlap::waiting_reason(&state.mstore, &def)).is_some();
97    if waits {
98        return;
99    }
100    let (state, host_id) = (state.clone(), host_id.to_string());
101    tokio::spawn(async move { crate::server::restart_resume::resume_after_go_ahead(&state, &host_id, &block_id).await });
102}
103
104fn decline(state: &AppState, cmd: CommandFolderOverlapDeclineData) -> Result<FolderOverlapDeclineResult, String> {
105    if !overlap::is_a_pair(&state.mstore, &cmd.host_id, &cmd.container_id) {
106        return Err("folderoverlapdecline: needs a host agent and a container agent".to_string());
107    }
108    // The pair stays as it was: no choice is kept, so every refusal for it stands.
109    let was_asked = asks().answer(&cmd.host_id, &cmd.container_id, false, agentmux_common::time::now_ms_u64());
110    publish_asks(state);
111    audit(state, None, "folder-overlap.decline", &cmd.host_id, &cmd.container_id, "");
112    Ok(FolderOverlapDeclineResult { declined: was_asked })
113}
114
115pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
116    let check_state = state.clone();
117    engine.register_typed(COMMAND_FOLDER_OVERLAP_CHECK, move |cmd: CommandFolderOverlapCheckData, _ctx| {
118        let state = check_state.clone();
119        async move { check(&state, cmd) }
120    });
121    let accept_state = state.clone();
122    engine.register_typed(COMMAND_FOLDER_OVERLAP_ACCEPT, move |cmd: CommandFolderOverlapAcceptData, ctx| {
123        let state = accept_state.clone();
124        async move {
125            ctx.operator_only(ONLY_THE_PERSON_GOES_AHEAD)?;
126            accept(&state, cmd)
127        }
128    });
129    let decline_state = state.clone();
130    engine.register_typed(COMMAND_FOLDER_OVERLAP_DECLINE, move |cmd: CommandFolderOverlapDeclineData, ctx| {
131        let state = decline_state.clone();
132        async move {
133            ctx.operator_only(ONLY_THE_PERSON_GOES_AHEAD)?;
134            decline(&state, cmd)
135        }
136    });
137    engine.register_typed(COMMAND_FOLDER_OVERLAP_ASKS, |_req: serde_json::Value, _ctx| async move {
138        Ok(FolderOverlapAsksResult { asks: asks().list(agentmux_common::time::now_ms_u64()) })
139    });
140}