use std::sync::Arc;
use adk_core::ApprovalRequest;
use async_trait::async_trait;
use crate::model::{CardDetail, Reversibility};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CardHint {
pub heading: Option<String>,
pub chat_heading: Option<String>,
pub money: Option<bool>,
pub reversibility: Option<Reversibility>,
pub offer_always: Option<bool>,
pub first_step: Option<String>,
pub detail: Option<CardDetail>,
pub media: Option<crate::evidence::MediaFacts>,
}
impl CardHint {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_heading(mut self, heading: impl Into<String>) -> Self {
self.heading = Some(heading.into());
self
}
#[must_use]
pub fn with_chat_heading(mut self, heading: impl Into<String>) -> Self {
self.chat_heading = Some(heading.into());
self
}
#[must_use]
pub fn spends_money(mut self) -> Self {
self.money = Some(true);
self
}
#[must_use]
pub fn with_reversibility(mut self, reversibility: Reversibility) -> Self {
self.reversibility = Some(reversibility);
self
}
#[must_use]
pub fn without_always_allow(mut self) -> Self {
self.offer_always = Some(false);
self
}
#[must_use]
pub fn with_first_step(mut self, step: impl Into<String>) -> Self {
self.first_step = Some(step.into());
self
}
#[must_use]
pub fn with_detail(mut self, detail: CardDetail) -> Self {
self.detail = Some(detail);
self
}
#[must_use]
pub fn with_media(mut self, media: crate::evidence::MediaFacts) -> Self {
self.media = Some(media);
self
}
pub(crate) fn then(self, later: Self) -> Self {
let money = (self.marks_money() || later.marks_money()).then_some(true);
let offer_always = (self.removes_always() || later.removes_always()).then_some(false);
Self {
heading: self.heading.or(later.heading),
chat_heading: self.chat_heading.or(later.chat_heading),
money,
reversibility: self.reversibility.or(later.reversibility),
offer_always,
first_step: self.first_step.or(later.first_step),
detail: self.detail.or(later.detail),
media: match (self.media, later.media) {
(Some(first), Some(second)) => Some(first.then(second)),
(first, second) => first.or(second),
},
}
}
pub(crate) fn marks_money(&self) -> bool {
self.money == Some(true)
}
pub(crate) fn removes_always(&self) -> bool {
self.offer_always == Some(false)
}
}
#[async_trait]
pub trait CardHints: Send + Sync {
async fn hint(&self, request: &ApprovalRequest) -> Option<CardHint>;
async fn names(&self, _request: &ApprovalRequest) -> Option<String> {
None
}
}
pub(crate) async fn named(
hints: &[Arc<dyn CardHints>],
request: &ApprovalRequest,
) -> Option<String> {
for hints in hints {
if let Some(name) = hints.names(request).await {
return Some(name);
}
}
crate::project::kernel_name(request)
}
#[cfg(test)]
mod tests {
use adk_core::{
ApprovalPolicy, ApprovalRisk, ApprovalScope, ApproverSelector, ToolConfirmationRequest,
};
use chrono::FixedOffset;
use proptest::prelude::*;
use serde_json::json;
use super::*;
use crate::origin::{Caller, Origin, SurfaceKind};
use crate::project::Projector;
use crate::rules::{Answer, allowed_answers};
fn words() -> impl Strategy<Value = Option<String>> {
proptest::option::of("[A-Za-z ]{1,12}")
}
fn reversibility() -> impl Strategy<Value = Option<Reversibility>> {
proptest::option::of(prop_oneof![
Just(Reversibility::CantBeUnsent),
Just(Reversibility::CantBeUndone),
Just(Reversibility::CanBeRemoved),
Just(Reversibility::CanBeChangedBack),
])
}
fn hint() -> impl Strategy<Value = CardHint> {
(
(words(), words(), any::<Option<bool>>()),
(reversibility(), any::<Option<bool>>(), words(), words()),
)
.prop_map(
|((heading, chat_heading, money), (reversibility, offer_always, step, detail))| {
CardHint {
heading,
chat_heading,
money,
reversibility,
offer_always,
first_step: step,
detail: detail.map(CardDetail::new),
media: None,
}
},
)
}
fn caller(row: usize) -> Caller {
let (surface, origin) = match row {
0 => (SurfaceKind::Web, Origin::Pointer),
1 => (SurfaceKind::Terminal, Origin::Keyboard),
2 => (SurfaceKind::Phone, Origin::Touch),
3 => (SurfaceKind::Tray, Origin::Pointer),
4 => (SurfaceKind::Chat, Origin::Chat { channel: "Telegram".into() }),
_ => (SurfaceKind::Web, Origin::Voice),
};
let caller = Caller::human("ana", surface, origin);
if row == 1 { caller.with_paired_local() } else { caller }
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn hints_merge_first_wins_and_stricter_counts(hints in proptest::collection::vec(hint(), 0..5)) {
let merged = hints.iter().cloned().fold(CardHint::new(), CardHint::then);
let first = |field: fn(&CardHint) -> Option<String>| hints.iter().find_map(field);
prop_assert_eq!(merged.heading.clone(), first(|hint| hint.heading.clone()));
prop_assert_eq!(merged.chat_heading.clone(), first(|hint| hint.chat_heading.clone()));
prop_assert_eq!(merged.first_step.clone(), first(|hint| hint.first_step.clone()));
prop_assert_eq!(
merged.detail.clone(),
hints.iter().find_map(|hint| hint.detail.clone())
);
prop_assert_eq!(merged.reversibility, hints.iter().find_map(|hint| hint.reversibility));
prop_assert_eq!(merged.marks_money(), hints.iter().any(CardHint::marks_money));
prop_assert_eq!(merged.removes_always(), hints.iter().any(CardHint::removes_always));
}
#[test]
fn a_hint_never_adds_an_answer_or_changes_the_risk(
hints in proptest::collection::vec(hint(), 0..4),
risk in prop_oneof![
Just(ApprovalRisk::Low),
Just(ApprovalRisk::Medium),
Just(ApprovalRisk::High),
Just(ApprovalRisk::Critical),
],
tool in prop_oneof![Just("payments_charge"), Just("send_email"), Just("verb_snooze")],
always in any::<bool>(),
row in 0usize..6,
) {
let merged = hints.into_iter().fold(CardHint::new(), CardHint::then);
let projector = Projector::new(FixedOffset::east_opt(0).unwrap());
let call = ToolConfirmationRequest::new(tool, json!({ "to": "[client email]" }));
let request = adk_core::ApprovalRequest::new(
"apr-1",
ApprovalScope::new("adk-rust", "ana", "s1"),
&call,
ApprovalPolicy::new([ApproverSelector::human("ana")]),
)
.with_risk(risk);
let label = always.then(|| "Always allow for this person".to_string());
let plain = projector.facts(&request, label.clone(), &CardHint::new());
let hinted = projector.facts(&request, label, &merged);
prop_assert_eq!(hinted.risk, plain.risk);
prop_assert_eq!(&hinted.allows, &plain.allows);
prop_assert!(hinted.money || !plain.money);
let caller = caller(row);
let answers = |facts| -> Vec<Answer> {
allowed_answers(&caller, facts).options.iter().map(|option| option.answer).collect()
};
let (before, after) = (answers(&plain), answers(&hinted));
prop_assert!(after.iter().all(|answer| before.contains(answer)), "{before:?} → {after:?}");
}
}
}