Skip to main content

agentmux_srv/server/
drone_payload.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `getdronepayloadschema`: what a drone can read of what starts it, for the canvas
5//! (Drone real-world jobs spec ยง3.6). One answer per job that runs the drone, and what a hand run has.
6
7use serde::{Deserialize, Serialize};
8use serde_json::{Map, Value};
9
10use crate::backend::jobs::definition::{action_kind, trigger_kind};
11use crate::backend::storage::cron::CronJob;
12use crate::drone::payload_schema::{by_hand_fields, fields_of, PayloadField};
13use crate::server::AppState;
14
15/// What `getdronepayloadschema` is asked.
16#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
17#[ts(export, export_to = "../../../frontend/types/rpc/")]
18pub struct PayloadSchemaReq {
19    pub drone_id: String,
20}
21
22/// One job that runs the drone, and the fields its trigger gives a run.
23#[derive(Debug, Serialize, ts_rs::TS)]
24#[ts(export, export_to = "../../../frontend/types/rpc/")]
25pub struct JobPayload {
26    pub job_id: String,
27    pub job_name: String,
28    /// `timer`, or the event source: `app_event`, `file_watch`, `webhook_local`, `poll`, `expect`.
29    pub trigger: String,
30    pub fields: Vec<PayloadField>,
31}
32
33/// The answer: one entry per job, and what a run started by hand (or by an agent) has.
34#[derive(Debug, Serialize, ts_rs::TS)]
35#[ts(export, export_to = "../../../frontend/types/rpc/")]
36pub struct PayloadSchemaResp {
37    pub jobs: Vec<JobPayload>,
38    pub by_hand: Vec<PayloadField>,
39}
40
41/// The event source of `job`'s trigger, or `None` for a timer.
42fn source_of(job: &CronJob) -> Option<String> {
43    if job.trigger_kind != trigger_kind::EVENT {
44        return None;
45    }
46    job.trigger_event.get("source").and_then(Value::as_str).map(str::to_string)
47}
48
49fn job_payload(job: &CronJob) -> JobPayload {
50    let source = source_of(job);
51    let filter: Map<String, Value> = job.trigger_event.get("filter").and_then(Value::as_object).cloned().unwrap_or_default();
52    JobPayload {
53        job_id: job.id.clone(),
54        job_name: job.name.clone(),
55        trigger: source.clone().unwrap_or_else(|| "timer".to_string()),
56        fields: fields_of(source.as_deref(), &filter),
57    }
58}
59
60/// `getdronepayloadschema`. The jobs are read where they live (the shared store, `server::cron::jobs_store`),
61/// not in the per-channel store, which has no jobs table of its own.
62pub(crate) fn get_payload_schema(state: &AppState, cmd: PayloadSchemaReq) -> Result<PayloadSchemaResp, String> {
63    let store = crate::server::cron::jobs_store(state).ok_or_else(|| "getdronepayloadschema: the shared store is unavailable".to_string())?;
64    let jobs = store.cron_list().map_err(|e| format!("getdronepayloadschema: {e}"))?;
65    let runs_it = |j: &CronJob| j.action.get("kind").and_then(Value::as_str) == Some(action_kind::DRONE) && j.action.get("drone_id").and_then(Value::as_str) == Some(cmd.drone_id.as_str());
66    Ok(PayloadSchemaResp { jobs: jobs.iter().filter(|j| runs_it(j)).map(job_payload).collect(), by_hand: by_hand_fields() })
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72    use serde_json::json;
73
74    fn job(trigger_kind: &str, trigger_event: Value) -> CronJob {
75        CronJob { id: "j1".into(), name: "watch".into(), trigger_kind: trigger_kind.into(), trigger_event, ..Default::default() }
76    }
77
78    /// The jobs that run a drone are read from the store jobs live in (the state's cron store), and a job of
79    /// another drone, or one that runs no drone, is not listed.
80    #[tokio::test]
81    async fn the_jobs_that_run_a_drone_are_read_from_the_jobs_store() {
82        let mut state = crate::server::tests::test_state();
83        crate::server::cron::use_test_store_for_jobs(&mut state);
84        let mut mine = crate::backend::cron::test_job("jp-1", "nightly", "t", "uid-t", "uid-c");
85        mine.action = json!({ "kind": "drone", "drone_id": "d-1" });
86        let mut other = crate::backend::cron::test_job("jp-2", "other", "t", "uid-t", "uid-c");
87        other.action = json!({ "kind": "drone", "drone_id": "d-2" });
88        let plain = crate::backend::cron::test_job("jp-3", "plain", "t", "uid-t", "uid-c");
89        for j in [&mine, &other, &plain] {
90            state.mstore.cron_create(j).unwrap();
91        }
92        let answer = get_payload_schema(&state, PayloadSchemaReq { drone_id: "d-1".into() }).unwrap();
93        assert_eq!(answer.jobs.iter().map(|j| (j.job_id.as_str(), j.trigger.as_str())).collect::<Vec<_>>(), [("jp-1", "timer")]);
94        assert!(!answer.by_hand.is_empty());
95        state.cron_store = None;
96        let err = get_payload_schema(&state, PayloadSchemaReq { drone_id: "d-1".into() }).unwrap_err();
97        assert!(err.contains("shared store is unavailable"), "{err}");
98    }
99
100    #[test]
101    fn a_timer_job_has_the_framing_and_what_the_sender_gave() {
102        let p = job_payload(&job("cron", Value::Null));
103        assert_eq!(p.trigger, "timer");
104        assert!(p.fields.iter().any(|f| f.path == "run_id" && f.clean));
105    }
106
107    #[test]
108    fn an_event_job_has_its_sources_fields() {
109        let p = job_payload(&job(trigger_kind::EVENT, json!({ "source": "poll", "filter": { "query": "tasks" } })));
110        assert_eq!(p.trigger, "poll");
111        assert!(p.fields.iter().any(|f| f.path == "item.title" && !f.clean));
112        assert!(p.fields.iter().any(|f| f.path == "item.num" && f.clean));
113    }
114}