Skip to main content

astrid_types/
ipc.rs

1//! Cross-boundary IPC message schemas and payloads.
2
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6use uuid::Uuid;
7
8/// A cross-boundary message sent over the event bus between WASM guests and the host.
9#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
10pub struct IpcMessage {
11    /// Topic pattern or exact match (e.g., `astrid.cli.input`).
12    pub topic: String,
13    /// Standardized payload structure.
14    pub payload: IpcPayload,
15    /// Optional cryptographic signature for stateless verification across a distributed swarm.
16    #[serde(default)]
17    pub signature: Option<Vec<u8>>,
18    /// Identifier of the sender plugin or agent.
19    pub source_id: Uuid,
20    /// Timestamp when the message was dispatched. Defaults to now on
21    /// deserialization so capsules forwarding bus messages over the wire
22    /// (e.g. the CLI proxy) don't need to fabricate a timestamp the SDK
23    /// doesn't expose to them. Only filled in by the `clock` feature
24    /// path (kernel-side); when the feature is off (capsule SDK
25    /// consumption on `wasm32-unknown-unknown`), missing timestamps
26    /// fall back to the Unix epoch — capsules read timestamps from
27    /// kernel-published messages, they never construct fresh ones.
28    #[cfg_attr(feature = "clock", serde(default = "Utc::now"))]
29    #[cfg_attr(not(feature = "clock"), serde(default = "default_unix_epoch"))]
30    pub timestamp: DateTime<Utc>,
31    /// Monotonic sequence number assigned by the event bus at publish time.
32    /// Used by the dispatcher to guarantee in-order delivery per capsule.
33    #[serde(default)]
34    pub seq: u64,
35    /// The principal (user identity) this message is acting on behalf of.
36    ///
37    /// `String` rather than `PrincipalId` because `astrid-types` must not
38    /// depend on `astrid-core`. Validation to `PrincipalId` happens at the
39    /// kernel boundary. `None` for system events (boot, lifecycle).
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub principal: Option<String>,
42}
43
44/// `DateTime<Utc>` at the Unix epoch — used as the serde default for
45/// `timestamp` fields when the `clock` feature is off and a message
46/// arrives without one. Capsule-side code never inspects this value;
47/// kernel-side code always sets a real timestamp before publish.
48#[cfg(not(feature = "clock"))]
49fn default_unix_epoch() -> DateTime<Utc> {
50    DateTime::<Utc>::from_timestamp(0, 0).unwrap_or_else(|| {
51        // chrono guarantees epoch is representable; this branch is
52        // unreachable. Use `MIN_UTC` as the safe fallback.
53        DateTime::<Utc>::MIN_UTC
54    })
55}
56
57impl IpcMessage {
58    /// Create a new IPC message stamped with the current wall-clock
59    /// time. Only available when the `clock` feature is enabled
60    /// (kernel-side); capsule code constructs `IpcMessage` from
61    /// payloads it receives, never from scratch.
62    #[cfg(feature = "clock")]
63    #[must_use]
64    pub fn new(topic: impl Into<String>, payload: IpcPayload, source_id: Uuid) -> Self {
65        Self {
66            topic: topic.into(),
67            payload,
68            signature: None,
69            source_id,
70            timestamp: Utc::now(),
71            seq: 0,
72            principal: None,
73        }
74    }
75
76    /// Attach a signature for swarm verification.
77    #[must_use]
78    pub fn with_signature(mut self, signature: Vec<u8>) -> Self {
79        self.signature = Some(signature);
80        self
81    }
82
83    /// Set the acting principal for this message.
84    #[must_use]
85    pub fn with_principal(mut self, principal: impl Into<String>) -> Self {
86        self.principal = Some(principal.into());
87        self
88    }
89}
90
91/// Default session ID for conversations.
92fn default_session_id() -> String {
93    "default".into()
94}
95
96/// Standardized cross-boundary payload schemas.
97#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
98#[serde(tag = "type", rename_all = "snake_case")]
99pub enum IpcPayload {
100    /// Raw, arbitrary JSON.
101    RawJson(Value),
102    /// User input provided via a frontend (CLI, Telegram).
103    UserInput {
104        /// The raw text input.
105        text: String,
106        /// Session ID for conversation continuity. Defaults to `"default"`.
107        #[serde(default = "default_session_id")]
108        session_id: String,
109        /// Optional extra context.
110        #[serde(default, skip_serializing_if = "Option::is_none")]
111        context: Option<Value>,
112    },
113    /// A response generated by an agent.
114    AgentResponse {
115        /// The text output.
116        text: String,
117        /// True if this is the final response in a chain.
118        is_final: bool,
119        /// Session ID for multi-session attribution.
120        #[serde(default = "default_session_id")]
121        session_id: String,
122    },
123    /// An interceptor or capsule request for capability approval.
124    ApprovalRequired {
125        /// Opaque correlation ID.
126        request_id: String,
127        /// The action being requested (e.g. "git push").
128        action: String,
129        /// The resource target (e.g. full command string).
130        resource: String,
131        /// Justification.
132        reason: String,
133    },
134    /// Response to an [`ApprovalRequired`](IpcPayload::ApprovalRequired).
135    ApprovalResponse {
136        /// Must match the `request_id` from the originating request.
137        request_id: String,
138        /// The user's decision.
139        decision: String,
140        /// Optional reason for the decision.
141        #[serde(default, skip_serializing_if = "Option::is_none")]
142        reason: Option<String>,
143    },
144    /// A capsule needs environment variables to be provided by the user.
145    OnboardingRequired {
146        /// The ID of the capsule requiring onboarding.
147        capsule_id: String,
148        /// Rich field descriptors for each missing env var.
149        fields: Vec<OnboardingField>,
150    },
151    /// Request an LLM provider capsule to generate a response.
152    LlmRequest {
153        /// The unique ID of the request, used for routing the response stream back.
154        request_id: Uuid,
155        /// The requested model name (e.g. "claude-3-5-sonnet").
156        model: String,
157        /// The conversation history.
158        messages: Vec<crate::llm::Message>,
159        /// The tools available to the model.
160        tools: Vec<crate::llm::LlmToolDefinition>,
161        /// The system prompt.
162        system: String,
163    },
164    /// A stream event from an LLM provider capsule.
165    LlmStreamEvent {
166        /// The unique ID of the request this stream belongs to.
167        request_id: Uuid,
168        /// The actual stream event (`TokenDelta`, `ToolCallStart`, etc).
169        event: crate::llm::StreamEvent,
170    },
171    /// The final, non-streaming LLM response.
172    LlmResponse {
173        /// The unique ID of the request this response belongs to.
174        request_id: Uuid,
175        /// The final response object.
176        response: crate::llm::LlmResponse,
177    },
178    /// Request the Tool Router capsule to execute a tool.
179    ToolExecuteRequest {
180        /// The unique ID of the tool call.
181        call_id: String,
182        /// The name of the tool to execute.
183        tool_name: String,
184        /// The JSON arguments.
185        arguments: Value,
186    },
187    /// The result of a tool execution.
188    ToolExecuteResult {
189        /// The unique ID of the tool call.
190        call_id: String,
191        /// The result of the execution.
192        result: crate::llm::ToolCallResult,
193    },
194    /// Request cancellation of in-flight tool executions.
195    ToolCancelRequest {
196        /// The call IDs of the tool invocations to cancel.
197        call_ids: Vec<String>,
198    },
199    /// A capsule is requesting the user to select from a list of options.
200    SelectionRequired {
201        /// Opaque ID so the capsule can correlate the response.
202        request_id: String,
203        /// Title/prompt shown above the list.
204        title: String,
205        /// The selectable options.
206        options: Vec<SelectionOption>,
207        /// IPC topic to publish the user's choice back on.
208        callback_topic: String,
209    },
210    /// A lifecycle hook is requesting user input via the `elicit` API.
211    ElicitRequest {
212        /// Correlation ID.
213        request_id: Uuid,
214        /// The capsule requesting input.
215        capsule_id: String,
216        /// Field descriptor reusing the onboarding schema.
217        field: OnboardingField,
218    },
219    /// Response to an [`ElicitRequest`](IpcPayload::ElicitRequest).
220    ElicitResponse {
221        /// Must match the `request_id` from the originating request.
222        request_id: Uuid,
223        /// The user's input. `None` if the user cancelled.
224        #[serde(default, skip_serializing_if = "Option::is_none")]
225        value: Option<String>,
226        /// For `Array`-type fields, the collected items.
227        #[serde(default, skip_serializing_if = "Option::is_none")]
228        values: Option<Vec<String>>,
229    },
230    /// A client has connected.
231    Connect,
232    /// A client is disconnecting gracefully.
233    Disconnect {
234        /// Optional reason for disconnection (e.g. "quit", "timeout").
235        #[serde(default, skip_serializing_if = "Option::is_none")]
236        reason: Option<String>,
237    },
238    /// Arbitrary JSON data for unstructured plugins.
239    Custom {
240        /// Raw data.
241        data: Value,
242    },
243    /// Unrecognized payload type from a newer protocol version.
244    #[serde(other)]
245    Unknown,
246}
247
248impl IpcPayload {
249    /// Returns `true` if `tag` matches a known serde variant name.
250    #[must_use]
251    pub fn is_known_tag(tag: &str) -> bool {
252        matches!(
253            tag,
254            "raw_json"
255                | "user_input"
256                | "agent_response"
257                | "approval_required"
258                | "approval_response"
259                | "onboarding_required"
260                | "llm_request"
261                | "llm_stream_event"
262                | "llm_response"
263                | "tool_execute_request"
264                | "tool_execute_result"
265                | "tool_cancel_request"
266                | "selection_required"
267                | "elicit_request"
268                | "elicit_response"
269                | "connect"
270                | "disconnect"
271                | "custom"
272        )
273    }
274
275    /// Deserialize a JSON [`Value`] into an `IpcPayload`, falling back to
276    /// [`Custom`](Self::Custom) for unrecognised or missing type tags.
277    pub fn from_json_value(data: Value) -> Self {
278        let is_known = data
279            .get("type")
280            .and_then(|v| v.as_str())
281            .is_some_and(Self::is_known_tag);
282
283        if is_known {
284            serde_json::from_value::<Self>(data.clone()).unwrap_or(Self::Custom { data })
285        } else {
286            Self::Custom { data }
287        }
288    }
289
290    /// Serialize only the guest-facing payload data.
291    ///
292    /// [`Custom`](Self::Custom) and [`RawJson`](Self::RawJson) payloads return
293    /// the inner data value directly (no `type` wrapper). Structured variants
294    /// return the full tagged serialization.
295    ///
296    /// # Errors
297    ///
298    /// Returns `serde_json::Error` if serialization fails.
299    pub fn to_guest_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
300        match self {
301            Self::Custom { data } | Self::RawJson(data) => serde_json::to_vec(data),
302            other => serde_json::to_vec(other),
303        }
304    }
305}
306
307/// A single option in a `SelectionRequired` picker.
308#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
309pub struct SelectionOption {
310    /// Machine-readable identifier sent back to the capsule.
311    pub id: String,
312    /// Human-readable label shown in the picker.
313    pub label: String,
314    /// Optional description shown alongside the label.
315    #[serde(default, skip_serializing_if = "Option::is_none")]
316    pub description: Option<String>,
317}
318
319/// A field descriptor for capsule onboarding.
320#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
321pub struct OnboardingField {
322    /// The environment variable key.
323    pub key: String,
324    /// The prompt shown to the user.
325    pub prompt: String,
326    /// Optional description for additional context.
327    #[serde(default, skip_serializing_if = "Option::is_none")]
328    pub description: Option<String>,
329    /// The input type for this field.
330    pub field_type: OnboardingFieldType,
331    /// Optional default value.
332    #[serde(default, skip_serializing_if = "Option::is_none")]
333    pub default: Option<String>,
334    /// Placeholder hint text shown when the input is empty (e.g. `"sk-..."`).
335    #[serde(default, skip_serializing_if = "Option::is_none")]
336    pub placeholder: Option<String>,
337}
338
339/// The type of input expected for an onboarding field.
340#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
341pub enum OnboardingFieldType {
342    /// Free-form text input.
343    Text,
344    /// Masked secret input.
345    Secret,
346    /// Selection from a fixed set of choices.
347    Enum(Vec<String>),
348    /// Multi-value array input (user adds items one at a time).
349    Array,
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355
356    #[test]
357    fn ipc_message_signature() {
358        let msg = IpcMessage::new(
359            "test.topic",
360            IpcPayload::AgentResponse {
361                text: "hello".into(),
362                is_final: true,
363                session_id: "default".into(),
364            },
365            Uuid::new_v4(),
366        );
367        assert!(msg.signature.is_none());
368
369        let signed = msg.with_signature(vec![1, 2, 3]);
370        assert_eq!(signed.signature, Some(vec![1, 2, 3]));
371    }
372
373    #[test]
374    fn ipc_message_principal() {
375        let msg = IpcMessage::new(
376            "test.topic",
377            IpcPayload::Custom {
378                data: serde_json::json!({}),
379            },
380            Uuid::new_v4(),
381        );
382        assert!(msg.principal.is_none());
383
384        let with_principal = msg.with_principal("alice");
385        assert_eq!(with_principal.principal.as_deref(), Some("alice"));
386    }
387
388    #[test]
389    fn ipc_message_principal_serde_roundtrip() {
390        let msg = IpcMessage::new(
391            "test.topic",
392            IpcPayload::Custom {
393                data: serde_json::json!({}),
394            },
395            Uuid::nil(),
396        )
397        .with_principal("bob");
398        let json = serde_json::to_string(&msg).unwrap();
399        assert!(json.contains(r#""principal":"bob""#));
400
401        let parsed: IpcMessage = serde_json::from_str(&json).unwrap();
402        assert_eq!(parsed.principal.as_deref(), Some("bob"));
403    }
404
405    #[test]
406    fn ipc_message_principal_absent_in_json() {
407        // Messages without principal should deserialize with None.
408        let json = r#"{"topic":"t","payload":{"type":"connect"},"source_id":"00000000-0000-0000-0000-000000000000","timestamp":"2024-01-01T00:00:00Z","seq":0}"#;
409        let msg: IpcMessage = serde_json::from_str(json).unwrap();
410        assert!(msg.principal.is_none());
411    }
412
413    #[test]
414    fn ipc_message_principal_not_serialized_when_none() {
415        let msg = IpcMessage::new("test.topic", IpcPayload::Connect, Uuid::nil());
416        let json = serde_json::to_string(&msg).unwrap();
417        assert!(!json.contains("principal"));
418    }
419
420    #[test]
421    fn unknown_type_tag_deserializes_to_unknown() {
422        let json = r#"{"type":"future_variant","some_data":42}"#;
423        let payload: IpcPayload = serde_json::from_str(json).unwrap();
424        assert_eq!(payload, IpcPayload::Unknown);
425    }
426
427    #[test]
428    fn ipc_message_parses_cli_proxy_wire_format() {
429        // The CLI proxy capsule (capsules/astrid-capsule-cli) forwards bus
430        // messages to socket clients using only the fields exposed by the
431        // SDK's `ipc::Message`: {topic, payload, source_id}. The SDK does
432        // not surface the original timestamp or signature, so the wire
433        // format omits them. Without serde defaults on those fields the
434        // headless client's `from_slice::<IpcMessage>` silently fails on
435        // every frame and the response never reaches the user.
436        let wire = r#"{"topic":"agent.v1.response","payload":{"type":"agent_response","text":"hi","is_final":true,"session_id":"00000000-0000-0000-0000-000000000000"},"source_id":"00000000-0000-0000-0000-000000000000"}"#;
437        let msg: IpcMessage = serde_json::from_str(wire).expect("cli proxy frame must parse");
438        assert_eq!(msg.topic, "agent.v1.response");
439        assert!(msg.signature.is_none());
440        assert_eq!(msg.seq, 0);
441        match msg.payload {
442            IpcPayload::AgentResponse { text, is_final, .. } => {
443                assert_eq!(text, "hi");
444                assert!(is_final);
445            },
446            other => panic!("unexpected payload variant: {other:?}"),
447        }
448    }
449
450    #[test]
451    fn known_variants_unaffected_by_unknown() {
452        let payload = IpcPayload::AgentResponse {
453            text: "hello".into(),
454            is_final: true,
455            session_id: "s1".into(),
456        };
457        let json = serde_json::to_string(&payload).unwrap();
458        let parsed: IpcPayload = serde_json::from_str(&json).unwrap();
459        assert_eq!(parsed, payload);
460    }
461
462    #[test]
463    fn unknown_variant_serializes_as_type_unknown() {
464        let json = serde_json::to_string(&IpcPayload::Unknown).unwrap();
465        assert_eq!(json, r#"{"type":"unknown"}"#);
466    }
467
468    /// Every variant's serialized `type` tag must be recognised by
469    /// `is_known_tag`. If a new variant is added without updating the
470    /// match arm *and* the representatives list below, this test fails.
471    #[test]
472    fn is_known_tag_covers_all_variants() {
473        const EXPECTED_VARIANT_COUNT: usize = 17;
474
475        let representatives: Vec<IpcPayload> = vec![
476            IpcPayload::RawJson(serde_json::json!({"key": "val"})),
477            IpcPayload::UserInput {
478                text: String::new(),
479                session_id: "s".into(),
480                context: None,
481            },
482            IpcPayload::AgentResponse {
483                text: String::new(),
484                is_final: false,
485                session_id: "s".into(),
486            },
487            IpcPayload::ApprovalRequired {
488                request_id: "req-1".into(),
489                action: String::new(),
490                resource: String::new(),
491                reason: String::new(),
492            },
493            IpcPayload::ApprovalResponse {
494                request_id: "req-1".into(),
495                decision: "approve".into(),
496                reason: None,
497            },
498            IpcPayload::OnboardingRequired {
499                capsule_id: String::new(),
500                fields: vec![],
501            },
502            IpcPayload::LlmRequest {
503                request_id: Uuid::nil(),
504                model: String::new(),
505                messages: vec![],
506                tools: vec![],
507                system: String::new(),
508            },
509            IpcPayload::LlmStreamEvent {
510                request_id: Uuid::nil(),
511                event: crate::llm::StreamEvent::TextDelta(String::new()),
512            },
513            IpcPayload::LlmResponse {
514                request_id: Uuid::nil(),
515                response: crate::llm::LlmResponse {
516                    message: crate::llm::Message {
517                        role: crate::llm::MessageRole::Assistant,
518                        content: crate::llm::MessageContent::Text(String::new()),
519                    },
520                    has_tool_calls: false,
521                    stop_reason: crate::llm::StopReason::EndTurn,
522                    usage: crate::llm::Usage {
523                        input_tokens: 0,
524                        output_tokens: 0,
525                    },
526                },
527            },
528            IpcPayload::ToolExecuteRequest {
529                call_id: String::new(),
530                tool_name: String::new(),
531                arguments: Value::Null,
532            },
533            IpcPayload::ToolExecuteResult {
534                call_id: String::new(),
535                result: crate::llm::ToolCallResult {
536                    call_id: String::new(),
537                    content: String::new(),
538                    is_error: false,
539                },
540            },
541            IpcPayload::SelectionRequired {
542                request_id: String::new(),
543                title: String::new(),
544                options: vec![],
545                callback_topic: String::new(),
546            },
547            IpcPayload::ElicitRequest {
548                request_id: Uuid::nil(),
549                capsule_id: String::new(),
550                field: OnboardingField {
551                    key: String::new(),
552                    prompt: String::new(),
553                    description: None,
554                    field_type: OnboardingFieldType::Text,
555                    default: None,
556                    placeholder: None,
557                },
558            },
559            IpcPayload::ElicitResponse {
560                request_id: Uuid::nil(),
561                value: None,
562                values: None,
563            },
564            IpcPayload::Connect,
565            IpcPayload::Disconnect { reason: None },
566            IpcPayload::Custom {
567                data: Value::Object(serde_json::Map::new()),
568            },
569        ];
570
571        assert_eq!(
572            representatives.len(),
573            EXPECTED_VARIANT_COUNT,
574            "IpcPayload variant count changed. Update the representatives list \
575             and bump EXPECTED_VARIANT_COUNT."
576        );
577
578        for variant in &representatives {
579            let json = serde_json::to_value(variant).unwrap();
580            let tag = json["type"]
581                .as_str()
582                .unwrap_or_else(|| panic!("variant {variant:?} has no `type` tag"));
583            assert!(
584                IpcPayload::is_known_tag(tag),
585                "is_known_tag does not recognise tag '{tag}' from variant {variant:?}"
586            );
587        }
588    }
589
590    #[test]
591    fn is_known_tag_rejects_unknown_tags() {
592        assert!(!IpcPayload::is_known_tag("my_plugin_msg"));
593        assert!(!IpcPayload::is_known_tag("unknown"));
594        assert!(!IpcPayload::is_known_tag(""));
595        assert!(!IpcPayload::is_known_tag("Raw_Json"));
596    }
597
598    #[test]
599    fn onboarding_field_roundtrip() {
600        let field = OnboardingField {
601            key: "apiKey".into(),
602            prompt: "Enter API key".into(),
603            description: None,
604            field_type: OnboardingFieldType::Secret,
605            default: None,
606            placeholder: None,
607        };
608        let json = serde_json::to_string(&field).unwrap();
609        let parsed: OnboardingField = serde_json::from_str(&json).unwrap();
610        assert_eq!(parsed, field);
611    }
612
613    #[test]
614    fn onboarding_field_roundtrip_array() {
615        let field = OnboardingField {
616            key: "relays".into(),
617            prompt: "Enter relay URLs".into(),
618            description: Some("Nostr relay endpoints".into()),
619            field_type: OnboardingFieldType::Array,
620            default: None,
621            placeholder: None,
622        };
623        let json = serde_json::to_string(&field).unwrap();
624        let parsed: OnboardingField = serde_json::from_str(&json).unwrap();
625        assert_eq!(parsed, field);
626    }
627
628    #[test]
629    fn onboarding_required_payload_roundtrip() {
630        let payload = IpcPayload::OnboardingRequired {
631            capsule_id: "test-capsule".into(),
632            fields: vec![
633                OnboardingField {
634                    key: "network".into(),
635                    prompt: "Select network".into(),
636                    description: Some("Choose the target network".into()),
637                    field_type: OnboardingFieldType::Enum(vec!["testnet".into(), "mainnet".into()]),
638                    default: Some("testnet".into()),
639                    placeholder: None,
640                },
641                OnboardingField {
642                    key: "apiKey".into(),
643                    prompt: "Enter API key".into(),
644                    description: None,
645                    field_type: OnboardingFieldType::Secret,
646                    default: None,
647                    placeholder: None,
648                },
649            ],
650        };
651        let json = serde_json::to_string(&payload).unwrap();
652        let parsed: IpcPayload = serde_json::from_str(&json).unwrap();
653        assert_eq!(parsed, payload);
654    }
655
656    #[test]
657    fn elicit_request_roundtrip() {
658        let payload = IpcPayload::ElicitRequest {
659            request_id: Uuid::nil(),
660            capsule_id: "my-capsule".into(),
661            field: OnboardingField {
662                key: "api_url".into(),
663                prompt: "Enter API URL".into(),
664                description: Some("The backend endpoint".into()),
665                field_type: OnboardingFieldType::Text,
666                default: Some("https://example.com".into()),
667                placeholder: None,
668            },
669        };
670        let json = serde_json::to_string(&payload).unwrap();
671        let parsed: IpcPayload = serde_json::from_str(&json).unwrap();
672        assert_eq!(parsed, payload);
673    }
674
675    #[test]
676    fn elicit_response_roundtrip() {
677        let payload = IpcPayload::ElicitResponse {
678            request_id: Uuid::nil(),
679            value: Some("hello".into()),
680            values: None,
681        };
682        let json = serde_json::to_string(&payload).unwrap();
683        let parsed: IpcPayload = serde_json::from_str(&json).unwrap();
684        assert_eq!(parsed, payload);
685    }
686
687    #[test]
688    fn disconnect_with_reason_roundtrip() {
689        let payload = IpcPayload::Disconnect {
690            reason: Some("quit".into()),
691        };
692        let json = serde_json::to_string(&payload).unwrap();
693        let parsed: IpcPayload = serde_json::from_str(&json).unwrap();
694        assert_eq!(parsed, payload);
695        assert!(json.contains(r#""type":"disconnect""#), "json: {json}");
696    }
697
698    #[test]
699    fn disconnect_without_reason_roundtrip() {
700        let payload = IpcPayload::Disconnect { reason: None };
701        let json = serde_json::to_string(&payload).unwrap();
702        let parsed: IpcPayload = serde_json::from_str(&json).unwrap();
703        assert_eq!(parsed, payload);
704        assert!(!json.contains("reason"), "json: {json}");
705    }
706
707    #[test]
708    fn to_guest_bytes_custom_returns_inner_data() {
709        let data = serde_json::json!({"session_id": "abc", "messages": []});
710        let payload = IpcPayload::Custom { data: data.clone() };
711        let bytes = payload.to_guest_bytes().unwrap();
712        let roundtrip: Value = serde_json::from_slice(&bytes).unwrap();
713        assert_eq!(roundtrip, data);
714        assert!(roundtrip.get("type").is_none());
715    }
716
717    #[test]
718    fn to_guest_bytes_structured_preserves_type_tag() {
719        let payload = IpcPayload::UserInput {
720            text: "hello".into(),
721            session_id: "default".into(),
722            context: None,
723        };
724        let bytes = payload.to_guest_bytes().unwrap();
725        let roundtrip: Value = serde_json::from_slice(&bytes).unwrap();
726        assert_eq!(
727            roundtrip.get("type").and_then(|v| v.as_str()),
728            Some("user_input")
729        );
730    }
731
732    #[test]
733    fn to_guest_bytes_raw_json_unwraps() {
734        let inner = serde_json::json!({"key": "value"});
735        let payload = IpcPayload::RawJson(inner.clone());
736        let bytes = payload.to_guest_bytes().unwrap();
737        let roundtrip: Value = serde_json::from_slice(&bytes).unwrap();
738        assert_eq!(roundtrip, inner);
739        assert!(roundtrip.get("type").is_none());
740    }
741
742    #[test]
743    fn to_guest_bytes_connect_unit_variant() {
744        let payload = IpcPayload::Connect;
745        let bytes = payload.to_guest_bytes().unwrap();
746        let roundtrip: Value = serde_json::from_slice(&bytes).unwrap();
747        assert_eq!(
748            roundtrip.get("type").and_then(|v| v.as_str()),
749            Some("connect")
750        );
751    }
752
753    #[test]
754    fn from_json_value_unknown_tag_becomes_custom() {
755        let data = serde_json::json!({"type": "my_plugin_msg", "foo": 42});
756        let payload = IpcPayload::from_json_value(data.clone());
757        assert_eq!(payload, IpcPayload::Custom { data });
758    }
759
760    #[test]
761    fn from_json_value_known_tag_parses() {
762        let data = serde_json::json!({
763            "type": "user_input",
764            "text": "hi",
765            "session_id": "s1"
766        });
767        let payload = IpcPayload::from_json_value(data);
768        assert!(matches!(payload, IpcPayload::UserInput { .. }));
769    }
770}