Skip to main content

agentmux_srv/sagas/
credential_notice.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A container agent that can't get a credential, told to the person in the agent's own pane.
5//!
6//! A container agent has no credential of its own: its GitHub token and its AWS session are brokered by the host,
7//! one use at a time. When the host refuses (GitHub isn't connected or the Cloud sign-in lapsed, the host's AWS login
8//! lapsed), the agent reads the reason in its shell and nothing else shows it: the person looking at the pane sees an
9//! agent that is stuck. This puts the same sentence the agent read on the pane as a line, with a link to Connectors
10//! for GitHub, and takes it away when the credential is given again.
11//!
12//! It asks nothing and waits for nothing (no countdown, no buttons): it is the `agent:notice` line, kept until the
13//! credential works or the person dismisses it. One line per cause per agent per hour, so a retry loop doesn't
14//! stack lines. It is drawn from srv's own record: the agent never supplies the words.
15
16use std::collections::HashMap;
17use std::sync::{LazyLock, Mutex};
18
19use crate::server::AppState;
20use agentmux_common::time::now_ms;
21
22use super::agent_notice::NoticeView;
23
24/// How long a line counts as "already shown" before a new refusal puts it up again.
25const REPEAT_MS: i64 = 60 * 60 * 1000;
26/// The most of the sentence the line carries (the tooltip carries the same).
27const MAX_SENTENCE: usize = 240;
28
29/// What the agent could not get.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31pub enum Cause {
32    Github,
33    Aws,
34}
35
36impl Cause {
37    fn kind(self) -> &'static str {
38        match self {
39            Cause::Github => "github",
40            Cause::Aws => "aws",
41        }
42    }
43}
44
45struct Shown {
46    id: String,
47    at_ms: i64,
48}
49
50static SHOWN: LazyLock<Mutex<HashMap<(String, Cause), Shown>>> = LazyLock::new(Default::default);
51
52fn shown() -> std::sync::MutexGuard<'static, HashMap<(String, Cause), Shown>> {
53    SHOWN.lock().unwrap_or_else(|e| e.into_inner())
54}
55
56/// What a refusal does to the pane: nothing (the line is still up), or put a line up, taking down the old one first
57/// when it is an hour old.
58#[derive(Debug, PartialEq, Eq)]
59struct Plan {
60    take_down: Option<String>,
61    put_up: String,
62}
63
64fn plan(map: &mut HashMap<(String, Cause), Shown>, slug: &str, cause: Cause, now: i64) -> Option<Plan> {
65    let key = (slug.to_string(), cause);
66    let old = map.get(&key);
67    if old.is_some_and(|s| now - s.at_ms < REPEAT_MS) {
68        return None;
69    }
70    let take_down = old.map(|s| s.id.clone());
71    let put_up = uuid::Uuid::new_v4().to_string();
72    map.insert(key, Shown { id: put_up.clone(), at_ms: now });
73    Some(Plan { take_down, put_up })
74}
75
76fn sentence(text: &str) -> String {
77    let one_line = text.split_whitespace().collect::<Vec<_>>().join(" ");
78    if one_line.chars().count() <= MAX_SENTENCE {
79        return one_line;
80    }
81    format!("{}…", one_line.chars().take(MAX_SENTENCE - 1).collect::<String>().trim_end())
82}
83
84fn view(id: &str, cause: Cause, block_id: &str, agent: &str, headline: &str, status: &'static str, now: i64) -> NoticeView {
85    NoticeView {
86        id: id.to_string(),
87        kind: cause.kind(),
88        block_id: block_id.to_string(),
89        agent: agent.to_string(),
90        headline: headline.to_string(),
91        body: String::new(),
92        quote: String::new(),
93        always_label: String::new(),
94        deadline_ms: 0,
95        opened_ms: now,
96        status,
97        outcome: String::new(),
98    }
99}
100
101fn publish(state: &AppState, v: &NoticeView) {
102    state.broker.publish_event::<crate::backend::mps_events::AgentNotice>(v, vec![], 32);
103}
104
105/// The host refused `agent` (the agent with uid `uid`, slug `slug`) the credential for `cause`, with `said`: the very
106/// sentence the agent was given. Shows it in the agent's pane unless it is already showing.
107pub fn refused(state: &AppState, uid: &str, slug: &str, cause: Cause, said: &str) {
108    // No pane open for the agent: nobody to tell, and a later refusal can still tell them.
109    let Some(block_id) = state.reactive_handler.block_for_uid(uid) else { return };
110    let now = now_ms();
111    let Some(plan) = plan(&mut shown(), slug, cause, now) else { return };
112    let headline = sentence(said);
113    if let Some(old) = &plan.take_down {
114        publish(state, &view(old, cause, &block_id, slug, &headline, "cleared", now));
115    }
116    publish(state, &view(&plan.put_up, cause, &block_id, slug, &headline, "line", now));
117    tracing::info!(target: "identity", agent = %slug, kind = cause.kind(), "credential notice: shown in the agent's pane");
118}
119
120/// The host gave `agent` the credential for `cause`: takes its line down, if one is up.
121pub fn worked(state: &AppState, uid: &str, slug: &str, cause: Cause) {
122    let Some(up) = shown().remove(&(slug.to_string(), cause)) else { return };
123    let block_id = state.reactive_handler.block_for_uid(uid).unwrap_or_default();
124    publish(state, &view(&up.id, cause, &block_id, slug, "", "cleared", now_ms()));
125}
126
127#[cfg(test)]
128#[path = "credential_notice_tests.rs"]
129mod tests;