Skip to main content

agentmux_srv_core/backend/
endpoint_notice.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The notice that goes with pointing an agent at another model server (`Agents env_set` of
5//! `ANTHROPIC_BASE_URL` and the variables that go with it, `backend::agent_env`), and the window in
6//! which anyone can undo it.
7//!
8//! The change is written at once and applies at the agent's next launch. For [`WINDOW_MS`] after it,
9//! a card in the agent's pane and a line in My Agents say who pointed it where, with an Undo that
10//! puts the environment back as it was. Past the window the change stands and is changed like any
11//! other, in My Agents or by `env_set`. The notice holds the text from before server-side only: it can
12//! hold the operator's own variables, so the event carries the address and model names and never it.
13
14use serde::Serialize;
15use std::sync::Mutex;
16
17/// How long an Undo is offered.
18pub const WINDOW_MS: i64 = 30_000;
19
20/// `agent:endpoint-notice`: an agent's model server was changed, or the change was undone.
21#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
22#[ts(export, export_to = "../../../frontend/types/rpc/")]
23pub struct EndpointNoticeEvent {
24    pub id: String,
25    pub agent_id: String,
26    pub agent_slug: String,
27    pub agent_name: String,
28    /// The agent that made the change (its display name), as srv's record has it.
29    pub by: String,
30    /// The server the agent is pointed at now, if it is.
31    #[serde(skip_serializing_if = "Option::is_none")]
32    #[ts(optional)]
33    pub base_url: Option<String>,
34    /// The model it was given, if one was named.
35    #[serde(skip_serializing_if = "Option::is_none")]
36    #[ts(optional)]
37    pub model: Option<String>,
38    /// The agent was pointed back at Anthropic: no server of its own any more.
39    pub cleared: bool,
40    /// `open`, or `undone` once the change was put back.
41    pub state: String,
42    #[ts(type = "number")]
43    pub window_ms: i64,
44    /// When the Undo stops being offered (epoch ms).
45    #[ts(type = "number")]
46    pub expires_at: i64,
47}
48
49struct Held {
50    event: EndpointNoticeEvent,
51    /// The environment before the change, and after it: Undo needs the first, and refuses when the
52    /// second is no longer what is stored.
53    previous: String,
54    applied: String,
55}
56
57static HELD: Mutex<Vec<Held>> = Mutex::new(Vec::new());
58
59/// What the change leaves the agent pointed at, from the new environment text.
60pub struct Pointed {
61    pub base_url: Option<String>,
62    pub model: Option<String>,
63    pub cleared: bool,
64    /// The address is not what it was: set, changed or taken away. A new key or timeout on the same address is not.
65    pub moved: bool,
66}
67
68/// Where `new` points the agent, against `old`.
69pub fn pointed(old: &str, new: &str) -> Pointed {
70    let (old, new) = (super::agent_env::effective(old), super::agent_env::effective(new));
71    let url = new.get("ANTHROPIC_BASE_URL").map(|u| u.trim().to_string()).filter(|u| !u.is_empty());
72    let model = new
73        .get("ANTHROPIC_MODEL")
74        .or_else(|| new.get("ANTHROPIC_DEFAULT_SONNET_MODEL"))
75        .map(|m| m.trim().to_string())
76        .filter(|m| !m.is_empty());
77    let old_url = old.get("ANTHROPIC_BASE_URL").map(|u| u.trim().to_string()).filter(|u| !u.is_empty());
78    Pointed { cleared: url.is_none() && old_url.is_some(), moved: old_url != url, base_url: url, model }
79}
80
81/// Opens the notice for a change and keeps what Undo needs. Returns the event to publish.
82pub fn open(agent: (&str, &str, &str), by: &str, pointed: Pointed, previous: &str, applied: &str, now: i64) -> EndpointNoticeEvent {
83    let event = EndpointNoticeEvent {
84        id: uuid::Uuid::new_v4().to_string(),
85        agent_id: agent.0.to_string(),
86        agent_slug: agent.1.to_string(),
87        agent_name: agent.2.to_string(),
88        by: by.to_string(),
89        base_url: pointed.base_url,
90        model: pointed.model,
91        cleared: pointed.cleared,
92        state: "open".to_string(),
93        window_ms: WINDOW_MS,
94        expires_at: now + WINDOW_MS,
95    };
96    let mut held = HELD.lock().unwrap_or_else(|p| p.into_inner());
97    held.retain(|h| h.event.expires_at > now);
98    held.push(Held { event: event.clone(), previous: previous.to_string(), applied: applied.to_string() });
99    event
100}
101
102/// The agent a held notice is for, if it is still held.
103pub fn agent_id_of(id: &str) -> Option<String> {
104    HELD.lock().unwrap_or_else(|p| p.into_inner()).iter().find(|h| h.event.id == id).map(|h| h.event.agent_id.clone())
105}
106
107/// Why an Undo was not done.
108#[derive(Debug, PartialEq, Eq)]
109pub enum Refusal {
110    /// No such notice, or it was already undone.
111    Unknown,
112    /// The window is over: the change stands.
113    Expired,
114    /// The environment was changed again since: putting the old text back would undo more than this change.
115    ChangedSince,
116}
117
118impl Refusal {
119    pub fn words(&self) -> &'static str {
120        match self {
121            Refusal::Unknown => "that change was already undone, or srv no longer has it",
122            Refusal::Expired => "the undo window is over; change the environment in My Agents",
123            Refusal::ChangedSince => "the environment was changed again since; change it in My Agents",
124        }
125    }
126}
127
128/// Checks the notice `id` for an Undo: the text to put back and the event that says it was undone.
129/// `current` is the environment as stored now. The notice stays held until [`finish_undo`], so a write
130/// that fails can be tried again inside the window.
131pub fn check_for_undo(id: &str, current: &str, now: i64) -> Result<(String, EndpointNoticeEvent), Refusal> {
132    let mut held = HELD.lock().unwrap_or_else(|p| p.into_inner());
133    let at = held.iter().position(|h| h.event.id == id).ok_or(Refusal::Unknown)?;
134    if now > held[at].event.expires_at {
135        held.remove(at);
136        return Err(Refusal::Expired);
137    }
138    if held[at].applied != current {
139        return Err(Refusal::ChangedSince);
140    }
141    let mut event = held[at].event.clone();
142    event.state = "undone".to_string();
143    Ok((held[at].previous.clone(), event))
144}
145
146/// The environment was put back: the notice cannot be undone again.
147pub fn finish_undo(id: &str) {
148    HELD.lock().unwrap_or_else(|p| p.into_inner()).retain(|h| h.event.id != id);
149}
150
151#[cfg(test)]
152fn take_for_undo(id: &str, current: &str, now: i64) -> Result<(String, EndpointNoticeEvent), Refusal> {
153    let taken = check_for_undo(id, current, now)?;
154    finish_undo(id);
155    Ok(taken)
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    const BEFORE: &str = "TZ=UTC\nOPERATOR_NOTE=keep\n";
163    const AFTER: &str = "TZ=UTC\nOPERATOR_NOTE=keep\nANTHROPIC_BASE_URL=http://192.0.2.68:11434\nANTHROPIC_MODEL=flint:40b-a2b\nANTHROPIC_AUTH_TOKEN=ollama\n";
164
165    fn opened(now: i64) -> EndpointNoticeEvent {
166        open(("a1", "lolly", "Lolly"), "AgentY", pointed(BEFORE, AFTER), BEFORE, AFTER, now)
167    }
168
169    #[test]
170    fn the_event_names_the_server_and_model_and_never_a_key_or_the_old_text() {
171        let event = opened(1_000);
172        assert_eq!(event.base_url.as_deref(), Some("http://192.0.2.68:11434"));
173        assert_eq!(event.model.as_deref(), Some("flint:40b-a2b"));
174        assert_eq!((event.by.as_str(), event.state.as_str(), event.expires_at), ("AgentY", "open", 1_000 + WINDOW_MS));
175        let wire = serde_json::to_string(&event).unwrap();
176        assert!(!wire.contains("ollama") && !wire.contains("OPERATOR_NOTE"), "{wire}");
177    }
178
179    #[test]
180    fn pointing_back_at_anthropic_is_a_clear() {
181        let p = pointed(AFTER, BEFORE);
182        assert!(p.cleared);
183        assert_eq!(p.base_url, None);
184        assert!(!pointed(BEFORE, AFTER).cleared);
185        assert!(pointed(AFTER, BEFORE).moved && pointed(BEFORE, AFTER).moved);
186        // The same address with another key or model is no new address.
187        let other_key = AFTER.replace("ollama", "none");
188        assert!(!pointed(AFTER, &other_key).moved);
189        assert!(!pointed(BEFORE, "TZ=UTC\n").moved);
190    }
191
192    #[test]
193    fn undo_in_the_window_gives_the_old_text_back_once() {
194        let event = opened(1_000);
195        let (text, undone) = take_for_undo(&event.id, AFTER, 1_000 + WINDOW_MS).unwrap();
196        assert_eq!(text, BEFORE);
197        assert_eq!(undone.state, "undone");
198        assert_eq!(take_for_undo(&event.id, BEFORE, 2_000), Err(Refusal::Unknown), "once");
199    }
200
201    #[test]
202    fn a_notice_stays_until_the_undo_was_written() {
203        let event = opened(1_000);
204        assert!(check_for_undo(&event.id, AFTER, 2_000).is_ok());
205        assert!(check_for_undo(&event.id, AFTER, 2_001).is_ok(), "a failed write can be tried again");
206        finish_undo(&event.id);
207        assert_eq!(check_for_undo(&event.id, AFTER, 2_002), Err(Refusal::Unknown));
208    }
209
210    #[test]
211    fn undo_after_the_window_or_after_a_further_change_is_refused() {
212        let late = opened(1_000);
213        assert_eq!(take_for_undo(&late.id, AFTER, 1_000 + WINDOW_MS + 1), Err(Refusal::Expired));
214        let changed = opened(1_000);
215        assert_eq!(take_for_undo(&changed.id, "TZ=UTC\n", 2_000), Err(Refusal::ChangedSince));
216        // Refused for being changed, it is still there once the text matches again.
217        assert!(take_for_undo(&changed.id, AFTER, 2_000).is_ok());
218        assert_eq!(take_for_undo("no-such-notice", AFTER, 2_000), Err(Refusal::Unknown));
219    }
220}