Skip to main content

adk_surface/web/
take_over.rs

1//! "Take over, then Done" on the web home and the phone (spec 3.3 §8.2, §10 H2): the secret
2//! a person types reaches the one tool call that asked for it, through the harness's
3//! [`TakeOver`], never the inbox, the engine's records or a log line.
4
5use std::fmt;
6
7use adk_core::CredentialSecret;
8use adk_harness::take_over::{TAKE_OVER_TOOL, TakeOver, TakeOverAnswer, TakeOverSurface};
9use axum::extract::{Path, State};
10use axum::response::{IntoResponse, Response};
11use axum::routing::post;
12use axum::{Json, Router};
13use schemars::JsonSchema;
14use serde::{Deserialize, Serialize};
15
16use super::{Context, Unauthenticated, caller, failed, paths, unauthenticated};
17use crate::engine::{CommandOutcome, SurfaceEngine};
18use crate::error::SurfaceError;
19use crate::model::CardStatus;
20use crate::origin::{Origin, SurfaceKind};
21
22/// `POST /surface/decisions/{id}/take-over` body: the secret typed on a surface, for the card
23/// at the version that surface showed (S-I2). Its `Debug` output redacts the secret.
24///
25/// # Example
26///
27/// ```rust
28/// use adk_surface::web::TakeOverRequest;
29///
30/// let request: TakeOverRequest = serde_json::from_value(serde_json::json!({
31///     "version": 1,
32///     "secret": "492817",
33/// }))
34/// .unwrap();
35/// assert_eq!(request.surface, adk_surface::SurfaceKind::Web);
36/// assert!(!format!("{request:?}").contains("492817"));
37/// ```
38#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
39#[serde(rename_all = "camelCase")]
40pub struct TakeOverRequest {
41    /// The surface: the web home (default) or the phone, the two that take over (§8.2).
42    #[serde(default = "web")]
43    pub surface: SurfaceKind,
44    /// The card's `version`.
45    pub version: u64,
46    /// What the person typed.
47    pub secret: String,
48}
49
50impl fmt::Debug for TakeOverRequest {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        f.debug_struct("TakeOverRequest")
53            .field("surface", &self.surface)
54            .field("version", &self.version)
55            .field("secret", &"[redacted]")
56            .finish()
57    }
58}
59
60fn web() -> SurfaceKind {
61    SurfaceKind::Web
62}
63
64#[derive(Clone)]
65struct TakeOverState {
66    engine: SurfaceEngine,
67    take_over: TakeOver,
68}
69
70/// `POST /surface/decisions/{id}/take-over`, relative to `/api` (spec 3.3 §8.2, §10 H2): the
71/// harness's `take_over` delivers what the caller typed to the call that asked, deciding the
72/// card at the version sent. Mount it with `ServerBuilder::add_api_routes` beside
73/// [`router`](super::router), over the same engine. The caller must own the decision (S-I8);
74/// an answer given first is `alreadyDecided`, never retried (S-I2).
75///
76/// # Example
77///
78/// ```rust,no_run
79/// use std::sync::Arc;
80/// use adk_harness::take_over::TakeOver;
81/// use adk_surface::{LocalSource, SurfaceEngine};
82///
83/// # fn example(source: LocalSource, take_over: TakeOver, builder: adk_server::ServerBuilder) {
84/// let engine = SurfaceEngine::builder(Arc::new(source)).build();
85/// let builder = builder
86///     .add_api_routes(adk_surface::web::router(engine.clone()))
87///     .add_api_routes(adk_surface::web::take_over_router(engine, take_over));
88/// # let _ = builder;
89/// # }
90/// ```
91pub fn take_over_router(engine: SurfaceEngine, take_over: TakeOver) -> Router {
92    Router::new()
93        .route(paths::TAKE_OVER, post(take_over_route))
94        .with_state(TakeOverState { engine, take_over })
95}
96
97async fn take_over_route(
98    State(state): State<TakeOverState>,
99    context: Context,
100    Path(id): Path<String>,
101    Json(request): Json<TakeOverRequest>,
102) -> Response {
103    let origin = match request.surface {
104        SurfaceKind::Web => Origin::Pointer,
105        SurfaceKind::Phone => Origin::Touch,
106        other => {
107            return failed(SurfaceError::Invalid(format!(
108                "a secret is typed on the web home or the phone, not the {other:?} surface"
109            )));
110        }
111    };
112    let caller = match caller(context, request.surface, Some(origin)) {
113        Ok(caller) => caller,
114        Err(Unauthenticated) => return unauthenticated(),
115    };
116    // A paired device takes over as its kind's surface, whatever the body says, and only a
117    // phone may (spec 3.3 §8.2): the record names where the secret was typed.
118    let surface = match caller.surface {
119        SurfaceKind::Web => TakeOverSurface::Web,
120        SurfaceKind::Phone => TakeOverSurface::Phone,
121        SurfaceKind::Terminal | SurfaceKind::Tray | SurfaceKind::Voice | SurfaceKind::Chat => {
122            return failed(SurfaceError::NotHere(
123                "a secret is typed on the web home or a paired phone: take over in the home".into(),
124            ));
125        }
126    };
127    // The caller's own decision, and a take over (S-I8).
128    let card = match state.engine.decision(&caller, &id).await {
129        Ok(card) => card,
130        Err(error) => return failed(error),
131    };
132    if card.call.tool != TAKE_OVER_TOOL {
133        return failed(SurfaceError::Invalid(format!(
134            "decision '{id}' does not ask for a secret; answer it with a decide command"
135        )));
136    }
137    let answer =
138        TakeOverAnswer::new(caller.subject.clone(), surface, CredentialSecret::new(request.secret));
139    let provided = state.take_over.provide(&id, request.version, answer).await;
140    let card = match state.engine.decision(&caller, &id).await {
141        Ok(card) => card,
142        Err(error) => return failed(error),
143    };
144    let outcome = match provided {
145        Ok(_) => {
146            state.engine.deliver_queued(&caller, &card.session_id);
147            CommandOutcome::Answered { card }
148        }
149        Err(error)
150            if matches!(error.code, "approval.version_conflict" | "approval.already_resolved") =>
151        {
152            match (card.status, card.decided.clone()) {
153                (CardStatus::Decided, Some(decided)) => {
154                    CommandOutcome::AlreadyDecided { decided, card }
155                }
156                _ => CommandOutcome::Changed { card },
157            }
158        }
159        Err(error) => return failed(SurfaceError::Source(error)),
160    };
161    Json(outcome).into_response()
162}