1use crate::gcode_index::{
19 BedArea, PlanFact, PlanMismatch, PlannedChange, PlannedChangeKind, Rise, SetValue, SlicerPlan,
20};
21use crate::records::{EffectiveBounds, Intervention, JobManifest, PrintRecord};
22use crate::watch::{DetectorHealth, DetectorHealthStatus};
23use printobserver_printer_api::{
24 HeaterSnapshot, JobError, JobSnapshot, PrinterSnapshot, PrinterState,
25};
26use printobserver_types::EventPayload;
27use printobserver_types::contract::Sample;
28use printobserver_types::schemars::JsonSchema;
29use printobserver_types::serde::{Deserialize, Serialize};
30use printobserver_types::serde_json::Value;
31use printobserver_types::{
32 EventId, EventKind, EventRecord, ImageRef, PrintId, Reported, Timestamp,
33};
34
35#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
37#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
38#[schemars(crate = "printobserver_types::schemars")]
39pub struct PrintContext {
40 pub print: PrintRecord,
42 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub printer: Option<PrinterSnapshot>,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
47 pub job: Option<JobSnapshot>,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
50 pub manifest: Option<JobManifest>,
51 pub bounds: EffectiveBounds,
53 pub interventions: Vec<Intervention>,
55 pub recent_events: Vec<EventRecord>,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub latest_image: Option<ImageRef>,
60 #[serde(default)]
62 pub detector: DetectorHealth,
63 #[serde(default, skip_serializing_if = "Option::is_none")]
67 pub slicer: Option<SlicerPlan>,
68}
69
70impl Sample for PrintContext {
71 fn sample_full() -> Self {
72 Self {
73 print: PrintRecord::sample_full(),
74 printer: Some(PrinterSnapshot::sample_full()),
75 job: Some(JobSnapshot::sample_full()),
76 manifest: Some(JobManifest::sample_full()),
77 bounds: EffectiveBounds::sample_full(),
78 interventions: vec![Intervention::sample_full()],
79 recent_events: vec![EventRecord::sample_full()],
80 latest_image: Some(ImageRef::sample_full()),
81 detector: DetectorHealth::sample_full(),
82 slicer: Some(SlicerPlan::sample_full()),
83 }
84 }
85
86 fn sample_minimal() -> Self {
87 Self {
88 print: PrintRecord::sample_minimal(),
89 printer: None,
90 job: None,
91 manifest: None,
92 bounds: EffectiveBounds::sample_full(),
93 interventions: vec![],
94 recent_events: vec![],
95 latest_image: None,
96 detector: DetectorHealth::sample_minimal(),
97 slicer: None,
98 }
99 }
100}
101
102const UNREAD_PAYLOAD_FIELDS: [&str; 8] = [
107 "printer",
108 "job",
109 "assessment",
110 "interval_s",
111 "session_name",
112 "harness_identity",
113 "delivered",
114 "waited_s",
115];
116
117pub const UNREAD_EVENT_KINDS: [&str; 5] = [
126 "camera_view_judged",
127 "camera_view_refit",
128 "check_image_changed",
129 "first_layer_alignment_judged",
130 <crate::kinds::GcodeIndexedPayload as EventPayload>::KIND,
131];
132
133#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
152#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
153#[schemars(crate = "printobserver_types::schemars")]
154pub struct AgentContext {
155 pub print: AgentPrint,
157 #[serde(default, skip_serializing_if = "Option::is_none")]
159 pub printer: Option<AgentPrinter>,
160 #[serde(default, skip_serializing_if = "Option::is_none")]
162 pub job_error: Option<JobError>,
163 pub bounds: EffectiveBounds,
165 pub interventions: Vec<Intervention>,
167 pub detector: DetectorHealthStatus,
170 pub recent_events: Vec<AgentEvent>,
173 #[serde(default, skip_serializing_if = "Option::is_none")]
176 pub latest_image: Option<ImageRef>,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
180 pub newest_event: Option<EventId>,
181 #[serde(default, skip_serializing_if = "Option::is_none")]
183 pub slicer: Option<AgentSlicerPlan>,
184}
185
186#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
193#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
194#[schemars(
195 crate = "printobserver_types::schemars",
196 transform = crate::gcode_index::null_is_sent
197)]
198pub struct AgentPlannedChange {
199 #[schemars(range(min = 1))]
201 pub number: u32,
202 pub kind: PlannedChangeKind,
204 pub offset_bytes: u64,
206 pub layer: u32,
209 pub z_mm: f64,
211 pub color: Option<String>,
214}
215
216impl From<&PlannedChange> for AgentPlannedChange {
217 fn from(change: &PlannedChange) -> Self {
218 Self {
219 number: change.index.saturating_add(1),
220 kind: change.kind,
221 offset_bytes: change.offset_bytes,
222 layer: change.layer,
223 z_mm: change.z_mm,
224 color: change.color.clone(),
225 }
226 }
227}
228
229#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
232#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
233#[schemars(crate = "printobserver_types::schemars")]
234pub struct AgentSlicerPlan {
235 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pub expected_color: Option<String>,
240 #[serde(default, skip_serializing_if = "Option::is_none")]
243 pub next_change: Option<AgentPlannedChange>,
244 #[serde(default, skip_serializing_if = "Option::is_none")]
248 pub minutes_to_next_change: Option<i64>,
249 #[serde(default, skip_serializing_if = "Option::is_none")]
252 pub change_waiting: Option<AgentPlannedChange>,
253 #[serde(default, skip_serializing_if = "Option::is_none")]
256 pub layer: Option<usize>,
257 #[serde(default, skip_serializing_if = "Option::is_none")]
259 pub z_mm: Option<f64>,
260 #[serde(default, skip_serializing_if = "Option::is_none")]
262 pub final_z_mm: Option<f64>,
263 #[serde(default, skip_serializing_if = "Vec::is_empty")]
266 pub types: Vec<String>,
267 #[serde(default, skip_serializing_if = "Option::is_none")]
269 pub minutes_left: Option<i64>,
270 #[serde(default, skip_serializing_if = "Option::is_none")]
272 pub flow_factor: Option<SetValue>,
273 #[serde(default, skip_serializing_if = "Option::is_none")]
275 pub fan_percent: Option<SetValue>,
276 #[serde(default, skip_serializing_if = "Option::is_none")]
278 pub object_count: Option<usize>,
279 #[serde(default, skip_serializing_if = "Vec::is_empty")]
283 pub objects: Vec<BedArea>,
284 #[serde(default, skip_serializing_if = "Option::is_none")]
287 pub rise: Option<Rise>,
288 #[serde(default, skip_serializing_if = "Vec::is_empty")]
290 pub at_odds: Vec<PlanMismatch>,
291 #[serde(default, skip_serializing_if = "Vec::is_empty")]
294 pub unknown: Vec<PlanFact>,
295}
296
297impl From<&SlicerPlan> for AgentSlicerPlan {
298 fn from(plan: &SlicerPlan) -> Self {
299 Self {
300 expected_color: plan.expected_color.clone(),
301 next_change: plan.next_change.as_ref().map(AgentPlannedChange::from),
302 minutes_to_next_change: plan.minutes_to_next_change,
303 change_waiting: plan.change_waiting.as_ref().map(AgentPlannedChange::from),
304 layer: plan.layer,
305 z_mm: plan.z_mm,
306 final_z_mm: plan.final_z_mm,
307 types: plan.types.clone(),
308 minutes_left: plan.minutes_left,
309 flow_factor: plan.flow_factor.clone(),
310 fan_percent: plan.fan_percent.clone(),
311 object_count: plan.object_count,
312 objects: plan.objects.clone(),
313 rise: plan.rise.clone(),
314 at_odds: plan.at_odds.clone(),
315 unknown: plan.unknown.clone(),
316 }
317 }
318}
319
320#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
322#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
323#[schemars(crate = "printobserver_types::schemars")]
324pub struct AgentPrint {
325 pub id: PrintId,
327 pub state: PrinterState,
329 #[serde(default, skip_serializing_if = "Option::is_none")]
331 pub end_reason: Option<String>,
332}
333
334#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
336#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
337#[schemars(crate = "printobserver_types::schemars")]
338pub struct AgentPrinter {
339 #[serde(default, skip_serializing_if = "Vec::is_empty")]
341 pub tools: Vec<AgentHeater>,
342 #[serde(default, skip_serializing_if = "Option::is_none")]
344 pub bed: Option<AgentHeater>,
345}
346
347#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
350#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
351#[schemars(crate = "printobserver_types::schemars")]
352pub struct AgentHeater {
353 #[serde(default, skip_serializing_if = "Option::is_none")]
355 pub actual_c: Option<f64>,
356 #[serde(default, skip_serializing_if = "Option::is_none")]
358 pub target_c: Option<f64>,
359}
360
361#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
364#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
365#[schemars(crate = "printobserver_types::schemars")]
366pub struct AgentEvent {
367 pub id: EventId,
369 pub kind: EventKind,
371 pub received_at: Timestamp,
373 #[serde(default, skip_serializing_if = "is_empty_payload")]
376 pub payload: Value,
377}
378
379fn is_empty_payload(payload: &Value) -> bool {
381 match payload {
382 Value::Null => true,
383 Value::Object(fields) => fields.is_empty(),
384 _ => false,
385 }
386}
387
388#[derive(Debug, Clone, Copy)]
391pub struct Since<'events> {
392 pub event: EventId,
394 pub newer: &'events [EventRecord],
396}
397
398impl PrintContext {
399 #[must_use]
402 pub fn for_agent(&self, since: Option<Since<'_>>) -> AgentContext {
403 let heater = |heater: &HeaterSnapshot| AgentHeater {
404 actual_c: in_range(heater.actual_c.as_ref()),
405 target_c: in_range(heater.target_c.as_ref()),
406 };
407 let (events, newest_event) = match since {
408 Some(since) => (
409 since.newer,
410 Some(since.newer.first().map_or(since.event, |newest| newest.id)),
411 ),
412 None => (
413 self.recent_events.as_slice(),
414 self.recent_events.first().map(|newest| newest.id),
415 ),
416 };
417 AgentContext {
418 print: AgentPrint {
419 id: self.print.id,
420 state: self.print.state.clone(),
421 end_reason: self.print.end_reason.clone(),
422 },
423 printer: self.printer.as_ref().map(|printer| AgentPrinter {
424 tools: printer.tools.iter().map(heater).collect(),
425 bed: printer.bed.as_ref().map(heater),
426 }),
427 job_error: self.job.as_ref().and_then(|job| job.error.clone()),
428 bounds: self.bounds.clone(),
429 interventions: self.interventions.clone(),
430 detector: self.detector.status(),
431 recent_events: events
432 .iter()
433 .filter(|event| !UNREAD_EVENT_KINDS.contains(&event.kind().as_str()))
434 .map(agent_event)
435 .collect(),
436 latest_image: self.latest_image.clone(),
437 newest_event,
438 slicer: self.slicer.as_ref().map(AgentSlicerPlan::from),
439 }
440 }
441}
442
443#[must_use]
454pub fn turn_facts(
455 context: &AgentContext,
456 shown: EventId,
457) -> Option<printobserver_types::serde_json::Map<String, Value>> {
458 let mut facts = context.clone();
459 facts.recent_events = unseen_events(&context.recent_events);
460 facts.recent_events.retain(|event| event.id != shown);
461 facts.newest_event = facts.newest_event.filter(|newest| *newest != shown);
462 facts.latest_image = None;
463 match printobserver_types::serde_json::to_value(facts) {
464 Ok(Value::Object(fields)) => Some(fields),
465 _ => None,
466 }
467}
468
469#[must_use]
481pub fn unseen_events(events: &[AgentEvent]) -> Vec<AgentEvent> {
482 let is_answer = |event: &AgentEvent| {
483 event.kind.as_str() == <crate::kinds::AgentAssessmentPayload as EventPayload>::KIND
484 };
485 let Some(answered) = events.iter().position(is_answer) else {
486 return events.to_vec();
487 };
488 let (newer, older) = events.split_at(answered);
489 let older = &older[1..];
490 let turn = &older[..older.iter().position(is_answer).unwrap_or(older.len())];
491 let during = events
492 .iter()
493 .find_map(agents_acknowledged_event)
494 .and_then(|answered_event| turn.iter().position(|event| event.id == answered_event))
495 .map_or(turn, |at| &turn[..at]);
496 let own: Vec<&Value> = during
497 .iter()
498 .filter(|event| is_agents_request(event))
499 .filter_map(|event| event.payload.get("action_id"))
500 .collect();
501 let acknowledged: Vec<&Value> = newer
502 .iter()
503 .filter(|event| agents_acknowledged_event(event).is_some())
504 .filter_map(|event| event.payload.get("action_id"))
505 .collect();
506 let mut unseen: Vec<AgentEvent> = newer
507 .iter()
508 .filter(|event| {
509 !event
510 .payload
511 .get("action_id")
512 .is_some_and(|action| acknowledged.contains(&action))
513 })
514 .cloned()
515 .collect();
516 unseen.extend(
517 during
518 .iter()
519 .filter(|event| {
520 !TURNS_OWN_KINDS.contains(&event.kind.as_str())
521 && !event
522 .payload
523 .get("action_id")
524 .is_some_and(|action| own.contains(&action))
525 })
526 .cloned(),
527 );
528 unseen
529}
530
531const TURNS_OWN_KINDS: [&str; 2] = [
534 <crate::kinds::CameraLookPayload as EventPayload>::KIND,
535 <printobserver_supervisor_api::SupervisionSessionOpenedPayload as EventPayload>::KIND,
536];
537
538fn is_agents_request(event: &AgentEvent) -> bool {
540 event.kind.as_str() == <crate::kinds::ActionRequestedPayload as EventPayload>::KIND
541 && event
542 .payload
543 .get("actor")
544 .is_some_and(|actor| actor.get("agent").is_some())
545}
546
547fn agents_acknowledged_event(event: &AgentEvent) -> Option<EventId> {
549 if !is_agents_request(event) {
550 return None;
551 }
552 let action = event.payload.get("action")?;
553 if action.get("action")?.as_str()? != "acknowledge_failure" {
554 return None;
555 }
556 printobserver_types::serde_json::from_value(action.get("event_id")?.clone()).ok()
557}
558
559#[must_use]
562pub fn newer_than(events: &[EventRecord], since: EventId) -> Option<&[EventRecord]> {
563 events
564 .iter()
565 .position(|event| event.id == since)
566 .map(|at| &events[..at])
567}
568
569fn in_range(reported: Option<&Reported<f64>>) -> Option<f64> {
571 reported
572 .filter(|reported| !reported.out_of_range())
573 .map(Reported::value)
574}
575
576fn agent_event(event: &EventRecord) -> AgentEvent {
578 let mut payload = event.body.payload.clone();
579 if let Value::Object(fields) = &mut payload {
580 for unread in UNREAD_PAYLOAD_FIELDS {
581 fields.remove(unread);
582 }
583 }
584 number_planned_changes(&mut payload);
585 AgentEvent {
586 id: event.id,
587 kind: event.kind().clone(),
588 received_at: event.received_at,
589 payload,
590 }
591}
592
593#[must_use]
597pub(crate) fn as_a_turn_reads(event: &EventRecord) -> EventRecord {
598 let mut shown = event.clone();
599 number_planned_changes(&mut shown.body.payload);
600 shown
601}
602
603const PLANNED_CHANGE_INDICES: [(&str, &str); 2] = [
606 ("change_index", "change_number"),
607 ("planned_change", "planned_change_number"),
608];
609
610fn number_planned_changes(value: &mut Value) {
618 match value {
619 Value::Object(fields) => {
620 for (index, number) in PLANNED_CHANGE_INDICES {
621 if let Some(counted) = fields.get(index).and_then(Value::as_u64) {
622 fields.remove(index);
623 fields.insert(number.to_owned(), Value::from(counted.saturating_add(1)));
624 }
625 }
626 if let Some(change) = fields.get_mut("change") {
627 let numbered =
628 printobserver_types::serde_json::from_value::<PlannedChange>(change.clone())
629 .ok()
630 .and_then(|planned| {
631 printobserver_types::serde_json::to_value(AgentPlannedChange::from(
632 &planned,
633 ))
634 .ok()
635 });
636 if let Some(numbered) = numbered {
637 *change = numbered;
638 }
639 }
640 fields.values_mut().for_each(number_planned_changes);
641 }
642 Value::Array(items) => items.iter_mut().for_each(number_planned_changes),
643 _ => {}
644 }
645}
646
647impl Sample for AgentContext {
648 fn sample_full() -> Self {
649 PrintContext::sample_full().for_agent(None)
650 }
651
652 fn sample_minimal() -> Self {
653 PrintContext::sample_minimal().for_agent(None)
654 }
655}