Skip to main content

trusty_code/
events.rs

1//! Process-wide event bus for real-time UI streaming (#192 Phase B; #2055
2//! formalises the session-attach envelope on top of it).
3//!
4//! Why: The 2-second stderr polling model from #149 is slow, lossy, and only
5//! handles workflow phase transitions. The UI needs immediate feedback on
6//! every PM thinking turn, every sub-agent message, every tool call — across
7//! both the in-process Axum server path AND the subprocess workflow path.
8//! A `tokio::sync::broadcast` channel exposed via a process-global `OnceLock`
9//! lets any code path emit events without threading the bus through dozens of
10//! function signatures, while SSE subscribers fan out to all browsers.
11//!
12//! #2055 adds [`SessionEventEnvelope`]: every event the `session.attach`
13//! protocol (#2054) cares about is session-scoped, so the bus now carries the
14//! ENVELOPE (`session_id`, a per-session monotonic `seq`, a UTC timestamp,
15//! and the tagged [`Event`] payload) rather than a bare `Event`. This is the
16//! same "envelope wraps a domain-tagged payload" shape as
17//! `trusty-agents-common`'s `HarnessEvent`/`HarnessPayload` convention, with
18//! two deliberate divergences (documented on the struct itself): `seq` is
19//! PER-SESSION here (not process-global) because the session-attach
20//! replay->live continuity this ticket requires is scoped to one session's
21//! stream, and the payload stays a flat `#[serde(tag = "type")]` enum (not a
22//! nested `{domain, event}` wrapper) because #2054 already shipped that wire
23//! shape and rewriting it would break the shipped `session.attach` contract.
24//! `session::registry::SessionRegistry` is the sole assigner of `seq`
25//! (see its `record` method) since it already owns the per-session ring
26//! buffer this must stay consistent with.
27//!
28//! What: Defines the `Event` enum (the tagged payload), `SessionEventEnvelope`
29//! (the wire envelope), a process-global `EVENT_BUS` initialised lazily from
30//! any thread carrying envelopes, helpers to publish and subscribe, and a
31//! `__OMPM_EVENT__ <json>\n` stderr-relay protocol so events emitted by
32//! `--workflow` subprocesses can be re-broadcast by the parent API server.
33//! Test: `events::publish` round-trips through `subscribe()`. The relay
34//! prefix is stable so the parent stderr reader can detect and re-publish.
35
36use std::sync::OnceLock;
37
38use chrono::{DateTime, Utc};
39use serde::{Deserialize, Serialize};
40use tokio::sync::broadcast;
41
42/// Stderr line prefix used to relay events from a workflow subprocess to its
43/// parent API server. The parent reads stderr line-by-line; lines starting
44/// with this prefix are parsed as `Event` JSON and re-published on the
45/// parent's event bus instead of being mirrored to terminal stderr.
46///
47/// Why: Workflow phase + agent telemetry must reach the API server even
48/// though the workflow runs in a child process. Reusing the same stderr
49/// channel that already carries `__OMPM_PROGRESS__` (the legacy 2s-poll
50/// path) avoids inventing yet another IPC mechanism.
51/// What: Match by exact byte prefix; payload after the space is one JSON
52/// object decodable as `Event`.
53pub const EVENT_LINE_PREFIX: &str = "__OMPM_EVENT__ ";
54
55/// Capacity of the broadcast channel. Larger than `bus`'s 256 because event
56/// volume is much higher (every PM thought, every agent line). 1024 keeps
57/// memory bounded (~256KB at 256 bytes/event) while tolerating slow SSE
58/// subscribers without dropping recent events under typical load.
59const CHANNEL_CAPACITY: usize = 1024;
60
61/// Real-time event types streamed to UI clients (browser, future Tauri).
62///
63/// Why: A single tagged enum keeps wire-format evolution tractable —
64/// `serde(tag = "type")` produces `{"type":"agent_message", ...}` so the UI
65/// can pattern-match on type and the back-end can grow new variants without
66/// breaking older clients (unknown variants degrade to "ignored event").
67/// What: Variants cover the full PM lifecycle plus a `Ping` keepalive so SSE
68/// connections don't time out behind reverse proxies. `session_id` correlates
69/// events to a specific task; the UI filters by session when scoped to a
70/// task view.
71/// Test: `event_serializes_with_type_tag` asserts the wire shape for one
72/// variant; `Event::Ping` round-trips for the keepalive path.
73#[derive(Debug, Clone, Serialize, Deserialize)]
74#[serde(tag = "type", rename_all = "snake_case")]
75pub enum Event {
76    // -- Session lifecycle --
77    SessionStarted {
78        session_id: String,
79        project: String,
80    },
81    SessionDone {
82        session_id: String,
83        status: String,
84    },
85    SessionCancelled {
86        session_id: String,
87    },
88    /// A session's lifecycle status changed (#2054 session-attach protocol).
89    ///
90    /// Why: `SessionStarted`/`SessionDone`/`SessionCancelled` cover the two
91    /// endpoints of a session's life, but the daemon-owned `Session` model
92    /// (vision spec Axiom 4) also transitions through intermediate states
93    /// (e.g. `created` -> `running`) that a freshly-`session.attach`ed
94    /// client should see. This variant is the generic "status is now X"
95    /// signal `crate::session::registry::SessionRegistry` emits on every
96    /// transition, including the two endpoints (so a client that attaches
97    /// mid-stream sees a uniform status trail rather than mixing this
98    /// variant with the older ones).
99    /// What: `status` is a lowercase string matching
100    /// `session::model::SessionStatus`'s serde representation (`"created"`,
101    /// `"running"`, `"cancelled"`, `"finished"`, `"failed"`).
102    /// Test: `session::registry::tests::create_publishes_started_and_status_events`.
103    SessionStatusChanged {
104        session_id: String,
105        status: String,
106    },
107    /// Input was received for a session via `session.send` (#2054).
108    ///
109    /// Why: distinct from `AgentMessage` (sub-agent -> PM activity) —
110    /// this is the client -> daemon direction. Emitting it is what makes
111    /// `session.send` observably reach a freshly-`session.attach`ed client
112    /// in M1, ahead of any real agent-loop wiring (`task.*`, #2056).
113    /// What: `input` is the raw string the caller passed to `session.send`.
114    /// Test: `session::registry::tests::send_publishes_input_event`.
115    SessionInput {
116        session_id: String,
117        input: String,
118    },
119
120    // -- Tool lifecycle (#2055 taxonomy; emitted by #2056's agent loop) --
121    /// A tool invocation began. Distinct from the older `ToolCalled` (which
122    /// has no started/finished/error distinction or call-correlation id, and
123    /// predates the session-attach protocol) — this is the tcode
124    /// session.attach taxonomy's tool-lifecycle kind.
125    ///
126    /// Why: `call_id` correlates this with the matching `ToolFinished`/
127    /// `ToolError` when a session runs multiple tool calls in sequence or
128    /// concurrently.
129    /// What: `args_preview` is truncated via `preview()` before emission.
130    /// Test: `session::registry::registry_tests::record_tool_started_publishes_event`.
131    ToolStarted {
132        session_id: String,
133        tool: String,
134        call_id: String,
135        args_preview: String,
136    },
137    /// A tool invocation completed (success or failure signalled by `success`,
138    /// not a separate error variant — use `ToolError` for exceptional
139    /// failures the caller wants to narrate distinctly, e.g. a timeout).
140    ToolFinished {
141        session_id: String,
142        tool: String,
143        call_id: String,
144        success: bool,
145        result_preview: String,
146    },
147    /// A tool invocation raised an exceptional error (as opposed to
148    /// completing with `success: false`) — e.g. the tool process crashed or
149    /// timed out rather than returning a normal failure result.
150    ToolError {
151        session_id: String,
152        tool: String,
153        call_id: String,
154        error: String,
155    },
156
157    // -- Diagnostics / progress / generic message (#2055 taxonomy) --
158    /// A structured log line scoped to a session, for operators/UIs that
159    /// want daemon-side diagnostics without parsing stderr.
160    Log {
161        session_id: String,
162        /// `"debug"` | `"info"` | `"warn"` | `"error"`.
163        level: String,
164        message: String,
165    },
166    /// A coarse progress update for a long-running session operation.
167    /// `percent` is `None` when progress isn't quantifiable (e.g. "still
168    /// searching") — the UI falls back to an indeterminate spinner.
169    Progress {
170        session_id: String,
171        message: String,
172        percent: Option<f32>,
173    },
174    /// A generic, freeform session-scoped message that doesn't fit any more
175    /// specific kind — the taxonomy's catch-all, used sparingly.
176    Message {
177        session_id: String,
178        text: String,
179    },
180
181    // -- PM activity --
182    PmThinking {
183        session_id: String,
184        text: String,
185    },
186    PmDelegating {
187        session_id: String,
188        agent: String,
189        task_preview: String,
190    },
191
192    // -- Agent activity --
193    AgentSpawned {
194        session_id: String,
195        agent: String,
196    },
197    AgentMessage {
198        session_id: String,
199        agent: String,
200        text: String,
201    },
202    AgentDone {
203        session_id: String,
204        agent: String,
205        status: String,
206    },
207    AgentFailed {
208        session_id: String,
209        agent: String,
210        error: String,
211    },
212
213    // -- Tool calls --
214    ToolCalled {
215        session_id: String,
216        tool: String,
217        preview: String,
218    },
219    ToolResult {
220        session_id: String,
221        tool: String,
222        preview: String,
223    },
224
225    // -- AST analysis --
226    /// Emitted when an AST-native tool performs a structural code operation
227    /// (symbol lookup, edit, insert, import, validation, patch apply, or
228    /// project pre-indexing). Surfaces in the REPL's thinking-step display
229    /// so users can see structural analysis happening in real time.
230    ///
231    /// Why: AST-native tools replace whole-file rewrites with surgical edits.
232    /// Without dedicated telemetry the user only sees opaque `ToolCalled`
233    /// events and loses the narrative of "indexed project → looked up symbol
234    /// → staged edit → applied patch". This event makes the AST narrative
235    /// visible.
236    /// What: `op` is a short label (`index`, `lookup`, `edit`, `insert`,
237    /// `import`, `validate`, `patch`); `detail` is a human-readable
238    /// substring (e.g. "42 symbols from src/" or "fn parse_args in main.rs").
239    /// Test: `ast_operation_round_trips_through_subscribe` round-trips one
240    /// variant through the bus.
241    AstOperation {
242        session_id: String,
243        op: String,
244        detail: String,
245    },
246
247    // -- Phase (workflow) --
248    PhaseStarted {
249        session_id: String,
250        phase: String,
251    },
252    PhaseDone {
253        session_id: String,
254        phase: String,
255        status: String,
256    },
257    /// #196: a phase was skipped because the active persona opts out of it.
258    ///
259    /// Why: Operators and the UI need visibility when persona-aware skipping
260    /// changes the executed workflow shape (e.g. `[hacker]` skipping QA).
261    /// Without this event the run looks like phases silently disappeared.
262    /// What: Carries the phase name and the persona that triggered the skip.
263    PhaseSkipped {
264        session_id: String,
265        phase: String,
266        persona: String,
267    },
268
269    // -- Persona (workflow) --
270    /// #196: emitted once per workflow run when a persona is detected from the
271    /// task text. Lets the UI surface "running in [hacker] mode" before any
272    /// phases execute, so users immediately see why the pipeline shape may
273    /// differ from the default.
274    PersonaDetected {
275        session_id: String,
276        persona: String,
277    },
278
279    // -- LLM call lifecycle (#199) --
280    /// Emitted just before any LLM chat-completion HTTP call leaves the
281    /// process. Pairs with `LlmResponded` so consumers can compute latency
282    /// independently and surface in-flight calls in the UI.
283    ///
284    /// Why: Operators debugging slow runs need to see WHICH model is in flight
285    /// at any moment, not just retroactively in totals. `prompt_tokens` is
286    /// optional because we don't always know the prompt size up front.
287    /// What: `agent_name` may be empty for top-level PM calls; `model` is the
288    /// resolved provider/model string sent on the wire.
289    LlmRequested {
290        session_id: String,
291        agent_name: String,
292        model: String,
293        prompt_tokens: Option<u32>,
294    },
295
296    /// Emitted after every LLM chat-completion HTTP call returns successfully.
297    /// Carries the wall-clock latency so the UI can render "model X took Yms"
298    /// badges without waiting for end-of-run perf aggregation.
299    LlmResponded {
300        session_id: String,
301        agent_name: String,
302        model: String,
303        completion_tokens: Option<u32>,
304        latency_ms: u64,
305    },
306
307    /// Emitted when an agent's actual work loop begins — distinct from
308    /// `AgentSpawned`, which fires when the subprocess is kicked off.
309    /// `AgentStarted` fires AFTER the spawn handshake (or at the start of an
310    /// in-process runner loop) so the UI can show "spawning…" vs. "running"
311    /// states. `runner_type` is one of "subprocess", "claude-code", "inline".
312    AgentStarted {
313        session_id: String,
314        agent_name: String,
315        runner_type: String,
316    },
317
318    /// Emitted when an agent produces its final result before returning to
319    /// the PM. Lets the UI render "agent X returned a Y-word report" badges
320    /// without parsing the result body.
321    ///
322    /// Why: A coarse signal of agent productivity that complements
323    /// `AgentDone`. `word_count` is a cheap whitespace-split count; status
324    /// mirrors the agent's IPC status field ("success" or "error").
325    ReportGenerated {
326        session_id: String,
327        agent_name: String,
328        word_count: usize,
329        status: String,
330    },
331
332    /// Emitted when a session recap is generated after N completed tasks (#371).
333    /// Carries the session ID, a one-line prose summary, and structured table rows.
334    /// Consumed by TUI (renders `※ recap:` banner) and SSE → GUI (RecapPanel).
335    RecapGenerated {
336        session_id: String,
337        /// One-line prose summary, e.g. "Fixed a bug where X. Y is now deployed."
338        summary: String,
339        /// Structured rows for the recap table: [(step_label, result_text)]
340        table_rows: Vec<(String, String)>,
341    },
342
343    // -- Keepalive --
344    Ping,
345}
346
347impl Event {
348    /// Return the event's `session_id` if it has one. Used by the SSE
349    /// handler to filter the broadcast stream to a single task subscription.
350    ///
351    /// Why: Variants without a session (currently just `Ping`) must always
352    /// pass the filter — losing keepalives would defeat their purpose.
353    /// What: Returns `Some(&str)` for variants that carry a session, `None`
354    /// for keepalives. The SSE filter treats `None` as "always include".
355    pub fn session_id(&self) -> Option<&str> {
356        match self {
357            Event::SessionStarted { session_id, .. }
358            | Event::SessionDone { session_id, .. }
359            | Event::SessionCancelled { session_id }
360            | Event::SessionStatusChanged { session_id, .. }
361            | Event::SessionInput { session_id, .. }
362            | Event::ToolStarted { session_id, .. }
363            | Event::ToolFinished { session_id, .. }
364            | Event::ToolError { session_id, .. }
365            | Event::Log { session_id, .. }
366            | Event::Progress { session_id, .. }
367            | Event::Message { session_id, .. }
368            | Event::PmThinking { session_id, .. }
369            | Event::PmDelegating { session_id, .. }
370            | Event::AgentSpawned { session_id, .. }
371            | Event::AgentMessage { session_id, .. }
372            | Event::AgentDone { session_id, .. }
373            | Event::AgentFailed { session_id, .. }
374            | Event::ToolCalled { session_id, .. }
375            | Event::ToolResult { session_id, .. }
376            | Event::AstOperation { session_id, .. }
377            | Event::PhaseStarted { session_id, .. }
378            | Event::PhaseDone { session_id, .. }
379            | Event::PhaseSkipped { session_id, .. }
380            | Event::PersonaDetected { session_id, .. }
381            | Event::LlmRequested { session_id, .. }
382            | Event::LlmResponded { session_id, .. }
383            | Event::AgentStarted { session_id, .. }
384            | Event::ReportGenerated { session_id, .. }
385            | Event::RecapGenerated { session_id, .. } => Some(session_id),
386            Event::Ping => None,
387        }
388    }
389
390    /// The stable `kind` string for this event — identical to the serde
391    /// `"type"` tag `#[serde(tag = "type", rename_all = "snake_case")]`
392    /// produces on the wire.
393    ///
394    /// Why (#2055): `SessionEventEnvelope` carries `kind` as a top-level
395    /// field (vision spec's envelope requirement) so a client can filter/
396    /// route on it without parsing into the nested `event` payload. Hand-
397    /// written rather than derived from serde reflection (no such API exists
398    /// without an extra dependency) — `kind_matches_serde_tag_for_every_variant`
399    /// guards the two from drifting apart.
400    /// What: Returns the exact snake_case tag string for every variant.
401    /// Test: `kind_matches_serde_tag_for_every_variant`.
402    pub fn kind(&self) -> &'static str {
403        match self {
404            Event::SessionStarted { .. } => "session_started",
405            Event::SessionDone { .. } => "session_done",
406            Event::SessionCancelled { .. } => "session_cancelled",
407            Event::SessionStatusChanged { .. } => "session_status_changed",
408            Event::SessionInput { .. } => "session_input",
409            Event::ToolStarted { .. } => "tool_started",
410            Event::ToolFinished { .. } => "tool_finished",
411            Event::ToolError { .. } => "tool_error",
412            Event::Log { .. } => "log",
413            Event::Progress { .. } => "progress",
414            Event::Message { .. } => "message",
415            Event::PmThinking { .. } => "pm_thinking",
416            Event::PmDelegating { .. } => "pm_delegating",
417            Event::AgentSpawned { .. } => "agent_spawned",
418            Event::AgentMessage { .. } => "agent_message",
419            Event::AgentDone { .. } => "agent_done",
420            Event::AgentFailed { .. } => "agent_failed",
421            Event::ToolCalled { .. } => "tool_called",
422            Event::ToolResult { .. } => "tool_result",
423            Event::AstOperation { .. } => "ast_operation",
424            Event::PhaseStarted { .. } => "phase_started",
425            Event::PhaseDone { .. } => "phase_done",
426            Event::PhaseSkipped { .. } => "phase_skipped",
427            Event::PersonaDetected { .. } => "persona_detected",
428            Event::LlmRequested { .. } => "llm_requested",
429            Event::LlmResponded { .. } => "llm_responded",
430            Event::AgentStarted { .. } => "agent_started",
431            Event::ReportGenerated { .. } => "report_generated",
432            Event::RecapGenerated { .. } => "recap_generated",
433            Event::Ping => "ping",
434        }
435    }
436}
437
438/// The stable, sequenced wire envelope for one session's event (#2055).
439///
440/// Why: `session.attach`'s ring-buffer replay and every live notification
441/// thereafter (both STDIO `session.event` notifications and the HTTP
442/// `GET /sessions/{id}/events` SSE stream) need the SAME shape so a client
443/// can detect gaps and stitch replay -> live into one ordered stream. See
444/// the module docs for how this aligns with / diverges from
445/// `trusty-agents-common`'s `HarnessEvent` convention.
446/// What: `session_id` (always present — every event this daemon emits is
447/// session-scoped), `seq` (per-session monotonic, assigned by
448/// `session::registry::SessionRegistry::record`, starting at 1), `at` (UTC
449/// emit timestamp), `kind` (== `event.kind()`, duplicated at the top level
450/// for cheap client-side filtering), and `event` (the full tagged payload).
451/// Test: `session_event_envelope_round_trips_through_json`.
452#[derive(Debug, Clone, Serialize, Deserialize)]
453pub struct SessionEventEnvelope {
454    pub session_id: String,
455    pub seq: u64,
456    pub at: DateTime<Utc>,
457    pub kind: String,
458    pub event: Event,
459}
460
461impl SessionEventEnvelope {
462    /// Build an envelope for `event`, computing `kind` from
463    /// [`Event::kind`].
464    ///
465    /// Why: the one place `kind` is derived from `event`, so the two can
466    /// never be constructed out of sync.
467    /// What: `session_id`/`seq`/`at` are supplied by the caller (the
468    /// registry, which owns the per-session sequence counter); `kind` is
469    /// computed here.
470    /// Test: `session_event_envelope_round_trips_through_json`.
471    pub fn new(session_id: String, seq: u64, at: DateTime<Utc>, event: Event) -> Self {
472        let kind = event.kind().to_string();
473        Self {
474            session_id,
475            seq,
476            at,
477            kind,
478            event,
479        }
480    }
481}
482
483/// Process-global event bus, initialised on first access.
484///
485/// Why: Threading a `broadcast::Sender<SessionEventEnvelope>` through every
486/// code path that might want to emit telemetry (workflow engine, agent
487/// runners, ctrl) would touch hundreds of function signatures. A `OnceLock`
488/// mirrors how `tracing` solves the same problem — emit-from-anywhere with
489/// zero overhead when no one is listening. Carries the full envelope
490/// (#2055), not a bare `Event`, since every current producer
491/// (`session::registry::SessionRegistry`) and every current consumer (the
492/// STDIO forwarder, the HTTP SSE route) is session-scoped and needs `seq`/
493/// `at`/`kind` alongside the payload — see the module docs for the
494/// `HarnessEvent` alignment/divergence rationale.
495/// What: `Sender::send` is non-blocking; when there are no subscribers it
496/// returns an error which we silently drop (events without listeners are
497/// the expected baseline).
498static EVENT_BUS: OnceLock<broadcast::Sender<SessionEventEnvelope>> = OnceLock::new();
499
500/// Get (or initialise) the process-global event bus sender.
501///
502/// Why: Called from any code path that wants to emit. First call wins; all
503/// subsequent calls receive the same `Sender`. Cheap (single atomic load on
504/// the hot path).
505/// What: Returns a clone of the global sender. The receiver half is created
506/// per subscriber via `subscribe()`.
507/// Test: `bus_is_singleton` confirms repeated calls return the same channel.
508pub fn bus() -> broadcast::Sender<SessionEventEnvelope> {
509    EVENT_BUS
510        .get_or_init(|| broadcast::channel(CHANNEL_CAPACITY).0)
511        .clone()
512}
513
514/// Subscribe to all future events on the global bus.
515///
516/// Why: SSE handlers + tests both need a fresh receiver without sharing one.
517/// `broadcast::Receiver::recv` is `&mut self` so each subscriber owns one.
518/// What: Returns a new `Receiver` that begins receiving events emitted after
519/// the call returns. Lagged subscribers receive `RecvError::Lagged(n)` and
520/// can resume.
521pub fn subscribe() -> broadcast::Receiver<SessionEventEnvelope> {
522    bus().subscribe()
523}
524
525/// Publish one envelope to the bus (best-effort, never panics).
526///
527/// Why: Most callers don't care whether anyone is listening — events are
528/// telemetry, not control flow. Failures (no subscribers) are normal. The
529/// envelope (not a bare `Event`) is the unit of publication so `seq`/`at`
530/// travel with the payload to every subscriber, including a client that
531/// only just attached.
532/// What: Sends the envelope on the broadcast channel, ignoring `SendError`.
533/// Test: `publish_round_trips_through_subscribe`.
534pub fn publish(envelope: SessionEventEnvelope) {
535    let _ = bus().send(envelope);
536}
537
538/// Publish an envelope AND emit it on stderr with the `__OMPM_EVENT__` prefix
539/// so a parent process can re-broadcast on its own bus.
540///
541/// Why: Workflow runs spawn as `tcode --workflow ...` subprocesses of the
542/// API server (`api/server.rs::run_task`). Events emitted inside that child
543/// reach the parent's bus only via the existing stderr stream. This helper
544/// does both in one call so emit sites don't have to know whether they're
545/// running as a child.
546/// What: Calls `publish(envelope.clone())` for in-process subscribers, then
547/// writes one NDJSON line to stderr prefixed with `__OMPM_EVENT__ `. The
548/// parent's stderr reader (in `api::server::run_task`) detects the prefix
549/// and re-publishes on its own bus.
550/// Test: Indirect — exercised by the workflow integration path.
551pub fn emit(envelope: SessionEventEnvelope) {
552    publish(envelope.clone());
553    if let Ok(line) = serde_json::to_string(&envelope) {
554        eprintln!("{EVENT_LINE_PREFIX}{line}");
555    }
556}
557
558/// Truncate a string to at most `max` characters, appending an ellipsis
559/// marker when truncation occurred. Operates on chars (not bytes) so
560/// multi-byte characters are not split.
561///
562/// Why: Event payloads should be human-readable previews; raw multi-KB
563/// agent outputs would saturate the broadcast channel and overwhelm the SSE
564/// stream. Centralising preview construction keeps emit sites tidy.
565/// What: Returns `s` unchanged when shorter than `max`; otherwise returns
566/// the first `max` chars plus a Unicode horizontal ellipsis.
567pub fn preview(s: &str, max: usize) -> String {
568    if s.chars().count() <= max {
569        return s.to_string();
570    }
571    let mut out: String = s.chars().take(max).collect();
572    out.push('\u{2026}');
573    out
574}
575
576#[cfg(test)]
577mod tests {
578    use super::*;
579
580    #[test]
581    fn event_serializes_with_type_tag() {
582        let ev = Event::PmThinking {
583            session_id: "s1".into(),
584            text: "considering options".into(),
585        };
586        let s = serde_json::to_string(&ev).unwrap();
587        assert!(s.contains("\"type\":\"pm_thinking\""), "{s}");
588        assert!(s.contains("\"session_id\":\"s1\""), "{s}");
589    }
590
591    #[test]
592    fn ping_roundtrips() {
593        let s = serde_json::to_string(&Event::Ping).unwrap();
594        let back: Event = serde_json::from_str(&s).unwrap();
595        assert!(matches!(back, Event::Ping));
596    }
597
598    #[test]
599    fn session_id_returns_correct_field() {
600        let ev = Event::AgentMessage {
601            session_id: "abc".into(),
602            agent: "python".into(),
603            text: "hi".into(),
604        };
605        assert_eq!(ev.session_id(), Some("abc"));
606        assert_eq!(Event::Ping.session_id(), None);
607    }
608
609    #[test]
610    fn bus_is_singleton() {
611        let a = bus();
612        let b = bus();
613        // Two senders to the same channel: a message sent on `a` should be
614        // visible to a receiver from `b`.
615        let mut rx = b.subscribe();
616        let envelope = SessionEventEnvelope::new("s-bus".into(), 1, Utc::now(), Event::Ping);
617        let _ = a.send(envelope);
618        // Drain via try_recv to avoid an async runtime in this sync test.
619        let got = rx.try_recv().expect("expected an envelope");
620        assert!(matches!(got.event, Event::Ping));
621    }
622
623    #[tokio::test]
624    async fn publish_round_trips_through_subscribe() {
625        let mut rx = subscribe();
626        let envelope = SessionEventEnvelope::new(
627            "t1".into(),
628            1,
629            Utc::now(),
630            Event::SessionStarted {
631                session_id: "t1".into(),
632                project: "demo".into(),
633            },
634        );
635        publish(envelope);
636        let got = rx.recv().await.unwrap();
637        assert_eq!(got.session_id, "t1");
638        assert_eq!(got.seq, 1);
639        assert_eq!(got.kind, "session_started");
640        match got.event {
641            Event::SessionStarted {
642                session_id,
643                project,
644            } => {
645                assert_eq!(session_id, "t1");
646                assert_eq!(project, "demo");
647            }
648            other => panic!("unexpected event: {other:?}"),
649        }
650    }
651
652    /// `kind()` must match the serde `"type"` tag for every variant — the
653    /// guard `SessionEventEnvelope::new`'s doc comment references.
654    #[test]
655    fn kind_matches_serde_tag_for_every_variant() {
656        let samples: Vec<Event> = vec![
657            Event::SessionStarted {
658                session_id: "s".into(),
659                project: "p".into(),
660            },
661            Event::SessionDone {
662                session_id: "s".into(),
663                status: "done".into(),
664            },
665            Event::SessionCancelled {
666                session_id: "s".into(),
667            },
668            Event::SessionStatusChanged {
669                session_id: "s".into(),
670                status: "running".into(),
671            },
672            Event::SessionInput {
673                session_id: "s".into(),
674                input: "hi".into(),
675            },
676            Event::ToolStarted {
677                session_id: "s".into(),
678                tool: "bash".into(),
679                call_id: "c1".into(),
680                args_preview: "ls".into(),
681            },
682            Event::ToolFinished {
683                session_id: "s".into(),
684                tool: "bash".into(),
685                call_id: "c1".into(),
686                success: true,
687                result_preview: "ok".into(),
688            },
689            Event::ToolError {
690                session_id: "s".into(),
691                tool: "bash".into(),
692                call_id: "c1".into(),
693                error: "boom".into(),
694            },
695            Event::Log {
696                session_id: "s".into(),
697                level: "info".into(),
698                message: "m".into(),
699            },
700            Event::Progress {
701                session_id: "s".into(),
702                message: "m".into(),
703                percent: None,
704            },
705            Event::Message {
706                session_id: "s".into(),
707                text: "hi".into(),
708            },
709            Event::Ping,
710        ];
711        for ev in samples {
712            let value = serde_json::to_value(&ev).unwrap();
713            let wire_type = value["type"].as_str().unwrap_or("ping");
714            assert_eq!(
715                ev.kind(),
716                wire_type,
717                "kind() drifted from the serde tag for {ev:?}"
718            );
719        }
720    }
721
722    /// `SessionEventEnvelope` must round-trip through JSON with every field
723    /// present, and `kind` must be derived from `event.kind()`.
724    #[test]
725    fn session_event_envelope_round_trips_through_json() {
726        let event = Event::SessionInput {
727            session_id: "s1".into(),
728            input: "hello".into(),
729        };
730        let envelope = SessionEventEnvelope::new("s1".into(), 7, Utc::now(), event);
731
732        let value = serde_json::to_value(&envelope).unwrap();
733        assert_eq!(value["session_id"], "s1");
734        assert_eq!(value["seq"], 7);
735        assert_eq!(value["kind"], "session_input");
736        assert_eq!(value["event"]["type"], "session_input");
737        assert!(value["at"].is_string());
738
739        let back: SessionEventEnvelope = serde_json::from_value(value).unwrap();
740        assert_eq!(back.session_id, "s1");
741        assert_eq!(back.seq, 7);
742    }
743
744    #[test]
745    fn preview_truncates_at_char_boundary() {
746        assert_eq!(preview("hi", 5), "hi");
747        let out = preview("abcdef", 3);
748        assert_eq!(out.chars().count(), 4); // 3 + ellipsis
749        assert!(out.starts_with("abc"));
750        assert!(out.ends_with('\u{2026}'));
751    }
752
753    #[test]
754    fn event_line_prefix_is_stable() {
755        // Lock in the wire constant — changing it breaks the parent/child
756        // relay protocol.
757        assert_eq!(EVENT_LINE_PREFIX, "__OMPM_EVENT__ ");
758    }
759}