1use std::sync::Arc;
8
9use graphrt_core::{Event, Value};
10
11use crate::approvals::PausedRun;
12
13#[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#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
44pub struct RunResult {
45 pub status: RunStatus,
46 pub answer: String,
48 pub outputs_json: String,
50 pub error: Option<String>,
52 pub error_type: Option<String>,
54 pub result_json: String,
56}
57
58#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
60pub struct UiBlock {
61 pub kind: String,
63 pub title: Option<String>,
64 pub json: String,
66}
67
68#[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 NodeFailed {
86 node_id: String,
87 error: String,
88 error_type: String,
89 handled: bool,
90 },
91 ToolCalled {
93 node_id: String,
94 call_id: String,
95 name: String,
96 arguments_json: String,
97 },
98 ToolFinished {
100 node_id: String,
101 call_id: String,
102 name: String,
103 is_error: bool,
104 },
105 ToolDenied {
107 node_id: String,
108 call_id: String,
109 name: String,
110 },
111 AnswerChunk {
113 text: String,
114 },
115 Ui {
117 node_id: String,
118 block: UiBlock,
119 },
120 UiRejected {
122 node_id: String,
123 error: String,
124 },
125 Paused {
127 run: Arc<PausedRun>,
128 },
129 Finished {
131 result: RunResult,
132 },
133}
134
135#[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
148pub(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
211pub(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}