Skip to main content

graphrt_ffi/
events.rs

1//! Typed run events for [`RunListener`]: what an app shows (answer text, tool
2//! activity, UI blocks, requests for approval, the result) without parsing JSON.
3//!
4//! Every run started with `WorkflowHandle.start` or `resumePaused` ends with
5//! exactly one of [`RunEvent::Paused`] or [`RunEvent::Finished`].
6
7use std::sync::Arc;
8
9use graphrt_core::{Event, Value};
10
11use crate::approvals::PausedRun;
12
13/// How a run ended.
14#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]
15pub enum RunStatus {
16    Succeeded,
17    Failed,
18    Aborted,
19    Paused,
20}
21
22impl RunStatus {
23    pub(crate) fn as_str(self) -> &'static str {
24        match self {
25            RunStatus::Succeeded => "succeeded",
26            RunStatus::Failed => "failed",
27            RunStatus::Aborted => "aborted",
28            RunStatus::Paused => "paused",
29        }
30    }
31
32    pub(crate) fn of(terminal: Option<&Event>) -> Self {
33        match terminal {
34            Some(Event::RunSucceeded { .. }) => RunStatus::Succeeded,
35            Some(Event::RunAborted { .. }) => RunStatus::Aborted,
36            Some(Event::RunPaused { .. }) => RunStatus::Paused,
37            _ => RunStatus::Failed,
38        }
39    }
40}
41
42/// The result of a run that did not pause.
43#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
44pub struct RunResult {
45    pub status: RunStatus,
46    /// The whole answer text (what the `AnswerChunk` events carried).
47    pub answer: String,
48    /// The run's outputs (`end` node), as a JSON object.
49    pub outputs_json: String,
50    /// Why the run failed or was aborted.
51    pub error: Option<String>,
52    /// Machine readable category of a failure (`timeout`, `model`, `limit_exceeded`...).
53    pub error_type: Option<String>,
54    /// The same result as `RunHandle.waitJson` returns it.
55    pub result_json: String,
56}
57
58/// A UI block an agent produced, checked against its schema.
59#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
60pub struct UiBlock {
61    /// `adaptive_card`, `chart`, `table`, `stats` or `diagram`.
62    pub kind: String,
63    pub title: Option<String>,
64    /// The block as JSON (`{"$ui": "...", "version": 1, ...}`).
65    pub json: String,
66}
67
68/// An event of a run.
69#[derive(Clone, Debug, uniffi::Enum)]
70pub enum RunEvent {
71    Started {
72        run_id: String,
73        resumed: bool,
74    },
75    NodeStarted {
76        node_id: String,
77        kind: String,
78        title: String,
79    },
80    NodeSucceeded {
81        node_id: String,
82        elapsed_ms: u64,
83    },
84    /// A node failed; with `handled` its error strategy kept the run going.
85    NodeFailed {
86        node_id: String,
87        error: String,
88        error_type: String,
89        handled: bool,
90    },
91    /// An agent called a tool.
92    ToolCalled {
93        node_id: String,
94        call_id: String,
95        name: String,
96        arguments_json: String,
97    },
98    /// A tool call finished.
99    ToolFinished {
100        node_id: String,
101        call_id: String,
102        name: String,
103        is_error: bool,
104    },
105    /// A held tool call was not approved.
106    ToolDenied {
107        node_id: String,
108        call_id: String,
109        name: String,
110    },
111    /// User facing answer text, in order, as it is produced.
112    AnswerChunk {
113        text: String,
114    },
115    /// A UI block in a node's outputs that passed validation (feature `ui`).
116    Ui {
117        node_id: String,
118        block: UiBlock,
119    },
120    /// A UI block that failed validation and must not be shown.
121    UiRejected {
122        node_id: String,
123        error: String,
124    },
125    /// The run paused and waits for answers. Terminal.
126    Paused {
127        run: Arc<PausedRun>,
128    },
129    /// The run ended. Terminal.
130    Finished {
131        result: RunResult,
132    },
133}
134
135/// Receives the typed events of one run. Implemented in the host language.
136///
137/// Called on a background thread, in order; marshal to the UI thread yourself.
138/// Exceptions thrown here are swallowed so they cannot break the run.
139#[uniffi::export(with_foreign)]
140pub trait RunListener: Send + Sync {
141    fn on_event(&self, event: RunEvent);
142}
143
144fn json_string(value: &serde_json::Value, key: &str) -> String {
145    value.get(key).and_then(serde_json::Value::as_str).unwrap_or_default().to_owned()
146}
147
148/// The typed events of one engine event, appended to `out`. Answer chunks and
149/// the terminal event are produced by the caller, which assembles the answer.
150pub(crate) fn translate(event: &Event, out: &mut Vec<RunEvent>) {
151    match event {
152        Event::RunStarted { run_id, resumed } => {
153            out.push(RunEvent::Started { run_id: run_id.clone(), resumed: *resumed })
154        }
155        Event::NodeStarted { node_id, kind, title, .. } => out.push(RunEvent::NodeStarted {
156            node_id: node_id.to_string(),
157            kind: kind.to_string(),
158            title: title.to_string(),
159        }),
160        Event::NodeSucceeded { node_id, outputs, elapsed_ms, .. } => {
161            out.push(RunEvent::NodeSucceeded { node_id: node_id.to_string(), elapsed_ms: *elapsed_ms });
162            if let Ok(json) = serde_json::to_value(outputs) {
163                ui_events(node_id, &Value::from_json(json), out);
164            }
165        }
166        Event::NodeFailed { node_id, error, error_type, handled, .. } => out.push(RunEvent::NodeFailed {
167            node_id: node_id.to_string(),
168            error: error.clone(),
169            error_type: error_type.clone(),
170            handled: *handled,
171        }),
172        Event::NodeProgress { node_id, name, data, .. } => {
173            let data = data.to_json();
174            let node_id = node_id.to_string();
175            let call_id = json_string(&data, "id");
176            let tool = json_string(&data, "name");
177            match name.as_str() {
178                "tool_call" => out.push(RunEvent::ToolCalled {
179                    node_id,
180                    call_id,
181                    name: tool,
182                    arguments_json: data.get("arguments").map(|a| a.to_string()).unwrap_or_else(|| "{}".to_owned()),
183                }),
184                "tool_result" => out.push(RunEvent::ToolFinished {
185                    node_id,
186                    call_id,
187                    name: tool,
188                    is_error: data.get("is_error").and_then(serde_json::Value::as_bool).unwrap_or(false),
189                }),
190                "tool_denied" => out.push(RunEvent::ToolDenied { node_id, call_id, name: tool }),
191                _ => {}
192            }
193        }
194        _ => {}
195    }
196}
197
198#[cfg(feature = "ui")]
199fn ui_events(node_id: &str, outputs: &Value, out: &mut Vec<RunEvent>) {
200    for block in graphrt_core::ui::collect_ui_blocks(outputs) {
201        match crate::ui::checked(&block.to_json()) {
202            Ok(block) => out.push(RunEvent::Ui { node_id: node_id.to_owned(), block }),
203            Err(error) => out.push(RunEvent::UiRejected { node_id: node_id.to_owned(), error }),
204        }
205    }
206}
207
208#[cfg(not(feature = "ui"))]
209fn ui_events(_node_id: &str, _outputs: &Value, _out: &mut Vec<RunEvent>) {}
210
211/// The terminal typed event of a run.
212pub(crate) fn terminal(terminal: Option<&Event>, answer: &str, result_json: String) -> RunEvent {
213    if let Some(Event::RunPaused { reasons, snapshot }) = terminal {
214        return RunEvent::Paused { run: Arc::new(PausedRun::new((**snapshot).clone(), reasons.clone())) };
215    }
216    let status = RunStatus::of(terminal);
217    let (outputs_json, error, error_type) = match terminal {
218        Some(Event::RunSucceeded { outputs, .. }) => {
219            (serde_json::to_string(outputs).unwrap_or_else(|_| "{}".to_owned()), None, None)
220        }
221        Some(Event::RunFailed { error, error_type, .. }) => {
222            ("{}".to_owned(), Some(error.clone()), Some(error_type.clone()).filter(|t| !t.is_empty()))
223        }
224        Some(Event::RunAborted { reason, .. }) => ("{}".to_owned(), Some(reason.clone()), None),
225        _ => ("{}".to_owned(), Some("run ended without a terminal event".to_owned()), Some("internal".to_owned())),
226    };
227    RunEvent::Finished {
228        result: RunResult { status, answer: answer.to_owned(), outputs_json, error, error_type, result_json },
229    }
230}
231
232#[cfg(test)]
233mod tests {
234    use super::*;
235    use serde_json::json;
236
237    fn progress(name: &str, data: serde_json::Value) -> Event {
238        Event::NodeProgress {
239            frame: "".into(),
240            node_id: "assistant".into(),
241            exec_id: "e1".into(),
242            name: name.to_owned(),
243            data: Value::from_json(data),
244        }
245    }
246
247    #[test]
248    fn tool_progress_becomes_tool_events() {
249        let mut out = Vec::new();
250        translate(&progress("tool_call", json!({"id": "c1", "name": "device__battery", "arguments": {}})), &mut out);
251        translate(&progress("tool_result", json!({"id": "c1", "name": "device__battery", "is_error": true})), &mut out);
252        translate(&progress("tool_denied", json!({"id": "c2", "name": "device__send"})), &mut out);
253        translate(&progress("agent_step", json!({})), &mut out);
254        assert!(
255            matches!(&out[0], RunEvent::ToolCalled { call_id, arguments_json, .. } if call_id == "c1" && arguments_json == "{}")
256        );
257        assert!(matches!(&out[1], RunEvent::ToolFinished { is_error: true, .. }));
258        assert!(matches!(&out[2], RunEvent::ToolDenied { call_id, .. } if call_id == "c2"));
259        assert_eq!(out.len(), 3);
260    }
261
262    #[test]
263    fn a_failed_run_carries_its_error() {
264        let failed = Event::RunFailed {
265            error: "boom".into(),
266            error_type: "model".into(),
267            usage: graphrt_core::event::Usage::default(),
268            elapsed_ms: 1,
269        };
270        let RunEvent::Finished { result } = terminal(Some(&failed), "partial", "{}".into()) else {
271            unreachable!("a failed run finishes");
272        };
273        assert_eq!(result.status, RunStatus::Failed);
274        assert_eq!((result.error.as_deref(), result.error_type.as_deref()), (Some("boom"), Some("model")));
275        assert_eq!(result.answer, "partial");
276    }
277}