Skip to main content

core_api/
external_rpc.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4use crate::{AuthRequest, AuthenticatedSession, ServiceCoreInput, ServiceCoreOutput};
5use std::collections::HashMap;
6
7pub const EXTERNAL_CORE_PROTOCOL_VERSION: u32 = 18;
8/// Maximum single native artifact body, separate from the JSON control frame limit.
9pub const MAX_NATIVE_ARTIFACT_BYTES: usize = 50 * 1024 * 1024;
10pub const MAX_NATIVE_ARTIFACT_BASE64_BYTES: usize = MAX_NATIVE_ARTIFACT_BYTES.div_ceil(3) * 4;
11/// Protocol 18 sends large dataBase64 strings after the JSON frame. The JSON field
12/// is an empty string marker, followed by a u32 byte length and that many ASCII
13/// bytes on the same connection. Only artifact commit requests and open/read
14/// responses support this attachment. Control frames keep their 16 MiB limit.
15pub const ARTIFACT_ATTACHMENT_CHUNK_BYTES: usize = 1024 * 1024;
16pub const ARTIFACT_CONTENT_PATH_PREFIX: &str = "/artifact/v1/content/";
17pub const ARTIFACT_UPLOAD_PATH_PREFIX: &str = "/artifact/v1/upload/";
18
19/// Derive a bounded, workdir-specific Windows IPC name from the metadata socket path.
20/// The metadata itself stays in the ordinary runtime directory on every platform.
21pub fn external_core_pipe_name(socket_path: &std::path::Path) -> String {
22    use sha2::{Digest, Sha256};
23    let normalized = socket_path
24        .to_string_lossy()
25        .replace('/', "\\")
26        .to_lowercase();
27    format!(
28        r"\\.\pipe\meowcore-{:x}",
29        Sha256::digest(normalized.as_bytes())
30    )
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct ExternalCoreRequest {
35    pub id: String,
36    pub method: ExternalCoreMethod,
37    pub payload: Value,
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct ExternalCoreResponse {
42    pub id: String,
43    pub ok: bool,
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub result: Option<Value>,
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub error: Option<ExternalCoreError>,
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct ExternalCoreError {
52    pub code: String,
53    pub message: String,
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub details: Option<Value>,
56}
57
58impl From<crate::ErrorResponse> for ExternalCoreError {
59    fn from(error: crate::ErrorResponse) -> Self {
60        Self {
61            code: error.error,
62            message: error.message,
63            details: error.details,
64        }
65    }
66}
67
68impl From<ExternalCoreError> for crate::ErrorResponse {
69    fn from(error: ExternalCoreError) -> Self {
70        Self {
71            error: error.code,
72            message: error.message,
73            details: error.details,
74        }
75    }
76}
77
78impl std::fmt::Display for ExternalCoreError {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        write!(f, "[{}] {}", self.code, self.message)
81    }
82}
83
84impl std::error::Error for ExternalCoreError {}
85
86/// A completed JSON HTTP handler response, including non-2xx responses.
87/// This is an RPC result, not an RPC error. Hosts must preserve both fields.
88#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase")]
90pub struct HttpPayloadResponse {
91    pub status_code: u16,
92    pub body: Value,
93}
94
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub enum ExternalCoreMethod {
97    HandleCoreInput,
98    RegisterLocalAppClient,
99    RegisterNodeConnection,
100    CleanupWsState,
101    UpdateCallbackBase,
102    PutArtifact,
103    OpenArtifact,
104    AuthorizeArtifactRead,
105    AuthorizeArtifactUpload,
106    CommitArtifactUpload,
107    DeviceIdentity,
108    CommissionFingerprint,
109    CommissionPublicKeyBase64,
110    ListMdnsRecords,
111    PollEvents,
112    CompleteEvents,
113    CommissionChallengePayload,
114    PairingStartPayload,
115    SetupStartPayload,
116    GeneralWebhookPayload,
117    InvokeWasmPayload,
118    Health,
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub struct HandleCoreInputRequest {
123    pub input: ServiceCoreInput,
124}
125
126#[derive(Debug, Clone, Serialize, Deserialize)]
127pub struct HandleCoreInputResponse {
128    pub output: ServiceCoreOutput,
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct RegisterLocalAppClientRequest {
133    pub ws_id: String,
134    pub auth_request: AuthRequest,
135    pub session: AuthenticatedSession,
136}
137
138#[derive(Debug, Clone, Serialize, Deserialize)]
139pub struct RegisterNodeConnectionRequest {
140    pub ws_id: String,
141    pub session_id: String,
142    pub node_type: String,
143    pub node_id: String,
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub host_name: Option<String>,
146    pub tenant_id: String,
147    pub scope_id: String,
148}
149
150#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct CleanupWsStateRequest {
152    pub ws_id: String,
153}
154
155#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
156pub struct UpdateCallbackBaseRequest {
157    /// Host observation, never an independently discovered or fallback address.
158    pub network: crate::host::network::HostNetworkSnapshot,
159    /// Actual bound native HTTPS listener port. Zero means it is not ready.
160    pub port: u16,
161    /// Restricted third-party HTTP listener. Zero disables compatibility URLs.
162    #[serde(default)]
163    pub third_party_port: u16,
164}
165
166impl UpdateCallbackBaseRequest {
167    pub fn callback_base(&self, now_ms: i64) -> Option<String> {
168        if self.third_party_port == 0 {
169            return None;
170        }
171        self.network
172            .available_ipv4(now_ms)
173            .map(|ip| format!("http://{ip}:{}", self.third_party_port))
174    }
175    pub fn native_base(&self, now_ms: i64) -> Option<String> {
176        if self.port == 0 {
177            return None;
178        }
179        self.network
180            .available_ipv4(now_ms)
181            .map(|ip| format!("https://{ip}:{}", self.port))
182    }
183}
184
185#[derive(Debug, Clone, Serialize, Deserialize)]
186#[serde(rename_all = "camelCase")]
187pub struct ExternalCoreDeviceIdentity {
188    pub device_id: String,
189    pub device_name: String,
190}
191
192#[derive(Debug, Clone, Serialize, Deserialize)]
193#[serde(rename_all = "camelCase")]
194pub struct ListMdnsRecordsRequest {
195    pub port: u16,
196    pub addresses: Vec<String>,
197    pub host_type: String,
198}
199
200#[derive(Debug, Clone, Serialize, Deserialize)]
201#[serde(rename_all = "camelCase")]
202pub struct ExternalCoreMdnsRecord {
203    pub service_type: String,
204    pub instance_name: String,
205    pub port: u16,
206    pub properties: HashMap<String, String>,
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize)]
210#[serde(rename_all = "camelCase")]
211pub struct PollExternalCoreEventsRequest {
212    pub consumer_id: String,
213    pub max_events: u16,
214    pub timeout_ms: u64,
215}
216
217#[derive(Debug, Clone, Serialize, Deserialize)]
218#[serde(rename_all = "camelCase")]
219pub struct PollExternalCoreEventsResponse {
220    pub events: Vec<ExternalCoreEvent>,
221    pub timed_out: bool,
222}
223
224#[derive(Debug, Clone, Serialize, Deserialize)]
225#[serde(rename_all = "camelCase")]
226pub struct CompleteExternalCoreEventsRequest {
227    pub consumer_id: String,
228    pub completions: Vec<ExternalCoreEventCompletion>,
229}
230
231#[derive(Debug, Clone, Serialize, Deserialize)]
232#[serde(rename_all = "camelCase")]
233pub struct CompleteExternalCoreEventsResponse {
234    pub completed_event_ids: Vec<String>,
235    pub missing_event_ids: Vec<String>,
236}
237
238#[derive(Debug, Clone, Serialize, Deserialize)]
239#[serde(rename_all = "camelCase")]
240pub struct ExternalCoreEvent {
241    pub event_id: String,
242    pub kind: ExternalCoreEventKind,
243    pub payload: Value,
244    pub expects_response: bool,
245}
246
247#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
248#[serde(rename_all = "camelCase")]
249pub enum ExternalCoreEventKind {
250    MdnsRecordsChanged,
251    DeliveryRequested,
252    ConnectionControlRequested,
253    HostRuntimeRequest,
254    ServiceAppFacadeRequest,
255    ScopeOwnedDataPurgeRequested,
256    ArtifactDeliveryProjectionRequested,
257    ArtifactUploadProjectionRequested,
258}
259
260/// Messaging-only Core -> Host request. A successful response means delivery was accepted by
261/// the provider implementation, not merely queued in the Core event pump or read by a user.
262#[derive(Debug, Clone, Serialize, Deserialize)]
263#[serde(rename_all = "camelCase", deny_unknown_fields)]
264pub struct MessagingDeliveryRequest {
265    pub tenant_id: String,
266    pub scope_id: String,
267    pub surface_id: String,
268    pub target: String,
269    pub payload: String,
270}
271
272#[derive(Debug, Clone, Serialize, Deserialize)]
273#[serde(rename_all = "camelCase", deny_unknown_fields)]
274pub struct MessagingDeliveryResponse {
275    pub outcome: crate::DeliveryOutcome,
276}
277
278#[derive(Debug, Clone, Serialize, Deserialize)]
279#[serde(rename_all = "camelCase", deny_unknown_fields)]
280pub struct ExternalArtifactRequestContext {
281    pub tenant_id: String,
282    pub scope_id: String,
283    pub actor_user_id: String,
284    pub client_id: String,
285}
286
287#[derive(Debug, Clone, Serialize, Deserialize)]
288#[serde(rename_all = "camelCase", deny_unknown_fields)]
289pub struct ExternalPutArtifactRequest {
290    pub context: ExternalArtifactRequestContext,
291    pub artifact: artifact_api::PutArtifactRequest,
292}
293
294#[derive(Debug, Clone, Serialize, Deserialize)]
295#[serde(rename_all = "camelCase", deny_unknown_fields)]
296pub struct ExternalOpenArtifactRequest {
297    pub context: ExternalArtifactRequestContext,
298    pub uri: String,
299}
300
301#[derive(Debug, Clone, Serialize, Deserialize)]
302#[serde(rename_all = "camelCase", deny_unknown_fields)]
303pub struct ExternalAuthorizeArtifactReadRequest {
304    pub grant: String,
305}
306
307#[derive(Debug, Clone, Serialize, Deserialize)]
308#[serde(rename_all = "camelCase", deny_unknown_fields)]
309pub struct ExternalAuthorizeArtifactUploadRequest {
310    pub grant: String,
311}
312
313#[derive(Debug, Clone, Serialize, Deserialize)]
314#[serde(rename_all = "camelCase", deny_unknown_fields)]
315pub struct ExternalCommitArtifactUploadRequest {
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub data_base64: Option<String>,
318    pub grant: String,
319}
320
321#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
322#[serde(rename_all = "camelCase", deny_unknown_fields)]
323pub struct ExternalArtifactReadDescriptor {
324    #[serde(default, skip_serializing_if = "Option::is_none")]
325    pub data_base64: Option<String>,
326    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
327    pub temporary: bool,
328    pub path: String,
329    pub kind: artifact_api::ArtifactKind,
330    pub mime_type: String,
331    pub size_bytes: u64,
332    #[serde(default, skip_serializing_if = "Option::is_none")]
333    pub width: Option<u32>,
334    #[serde(default, skip_serializing_if = "Option::is_none")]
335    pub height: Option<u32>,
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    pub duration_millis: Option<u64>,
338    pub sha256: String,
339}
340
341#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
342#[serde(rename_all = "camelCase", deny_unknown_fields)]
343pub struct ExternalArtifactUploadDescriptor {
344    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
345    pub temporary: bool,
346    pub upload_id: String,
347    pub path: String,
348    pub kind: artifact_api::ArtifactKind,
349    pub mime_type: String,
350    pub size_bytes: u64,
351    pub sha256: String,
352    #[serde(default, skip_serializing_if = "Option::is_none")]
353    pub duration_millis: Option<u64>,
354    pub expires_at_unix_ms: u64,
355}
356
357#[derive(Debug, Clone, Serialize, Deserialize)]
358#[serde(rename_all = "camelCase", deny_unknown_fields)]
359pub struct ArtifactDeliveryProjectionRequest {
360    /// Explicit compatibility request; native traffic must remain HTTPS.
361    #[serde(default)]
362    pub third_party: bool,
363    pub grant: String,
364    pub expires_at_unix_ms: u64,
365    pub client_id: String,
366}
367
368#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
369#[serde(rename_all = "camelCase", deny_unknown_fields)]
370pub struct ArtifactDeliveryProjectionResponse {
371    #[serde(default, skip_serializing_if = "Option::is_none")]
372    pub host_identity: Option<artifact_api::HostTlsIdentity>,
373    pub url: String,
374}
375
376#[derive(Debug, Clone, Serialize, Deserialize)]
377#[serde(rename_all = "camelCase", deny_unknown_fields)]
378pub struct ArtifactUploadProjectionRequest {
379    pub grant: String,
380    pub expires_at_unix_ms: u64,
381    pub client_id: String,
382}
383
384#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
385#[serde(rename_all = "camelCase", deny_unknown_fields)]
386pub struct ArtifactUploadProjectionResponse {
387    #[serde(default, skip_serializing_if = "Option::is_none")]
388    pub host_identity: Option<artifact_api::HostTlsIdentity>,
389    pub url: String,
390}
391
392/// An App Facade request delegated by an externally hosted Core to the
393/// application service that owns the target's business logic.
394#[derive(Debug, Clone, Serialize, Deserialize)]
395#[serde(rename_all = "camelCase")]
396pub struct ExternalServiceAppFacadeRequest {
397    pub target: String,
398    pub tenant_id: String,
399    pub scope_id: String,
400    pub user_id: String,
401    #[serde(default, skip_serializing_if = "Option::is_none")]
402    pub client_id: Option<String>,
403    pub payload: Value,
404}
405
406/// A platform capability request emitted by an externally hosted Core.
407///
408/// Core owns the onboarding workflow. The native host owns LAN discovery and
409/// transport to a discovered candidate, so Android can satisfy this contract
410/// without moving application logic into the mobile shell.
411#[derive(Debug, Clone, Serialize, Deserialize)]
412#[serde(rename_all = "camelCase")]
413pub struct ExternalHostRuntimeRequest {
414    #[serde(default, skip_serializing_if = "Option::is_none")]
415    pub host_public_key: Option<crate::host::auth::PublicKey>,
416    pub method: ExternalHostRuntimeMethod,
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub candidate_id: Option<String>,
419    #[serde(default, skip_serializing_if = "Option::is_none")]
420    pub action: Option<String>,
421    #[serde(default, skip_serializing_if = "Option::is_none")]
422    pub payload: Option<Value>,
423}
424
425#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
426#[serde(rename_all = "camelCase")]
427pub enum ExternalHostRuntimeMethod {
428    Discovery,
429    CandidateRequest,
430}
431
432#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
433#[serde(rename_all = "camelCase")]
434pub struct ScopeOwnedDataPurgeRequest {
435    pub tenant_id: String,
436    pub scope_id: String,
437}
438
439#[derive(Debug, Clone, Serialize, Deserialize)]
440#[serde(rename_all = "camelCase")]
441pub struct ExternalCoreEventCompletion {
442    pub event_id: String,
443    pub ok: bool,
444    #[serde(default, skip_serializing_if = "Option::is_none")]
445    pub response: Option<Value>,
446    #[serde(default, skip_serializing_if = "Option::is_none")]
447    pub error: Option<ExternalCoreError>,
448}
449
450#[derive(Debug, Clone, Serialize, Deserialize)]
451pub struct HttpPayloadRequest {
452    pub payload: Value,
453}
454
455#[derive(Debug, Clone, Serialize, Deserialize)]
456pub struct EndpointPayloadRequest {
457    pub endpoint_id: String,
458    pub payload: Value,
459}
460
461#[derive(Debug, Clone, Serialize, Deserialize)]
462#[serde(rename_all = "camelCase")]
463pub struct ExternalCoreRuntimeMetadata {
464    pub backend: String,
465    pub instance_id: String,
466    pub pid: u32,
467    pub state: String,
468    pub started_at: String,
469    pub protocol_version: u32,
470    pub binary_version: String,
471    pub socket_path: String,
472}
473
474#[derive(Debug, Clone, Serialize, Deserialize)]
475#[serde(rename_all = "camelCase")]
476pub struct ExternalCoreHealth {
477    pub ok: bool,
478    pub ready: bool,
479    pub backend: String,
480    pub binary_version: String,
481    pub agent_version: String,
482    pub protocol_version: u32,
483    #[serde(skip_serializing_if = "Option::is_none")]
484    pub instance_id: Option<String>,
485    #[serde(skip_serializing_if = "Option::is_none")]
486    pub pid: Option<u32>,
487    #[serde(skip_serializing_if = "Option::is_none")]
488    pub state: Option<String>,
489    #[serde(skip_serializing_if = "Option::is_none")]
490    pub started_at: Option<String>,
491    #[serde(default)]
492    pub capabilities: Vec<String>,
493}
494
495impl ExternalArtifactReadDescriptor {
496    /// Decode the bounded inline variant. File descriptors return None.
497    pub fn inline_content(&self) -> Result<Option<Vec<u8>>, String> {
498        use base64::Engine as _;
499        use sha2::{Digest, Sha256};
500        let Some(encoded) = &self.data_base64 else {
501            return if self.path.is_empty() {
502                Err("artifact descriptor has no content".into())
503            } else {
504                Ok(None)
505            };
506        };
507        if !self.path.is_empty()
508            || self.size_bytes > MAX_NATIVE_ARTIFACT_BYTES as u64
509            || encoded.len() > MAX_NATIVE_ARTIFACT_BASE64_BYTES
510        {
511            return Err("invalid inline artifact descriptor".into());
512        }
513        let bytes = base64::engine::general_purpose::STANDARD
514            .decode(encoded)
515            .map_err(|_| "invalid inline artifact base64")?;
516        if bytes.len() as u64 != self.size_bytes
517            || format!("{:x}", Sha256::digest(&bytes)) != self.sha256
518        {
519            return Err("inline artifact failed its integrity check".into());
520        }
521        Ok(Some(bytes))
522    }
523}
524
525#[cfg(test)]
526mod tests {
527    use super::*;
528
529    #[test]
530    fn callback_address_requires_a_fresh_host_observation_and_bound_port() {
531        let mut request = UpdateCallbackBaseRequest {
532            third_party_port: 0,
533            network: crate::host::network::HostNetworkSnapshot {
534                lan_ipv4: Some("192.168.1.5".parse().unwrap()),
535                observed_at_ms: 100_000,
536            },
537            port: 3210,
538        };
539        assert_eq!(
540            request.native_base(100_000).as_deref(),
541            Some("https://192.168.1.5:3210")
542        );
543        let roundtrip: UpdateCallbackBaseRequest =
544            serde_json::from_value(serde_json::to_value(&request).unwrap()).unwrap();
545        assert_eq!(request, roundtrip);
546        assert_eq!(request.callback_base(100_000), None);
547        request.third_party_port = 3211;
548        assert_eq!(
549            request.callback_base(100_000).as_deref(),
550            Some("http://192.168.1.5:3211")
551        );
552        assert_eq!(request.callback_base(145_000), None);
553        assert_eq!(request.native_base(145_000), None);
554        request.port = 0;
555        assert_eq!(request.native_base(100_000), None);
556        assert_eq!(
557            UpdateCallbackBaseRequest::default().native_base(100_000),
558            None
559        );
560    }
561
562    #[test]
563    fn messaging_delivery_is_a_closed_request_response_contract() {
564        let request = serde_json::json!({"tenantId":"t", "scopeId":"s", "surfaceId":"m",
565            "target":"/chat/event", "payload":"{}"});
566        let decoded: MessagingDeliveryRequest = serde_json::from_value(request.clone()).unwrap();
567        assert_eq!(serde_json::to_value(decoded).unwrap(), request);
568        let mut invalid = request;
569        invalid["unknown"] = serde_json::json!(true);
570        assert!(serde_json::from_value::<MessagingDeliveryRequest>(invalid).is_err());
571        assert!(
572            serde_json::from_value::<MessagingDeliveryResponse>(serde_json::json!({})).is_err()
573        );
574        assert_eq!(
575            serde_json::to_value(ExternalCoreEventKind::DeliveryRequested).unwrap(),
576            "deliveryRequested"
577        );
578    }
579
580    #[test]
581    fn external_events_use_the_current_wire_shape() {
582        let event = ExternalCoreEvent {
583            event_id: "event-1".to_string(),
584            kind: ExternalCoreEventKind::ScopeOwnedDataPurgeRequested,
585            payload: serde_json::to_value(ScopeOwnedDataPurgeRequest {
586                tenant_id: "tenant-1".to_string(),
587                scope_id: "scope-1".to_string(),
588            })
589            .unwrap(),
590            expects_response: true,
591        };
592
593        let value = serde_json::to_value(event).unwrap();
594        assert_eq!(EXTERNAL_CORE_PROTOCOL_VERSION, 18);
595        assert_eq!(value["kind"], "scopeOwnedDataPurgeRequested");
596        assert_eq!(value["payload"]["tenantId"], "tenant-1");
597        assert_eq!(value["payload"]["scopeId"], "scope-1");
598        assert_eq!(value["expectsResponse"], true);
599
600        let facade = ExternalCoreEvent {
601            event_id: "event-2".to_string(),
602            kind: ExternalCoreEventKind::ServiceAppFacadeRequest,
603            payload: serde_json::to_value(ExternalServiceAppFacadeRequest {
604                target: "/app/messaging/provider/list".to_string(),
605                tenant_id: "tenant-1".to_string(),
606                scope_id: "scope-1".to_string(),
607                user_id: "user-1".to_string(),
608                client_id: None,
609                payload: serde_json::json!({"placement": "local"}),
610            })
611            .unwrap(),
612            expects_response: true,
613        };
614        let value = serde_json::to_value(facade).unwrap();
615        assert_eq!(value["kind"], "serviceAppFacadeRequest");
616        assert_eq!(value["payload"]["target"], "/app/messaging/provider/list");
617        assert_eq!(value["payload"]["userId"], "user-1");
618        assert!(value["payload"].get("clientId").is_none());
619    }
620
621    #[test]
622    fn artifact_host_contract_uses_canonical_wire_types() {
623        let descriptor = ExternalArtifactReadDescriptor {
624            temporary: false,
625            data_base64: None,
626            path: "/runtime/artifacts/blob".to_string(),
627            kind: artifact_api::ArtifactKind::Audio,
628            mime_type: "audio/ogg".to_string(),
629            size_bytes: 42,
630            width: None,
631            height: None,
632            duration_millis: Some(1_500),
633            sha256: "a".repeat(64),
634        };
635        let value = serde_json::to_value(descriptor).unwrap();
636        assert_eq!(value["kind"], "AUDIO");
637        assert_eq!(value["mimeType"], "audio/ogg");
638        assert_eq!(value["durationMillis"], 1_500);
639        assert!(value.get("width").is_none());
640
641        let request = ArtifactDeliveryProjectionRequest {
642            third_party: false,
643            grant: "payload.signature".to_string(),
644            expires_at_unix_ms: 123,
645            client_id: "L:client".to_string(),
646        };
647        let value = serde_json::to_value(request).unwrap();
648        assert_eq!(value["expiresAtUnixMs"], 123);
649        assert_eq!(value["clientId"], "L:client");
650    }
651
652    #[test]
653    fn playground_uses_only_the_general_webhook_contract() {
654        let general = serde_json::to_value(ExternalCoreMethod::GeneralWebhookPayload).unwrap();
655        assert_eq!(general, serde_json::json!("GeneralWebhookPayload"));
656        assert!(
657            serde_json::from_value::<ExternalCoreMethod>(serde_json::json!(
658                "PlaygroundWebhookPayload"
659            ))
660            .is_err()
661        );
662    }
663}