use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use adk_core::{ApprovalRequest, Event, Part, RequestedCall, RequestedViaKind};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde_json::Value;
use crate::hints::{CardHint, CardHints};
use crate::model::CardDetail;
use crate::project::{self, Projector};
use crate::source::Source;
use crate::words;
const REMEMBERED: usize = 4_096;
const HOLD_WRITTEN_WITHIN_SECS: i64 = 30;
const PRESSED: usize = 256;
const REQUEST_MADE_WITHIN_SECS: i64 = 120;
struct Pressed {
user: String,
session: String,
tool: String,
args: Value,
at: DateTime<Utc>,
call_id: String,
form: Option<(String, u64)>,
app: Option<String>,
request: Option<String>,
digest: Option<String>,
}
#[derive(Debug, Clone)]
pub(crate) struct SentCall {
pub(crate) call_id: String,
pub(crate) args: Value,
pub(crate) form: (String, u64),
pub(crate) digest: Option<String>,
}
pub(crate) struct DrawnHints {
source: Arc<dyn Source>,
projector: Projector,
known: Mutex<HashMap<String, Option<CardHint>>>,
pressed: Mutex<VecDeque<Pressed>>,
}
fn written(events: &[Event], call_id: &str) -> bool {
events
.iter()
.filter_map(|event| event.llm_response.content.as_ref())
.flat_map(|content| &content.parts)
.any(|part| match part {
Part::FunctionCall { id, .. } | Part::FunctionResponse { id, .. } => {
id.as_deref() == Some(call_id)
}
_ => false,
})
}
impl DrawnHints {
pub(crate) fn new(source: Arc<dyn Source>, projector: Projector) -> Self {
Self {
source,
projector,
known: Mutex::new(HashMap::new()),
pressed: Mutex::new(VecDeque::new()),
}
}
pub(crate) fn begin_send(
&self,
user: &str,
session: &str,
(surface, version): (&str, u64),
call: &RequestedCall,
events: &[Event],
) -> bool {
let mut pressed = self.pressed.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let now = Utc::now();
let on_its_way = pressed.iter().any(|earlier| {
earlier.user == user
&& earlier.session == session
&& earlier.form.as_ref().is_some_and(|(id, at)| id == surface && *at == version)
&& now.signed_duration_since(earlier.at).num_seconds() <= REQUEST_MADE_WITHIN_SECS
&& !written(events, &earlier.call_id)
});
if on_its_way {
return false;
}
Self::note(
&mut pressed,
Pressed {
user: user.to_string(),
session: session.to_string(),
tool: call.tool_name.clone(),
args: call.args.clone(),
at: now,
call_id: call.function_call_id.clone(),
form: Some((surface.to_string(), version)),
app: None,
digest: call.via.digest.clone(),
request: None,
},
);
true
}
#[cfg(feature = "genui-apps")]
pub(crate) fn app_asked(&self, user: &str, session: &str, call: &RequestedCall, app: &str) {
let mut pressed = self.pressed.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
Self::note(
&mut pressed,
Pressed {
user: user.to_string(),
session: session.to_string(),
tool: call.tool_name.clone(),
args: call.args.clone(),
at: Utc::now(),
call_id: call.function_call_id.clone(),
form: None,
app: Some(app.to_string()),
request: None,
digest: None,
},
);
}
pub(crate) fn withdraw(&self, call_id: &str) {
self.pressed
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.retain(|pressed| pressed.call_id != call_id);
}
fn note(pressed: &mut VecDeque<Pressed>, send: Pressed) {
if pressed.len() >= PRESSED {
pressed.pop_front();
}
pressed.push_back(send);
}
fn sent_here(&self, request: &ApprovalRequest) -> Option<(DateTime<Utc>, Option<String>)> {
let mut pressed = self.pressed.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let send = pressed.iter_mut().rev().find(|pressed| {
pressed.user == request.scope.user_id
&& pressed.session == request.scope.session_id
&& pressed.tool == request.tool_name
&& pressed.args == request.args_redacted
&& pressed.request.as_ref().is_none_or(|id| *id == request.id)
&& pressed.at <= request.created_at + chrono::Duration::seconds(1)
&& request.created_at.signed_duration_since(pressed.at).num_seconds()
<= REQUEST_MADE_WITHIN_SECS
})?;
send.request = Some(request.id.clone());
Some((send.at, send.app.clone()))
}
pub(crate) fn sent_call(&self, request: &ApprovalRequest) -> Option<SentCall> {
let pressed = self.pressed.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let send = pressed.iter().rev().find(|pressed| {
pressed.request.as_deref() == Some(request.id.as_str())
|| (pressed.request.is_none()
&& pressed.user == request.scope.user_id
&& pressed.session == request.scope.session_id
&& pressed.tool == request.tool_name
&& pressed.args == request.args_redacted)
})?;
Some(SentCall {
call_id: send.call_id.clone(),
args: send.args.clone(),
form: send.form.clone()?,
digest: send.digest.clone(),
})
}
fn app_hint(&self, app: &str, at: DateTime<Utc>) -> CardHint {
CardHint::new()
.without_always_allow()
.with_first_step(words::app_asked(app, &self.projector.hh_mm(at)))
.with_detail(CardDetail::new(words::from_the_app(app)))
}
fn form_hint(&self, request: &ApprovalRequest, at: DateTime<Utc>) -> CardHint {
let agent = self.projector.agent(&project::agent_name(request)).display_name;
CardHint::new()
.without_always_allow()
.with_first_step(words::pressed_send_on_form(&agent, &self.projector.hh_mm(at)))
.with_detail(CardDetail::new(words::from_a_form(&agent)))
}
fn remember(&self, id: &str, hint: Option<CardHint>) {
let mut known = self.known.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if known.len() >= REMEMBERED {
known.clear();
}
known.insert(id.to_string(), hint);
}
}
#[async_trait]
impl CardHints for DrawnHints {
async fn hint(&self, request: &ApprovalRequest) -> Option<CardHint> {
if let Some(known) =
self.known.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&request.id)
{
return known.clone();
}
let events = match self
.source
.transcript(&request.scope.user_id, &request.scope.session_id)
.await
{
Ok(Some(events)) => events,
Ok(None) => Vec::new(),
Err(error) => {
tracing::warn!(approval.id = %request.id, error = %error, "could not read the session of a decision; its card says less");
Vec::new()
}
};
let links = project::links(&events, std::slice::from_ref(request));
let held = links
.iter()
.find(|(_, link)| link.id == request.id)
.and_then(|(seq, _)| events.get(usize::try_from(*seq).ok()?.checked_sub(1)?));
let Some(held) = held else {
if let Some((at, app)) = self.sent_here(request) {
return Some(match app {
Some(app) => self.app_hint(&app, at),
None => self.form_hint(request, at),
});
}
if Utc::now().signed_duration_since(request.created_at).num_seconds()
> HOLD_WRITTEN_WITHIN_SECS
{
self.remember(&request.id, None);
}
return None;
};
let pressed_at = self
.pressed
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.iter()
.find(|pressed| pressed.request.as_deref() == Some(request.id.as_str()))
.map(|pressed| pressed.at);
let hint = super::requested_via(held).map(|via| match via.kind {
RequestedViaKind::Form => self.form_hint(request, pressed_at.unwrap_or(held.timestamp)),
RequestedViaKind::App => {
match request.origin.as_ref().and_then(|origin| origin.source.strip_prefix("mcp:"))
{
Some(server) => self.app_hint(&super::app_name(server), held.timestamp),
None => CardHint::new().without_always_allow(),
}
}
_ => CardHint::new().without_always_allow(),
});
self.remember(&request.id, hint.clone());
hint
}
}