Skip to main content

wavekat_platform_client/
voice.rs

1//! Voice-product resources synced from the desktop daemon up to the
2//! platform.
3//!
4//! The first shipped marker is [`VoiceCalls`] — per-call metadata for
5//! the platform's `/voice/calls` history page (see
6//! `wavekat-voice/docs/21-platform-call-history-sync.md`). Recordings
7//! (`VoiceRecordings`), transcripts (`VoiceTranscripts`), and summaries
8//! will follow the same shape: a marker type, a wire-record struct, and
9//! a typed query — no new HTTP plumbing.
10//!
11//! All wire shapes use camelCase JSON to match the platform's Hono/Zod
12//! convention. The Rust types stay snake_case so consumers feel native.
13
14use serde::{Deserialize, Serialize};
15
16use crate::client::Client;
17use crate::error::{Error, Result};
18use crate::sign::ReleaseCredential;
19use crate::sync::{stamp_schema_version, HasSyncEnvelope, SyncEndpoint, SyncEnvelope, SyncRequest};
20
21/// Inbound vs. outbound. Wire-stable snake_case strings — never
22/// renumber or rename. New states (e.g. `internal`) would be a wire
23/// addition, not a replacement.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26pub enum VoiceCallDirection {
27    Inbound,
28    Outbound,
29}
30
31/// User-visible disposition. Derived from [`VoiceCallEndReason`] by the
32/// daemon; the platform stores both, so future UI surfaces can read
33/// either without re-deriving.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum VoiceCallDisposition {
37    Answered,
38    Missed,
39    Rejected,
40    Cancelled,
41    Failed,
42}
43
44/// Finer-grained terminal reason — kept distinct from
45/// [`VoiceCallDisposition`] because the disposition collapses
46/// `hangup_local` and `hangup_remote` to `Answered`, losing the
47/// "who hung up?" answer the row otherwise carries.
48///
49/// Wire-stable snake_case strings; the daemon's matching enum is the
50/// canonical source.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
52#[serde(rename_all = "snake_case")]
53pub enum VoiceCallEndReason {
54    HangupLocal,
55    HangupRemote,
56    RejectedLocal,
57    RejectedRemote,
58    Missed,
59    CancelledLocal,
60    /// We blind-transferred the call to a third party (RFC 3515) and
61    /// dropped our own leg once the target answered. Distinct from
62    /// `HangupLocal`: the user didn't hang up, they handed the call off.
63    /// The destination is carried alongside in
64    /// [`VoiceCallRecord::transfer_target`]. Rows with this reason still
65    /// carry [`VoiceCallDisposition::Answered`].
66    TransferredLocal,
67    /// An established call torn down because its connection died —
68    /// the daemon's RFC 4028 session keepalive stopped getting
69    /// answers (peer crashed, NAT binding dropped). Distinct from
70    /// `HangupLocal`: the user didn't end this call. Rows with this
71    /// reason still carry [`VoiceCallDisposition::Answered`].
72    ConnectionLost,
73    Failed,
74}
75
76/// The audio codec a call negotiated, stamped once audio flows. Wire-
77/// stable snake_case strings matching the daemon's `CallCodec` enum —
78/// the platform validates against this exact list, so a rename here
79/// would bounce every upload with a 400. New codecs (e.g. `ilbc`) are
80/// wire additions, not replacements.
81///
82/// Consumers render this as a quality tier ("HD" for Opus, "Standard"
83/// for the G.711 pair), not the codec name alone — see the desktop
84/// client's call-details page for the canonical presentation.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(rename_all = "snake_case")]
87pub enum VoiceCallCodec {
88    /// Opus wideband (16 kHz) — the "HD" tier.
89    Opus,
90    /// G.711 µ-law — the narrowband "Standard" tier.
91    Pcmu,
92    /// G.711 A-law — the narrowband "Standard" tier.
93    Pcma,
94}
95
96/// How a call flow's ("receptionist") run ended, folded by the daemon
97/// from the run's terminal trace step. Wire-stable snake_case strings
98/// matching `wavekat_flow::trace::FlowOutcome` — declared here rather
99/// than re-exported so this crate stays free of a `wavekat-flow`
100/// dependency; the two lists must be kept in step.
101///
102/// Consumers prefer this over [`VoiceCallEndReason`] when rendering a
103/// flow-answered call's outcome: the flow's own goodbye sends the BYE,
104/// so the SIP-level reason reads `HangupLocal` ("you hung up") for a
105/// call the user never touched.
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(rename_all = "snake_case")]
108pub enum VoiceCallFlowOutcome {
109    /// A `ring` node was answered by a human; the engine stepped out.
110    Answered,
111    /// A `message` node recorded a voicemail.
112    MessageLeft,
113    /// A `transfer` node handed the call to an external number.
114    Transferred,
115    /// A `hangup` node ended the call.
116    HungUp,
117    /// An effect failed mid-run (the call likely dropped).
118    Aborted,
119    /// The flow reached an impossible state. Validation is meant to
120    /// prevent this, so it signals a defect worth alerting on.
121    Defect,
122}
123
124/// One step of a call flow's run, as the daemon projects it from its
125/// local `call_flow_step` events.
126///
127/// Deliberately structural rather than a rendered sentence. The daemon
128/// has an English summary for each step, but the platform's web UI
129/// serves nine locales — shipping prose would make these permanently
130/// untranslatable there. Consumers get the parts and compose the
131/// sentence themselves.
132///
133/// `kind` is a plain `String`, not an enum, and that is the point: step
134/// kinds grow every time the flow engine gains a node type, and a
135/// consumer built against an older version of this crate must still be
136/// able to deserialize a newer daemon's trace. An unknown kind is
137/// rendered as an unnamed marker rather than rejected.
138#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
139#[serde(rename_all = "camelCase")]
140pub struct VoiceCallFlowStep {
141    /// Milliseconds from the call's answer time — the same zero the
142    /// recording starts at, so a step lines up with the audio.
143    pub at_ms: i64,
144    /// The engine's step tag: `spoke`, `hours`, `menu_choice`,
145    /// `menu_no_input`, `menu_invalid`, `ring`, `message_recorded`,
146    /// `transferred`, `hung_up`, or the synthetic `answered` marking a
147    /// mid-run take-over by the owner.
148    pub kind: String,
149    /// The flow node this step belongs to, when it names one.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub node: Option<String>,
152    /// The key the caller pressed — `menu_choice` only.
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub digit: Option<String>,
155    /// Recorded message length in seconds — `message_recorded` only.
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub secs: Option<i64>,
158    /// Where the call was sent — `transferred` only.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub target: Option<String>,
161    /// Whether an hours check landed inside business hours.
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub open: Option<bool>,
164    /// Whether a `ring` step was picked up.
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    pub answered: Option<bool>,
167}
168
169/// One historical call as it crosses the wire from the daemon up to the
170/// platform.
171///
172/// Mirrors the daemon's local `CallRecord` (see
173/// `wavekat-voice/crates/wavekat-voice/src/db.rs`) with one rename:
174/// the daemon's local primary key (`id`) is shipped as `source_id`
175/// because the platform allocates its own row id and treats the
176/// daemon-side UUID as the idempotency key.
177#[derive(Debug, Clone, Serialize, Deserialize)]
178#[serde(rename_all = "camelCase")]
179pub struct VoiceCallRecord {
180    /// Daemon-generated UUID. The platform's `(user_id, source_id)`
181    /// upsert key — re-syncing the same id is a no-op.
182    pub source_id: String,
183    /// SIP account UUID on the daemon side. Opaque to the platform.
184    pub account_id: String,
185    pub direction: VoiceCallDirection,
186    /// SIP `From:` (inbound) or `To:` (outbound). Free text — caller
187    /// IDs, display names, and SIP URIs all land here.
188    pub party: String,
189    /// RFC 3339. First ring (inbound) or first dial-out (outbound).
190    pub ring_at: String,
191    /// RFC 3339. Present only when the call reached the answered
192    /// state.
193    #[serde(default, skip_serializing_if = "Option::is_none")]
194    pub answer_at: Option<String>,
195    /// RFC 3339. Terminal timestamp; the platform uses this as the
196    /// list cursor.
197    pub end_at: String,
198    /// `answer_at` → `end_at` in milliseconds. `None` for calls that
199    /// were never answered.
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub duration_ms: Option<i64>,
202    pub disposition: VoiceCallDisposition,
203    pub end_reason: VoiceCallEndReason,
204    /// Free-text error, populated only when `disposition == Failed`.
205    #[serde(default, skip_serializing_if = "Option::is_none")]
206    pub error: Option<String>,
207    /// Visibility tier of any *active* (not revoked / expired) share on this
208    /// call's recording, or `None` when it isn't shared. Read-only: the
209    /// platform sets it on list (`GET /api/voice/calls`) and detail responses
210    /// so a consumer can badge the row "Public" / "Invited only"; it is
211    /// skipped on serialize, so syncing a call never sends it. `Private` never
212    /// appears here — an unshared call is `None`.
213    #[serde(default, skip_serializing_if = "Option::is_none")]
214    pub share_visibility: Option<ShareVisibility>,
215    /// Where a transferred call was sent — the number or SIP address the
216    /// far end was asked to call (RFC 3515 `Refer-To`). Set only when
217    /// `end_reason == TransferredLocal`; `None` for every other call.
218    /// Unlike `share_visibility` this is daemon-owned data, so it *is*
219    /// sent on sync (serialized when present) and echoed back on read.
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub transfer_target: Option<String>,
222    /// The negotiated audio codec, present when the call reached the
223    /// audio-flowing state on a daemon new enough to record it; `None`
224    /// for never-answered calls and rows synced by older daemons. Like
225    /// `transfer_target` this is daemon-owned data, so it *is* sent on
226    /// sync (serialized when present) and echoed back on read.
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub codec: Option<VoiceCallCodec>,
229    /// Which call flow ("receptionist") answered this call, when one
230    /// did: the platform flow id the daemon held at answer time, and
231    /// the flow's display name *at that moment*. The name is shipped
232    /// verbatim rather than resolved from the flow on read, so a later
233    /// rename or delete doesn't rewrite what history says happened.
234    /// Both `None` for calls the user answered themselves. Daemon-owned
235    /// data like `codec`, so both are sent on sync and echoed on read.
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub flow_id: Option<String>,
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub flow_name: Option<String>,
240    /// How the flow's run ended. `None` when no flow answered, and for
241    /// runs with no terminal step (the caller hung up mid-flow) — there
242    /// [`VoiceCallRecord::end_reason`] is already the honest story.
243    #[serde(default, skip_serializing_if = "Option::is_none")]
244    pub flow_outcome: Option<VoiceCallFlowOutcome>,
245    /// The flow run's step-by-step trace, in answer-time order. Drives
246    /// the markers the platform's call-detail page draws on the
247    /// recording waveform.
248    ///
249    /// `None` for human-answered calls and for daemons predating the
250    /// trace. Sent on sync like the other daemon-owned fields, but
251    /// echoed back only on the *detail* read (`GET /api/voice/calls/
252    /// {sourceId}`) — the list route omits it, since nothing on a list
253    /// row renders a trace and it would weigh down every page.
254    #[serde(default, skip_serializing_if = "Option::is_none")]
255    pub flow_steps: Option<Vec<VoiceCallFlowStep>>,
256    /// RFC 3339 soft-delete tombstone. `None` = live; `Some` = the user
257    /// deleted this call at that time.
258    ///
259    /// Calls are otherwise immutable one-way pushes, and this is the
260    /// single exception: a delete has to reach the platform somehow, and
261    /// a hard `DELETE` can't sync under a "push the row" model — once
262    /// the row is gone there's nothing left to push. So a delete rides
263    /// as an ordinary upsert with this field set, exactly like
264    /// [`VoiceAccountRecord::deleted_at`].
265    ///
266    /// Where it differs from the account tombstone: **the platform
267    /// treats this one as sticky, not last-write-wins.** An account is
268    /// genuinely mutable, so it carries `updated_at` and conflicts
269    /// resolve on it; a call has no such field because delete is the
270    /// only mutation it has. The platform resolves the column
271    /// `COALESCE(existing, incoming)`, so once a call is deleted a
272    /// later sync of the same `source_id` can never revive it — which
273    /// also means a consumer must not expect to "undelete" by syncing
274    /// the row again with `None`.
275    ///
276    /// Deleting a call is not only a flag on the platform side: the
277    /// recording bytes are removed from object storage, the recording
278    /// and transcript rows are dropped, and any live share link is
279    /// revoked (it answers 410 thereafter). The tombstone row is
280    /// retained so a late-syncing device still learns about the delete
281    /// — read it via `include_deleted` on
282    /// [`VoiceCallsQuery`]. `GET /api/voice/calls/{sourceId}` returns
283    /// 404 for a deleted call rather than echoing the tombstone.
284    #[serde(default, skip_serializing_if = "Option::is_none")]
285    pub deleted_at: Option<String>,
286    /// Version + forward-compat fields shared by every sync record.
287    /// Flattened so `schemaVersion` and `extras` sit at the top of
288    /// the JSON object alongside the other columns. See
289    /// [`SyncEnvelope`] and doc 21 §"Versioning and forward
290    /// compatibility".
291    #[serde(flatten, default)]
292    pub envelope: SyncEnvelope,
293}
294
295/// Query params for `GET /api/voice/calls`. All fields optional — the
296/// default returns the newest page.
297#[derive(Debug, Clone, Default, Serialize, Deserialize)]
298#[serde(rename_all = "camelCase")]
299pub struct VoiceCallsQuery {
300    /// Include soft-deleted tombstones in the response. Absent / false
301    /// returns only live calls — what a human-facing list wants. A
302    /// delta-syncing device sets this `true` to learn about deletes
303    /// made on another device or on the web, so it can reap its local
304    /// copy.
305    ///
306    /// Unlike [`VoiceAccountsQuery::include_deleted`] there is no
307    /// "restore a fresh device" use for this: a tombstoned call has had
308    /// its recording and transcript destroyed, so the only thing left
309    /// to learn from it is that it's gone.
310    #[serde(default, skip_serializing_if = "Option::is_none")]
311    pub include_deleted: Option<bool>,
312    /// RFC 3339 cursor; rows with `end_at < before` are returned.
313    #[serde(default, skip_serializing_if = "Option::is_none")]
314    pub before: Option<String>,
315    /// 1..=200. Server default is 50.
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub limit: Option<u32>,
318}
319
320/// Marker for the `/api/voice/calls/{sync,list}` endpoint pair.
321///
322/// Use as a type parameter, never construct: `client.sync::<VoiceCalls>(&items)`.
323pub struct VoiceCalls;
324
325impl SyncEndpoint for VoiceCalls {
326    const RESOURCE: &'static str = "calls";
327    type Record = VoiceCallRecord;
328    type Query = VoiceCallsQuery;
329}
330
331impl HasSyncEnvelope for VoiceCallRecord {
332    fn envelope_mut(&mut self) -> &mut SyncEnvelope {
333        &mut self.envelope
334    }
335}
336
337// ---- VoiceRecordings ------------------------------------------------------
338
339/// One per-call recording's metadata as it crosses the wire from the
340/// daemon up to the platform. The WAV bytes ride on a separate
341/// follow-up call ([`Client::upload_recording_bytes`]) so the
342/// idempotent metadata sync stays small and a flaky bytes upload
343/// doesn't force the daemon to re-ship the row.
344///
345/// Mirrors the daemon's `RecordingArtifact` (see
346/// `wavekat-voice/crates/wavekat-voice/src/recording.rs`) with one
347/// rename: the daemon's local id (`id`) ships as `source_id` because
348/// the platform allocates its own row id and treats the daemon-side
349/// UUID as the idempotency key (same convention as
350/// [`VoiceCallRecord`]).
351#[derive(Debug, Clone, Serialize, Deserialize)]
352#[serde(rename_all = "camelCase")]
353pub struct VoiceRecordingRecord {
354    /// Daemon-generated UUID for this recording artifact. Upsert key
355    /// on the platform side.
356    pub source_id: String,
357    /// Daemon's `calls.id` — the call this recording belongs to.
358    /// The platform stores both so the /voice/calls history page can
359    /// link a call to its recording without a separate join table.
360    pub call_source_id: String,
361    /// Byte length of the WAV file the daemon will PUT in the follow-
362    /// up bytes call. The platform refuses a PUT whose body length
363    /// disagrees.
364    pub size_bytes: u64,
365    pub duration_ms: u64,
366    pub sample_rate: u32,
367    pub channels: u16,
368    /// RFC 3339 timestamp the daemon stamped on the artifact at
369    /// finalize time. Drives the platform's `/voice/recordings` GET
370    /// cursor.
371    pub created_at: String,
372    #[serde(flatten, default)]
373    pub envelope: SyncEnvelope,
374}
375
376/// Query params for `GET /api/voice/recordings`.
377#[derive(Debug, Clone, Default, Serialize, Deserialize)]
378#[serde(rename_all = "camelCase")]
379pub struct VoiceRecordingsQuery {
380    /// RFC 3339 cursor; rows with `created_at < before` are returned.
381    #[serde(default, skip_serializing_if = "Option::is_none")]
382    pub before: Option<String>,
383    #[serde(default, skip_serializing_if = "Option::is_none")]
384    pub limit: Option<u32>,
385}
386
387/// Marker for the `/api/voice/recordings/{sync,list}` endpoint pair.
388///
389/// The corresponding bytes-upload endpoint
390/// (`PUT /api/voice/recordings/{sourceId}/bytes`) is invoked via
391/// [`Client::upload_recording_bytes`] — it doesn't fit the
392/// `SyncEndpoint` mold (no batch, no JSON body) so it has its own
393/// inherent method on `Client`.
394pub struct VoiceRecordings;
395
396impl SyncEndpoint for VoiceRecordings {
397    const RESOURCE: &'static str = "recordings";
398    type Record = VoiceRecordingRecord;
399    type Query = VoiceRecordingsQuery;
400}
401
402impl HasSyncEnvelope for VoiceRecordingRecord {
403    fn envelope_mut(&mut self) -> &mut SyncEnvelope {
404        &mut self.envelope
405    }
406}
407
408/// One item in the platform's response to
409/// `POST /api/voice/recordings/sync`. Lets the daemon learn the R2
410/// key the platform stamped (so a subsequent bytes PUT can target it)
411/// without re-deriving it, and check whether bytes have already
412/// landed on a prior cycle (so the daemon can mark the local row
413/// synced without re-uploading the WAV).
414#[derive(Debug, Clone, Serialize, Deserialize)]
415#[serde(rename_all = "camelCase")]
416pub struct VoiceRecordingSyncItem {
417    pub source_id: String,
418    pub r2_key: String,
419    pub bytes_uploaded: bool,
420}
421
422/// Full response from `POST /api/voice/recordings/sync`. Superset of
423/// the generic [`crate::SyncResponse`] — see [`Client::sync_recordings`].
424#[derive(Debug, Clone, Serialize, Deserialize)]
425#[serde(rename_all = "camelCase")]
426pub struct VoiceRecordingsSyncResponse {
427    pub accepted: u32,
428    pub skipped: u32,
429    pub items: Vec<VoiceRecordingSyncItem>,
430}
431
432// ---- VoiceTranscripts -----------------------------------------------------
433
434/// Wire-stable transcript channel tag. Matches the daemon's
435/// `TranscriptChannelLabel` and `events::TranscriptChannel`.
436#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
437#[serde(rename_all = "snake_case")]
438pub enum VoiceTranscriptChannel {
439    /// Local mic audio — what the user said.
440    Local,
441    /// Received RTP audio — what the remote party said.
442    Remote,
443}
444
445/// One ASR transcript segment ("final" in wavekat-asr parlance) as it
446/// crosses the wire. Each segment is a row on the daemon side
447/// (`transcripts` table); the daemon batches a slice of them per
448/// upload and the platform upserts per (user_id, source_id).
449#[derive(Debug, Clone, Serialize, Deserialize)]
450#[serde(rename_all = "camelCase")]
451pub struct VoiceTranscriptRecord {
452    /// Daemon-side row id, formatted as text (the column is an
453    /// autoincrement integer on SQLite). Stable per (call, segment)
454    /// so re-shipping converges.
455    pub source_id: String,
456    /// Daemon's `calls.id` — the call this segment belongs to.
457    pub call_source_id: String,
458    pub channel: VoiceTranscriptChannel,
459    /// Start of the segment in milliseconds relative to the start of
460    /// the call's audio stream (not wall-clock).
461    pub ts_ms: i64,
462    /// End of the segment, same reference frame as `ts_ms`.
463    pub end_ms: i64,
464    /// Recognised text. Free-form; the platform stores it verbatim.
465    pub text: String,
466    #[serde(flatten, default)]
467    pub envelope: SyncEnvelope,
468}
469
470/// Query params for `GET /api/voice/transcripts` — required
471/// `call_source_id` (the endpoint refuses a flat list).
472#[derive(Debug, Clone, Default, Serialize, Deserialize)]
473#[serde(rename_all = "camelCase")]
474pub struct VoiceTranscriptsQuery {
475    pub call_source_id: String,
476}
477
478/// Marker for the `/api/voice/transcripts/{sync,list}` endpoint pair.
479pub struct VoiceTranscripts;
480
481impl SyncEndpoint for VoiceTranscripts {
482    const RESOURCE: &'static str = "transcripts";
483    type Record = VoiceTranscriptRecord;
484    type Query = VoiceTranscriptsQuery;
485}
486
487impl HasSyncEnvelope for VoiceTranscriptRecord {
488    fn envelope_mut(&mut self) -> &mut SyncEnvelope {
489        &mut self.envelope
490    }
491}
492
493// ---- VoiceAccounts --------------------------------------------------------
494
495/// SIP transport for a synced account line. Wire-stable snake_case;
496/// mirrors the daemon's `TransportKind`.
497#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
498#[serde(rename_all = "snake_case")]
499pub enum VoiceTransport {
500    Udp,
501    Tcp,
502}
503
504/// One SIP account line's *configuration* as it crosses the wire from a
505/// device up to the platform and back down to another device
506/// (`wavekat-voice/docs/40-account-config-sync.md`).
507///
508/// Unlike calls / recordings / transcripts — which are immutable,
509/// one-way pushes — account config is **mutable and bidirectional**: a
510/// line is edited, toggled, renamed, and deleted, and those changes must
511/// restore onto a second device. The same idempotent
512/// `(user_id, source_id)` upsert that [`Client::sync`] performs carries
513/// every kind of change here; a *delete* is a soft-delete that rides as
514/// an upsert with `deleted_at` set, because a hard DELETE can't sync
515/// under a "push the row" model — once the row is gone there's nothing
516/// left to push.
517///
518/// **No secret field, by construction.** The SIP password never appears
519/// on this wire. Config sync (policy levels 1–2) keeps the credential
520/// device-local, and the end-to-end-encrypted secret path (level 3)
521/// ships its ciphertext through a *separate* opaque resource, never as a
522/// field here. Omitting it means level 3 can't be populated by accident
523/// before it exists.
524#[derive(Debug, Clone, Serialize, Deserialize)]
525#[serde(rename_all = "camelCase")]
526pub struct VoiceAccountRecord {
527    /// Daemon-side account UUID (`accounts.id`). The platform's
528    /// `(user_id, source_id)` upsert key — re-syncing the same id
529    /// updates the row in place (mutable), unlike the immutable
530    /// resources where a re-sync is a no-op.
531    pub source_id: String,
532    /// Whether the line registers on daemon boot. Pausing a line is a
533    /// portable preference, so it rides along.
534    pub enabled: bool,
535    pub display_name: String,
536    pub username: String,
537    pub domain: String,
538    #[serde(default, skip_serializing_if = "Option::is_none")]
539    pub auth_username: Option<String>,
540    #[serde(default, skip_serializing_if = "Option::is_none")]
541    pub server: Option<String>,
542    #[serde(default, skip_serializing_if = "Option::is_none")]
543    pub port: Option<u16>,
544    pub transport: VoiceTransport,
545    pub register_expires: u32,
546    #[serde(default, skip_serializing_if = "Option::is_none")]
547    pub keepalive_secs: Option<u32>,
548    /// Record-disclosure beep toggle — a column on the account row, so
549    /// it rides along for free (the account-portable taxonomy in doc 40).
550    pub disclosure_enabled: bool,
551    /// RFC 3339 last-modification time — the **last-write-wins key**. On
552    /// conflict the platform (and a pulling client) keep the copy with
553    /// the later `updated_at`. Whole-row LWW for v1; per-field merge is
554    /// deferred until users actually report lost edits (doc 40).
555    pub updated_at: String,
556    /// RFC 3339 soft-delete tombstone. `None` = live; `Some` = the line
557    /// was deleted on some device at that time. A tombstone syncs like
558    /// any other mutation so the delete propagates to other devices,
559    /// then is reaped locally once confirmed. The platform retains
560    /// tombstones so a late-syncing device still learns about the delete.
561    #[serde(default, skip_serializing_if = "Option::is_none")]
562    pub deleted_at: Option<String>,
563    /// Version + forward-compat fields shared by every sync record.
564    #[serde(flatten, default)]
565    pub envelope: SyncEnvelope,
566}
567
568/// Query params for `GET /api/voice/accounts`. All fields optional.
569#[derive(Debug, Clone, Default, Serialize, Deserialize)]
570#[serde(rename_all = "camelCase")]
571pub struct VoiceAccountsQuery {
572    /// Include soft-deleted tombstones in the response. Absent / false
573    /// returns only live lines — the restore-grade pull a fresh device
574    /// wants. A delta-syncing device sets this `true` to also learn
575    /// about deletes made elsewhere (doc 40).
576    #[serde(default, skip_serializing_if = "Option::is_none")]
577    pub include_deleted: Option<bool>,
578}
579
580/// Marker for the `/api/voice/accounts/{sync,list}` endpoint pair.
581///
582/// Accounts are the first *mutable, bidirectional* sync resource, but
583/// the wire shape is the same idempotent upsert the immutable resources
584/// use — the [`SyncResponse::skipped`](crate::sync::SyncResponse) field
585/// was reserved for exactly this case — so no new HTTP plumbing is
586/// needed: `client.sync::<VoiceAccounts>(&items)` uploads (including
587/// tombstones), `client.list::<VoiceAccounts>(&query)` pulls.
588pub struct VoiceAccounts;
589
590impl SyncEndpoint for VoiceAccounts {
591    const RESOURCE: &'static str = "accounts";
592    type Record = VoiceAccountRecord;
593    type Query = VoiceAccountsQuery;
594}
595
596impl HasSyncEnvelope for VoiceAccountRecord {
597    fn envelope_mut(&mut self) -> &mut SyncEnvelope {
598        &mut self.envelope
599    }
600}
601
602// ---- VoiceFlows (published pull) -------------------------------------------
603//
604// The daemon-facing pull leg of the call-flow ("Receptionist") system —
605// `wavekat-voice/docs/48-ivr-call-flows.md`'s control-plane split. Flows
606// are *authored* on the platform (drafts, publish gate, version
607// history); the daemon only ever reads the published snapshots, caches
608// them locally, and runs them offline. There is no upload direction, so
609// this is not a `SyncEndpoint` (that trait models the `{resource}/sync`
610// + list pair): it's a single typed GET, like the share commands above.
611
612/// One published call-flow snapshot as served by
613/// `GET /api/voice/flows/published`: the latest published version of a
614/// flow the bearer authored. The YAML carries the platform-stamped
615/// `id`/`name`/`version` and is served verbatim — the daemon re-parses
616/// and re-validates it on load rather than trusting the wire.
617#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
618#[serde(rename_all = "camelCase")]
619pub struct VoiceFlowRecord {
620    /// Platform-assigned flow id (`flow_…`), stable across versions.
621    pub id: String,
622    pub name: String,
623    /// Latest published version number (1-based, bumps on publish).
624    pub version: u32,
625    /// The immutable published document, verbatim.
626    pub yaml: String,
627    /// RFC 3339 time this version was published.
628    pub published_at: String,
629}
630
631/// Query params for `GET /api/voice/flows/published`. Cursor-paginated
632/// by flow id ascending; pass the previous page's `next_after` until it
633/// comes back `None` to collect the full set. The full set is what the
634/// daemon's reconcile wants — a cached flow absent from a complete pull
635/// was deleted on the platform.
636#[derive(Debug, Clone, Default, Serialize, Deserialize)]
637#[serde(rename_all = "camelCase")]
638pub struct VoiceFlowsQuery {
639    #[serde(default, skip_serializing_if = "Option::is_none")]
640    pub after: Option<String>,
641    /// Page size, server-capped at 100. `None` = server default (50).
642    #[serde(default, skip_serializing_if = "Option::is_none")]
643    pub limit: Option<u32>,
644    /// The document versions this caller's flow engine can run —
645    /// `wavekat_flow::SUPPORTED_SCHEMA_VERSIONS`, comma-separated
646    /// ascending ("1,2"). The platform withholds documents in any other
647    /// version rather than serving one the caller would fail to parse.
648    ///
649    /// **Send it.** `None` does not mean "anything goes": the platform
650    /// reads a missing value as version 1 only, because this parameter
651    /// arrived alongside version 2 and a caller that omits it is an
652    /// older build. A client that can run a newer version and stays
653    /// quiet silently loses those flows.
654    //
655    // Explicitly renamed: the struct is camelCase overall, but this
656    // route's query parameter is `schema_versions`, and a silently
657    // camelCased key would be ignored by the server — which reads
658    // exactly like a platform that has no such flows.
659    #[serde(
660        rename = "schema_versions",
661        default,
662        skip_serializing_if = "Option::is_none"
663    )]
664    pub schema_versions: Option<String>,
665}
666
667/// One page of published flow snapshots.
668#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
669#[serde(rename_all = "camelCase")]
670pub struct VoiceFlowsPage {
671    pub items: Vec<VoiceFlowRecord>,
672    /// Cursor for the next page; `None` = end of the set.
673    #[serde(default)]
674    pub next_after: Option<String>,
675}
676
677/// One frozen audio asset of a published flow version, as served by
678/// `GET /api/voice/flows/{id}/versions/{version}/assets` (wavekat-platform
679/// docs 16/17). The bytes were copied into a version-owned R2 object at
680/// publish time and never change, so `content_hash` identifies them
681/// exactly — the daemon diffs its local cache against it rather than
682/// trusting a bare filename, because the *same* `ref` can carry different
683/// bytes across two versions of the same flow.
684#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
685#[serde(rename_all = "camelCase")]
686pub struct VoiceFlowVersionAsset {
687    /// The `vprompt_…` reference exactly as it appears in the flow YAML.
688    #[serde(rename = "ref")]
689    pub asset_ref: String,
690    /// Source telephony format the clip was frozen as (`ulaw_8000`,
691    /// `pcm_16000`, `mp3`, …); the container is WAV unless `mp3`.
692    pub format: String,
693    /// Size of the frozen bytes.
694    pub byte_size: u64,
695    /// Clip duration if the platform knew it at freeze time.
696    #[serde(default)]
697    pub duration_ms: Option<u64>,
698    /// sha256 of the frozen bytes — the cache's content key.
699    pub content_hash: String,
700}
701
702/// The frozen-asset manifest for one published version. Not paginated:
703/// a flow's asset count is bounded by its node count (a phone tree is
704/// tens of clips), so the platform returns them all in one response.
705#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
706#[serde(rename_all = "camelCase")]
707pub struct VoiceFlowAssetsPage {
708    pub assets: Vec<VoiceFlowVersionAsset>,
709}
710
711// ---- System flows (public, unauthenticated) --------------------------------
712//
713// The platform's curated set of ready-made call flows, served to every
714// device — signed in or not — and cached locally for offline use. These
715// are distinct from a user's own authored flows (the published-flows
716// endpoint above) and are read-only to clients; the flows are authored
717// on the platform and have no upload direction. Keyed by language tier
718// and published schema version (spec §5, doc 48 amendment 2026-08-27).
719
720/// One system (ready-made) call-flow record as served by the unauthenticated
721/// `GET /api/voice/flows/system?language=…&schema_versions=…` endpoint.
722/// Public by design — a signed-out device lists the catalogue and may
723/// preview, cache, and arm from it (gated by entitlement at arming time).
724///
725/// `description`, `publishedAt`, and `systemTags` may be absent on older
726/// rows or when the platform withheld them; all are optional.
727#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
728#[serde(rename_all = "camelCase")]
729pub struct VoiceSystemFlowRecord {
730    /// Platform-assigned flow id (`flow_…`), stable across versions.
731    pub id: String,
732    pub name: String,
733    /// Optional short description of what the flow does.
734    #[serde(default)]
735    pub description: String,
736    /// BCP-47-ish language tag — the tier this flow was selected in by
737    /// the device's language preference.
738    pub language: String,
739    /// Published version number (1-based).
740    pub version: u32,
741    /// The immutable published YAML document, verbatim.
742    pub yaml: String,
743    /// When this version was published, **verbatim from the platform's D1
744    /// column** — which defaults to SQLite `CURRENT_TIMESTAMP` and so is
745    /// `"YYYY-MM-DD HH:MM:SS"` in UTC, *not* RFC 3339 (space separator, no
746    /// offset). Some rows do carry RFC 3339. Consumers must accept **both**:
747    /// a strict RFC 3339 parse is how every pulled flow once rendered as
748    /// "Updated Jan 1, 1970" in the desktop client. Absent on older rows.
749    #[serde(default)]
750    pub published_at: Option<String>,
751    /// Platform-resolved arming rung. One of `"open"`, `"account"`, `"pro"`,
752    /// or an unknown value (forward-compat for new platform rungs). Unknown
753    /// values are treated as the strictest known rung at arm time.
754    pub access: String,
755    /// Raw platform tags, preserved verbatim so a future feature can read
756    /// a new tag without a daemon release.
757    #[serde(default)]
758    pub system_tags: Vec<String>,
759}
760
761/// One page of system flows as served by
762/// `GET /api/voice/flows/system?language=…&schema_versions=…`.
763#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
764#[serde(rename_all = "camelCase")]
765pub struct VoiceSystemFlowsPage {
766    pub flows: Vec<VoiceSystemFlowRecord>,
767}
768
769impl Client {
770    /// `GET /api/voice/flows/published` — one page of the caller's
771    /// published flow snapshots (latest version each). Strictly
772    /// creator-scoped server-side; never returns another user's flows.
773    pub async fn published_flows(&self, query: &VoiceFlowsQuery) -> Result<VoiceFlowsPage> {
774        self.get_json_query::<VoiceFlowsPage, _>("/api/voice/flows/published", query)
775            .await
776    }
777
778    /// `GET /api/voice/flows/{id}/versions/{version}/assets` — the frozen
779    /// audio manifest for one published version (docs 16/17). Flow-scoped
780    /// server-side: a version of a flow the caller doesn't own is a 404,
781    /// never another user's assets. An existing, visible version with no
782    /// generated audio returns an empty manifest.
783    pub async fn flow_version_assets(
784        &self,
785        flow_id: &str,
786        version: u32,
787    ) -> Result<VoiceFlowAssetsPage> {
788        let path = format!("/api/voice/flows/{flow_id}/versions/{version}/assets");
789        self.get_json::<VoiceFlowAssetsPage>(&path).await
790    }
791
792    /// `GET /api/voice/flows/{id}/versions/{version}/assets/{ref}/bytes` —
793    /// the immutable frozen copy of one clip, served from the version's own
794    /// asset set (never the mutable library). Returned in memory because a
795    /// clip is tens of KB and the daemon writes it atomically into its
796    /// on-disk cache; same flow-scoped 404 as the manifest.
797    pub async fn flow_version_asset_bytes(
798        &self,
799        flow_id: &str,
800        version: u32,
801        asset_ref: &str,
802    ) -> Result<Vec<u8>> {
803        let path =
804            format!("/api/voice/flows/{flow_id}/versions/{version}/assets/{asset_ref}/bytes");
805        self.get_bytes(&path).await
806    }
807
808    /// `GET /api/voice/flows/system?language=…&schema_versions=…` — the
809    /// curated system (ready-made) flow catalogue, tier-cut by language and
810    /// filterable by supported schema versions. Public by design — a
811    /// signed-out device lists and caches the catalogue. No bearer auth
812    /// on purpose; the endpoint is available before any sign-in.
813    ///
814    /// `language` is optional (the platform lists all when absent); pass
815    /// `None` to omit it. `schema_versions` is a comma-separated ascending
816    /// list (`"1,2"`) and is always sent — the platform reads silence as
817    /// "v1 only", same warning as [`VoiceFlowsQuery::schema_versions`].
818    pub async fn system_flows(
819        base_url: &str,
820        language: Option<&str>,
821        schema_versions: &str,
822    ) -> Result<VoiceSystemFlowsPage> {
823        let language_owned;
824        let mut query: Vec<(&str, &str)> = vec![("schema_versions", schema_versions)];
825        if let Some(lang) = language {
826            language_owned = lang.to_string();
827            query.push(("language", &language_owned));
828        }
829        Self::get_public_json::<VoiceSystemFlowsPage>(base_url, "/api/voice/flows/system", &query)
830            .await
831    }
832
833    /// `GET /api/voice/flows/system/{id}/versions/{version}/assets` — the
834    /// frozen audio manifest for one system flow version. Public by design.
835    /// Returns an empty manifest if the version has no generated audio.
836    ///
837    /// Reuses [`VoiceFlowAssetsPage`], which is the same wire shape as the
838    /// gated manifest for owned flows.
839    pub async fn system_flow_version_assets(
840        base_url: &str,
841        flow_id: &str,
842        version: u32,
843    ) -> Result<VoiceFlowAssetsPage> {
844        let path = format!("/api/voice/flows/system/{flow_id}/versions/{version}/assets");
845        Self::get_public_json::<VoiceFlowAssetsPage>(base_url, &path, &[]).await
846    }
847
848    /// `GET /api/voice/flows/system/{id}/versions/{version}/assets/{ref}/bytes`
849    /// — one clip from a
850    /// system flow's frozen asset set. Public by design — a signed-out
851    /// device fetches clips for offline preview and caching. Returned in
852    /// memory because a clip is tens of KB; same atomicity and offline-safe
853    /// guarantees as the gated owned-flow asset fetch.
854    pub async fn system_flow_version_asset_bytes(
855        base_url: &str,
856        flow_id: &str,
857        version: u32,
858        asset_ref: &str,
859    ) -> Result<Vec<u8>> {
860        let path = format!(
861            "/api/voice/flows/system/{flow_id}/versions/{version}/assets/{asset_ref}/bytes"
862        );
863        Self::get_public_bytes(base_url, &path).await
864    }
865}
866
867// ---- Booking (mid-call, synchronous) ---------------------------------------
868//
869// The action plane of wavekat-platform's docs/30: a `book` step asking
870// "when is this business free?" and then "put the caller in at this
871// time", with the caller on the line.
872//
873// Unlike every other endpoint in this file, these are **synchronous and
874// in-call**. Nothing here is queued, batched or retried: a person is
875// waiting, so the platform answers within seconds or answers
876// `unavailable`, and the flow takes its fallback exit. Callers should
877// give these a short timeout of their own and treat expiry the same way
878// they treat `unavailable`.
879//
880// The calendar credential never reaches this crate. The platform holds
881// the connection and answers in times and outcomes — which is what makes
882// booking a pair of platform calls rather than a Google client in every
883// daemon.
884//
885// Wire note: these routes use `snake_case` bodies, unlike the camelCase
886// sync resources above, so these types carry no `rename_all`.
887
888/// One open window in a business's week, `"HH:MM"` 24-hour local time —
889/// the same shape the flow document's `hours`/`book` steps carry.
890#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
891pub struct BookingTimeRange {
892    pub open: String,
893    pub close: String,
894}
895
896/// Open windows per weekday. A missing or empty day is closed.
897#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
898pub struct BookingSchedule {
899    #[serde(default, skip_serializing_if = "Vec::is_empty")]
900    pub mon: Vec<BookingTimeRange>,
901    #[serde(default, skip_serializing_if = "Vec::is_empty")]
902    pub tue: Vec<BookingTimeRange>,
903    #[serde(default, skip_serializing_if = "Vec::is_empty")]
904    pub wed: Vec<BookingTimeRange>,
905    #[serde(default, skip_serializing_if = "Vec::is_empty")]
906    pub thu: Vec<BookingTimeRange>,
907    #[serde(default, skip_serializing_if = "Vec::is_empty")]
908    pub fri: Vec<BookingTimeRange>,
909    #[serde(default, skip_serializing_if = "Vec::is_empty")]
910    pub sat: Vec<BookingTimeRange>,
911    #[serde(default, skip_serializing_if = "Vec::is_empty")]
912    pub sun: Vec<BookingTimeRange>,
913}
914
915/// A single-date override of the weekly schedule (a holiday, or special
916/// hours).
917#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
918pub struct BookingException {
919    /// `"YYYY-MM-DD"` in the schedule's own timezone.
920    pub date: String,
921    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
922    pub closed: bool,
923    #[serde(default, skip_serializing_if = "Vec::is_empty")]
924    pub ranges: Vec<BookingTimeRange>,
925}
926
927/// Body of `POST /api/voice/booking/slots`.
928///
929/// Everything except `source_id` comes straight off the flow document's
930/// `book` step; the platform holds no per-node configuration of its own.
931#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
932pub struct BookingSlotsRequest {
933    /// The call this offer belongs to (`voice_calls.source_id`). Slots
934    /// are held against it, which is what stops a caller being blocked
935    /// by their own offers — and what stops a second caller being
936    /// offered the same time.
937    pub source_id: String,
938    pub duration_mins: u32,
939    #[serde(default)]
940    pub buffer_mins: u32,
941    #[serde(default)]
942    pub lead_mins: u32,
943    #[serde(default)]
944    pub horizon_days: u32,
945    pub schedule: BookingSchedule,
946    /// IANA zone the schedule is written in.
947    pub timezone: String,
948    #[serde(default, skip_serializing_if = "Vec::is_empty")]
949    pub exceptions: Vec<BookingException>,
950    /// How many times to offer. The answer may be shorter, never longer.
951    pub limit: u32,
952}
953
954/// One offerable appointment, as absolute RFC 3339 instants.
955#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
956pub struct BookingSlot {
957    pub start: String,
958    pub end: String,
959}
960
961/// Answer to `POST /api/voice/booking/slots`.
962///
963/// `slots` empty is a real answer — the calendar is full, or the window
964/// closed — and not an error: the flow takes its no-slots exit.
965#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
966pub struct BookingSlotsResponse {
967    #[serde(default)]
968    pub slots: Vec<BookingSlot>,
969    /// The zone the times should be *spoken* in — the business's, echoed
970    /// back so the caller isn't told a time in the server's zone.
971    #[serde(default)]
972    pub timezone: String,
973    /// Set when the platform could not read the calendar at all
974    /// (`"unavailable"`); `slots` is then empty and the reason is for
975    /// logs, never for a caller.
976    #[serde(default, skip_serializing_if = "Option::is_none")]
977    pub status: Option<String>,
978    #[serde(default, skip_serializing_if = "Option::is_none")]
979    pub reason: Option<String>,
980}
981
982/// Body of `POST /api/voice/booking/book`.
983///
984/// Idempotent on `source_id`: a retried request for a call that already
985/// has an appointment answers `booked` with the existing event's start,
986/// without touching the calendar. A timed-out request is therefore safe
987/// to repeat.
988#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
989pub struct BookingBookRequest {
990    pub source_id: String,
991    /// One of the `start`s `/slots` handed back, verbatim.
992    pub start: String,
993    pub duration_mins: u32,
994    pub timezone: String,
995    /// Who is booking, for the calendar entry. Empty when the call
996    /// carried no caller id.
997    #[serde(default)]
998    pub caller_number: String,
999    #[serde(default, skip_serializing_if = "Option::is_none")]
1000    pub caller_name: Option<String>,
1001}
1002
1003/// Answer to `POST /api/voice/booking/book`.
1004///
1005/// Three outcomes, and the flow does something different with each:
1006/// `booked` continues, `slot_taken` can offer again, `unavailable` falls
1007/// back. Left as a string rather than an enum so a status added later
1008/// deserializes instead of failing the call.
1009#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1010pub struct BookingBookResponse {
1011    pub status: String,
1012    /// Present on `booked` — the instant the appointment actually
1013    /// starts, which on an idempotent retry is the *existing* event's
1014    /// start and not necessarily the one that was asked for.
1015    #[serde(default, skip_serializing_if = "Option::is_none")]
1016    pub start: Option<String>,
1017    #[serde(default, skip_serializing_if = "Option::is_none")]
1018    pub reason: Option<String>,
1019}
1020
1021impl Client {
1022    /// `POST /api/voice/booking/slots` — when is this business free?
1023    ///
1024    /// Writes as well as reads: every time it returns is held for
1025    /// `source_id` for a couple of minutes, so a second caller is not
1026    /// offered it while this one is still deciding. Re-offering the same
1027    /// call refreshes its own holds rather than colliding with them.
1028    pub async fn booking_slots(
1029        &self,
1030        request: &BookingSlotsRequest,
1031    ) -> Result<BookingSlotsResponse> {
1032        self.post_json::<BookingSlotsResponse, _>("/api/voice/booking/slots", request)
1033            .await
1034    }
1035
1036    /// `POST /api/voice/booking/book` — put the caller in at this time.
1037    pub async fn booking_book(&self, request: &BookingBookRequest) -> Result<BookingBookResponse> {
1038        self.post_json::<BookingBookResponse, _>("/api/voice/booking/book", request)
1039            .await
1040    }
1041}
1042
1043// ---- Anonymous install heartbeat ------------------------------------------
1044//
1045// A first-run / per-launch ping the desktop daemon fires *before* (and
1046// independently of) any platform sign-in, so the platform can count
1047// installs and track version / OS adoption for users who never sign in.
1048// It hits the public, unauthenticated `POST /api/voice/installs/heartbeat`
1049// and upserts a row keyed by `install_id` alone (no user) — distinct
1050// from the authenticated `voice_clients` heartbeat, which is keyed by
1051// `(user, install_id)`.
1052//
1053// The environment fields (os / os_version / arch / locale) are gathered
1054// *here*, inside the client crate, rather than on the consumer side:
1055// the daemon only owns the two values this crate genuinely cannot
1056// discover — the persisted `install_id` and its own app version.
1057
1058/// Best-effort snapshot of the host environment, detected at call time.
1059/// Every field is best-effort; a probe that fails contributes `None`
1060/// (or, for the always-available `os` / `arch`, the compile-time
1061/// target) rather than failing the heartbeat.
1062#[derive(Debug, Clone, PartialEq, Eq)]
1063pub struct SystemInfo {
1064    /// `std::env::consts::OS` — `"macos"`, `"windows"`, `"linux"`, …
1065    pub os: String,
1066    /// Human OS version, e.g. `"15.5.0"`. `None` when the OS probe
1067    /// can't determine it.
1068    pub os_version: Option<String>,
1069    /// `std::env::consts::ARCH` — `"aarch64"`, `"x86_64"`, …
1070    pub arch: String,
1071    /// BCP-47 system locale, e.g. `"en-NZ"`. `None` when unset /
1072    /// undetectable (common for GUI-launched apps on some platforms).
1073    pub locale: Option<String>,
1074}
1075
1076impl SystemInfo {
1077    /// Probe the current host. Cheap enough to call per heartbeat; we
1078    /// don't cache so a locale change between launches is reflected.
1079    pub fn detect() -> Self {
1080        let os_version = match os_info::get().version() {
1081            os_info::Version::Unknown => None,
1082            v => Some(v.to_string()),
1083        };
1084        SystemInfo {
1085            os: std::env::consts::OS.to_string(),
1086            os_version,
1087            arch: std::env::consts::ARCH.to_string(),
1088            locale: sys_locale::get_locale(),
1089        }
1090    }
1091}
1092
1093/// Body of `POST /api/voice/installs/heartbeat`. The daemon supplies
1094/// `install_id` + `app_version`; [`Client::install_heartbeat`] fills the
1095/// environment fields from [`SystemInfo::detect`].
1096#[derive(Debug, Clone, Serialize, Deserialize)]
1097#[serde(rename_all = "camelCase")]
1098pub struct InstallHeartbeatRequest {
1099    /// The daemon's persisted install UUID — the platform's upsert key.
1100    pub install_id: String,
1101    /// WaveKat Voice's own version (`env!("CARGO_PKG_VERSION")` on the
1102    /// daemon side) — *not* this crate's version.
1103    pub app_version: String,
1104    pub os: String,
1105    #[serde(default, skip_serializing_if = "Option::is_none")]
1106    pub os_version: Option<String>,
1107    #[serde(default, skip_serializing_if = "Option::is_none")]
1108    pub arch: Option<String>,
1109    #[serde(default, skip_serializing_if = "Option::is_none")]
1110    pub locale: Option<String>,
1111    /// How this copy was obtained — `"direct"` for a plain download,
1112    /// `"mas"` for the sandboxed Mac App Store build. Unlike every other
1113    /// field here it is **not** detectable: the two macOS builds share a
1114    /// bundle id and a version, and the binary is identical, so only the
1115    /// consumer knows which one it is shipping inside. Hence a caller
1116    /// argument rather than part of [`SystemInfo`].
1117    ///
1118    /// Free text by contract, not an enum: the platform stores whatever
1119    /// arrives so a new distribution can ship without a server release.
1120    /// `None` when the consumer has nothing meaningful to say (a source
1121    /// build, a package this crate has never heard of) — omitted from
1122    /// the body entirely rather than sent as null.
1123    #[serde(default, skip_serializing_if = "Option::is_none")]
1124    pub distribution: Option<String>,
1125}
1126
1127/// The platform's view of an install row, echoed back from a heartbeat.
1128#[derive(Debug, Clone, Serialize, Deserialize)]
1129#[serde(rename_all = "camelCase")]
1130pub struct InstallHeartbeatResponse {
1131    pub id: String,
1132    pub install_id: String,
1133    pub app_version: String,
1134    pub os: String,
1135    pub os_version: Option<String>,
1136    pub arch: Option<String>,
1137    pub locale: Option<String>,
1138    /// Echoed back. `#[serde(default)]` because a platform deployed
1139    /// before this field existed omits the key rather than sending null,
1140    /// and a heartbeat must not fail to parse against an older server.
1141    #[serde(default)]
1142    pub distribution: Option<String>,
1143    pub first_seen_at: String,
1144    pub last_seen_at: String,
1145}
1146
1147impl Client {
1148    /// `POST /api/voice/installs/heartbeat` — the anonymous, no-auth
1149    /// first-run install ping. Detects the host environment internally
1150    /// and posts it alongside the caller-supplied `install_id` +
1151    /// `app_version`. Associated (not a method) because the endpoint is
1152    /// unauthenticated — there's no token, and at first run there's no
1153    /// signed-in `Client` to hang it off of.
1154    ///
1155    /// Though unauthenticated, the request is **signed** with the release
1156    /// credential `cred` (a per-version Ed25519 key + master-issued
1157    /// certificate the consumer bakes in at build time) so the platform
1158    /// can verify it came from a genuine release and reject forged or
1159    /// replayed pings — see [`Client::post_public_signed_json`] and
1160    /// [`crate::sign`]. The platform needs only the master *public* key to
1161    /// verify.
1162    ///
1163    /// `base_url` is the platform base (e.g. `https://platform.wavekat.com`).
1164    ///
1165    /// `distribution` says how this copy was obtained (`"direct"`,
1166    /// `"mas"`, …). It is the one field this call can't detect for
1167    /// itself — see [`InstallHeartbeatRequest::distribution`] — so pass
1168    /// `None` if the consumer has nothing meaningful to say.
1169    pub async fn install_heartbeat(
1170        base_url: &str,
1171        install_id: &str,
1172        app_version: &str,
1173        distribution: Option<&str>,
1174        cred: &ReleaseCredential,
1175    ) -> Result<InstallHeartbeatResponse> {
1176        let sys = SystemInfo::detect();
1177        let body = InstallHeartbeatRequest {
1178            install_id: install_id.to_string(),
1179            app_version: app_version.to_string(),
1180            os: sys.os,
1181            os_version: sys.os_version,
1182            arch: Some(sys.arch),
1183            locale: sys.locale,
1184            distribution: distribution.map(str::to_string),
1185        };
1186        Client::post_public_signed_json::<InstallHeartbeatResponse, _>(
1187            base_url,
1188            "/api/voice/installs/heartbeat",
1189            &body,
1190            cred,
1191        )
1192        .await
1193    }
1194}
1195
1196// ---- Client surface for recordings ----------------------------------------
1197//
1198// Recordings don't fit the generic `Client::sync` shape cleanly:
1199//
1200//   - the response carries per-item provenance (the platform-stamped
1201//     `r2Key`, plus whether bytes have already landed) that the
1202//     daemon needs in order to decide which rows still owe a PUT;
1203//   - the bytes upload is its own HTTP call (`PUT
1204//     /api/voice/recordings/{sourceId}/bytes`), not a JSON batch.
1205//
1206// Rather than overloading `SyncEndpoint` to carry these shapes, we
1207// expose two inherent methods on `Client` that compose the existing
1208// JSON / bytes-PUT primitives.
1209
1210impl Client {
1211    /// `POST /api/voice/recordings/sync` — idempotent batch upsert of
1212    /// recording metadata. Returns the per-item `r2Key` the daemon
1213    /// should target for the follow-up bytes PUT, and whether bytes
1214    /// have already landed for each row.
1215    ///
1216    /// Batch sizing rules match [`Client::sync`]: the platform rejects
1217    /// batches over 100 items; the daemon's uploader chunks at 50.
1218    pub async fn sync_recordings(
1219        &self,
1220        items: &[VoiceRecordingRecord],
1221    ) -> Result<VoiceRecordingsSyncResponse> {
1222        let stamped = stamp_schema_version::<VoiceRecordings>(items);
1223        let body = SyncRequest { items: stamped };
1224        self.post_json::<VoiceRecordingsSyncResponse, _>("/api/voice/recordings/sync", &body)
1225            .await
1226    }
1227
1228    /// `PUT /api/voice/recordings/{sourceId}/bytes` — upload the WAV
1229    /// bytes for a recording whose metadata was previously synced via
1230    /// [`Client::sync_recordings`]. The platform refuses (`HTTP 413`)
1231    /// if `bytes.len()` disagrees with the synced `sizeBytes`.
1232    ///
1233    /// `source_id` is path-segmented as-is; callers pass the
1234    /// daemon-side UUID they used for the metadata sync. Empty /
1235    /// path-traversal-shaped ids are not specifically guarded here —
1236    /// the platform's Zod schema rejects them server-side, so a
1237    /// malformed id surfaces as a 4xx via [`Error::Http`].
1238    pub async fn upload_recording_bytes(&self, source_id: &str, bytes: Vec<u8>) -> Result<()> {
1239        if source_id.is_empty() {
1240            return Err(Error::BadRequest("source_id must not be empty".into()));
1241        }
1242        let path = format!("/api/voice/recordings/{source_id}/bytes");
1243        self.put_raw_bytes(&path, "audio/wav", bytes).await
1244    }
1245}
1246
1247// ---- Recording sharing ----------------------------------------------------
1248//
1249// Sharing is a *command* — mutate one recording's share state and get a
1250// result back — not the "batch upsert + cursor list" shape `SyncEndpoint`
1251// exists for (see wavekat-voice doc 38). So it's a typed method pair on
1252// `Client` (mirroring `whoami` rather than `sync::<E>()`), not a marker.
1253//
1254// The desktop daemon keeps only a *mirror* of what these return; the
1255// platform is authoritative for who may open a share. See
1256// `wavekat-voice/docs/38-share-a-recording.md`.
1257
1258/// Access tier for a shared recording, mirroring Loom's model. Wire-stable
1259/// snake_case strings — the platform's Zod schema validates against this
1260/// exact list, so a rename here would bounce every share command with a 400.
1261///
1262/// - `Private` — owner only (the default; "not shared").
1263/// - `Restricted` — owner + explicitly invited WaveKat accounts; the
1264///   recipient must be signed in as an invited identity ("protected by login").
1265/// - `Public` — anyone holding the capability link, no sign-in.
1266#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1267#[serde(rename_all = "snake_case")]
1268pub enum ShareVisibility {
1269    Private,
1270    Restricted,
1271    Public,
1272}
1273
1274/// How a shared recording's caller/callee identity (the call's `party`) is
1275/// exposed to a viewer. Wire-stable snake_case, matching the platform's Zod
1276/// enum, so a rename here bounces a share command with a 400.
1277///
1278/// - `Full` — hidden behind a neutral direction label ("Inbound call").
1279/// - `Partial` — best-effort redaction (keeps shape, drops the value).
1280/// - `None` — the raw `party` is shown.
1281///
1282/// Absent on the wire → the platform defaults to `Partial` (identity
1283/// masked) — privacy-forward without fully erasing the caller. See
1284/// `wavekat-platform` docs/14.
1285#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1286#[serde(rename_all = "snake_case")]
1287pub enum PartyMasking {
1288    Full,
1289    Partial,
1290    None,
1291}
1292
1293/// Body of `POST /api/voice/recordings/{id}/share` — create or update a
1294/// recording's share. The recording must already be synced (metadata +
1295/// bytes) or the platform returns 404.
1296#[derive(Debug, Clone, Serialize, Deserialize)]
1297#[serde(rename_all = "camelCase")]
1298pub struct ShareRecordingRequest {
1299    /// The artifact UUID, as synced (daemon-side `artifacts.id`). Goes in
1300    /// the URL path; carried in the struct so callers pass one value.
1301    pub recording_source_id: String,
1302    pub visibility: ShareVisibility,
1303    /// Restricted tier — the WaveKat-account emails allowed to open the
1304    /// share. Ignored (and omitted) for `Private` / `Public`.
1305    #[serde(default, skip_serializing_if = "Option::is_none")]
1306    pub invited_emails: Option<Vec<String>>,
1307    /// Per-share visibility controls (platform docs/14) — what a viewer may
1308    /// see. Each is omitted when unset; the platform then applies its
1309    /// privacy-forward default (identity masked, transcript hidden, audio
1310    /// shown, download off). NB the platform treats the request as the
1311    /// *full* desired state, so an omitted control is reset to its default,
1312    /// not preserved from a prior share — send all of them when editing an
1313    /// existing share's controls.
1314    #[serde(default, skip_serializing_if = "Option::is_none")]
1315    pub party_masking: Option<PartyMasking>,
1316    #[serde(default, skip_serializing_if = "Option::is_none")]
1317    pub show_transcript: Option<bool>,
1318    #[serde(default, skip_serializing_if = "Option::is_none")]
1319    pub show_audio: Option<bool>,
1320    /// Whether a viewer may *download* the WAV, distinct from hearing it.
1321    /// Off by default and only meaningful while `show_audio` is true — the
1322    /// platform forces it off otherwise (you can't save what you can't
1323    /// hear). A soft control: it hides the viewer's Download affordance,
1324    /// not the bytes a listener already fetches to play.
1325    #[serde(default, skip_serializing_if = "Option::is_none")]
1326    pub allow_download: Option<bool>,
1327    /// Per-channel playback defaults — which side is *audible by default*
1328    /// in the viewer's player (docs/14). A call has two channels: `local`
1329    /// (the owner's microphone, "your side") and `remote` (the other
1330    /// party, "their side"). `true` means that side starts muted; the
1331    /// viewer can still un-mute it, and the audio file is unchanged — this
1332    /// is only the player's starting state. Each is omitted when unset, in
1333    /// which case the platform defaults to audible (`false`). Only
1334    /// meaningful while `show_audio` is true; ignored when audio is hidden.
1335    #[serde(default, skip_serializing_if = "Option::is_none")]
1336    pub default_mute_local: Option<bool>,
1337    #[serde(default, skip_serializing_if = "Option::is_none")]
1338    pub default_mute_remote: Option<bool>,
1339    /// Phase 2 — out-of-band password gate. Omitted when unset.
1340    #[serde(default, skip_serializing_if = "Option::is_none")]
1341    pub password: Option<String>,
1342    /// Phase 2 — RFC 3339 auto-revoke time. Omitted when unset.
1343    #[serde(default, skip_serializing_if = "Option::is_none")]
1344    pub expires_at: Option<String>,
1345}
1346
1347/// The platform's response to a successful share command. `share_url` is
1348/// the full https link the user copies; `token` is the opaque capability
1349/// identifier embedded in it (returned separately so the daemon can store
1350/// it for display without re-parsing the URL).
1351#[derive(Debug, Clone, Serialize, Deserialize)]
1352#[serde(rename_all = "camelCase")]
1353pub struct ShareRecordingResponse {
1354    pub visibility: ShareVisibility,
1355    pub token: String,
1356    pub share_url: String,
1357    /// RFC 3339 — when the recording was first shared.
1358    pub shared_at: String,
1359    /// Effective visibility controls the platform stored (docs/14). Optional
1360    /// for tolerance — a platform predating the feature omits them, in which
1361    /// case the daemon should assume the defaults (identity masked, transcript
1362    /// hidden, audio shown, download off).
1363    #[serde(default, skip_serializing_if = "Option::is_none")]
1364    pub party_masking: Option<PartyMasking>,
1365    #[serde(default, skip_serializing_if = "Option::is_none")]
1366    pub show_transcript: Option<bool>,
1367    #[serde(default, skip_serializing_if = "Option::is_none")]
1368    pub show_audio: Option<bool>,
1369    /// Effective download permission — `show_audio && allow_download`, so
1370    /// it's never true when the audio is hidden. Absent on a platform
1371    /// predating the control (assume off).
1372    #[serde(default, skip_serializing_if = "Option::is_none")]
1373    pub allow_download: Option<bool>,
1374    /// Effective per-channel playback defaults the platform stored — which
1375    /// side starts muted in the viewer's player (docs/14). Absent on a
1376    /// platform predating the control (assume audible, `false`).
1377    #[serde(default, skip_serializing_if = "Option::is_none")]
1378    pub default_mute_local: Option<bool>,
1379    #[serde(default, skip_serializing_if = "Option::is_none")]
1380    pub default_mute_remote: Option<bool>,
1381}
1382
1383/// The platform's response to `GET /api/voice/recordings/{id}/share` — the
1384/// *authoritative* current share state for an owned recording. The POST
1385/// reply omits the invited-email list and a local mirror can't reflect a
1386/// share changed from another device, so the desktop "who can open this"
1387/// panel reads here.
1388///
1389/// A recording that was never shared (or whose share is revoked / expired)
1390/// comes back as [`ShareVisibility::Private`] with the optional fields
1391/// absent — the same "not shared" state DELETE leaves behind.
1392#[derive(Debug, Clone, Serialize, Deserialize)]
1393#[serde(rename_all = "camelCase")]
1394pub struct ShareStateResponse {
1395    pub visibility: ShareVisibility,
1396    /// Absent when `visibility == Private` (nothing is shared).
1397    #[serde(default, skip_serializing_if = "Option::is_none")]
1398    pub token: Option<String>,
1399    #[serde(default, skip_serializing_if = "Option::is_none")]
1400    pub share_url: Option<String>,
1401    /// RFC 3339 — when the recording was first shared. Absent when private.
1402    #[serde(default, skip_serializing_if = "Option::is_none")]
1403    pub shared_at: Option<String>,
1404    /// The restricted tier's audience (lowercased, de-duped). Present
1405    /// (possibly empty) only for [`ShareVisibility::Restricted`].
1406    #[serde(default, skip_serializing_if = "Option::is_none")]
1407    pub invited_emails: Option<Vec<String>>,
1408    /// Per-share visibility controls (docs/14). Present for a live share;
1409    /// absent when `Private` (nothing is shared, so no controls apply).
1410    #[serde(default, skip_serializing_if = "Option::is_none")]
1411    pub party_masking: Option<PartyMasking>,
1412    #[serde(default, skip_serializing_if = "Option::is_none")]
1413    pub show_transcript: Option<bool>,
1414    #[serde(default, skip_serializing_if = "Option::is_none")]
1415    pub show_audio: Option<bool>,
1416    /// Effective download permission — `show_audio && allow_download`, so
1417    /// never true when the audio is hidden. Absent when private.
1418    #[serde(default, skip_serializing_if = "Option::is_none")]
1419    pub allow_download: Option<bool>,
1420    /// Effective per-channel playback defaults — which side starts muted in
1421    /// the viewer's player (docs/14). Absent when private.
1422    #[serde(default, skip_serializing_if = "Option::is_none")]
1423    pub default_mute_local: Option<bool>,
1424    #[serde(default, skip_serializing_if = "Option::is_none")]
1425    pub default_mute_remote: Option<bool>,
1426}
1427
1428impl Client {
1429    /// `POST /api/voice/recordings/{id}/share` — create or update a share
1430    /// for an already-synced recording. Returns the capability link + token
1431    /// the desktop UI puts on the clipboard.
1432    ///
1433    /// Per the 404-not-403 ownership rule (doc 21 §"Authorization"), asking
1434    /// to share a recording the caller doesn't own surfaces as
1435    /// [`Error::Http`] with status 404 — existence doesn't leak.
1436    pub async fn share_recording(
1437        &self,
1438        req: &ShareRecordingRequest,
1439    ) -> Result<ShareRecordingResponse> {
1440        if req.recording_source_id.is_empty() {
1441            return Err(Error::BadRequest(
1442                "recording_source_id must not be empty".into(),
1443            ));
1444        }
1445        let path = format!("/api/voice/recordings/{}/share", req.recording_source_id);
1446        self.post_json::<ShareRecordingResponse, _>(&path, req)
1447            .await
1448    }
1449
1450    /// `GET /api/voice/recordings/{id}/share` — read the authoritative
1451    /// share state for an owned recording, including the restricted tier's
1452    /// invited emails (which the share command's reply omits). Like
1453    /// [`share_recording`](Self::share_recording), a recording the caller
1454    /// doesn't own surfaces as [`Error::Http`] with status 404.
1455    pub async fn get_recording_share(
1456        &self,
1457        recording_source_id: &str,
1458    ) -> Result<ShareStateResponse> {
1459        if recording_source_id.is_empty() {
1460            return Err(Error::BadRequest(
1461                "recording_source_id must not be empty".into(),
1462            ));
1463        }
1464        let path = format!("/api/voice/recordings/{recording_source_id}/share");
1465        self.get_json::<ShareStateResponse>(&path).await
1466    }
1467
1468    /// `DELETE /api/voice/recordings/{id}/share` — revoke the share. The
1469    /// recording reverts to Private and any outstanding link returns 410.
1470    pub async fn revoke_recording_share(&self, recording_source_id: &str) -> Result<()> {
1471        if recording_source_id.is_empty() {
1472            return Err(Error::BadRequest(
1473                "recording_source_id must not be empty".into(),
1474            ));
1475        }
1476        let path = format!("/api/voice/recordings/{recording_source_id}/share");
1477        self.delete(&path).await
1478    }
1479}
1480
1481#[cfg(test)]
1482mod tests {
1483    use super::*;
1484
1485    #[test]
1486    fn share_visibility_types_are_reachable_from_the_crate_root() {
1487        // Regression for the 0.0.13 gap: `PartyMasking` was added to this
1488        // module but left out of the crate-root `pub use voice::{…}`, and the
1489        // module is private — so a consumer (`wavekat-voice`) couldn't name
1490        // the type to build a `ShareRecordingRequest`. Pin every share-control
1491        // type to the root path so dropping one fails to compile here, not in
1492        // a downstream crate. The body never runs; reachability is the test.
1493        #[allow(dead_code)]
1494        fn _reachable() {
1495            let _: Option<crate::PartyMasking> = Some(crate::PartyMasking::Partial);
1496            let _: Option<crate::ShareVisibility> = Some(crate::ShareVisibility::Public);
1497            let _: fn(&crate::ShareRecordingRequest) = |_| {};
1498            let _: fn(&crate::ShareRecordingResponse) = |_| {};
1499        }
1500    }
1501
1502    #[test]
1503    fn record_serializes_with_camel_case_keys() {
1504        let r = VoiceCallRecord {
1505            source_id: "11111111-1111-4111-8111-111111111111".into(),
1506            account_id: "22222222-2222-4222-8222-222222222222".into(),
1507            direction: VoiceCallDirection::Inbound,
1508            party: "+14155550123".into(),
1509            ring_at: "2026-05-16T10:00:00Z".into(),
1510            answer_at: Some("2026-05-16T10:00:05Z".into()),
1511            end_at: "2026-05-16T10:01:00Z".into(),
1512            duration_ms: Some(55_000),
1513            disposition: VoiceCallDisposition::Answered,
1514            end_reason: VoiceCallEndReason::HangupRemote,
1515            error: None,
1516            share_visibility: None,
1517            transfer_target: None,
1518            codec: None,
1519            flow_id: None,
1520            flow_name: None,
1521            flow_outcome: None,
1522            flow_steps: None,
1523            deleted_at: None,
1524            envelope: SyncEnvelope::for_endpoint::<VoiceCalls>(),
1525        };
1526        let s = serde_json::to_string(&r).unwrap();
1527        assert!(s.contains("\"sourceId\":"), "{s}");
1528        assert!(s.contains("\"accountId\":"), "{s}");
1529        assert!(s.contains("\"ringAt\":"), "{s}");
1530        assert!(s.contains("\"endAt\":"), "{s}");
1531        assert!(s.contains("\"durationMs\":55000"), "{s}");
1532        // Optional `error` is None — should be omitted from the wire.
1533        assert!(!s.contains("\"error\""), "error should be omitted: {s}");
1534        // Optional `transferTarget` is None here — omitted from the wire,
1535        // exactly like a non-transferred call ships.
1536        assert!(
1537            !s.contains("\"transferTarget\""),
1538            "transferTarget should be omitted: {s}"
1539        );
1540        // Optional `codec` is None (never-answered call, or an older
1541        // daemon) — omitted from the wire, never `null`.
1542        assert!(!s.contains("\"codec\""), "codec should be omitted: {s}");
1543        // Envelope flattens to the top of the object — schemaVersion
1544        // sits next to the other fields rather than nested under
1545        // "envelope". Future resources rely on this layout.
1546        assert!(
1547            s.contains("\"schemaVersion\":1"),
1548            "schemaVersion should flatten: {s}"
1549        );
1550        // `extras` is None, so the envelope contributes no `extras`
1551        // key. Stays out of the row to keep the small/fast path.
1552        assert!(!s.contains("\"extras\""), "extras should be omitted: {s}");
1553        // A live call omits the tombstone entirely rather than sending
1554        // `null` — every ordinary sync is a live call, so this is the
1555        // common path and it should stay off the wire.
1556        assert!(
1557            !s.contains("\"deletedAt\""),
1558            "deletedAt should be omitted on a live call: {s}"
1559        );
1560    }
1561
1562    #[test]
1563    fn call_tombstone_serializes_deleted_at() {
1564        // The delete-propagation mechanism: a deleted call rides up as
1565        // an ordinary upsert with `deletedAt` set (platform docs/22),
1566        // the same shape the account tombstone uses.
1567        let mut r = VoiceCallRecord {
1568            source_id: "11111111-1111-4111-8111-111111111111".into(),
1569            account_id: "22222222-2222-4222-8222-222222222222".into(),
1570            direction: VoiceCallDirection::Inbound,
1571            party: "+14155550123".into(),
1572            ring_at: "2026-05-16T10:00:00Z".into(),
1573            answer_at: None,
1574            end_at: "2026-05-16T10:01:00Z".into(),
1575            duration_ms: None,
1576            disposition: VoiceCallDisposition::Missed,
1577            end_reason: VoiceCallEndReason::HangupRemote,
1578            error: None,
1579            share_visibility: None,
1580            transfer_target: None,
1581            codec: None,
1582            flow_id: None,
1583            flow_name: None,
1584            flow_outcome: None,
1585            flow_steps: None,
1586            deleted_at: None,
1587            envelope: SyncEnvelope::for_endpoint::<VoiceCalls>(),
1588        };
1589        r.deleted_at = Some("2026-07-30T12:00:00Z".into());
1590        let s = serde_json::to_string(&r).unwrap();
1591        assert!(s.contains("\"deletedAt\":\"2026-07-30T12:00:00Z\""), "{s}");
1592    }
1593
1594    #[test]
1595    fn call_record_parses_without_deleted_at() {
1596        // Reading back a live call from `GET /api/voice/calls`: the
1597        // platform sends `deletedAt: null`, and a platform build
1598        // predating the field sends nothing at all. Both must land as
1599        // `None` rather than failing the whole page.
1600        let raw = r#"{
1601            "sourceId": "a",
1602            "accountId": "b",
1603            "direction": "outbound",
1604            "party": "+14155550123",
1605            "ringAt": "2026-05-16T10:00:00Z",
1606            "endAt": "2026-05-16T10:01:00Z",
1607            "disposition": "answered",
1608            "endReason": "hangup_local"
1609        }"#;
1610        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1611        assert!(parsed.deleted_at.is_none());
1612
1613        let with_null: VoiceCallRecord =
1614            serde_json::from_str(&raw.replace('}', r#", "deletedAt": null }"#)).unwrap();
1615        assert!(with_null.deleted_at.is_none());
1616    }
1617
1618    #[test]
1619    fn calls_query_serializes_include_deleted() {
1620        // The delta-pull flag a device sets to learn about deletes made
1621        // elsewhere. Omitted when unset, so an ordinary list request is
1622        // unchanged.
1623        let live = VoiceCallsQuery::default();
1624        assert_eq!(serde_json::to_string(&live).unwrap(), "{}");
1625
1626        let delta = VoiceCallsQuery {
1627            include_deleted: Some(true),
1628            ..Default::default()
1629        };
1630        let s = serde_json::to_string(&delta).unwrap();
1631        assert!(s.contains("\"includeDeleted\":true"), "{s}");
1632    }
1633
1634    #[test]
1635    fn record_round_trips_optional_fields() {
1636        // An unanswered call has answer_at/duration_ms/error all absent.
1637        let raw = r#"{
1638            "sourceId": "a",
1639            "accountId": "b",
1640            "direction": "inbound",
1641            "party": "anonymous",
1642            "ringAt": "2026-05-16T10:00:00Z",
1643            "endAt": "2026-05-16T10:00:30Z",
1644            "disposition": "missed",
1645            "endReason": "missed"
1646        }"#;
1647        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1648        assert!(parsed.answer_at.is_none());
1649        assert!(parsed.duration_ms.is_none());
1650        assert!(parsed.error.is_none());
1651        assert_eq!(parsed.disposition, VoiceCallDisposition::Missed);
1652        assert_eq!(parsed.end_reason, VoiceCallEndReason::Missed);
1653    }
1654
1655    #[test]
1656    fn query_omits_unset_fields() {
1657        let q = VoiceCallsQuery::default();
1658        let s = serde_json::to_string(&q).unwrap();
1659        // Empty object — every field skipped when None.
1660        assert_eq!(
1661            s, "{}",
1662            "default query should serialize to empty object: {s}"
1663        );
1664    }
1665
1666    #[test]
1667    fn enum_round_trip_via_json() {
1668        // The wire form for each direction/disposition/reason must
1669        // match what the daemon and platform expect — this guards
1670        // against accidental Rust-side renames.
1671        for d in [VoiceCallDirection::Inbound, VoiceCallDirection::Outbound] {
1672            let s = serde_json::to_string(&d).unwrap();
1673            let back: VoiceCallDirection = serde_json::from_str(&s).unwrap();
1674            assert_eq!(d, back);
1675        }
1676        for d in [
1677            VoiceCallDisposition::Answered,
1678            VoiceCallDisposition::Missed,
1679            VoiceCallDisposition::Rejected,
1680            VoiceCallDisposition::Cancelled,
1681            VoiceCallDisposition::Failed,
1682        ] {
1683            let s = serde_json::to_string(&d).unwrap();
1684            let back: VoiceCallDisposition = serde_json::from_str(&s).unwrap();
1685            assert_eq!(d, back);
1686        }
1687        for r in [
1688            VoiceCallEndReason::HangupLocal,
1689            VoiceCallEndReason::HangupRemote,
1690            VoiceCallEndReason::RejectedLocal,
1691            VoiceCallEndReason::RejectedRemote,
1692            VoiceCallEndReason::Missed,
1693            VoiceCallEndReason::CancelledLocal,
1694            VoiceCallEndReason::TransferredLocal,
1695            VoiceCallEndReason::ConnectionLost,
1696            VoiceCallEndReason::Failed,
1697        ] {
1698            let s = serde_json::to_string(&r).unwrap();
1699            let back: VoiceCallEndReason = serde_json::from_str(&s).unwrap();
1700            assert_eq!(r, back);
1701        }
1702    }
1703
1704    #[test]
1705    fn connection_lost_pins_its_wire_string() {
1706        // The platform's sync endpoint validates end reasons against
1707        // an exact string list — a rename here would make every
1708        // upload from a session-timer teardown bounce with a 400.
1709        let s = serde_json::to_string(&VoiceCallEndReason::ConnectionLost).unwrap();
1710        assert_eq!(s, "\"connection_lost\"");
1711    }
1712
1713    #[test]
1714    fn transferred_local_pins_its_wire_string() {
1715        // Same contract as `connection_lost`: the platform validates
1716        // against an exact string list, so a rename here would bounce
1717        // every transferred-call upload with a 400.
1718        let s = serde_json::to_string(&VoiceCallEndReason::TransferredLocal).unwrap();
1719        assert_eq!(s, "\"transferred_local\"");
1720    }
1721
1722    #[test]
1723    fn record_round_trips_transfer_target() {
1724        // A transferred call carries `transferTarget` both ways — the
1725        // daemon ships it (it's its own data, not read-only decoration),
1726        // and the platform echoes it back on read.
1727        let raw = r#"{
1728            "sourceId": "a",
1729            "accountId": "b",
1730            "direction": "inbound",
1731            "party": "Alice <sip:alice@example.com>",
1732            "ringAt": "2026-06-28T10:00:00Z",
1733            "answerAt": "2026-06-28T10:00:05Z",
1734            "endAt": "2026-06-28T10:00:30Z",
1735            "durationMs": 25000,
1736            "disposition": "answered",
1737            "endReason": "transferred_local",
1738            "transferTarget": "1002"
1739        }"#;
1740        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1741        assert_eq!(parsed.end_reason, VoiceCallEndReason::TransferredLocal);
1742        assert_eq!(parsed.transfer_target.as_deref(), Some("1002"));
1743        // And it survives a re-serialize (daemon → platform direction).
1744        let s = serde_json::to_string(&parsed).unwrap();
1745        assert!(s.contains("\"transferTarget\":\"1002\""), "{s}");
1746    }
1747
1748    #[test]
1749    fn codec_pins_its_wire_strings() {
1750        // The platform's sync endpoint validates the codec against an
1751        // exact string list, and the daemon's `CallCodec::as_str` emits
1752        // these same strings — a rename here would bounce every upload
1753        // from an answered call with a 400.
1754        for (codec, wire) in [
1755            (VoiceCallCodec::Opus, "\"opus\""),
1756            (VoiceCallCodec::Pcmu, "\"pcmu\""),
1757            (VoiceCallCodec::Pcma, "\"pcma\""),
1758        ] {
1759            assert_eq!(serde_json::to_string(&codec).unwrap(), wire);
1760            let back: VoiceCallCodec = serde_json::from_str(wire).unwrap();
1761            assert_eq!(back, codec);
1762        }
1763    }
1764
1765    #[test]
1766    fn record_round_trips_codec() {
1767        // An answered call carries `codec` both ways — the daemon ships
1768        // it (its own data, like transferTarget), and the platform
1769        // echoes it back on read so the website can show the call's
1770        // audio quality.
1771        let raw = r#"{
1772            "sourceId": "a",
1773            "accountId": "b",
1774            "direction": "inbound",
1775            "party": "Alice <sip:alice@example.com>",
1776            "ringAt": "2026-07-03T10:00:00Z",
1777            "answerAt": "2026-07-03T10:00:05Z",
1778            "endAt": "2026-07-03T10:00:30Z",
1779            "durationMs": 25000,
1780            "disposition": "answered",
1781            "endReason": "hangup_remote",
1782            "codec": "opus"
1783        }"#;
1784        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1785        assert_eq!(parsed.codec, Some(VoiceCallCodec::Opus));
1786        // And it survives a re-serialize (daemon → platform direction).
1787        let s = serde_json::to_string(&parsed).unwrap();
1788        assert!(s.contains("\"codec\":\"opus\""), "{s}");
1789
1790        // A row from an older daemon has no codec — reads as None.
1791        let legacy = raw.replace(",\n            \"codec\": \"opus\"", "");
1792        let parsed: VoiceCallRecord = serde_json::from_str(&legacy).unwrap();
1793        assert_eq!(parsed.codec, None);
1794    }
1795
1796    #[test]
1797    fn flow_outcome_pins_its_wire_strings() {
1798        // Three parties agree on these exact strings: the daemon's
1799        // `flow_outcome_to_str`, `wavekat_flow::trace::FlowOutcome`'s
1800        // snake_case serde, and the platform's zod enum. A rename here
1801        // 400s every flow-answered call's batch.
1802        for (outcome, wire) in [
1803            (VoiceCallFlowOutcome::Answered, "\"answered\""),
1804            (VoiceCallFlowOutcome::MessageLeft, "\"message_left\""),
1805            (VoiceCallFlowOutcome::Transferred, "\"transferred\""),
1806            (VoiceCallFlowOutcome::HungUp, "\"hung_up\""),
1807            (VoiceCallFlowOutcome::Aborted, "\"aborted\""),
1808            (VoiceCallFlowOutcome::Defect, "\"defect\""),
1809        ] {
1810            assert_eq!(serde_json::to_string(&outcome).unwrap(), wire);
1811            let back: VoiceCallFlowOutcome = serde_json::from_str(wire).unwrap();
1812            assert_eq!(back, outcome);
1813        }
1814    }
1815
1816    #[test]
1817    fn record_round_trips_flow_attribution() {
1818        // A flow-answered call carries which flow took it and how the
1819        // run ended, both ways: the daemon ships them, the platform
1820        // echoes them so the website can say "Answered by “X”" and show
1821        // the run's own outcome instead of the misleading SIP one.
1822        let raw = r#"{
1823            "sourceId": "a",
1824            "accountId": "b",
1825            "direction": "inbound",
1826            "party": "Alice <sip:alice@example.com>",
1827            "ringAt": "2026-07-03T10:00:00Z",
1828            "answerAt": "2026-07-03T10:00:05Z",
1829            "endAt": "2026-07-03T10:00:30Z",
1830            "durationMs": 25000,
1831            "disposition": "answered",
1832            "endReason": "hangup_local",
1833            "flowId": "flow_after_hours",
1834            "flowName": "After hours",
1835            "flowOutcome": "message_left"
1836        }"#;
1837        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1838        assert_eq!(parsed.flow_id.as_deref(), Some("flow_after_hours"));
1839        assert_eq!(parsed.flow_name.as_deref(), Some("After hours"));
1840        assert_eq!(parsed.flow_outcome, Some(VoiceCallFlowOutcome::MessageLeft));
1841
1842        let s = serde_json::to_string(&parsed).unwrap();
1843        assert!(s.contains("\"flowId\":\"flow_after_hours\""), "{s}");
1844        assert!(s.contains("\"flowName\":\"After hours\""), "{s}");
1845        assert!(s.contains("\"flowOutcome\":\"message_left\""), "{s}");
1846    }
1847
1848    #[test]
1849    fn record_round_trips_a_flow_step_trace() {
1850        // Pins the per-step field names. These are consumed by the
1851        // platform's Zod schema on one side and produced by the daemon's
1852        // projection on the other; a silent rename here breaks both.
1853        let raw = r#"{
1854            "sourceId": "a",
1855            "accountId": "b",
1856            "direction": "inbound",
1857            "party": "sip:alice@example.com",
1858            "ringAt": "2026-07-03T10:00:00Z",
1859            "answerAt": "2026-07-03T10:00:05Z",
1860            "endAt": "2026-07-03T10:00:30Z",
1861            "disposition": "answered",
1862            "endReason": "hangup_local",
1863            "flowId": "f",
1864            "flowName": "F",
1865            "flowSteps": [
1866                { "atMs": 0, "kind": "spoke", "node": "greeting" },
1867                { "atMs": 4200, "kind": "menu_choice", "digit": "2" },
1868                { "atMs": 9100, "kind": "message_recorded", "secs": 31 }
1869            ]
1870        }"#;
1871        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1872        let steps = parsed.flow_steps.as_deref().expect("steps present");
1873        assert_eq!(steps.len(), 3);
1874        assert_eq!(steps[1].kind, "menu_choice");
1875        assert_eq!(steps[1].digit.as_deref(), Some("2"));
1876        assert_eq!(steps[2].secs, Some(31));
1877        // Absent per-step fields stay absent rather than serializing as
1878        // nulls — same contract as the record's own optional fields.
1879        let s = serde_json::to_string(&steps[0]).unwrap();
1880        assert_eq!(s, r#"{"atMs":0,"kind":"spoke","node":"greeting"}"#);
1881    }
1882
1883    #[test]
1884    fn flow_step_accepts_a_kind_this_build_does_not_know() {
1885        // The whole reason `kind` is a String. A consumer pinned to an
1886        // older crate version must still deserialize a newer daemon's
1887        // trace — rejecting would fail the entire call record, not one
1888        // step.
1889        let step: VoiceCallFlowStep =
1890            serde_json::from_str(r#"{"atMs": 10, "kind": "consulted_the_oracle"}"#).unwrap();
1891        assert_eq!(step.kind, "consulted_the_oracle");
1892        assert_eq!(step.digit, None);
1893    }
1894
1895    #[test]
1896    fn record_omits_flow_steps_for_a_human_answered_call() {
1897        // A call the user took themselves has no trace. The field must
1898        // stay off the wire entirely rather than serializing as null.
1899        let raw = r#"{
1900            "sourceId": "a",
1901            "accountId": "b",
1902            "direction": "inbound",
1903            "party": "sip:alice@example.com",
1904            "ringAt": "2026-07-03T10:00:00Z",
1905            "endAt": "2026-07-03T10:00:30Z",
1906            "disposition": "answered",
1907            "endReason": "hangup_local"
1908        }"#;
1909        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1910        assert!(parsed.flow_steps.is_none());
1911        let s = serde_json::to_string(&parsed).unwrap();
1912        assert!(!s.contains("flowSteps"), "{s}");
1913    }
1914
1915    #[test]
1916    fn record_omits_flow_fields_for_a_human_answered_call() {
1917        // Calls the user took themselves — and every row from a daemon
1918        // predating call flows — carry none of the three. They must
1919        // stay off the wire entirely, not serialize as nulls.
1920        let raw = r#"{
1921            "sourceId": "a",
1922            "accountId": "b",
1923            "direction": "inbound",
1924            "party": "sip:alice@example.com",
1925            "ringAt": "2026-07-03T10:00:00Z",
1926            "endAt": "2026-07-03T10:00:30Z",
1927            "disposition": "answered",
1928            "endReason": "hangup_remote"
1929        }"#;
1930        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1931        assert_eq!(parsed.flow_id, None);
1932        assert_eq!(parsed.flow_name, None);
1933        assert_eq!(parsed.flow_outcome, None);
1934
1935        let s = serde_json::to_string(&parsed).unwrap();
1936        assert!(!s.contains("\"flowId\""), "flowId should be omitted: {s}");
1937        assert!(
1938            !s.contains("\"flowName\""),
1939            "flowName should be omitted: {s}"
1940        );
1941        assert!(
1942            !s.contains("\"flowOutcome\""),
1943            "flowOutcome should be omitted: {s}"
1944        );
1945    }
1946
1947    #[test]
1948    fn voice_calls_marker_resource_is_calls() {
1949        assert_eq!(<VoiceCalls as SyncEndpoint>::RESOURCE, "calls");
1950    }
1951
1952    #[test]
1953    fn record_accepts_unknown_extras_for_forward_compat() {
1954        // A newer client shipping a `notes` field that this platform
1955        // version doesn't have a column for should round-trip via
1956        // the `extras` envelope. The platform persists the blob
1957        // verbatim; a future deploy can promote it to a typed
1958        // column without data loss.
1959        let raw = r#"{
1960            "sourceId": "a",
1961            "accountId": "b",
1962            "direction": "inbound",
1963            "party": "anon",
1964            "ringAt": "2026-05-16T10:00:00Z",
1965            "endAt": "2026-05-16T10:00:30Z",
1966            "disposition": "answered",
1967            "endReason": "hangup_remote",
1968            "schemaVersion": 2,
1969            "extras": { "notes": "from staging build" }
1970        }"#;
1971        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1972        assert_eq!(parsed.envelope.schema_version, Some(2));
1973        let extras = parsed.envelope.extras.as_ref().expect("extras present");
1974        assert_eq!(extras["notes"], "from staging build");
1975    }
1976
1977    #[test]
1978    fn call_record_parses_share_visibility_from_list_response() {
1979        // The list / detail endpoints decorate a call with the tier of any
1980        // active share on its recording, so a consumer can badge the row.
1981        let raw = r#"{
1982            "sourceId": "a",
1983            "accountId": "b",
1984            "direction": "outbound",
1985            "party": "+14155550123",
1986            "ringAt": "2026-05-16T10:00:00Z",
1987            "endAt": "2026-05-16T10:00:30Z",
1988            "disposition": "answered",
1989            "endReason": "hangup_remote",
1990            "shareVisibility": "public"
1991        }"#;
1992        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1993        assert_eq!(parsed.share_visibility, Some(ShareVisibility::Public));
1994
1995        let restricted = raw.replace("public", "restricted");
1996        let parsed: VoiceCallRecord = serde_json::from_str(&restricted).unwrap();
1997        assert_eq!(parsed.share_visibility, Some(ShareVisibility::Restricted));
1998    }
1999
2000    #[test]
2001    fn call_record_unshared_has_no_share_visibility() {
2002        // Absent (older platform, or an unshared call) and an explicit
2003        // `null` both read as "not shared" — never `Some(Private)`.
2004        let base = r#"{
2005            "sourceId": "a",
2006            "accountId": "b",
2007            "direction": "inbound",
2008            "party": "anon",
2009            "ringAt": "2026-05-16T10:00:00Z",
2010            "endAt": "2026-05-16T10:00:30Z",
2011            "disposition": "missed",
2012            "endReason": "missed"
2013        }"#;
2014        let parsed: VoiceCallRecord = serde_json::from_str(base).unwrap();
2015        assert_eq!(parsed.share_visibility, None);
2016
2017        let with_null = base.replace(
2018            r#""endReason": "missed""#,
2019            r#""endReason": "missed", "shareVisibility": null"#,
2020        );
2021        let parsed: VoiceCallRecord = serde_json::from_str(&with_null).unwrap();
2022        assert_eq!(parsed.share_visibility, None);
2023    }
2024
2025    #[test]
2026    fn synced_call_omits_share_visibility() {
2027        // `share_visibility` is read-only decoration: a call uploaded via
2028        // sync must not carry it on the wire (skip_serializing_if = None),
2029        // so the round trip from a sync-shaped record stays clean.
2030        let raw = r#"{
2031            "sourceId": "a",
2032            "accountId": "b",
2033            "direction": "inbound",
2034            "party": "anon",
2035            "ringAt": "2026-05-16T10:00:00Z",
2036            "endAt": "2026-05-16T10:00:30Z",
2037            "disposition": "answered",
2038            "endReason": "hangup_remote"
2039        }"#;
2040        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
2041        assert_eq!(parsed.share_visibility, None);
2042        let s = serde_json::to_string(&parsed).unwrap();
2043        assert!(
2044            !s.contains("shareVisibility"),
2045            "sync payload leaked share_visibility: {s}"
2046        );
2047    }
2048
2049    #[test]
2050    fn recording_marker_resource_is_recordings() {
2051        // Path constant drives the URL in `Client::sync_recordings`;
2052        // a rename here would silently 404 against the platform.
2053        assert_eq!(<VoiceRecordings as SyncEndpoint>::RESOURCE, "recordings");
2054    }
2055
2056    #[test]
2057    fn recording_record_serializes_with_camel_case_and_envelope() {
2058        let r = VoiceRecordingRecord {
2059            source_id: "11111111-1111-4111-8111-111111111111".into(),
2060            call_source_id: "22222222-2222-4222-8222-222222222222".into(),
2061            size_bytes: 44 + 64_000,
2062            duration_ms: 2_000,
2063            sample_rate: 8_000,
2064            channels: 2,
2065            created_at: "2026-05-16T10:01:05Z".into(),
2066            envelope: SyncEnvelope::for_endpoint::<VoiceRecordings>(),
2067        };
2068        let s = serde_json::to_string(&r).unwrap();
2069        // Field-by-field wire contract — these strings are also what
2070        // the platform's Zod schema expects.
2071        assert!(s.contains("\"sourceId\":"), "{s}");
2072        assert!(s.contains("\"callSourceId\":"), "{s}");
2073        assert!(s.contains("\"sizeBytes\":64044"), "{s}");
2074        assert!(s.contains("\"durationMs\":2000"), "{s}");
2075        assert!(s.contains("\"sampleRate\":8000"), "{s}");
2076        assert!(s.contains("\"channels\":2"), "{s}");
2077        assert!(s.contains("\"createdAt\":"), "{s}");
2078        // Envelope flattens to the top of the object, same as VoiceCallRecord.
2079        assert!(s.contains("\"schemaVersion\":1"), "{s}");
2080    }
2081
2082    #[test]
2083    fn recordings_sync_response_round_trips() {
2084        // The richer-than-generic response carries per-item provenance —
2085        // the daemon's uploader reads `r2Key` for the bytes follow-up
2086        // and `bytesUploaded` to short-circuit when the row already
2087        // landed on a previous cycle.
2088        let raw = r#"{
2089            "accepted": 2,
2090            "skipped": 0,
2091            "items": [
2092                {"sourceId": "a", "r2Key": "voice/recordings/1/a.wav", "bytesUploaded": false},
2093                {"sourceId": "b", "r2Key": "voice/recordings/1/b.wav", "bytesUploaded": true}
2094            ]
2095        }"#;
2096        let parsed: VoiceRecordingsSyncResponse = serde_json::from_str(raw).unwrap();
2097        assert_eq!(parsed.accepted, 2);
2098        assert_eq!(parsed.items.len(), 2);
2099        assert_eq!(parsed.items[0].r2_key, "voice/recordings/1/a.wav");
2100        assert!(!parsed.items[0].bytes_uploaded);
2101        assert!(parsed.items[1].bytes_uploaded);
2102    }
2103
2104    #[test]
2105    fn install_heartbeat_request_serializes_with_camel_case_keys() {
2106        let req = InstallHeartbeatRequest {
2107            install_id: "11111111-1111-4111-8111-111111111111".into(),
2108            app_version: "0.0.21".into(),
2109            os: "macos".into(),
2110            os_version: Some("15.5.0".into()),
2111            arch: Some("aarch64".into()),
2112            locale: Some("en-NZ".into()),
2113            distribution: Some("mas".into()),
2114        };
2115        let s = serde_json::to_string(&req).unwrap();
2116        assert!(s.contains("\"installId\":"), "{s}");
2117        assert!(s.contains("\"appVersion\":\"0.0.21\""), "{s}");
2118        assert!(s.contains("\"os\":\"macos\""), "{s}");
2119        assert!(s.contains("\"osVersion\":\"15.5.0\""), "{s}");
2120        assert!(s.contains("\"arch\":\"aarch64\""), "{s}");
2121        assert!(s.contains("\"locale\":\"en-NZ\""), "{s}");
2122        assert!(s.contains("\"distribution\":\"mas\""), "{s}");
2123    }
2124
2125    #[test]
2126    fn install_heartbeat_request_omits_absent_optional_fields() {
2127        // A host where the OS version / locale probe came up empty
2128        // shouldn't send `null` — keeping the keys out lets the
2129        // platform's Zod `.optional()` accept the body and the column
2130        // stay NULL rather than the string "null".
2131        let req = InstallHeartbeatRequest {
2132            install_id: "x".into(),
2133            app_version: "0.0.21".into(),
2134            os: "linux".into(),
2135            os_version: None,
2136            arch: None,
2137            locale: None,
2138            distribution: None,
2139        };
2140        let s = serde_json::to_string(&req).unwrap();
2141        assert!(!s.contains("osVersion"), "osVersion should be omitted: {s}");
2142        assert!(!s.contains("arch"), "arch should be omitted: {s}");
2143        assert!(!s.contains("locale"), "locale should be omitted: {s}");
2144        assert!(
2145            !s.contains("distribution"),
2146            "distribution should be omitted: {s}"
2147        );
2148    }
2149
2150    #[test]
2151    fn install_heartbeat_response_parses_platform_shape() {
2152        let raw = r#"{
2153            "id": "abc-123",
2154            "installId": "11111111-1111-4111-8111-111111111111",
2155            "appVersion": "0.0.21",
2156            "os": "macos",
2157            "osVersion": "15.5.0",
2158            "arch": "aarch64",
2159            "locale": null,
2160            "firstSeenAt": "2026-05-31T10:00:00.000Z",
2161            "lastSeenAt": "2026-05-31T10:00:00.000Z"
2162        }"#;
2163        let parsed: InstallHeartbeatResponse = serde_json::from_str(raw).unwrap();
2164        assert_eq!(parsed.id, "abc-123");
2165        assert_eq!(parsed.app_version, "0.0.21");
2166        assert_eq!(parsed.os_version.as_deref(), Some("15.5.0"));
2167        assert!(parsed.locale.is_none());
2168        // The fixture above carries no `distribution` key at all, which
2169        // is what a platform deployed before the field looks like. It
2170        // must parse, not error — hence `#[serde(default)]`.
2171        assert!(parsed.distribution.is_none());
2172    }
2173
2174    #[test]
2175    fn install_heartbeat_response_reads_the_distribution_back() {
2176        let raw = r#"{
2177            "id": "abc-123",
2178            "installId": "11111111-1111-4111-8111-111111111111",
2179            "appVersion": "0.0.48",
2180            "os": "macos",
2181            "osVersion": "15.5.0",
2182            "arch": "aarch64",
2183            "locale": "en-NZ",
2184            "distribution": "mas",
2185            "firstSeenAt": "2026-08-22T10:00:00.000Z",
2186            "lastSeenAt": "2026-08-22T10:00:00.000Z"
2187        }"#;
2188        let parsed: InstallHeartbeatResponse = serde_json::from_str(raw).unwrap();
2189        assert_eq!(parsed.distribution.as_deref(), Some("mas"));
2190    }
2191
2192    #[test]
2193    fn install_heartbeat_response_accepts_an_unknown_distribution() {
2194        // Free text by contract: the platform stores whatever arrives so
2195        // a new distribution can ship without a server release. Parsing
2196        // it into an enum here would undo that on the client side.
2197        let raw = r#"{
2198            "id": "abc-123",
2199            "installId": "11111111-1111-4111-8111-111111111111",
2200            "appVersion": "0.1.0",
2201            "os": "windows",
2202            "osVersion": null,
2203            "arch": "x86_64",
2204            "locale": null,
2205            "distribution": "msstore",
2206            "firstSeenAt": "2026-08-22T10:00:00.000Z",
2207            "lastSeenAt": "2026-08-22T10:00:00.000Z"
2208        }"#;
2209        let parsed: InstallHeartbeatResponse = serde_json::from_str(raw).unwrap();
2210        assert_eq!(parsed.distribution.as_deref(), Some("msstore"));
2211    }
2212
2213    #[test]
2214    fn system_info_detect_fills_os_and_arch() {
2215        // os / arch come from compile-time consts, so they're always
2216        // non-empty on every supported target. os_version / locale are
2217        // best-effort and intentionally not asserted.
2218        let sys = SystemInfo::detect();
2219        assert!(!sys.os.is_empty(), "os should be a non-empty target string");
2220        assert!(
2221            !sys.arch.is_empty(),
2222            "arch should be a non-empty target string"
2223        );
2224    }
2225
2226    #[test]
2227    fn transcripts_marker_resource_is_transcripts() {
2228        assert_eq!(<VoiceTranscripts as SyncEndpoint>::RESOURCE, "transcripts");
2229    }
2230
2231    #[test]
2232    fn transcript_record_serializes_with_camel_case_and_channel_enum() {
2233        let r = VoiceTranscriptRecord {
2234            source_id: "1".into(),
2235            call_source_id: "22222222-2222-4222-8222-222222222222".into(),
2236            channel: VoiceTranscriptChannel::Remote,
2237            ts_ms: 100,
2238            end_ms: 1_500,
2239            text: "hello".into(),
2240            envelope: SyncEnvelope::for_endpoint::<VoiceTranscripts>(),
2241        };
2242        let s = serde_json::to_string(&r).unwrap();
2243        assert!(s.contains("\"sourceId\":"), "{s}");
2244        assert!(s.contains("\"callSourceId\":"), "{s}");
2245        // The channel enum is wire-stable snake_case — matches the
2246        // platform's Zod `enum(VOICE_TRANSCRIPT_CHANNELS)`.
2247        assert!(s.contains("\"channel\":\"remote\""), "{s}");
2248        assert!(s.contains("\"tsMs\":100"), "{s}");
2249        assert!(s.contains("\"endMs\":1500"), "{s}");
2250        assert!(s.contains("\"text\":\"hello\""), "{s}");
2251        assert!(s.contains("\"schemaVersion\":1"), "{s}");
2252    }
2253
2254    #[test]
2255    fn share_visibility_pins_its_wire_strings() {
2256        // The platform validates these against an exact string list; a
2257        // rename would bounce every share command with a 400.
2258        assert_eq!(
2259            serde_json::to_string(&ShareVisibility::Private).unwrap(),
2260            "\"private\""
2261        );
2262        assert_eq!(
2263            serde_json::to_string(&ShareVisibility::Restricted).unwrap(),
2264            "\"restricted\""
2265        );
2266        assert_eq!(
2267            serde_json::to_string(&ShareVisibility::Public).unwrap(),
2268            "\"public\""
2269        );
2270        for v in [
2271            ShareVisibility::Private,
2272            ShareVisibility::Restricted,
2273            ShareVisibility::Public,
2274        ] {
2275            let s = serde_json::to_string(&v).unwrap();
2276            let back: ShareVisibility = serde_json::from_str(&s).unwrap();
2277            assert_eq!(v, back);
2278        }
2279    }
2280
2281    #[test]
2282    fn share_request_serializes_with_camel_case_and_omits_unset() {
2283        let req = ShareRecordingRequest {
2284            recording_source_id: "11111111-1111-4111-8111-111111111111".into(),
2285            visibility: ShareVisibility::Public,
2286            invited_emails: None,
2287            party_masking: None,
2288            show_transcript: None,
2289            show_audio: None,
2290            allow_download: None,
2291            default_mute_local: None,
2292            default_mute_remote: None,
2293            password: None,
2294            expires_at: None,
2295        };
2296        let s = serde_json::to_string(&req).unwrap();
2297        assert!(s.contains("\"recordingSourceId\":"), "{s}");
2298        assert!(s.contains("\"visibility\":\"public\""), "{s}");
2299        // Phase-2 / tier-specific / visibility-control fields stay off the
2300        // wire when unset so the platform's `.optional()` schema accepts the
2301        // body (and the omitted controls fall to the platform defaults).
2302        assert!(!s.contains("invitedEmails"), "{s}");
2303        assert!(!s.contains("partyMasking"), "{s}");
2304        assert!(!s.contains("showTranscript"), "{s}");
2305        assert!(!s.contains("showAudio"), "{s}");
2306        assert!(!s.contains("allowDownload"), "{s}");
2307        assert!(!s.contains("defaultMuteLocal"), "{s}");
2308        assert!(!s.contains("defaultMuteRemote"), "{s}");
2309        assert!(!s.contains("password"), "{s}");
2310        assert!(!s.contains("expiresAt"), "{s}");
2311    }
2312
2313    #[test]
2314    fn share_request_serializes_visibility_controls_camel_case() {
2315        let req = ShareRecordingRequest {
2316            recording_source_id: "a".into(),
2317            visibility: ShareVisibility::Public,
2318            invited_emails: None,
2319            party_masking: Some(PartyMasking::Partial),
2320            show_transcript: Some(false),
2321            show_audio: Some(true),
2322            allow_download: Some(true),
2323            default_mute_local: Some(false),
2324            default_mute_remote: Some(true),
2325            password: None,
2326            expires_at: None,
2327        };
2328        let s = serde_json::to_string(&req).unwrap();
2329        assert!(s.contains("\"partyMasking\":\"partial\""), "{s}");
2330        assert!(s.contains("\"showTranscript\":false"), "{s}");
2331        assert!(s.contains("\"showAudio\":true"), "{s}");
2332        assert!(s.contains("\"allowDownload\":true"), "{s}");
2333        // The owner muted their own side by default but left the other
2334        // party audible — both ride the wire as camelCase booleans.
2335        assert!(s.contains("\"defaultMuteLocal\":false"), "{s}");
2336        assert!(s.contains("\"defaultMuteRemote\":true"), "{s}");
2337    }
2338
2339    #[test]
2340    fn share_request_carries_invited_emails_for_restricted() {
2341        let req = ShareRecordingRequest {
2342            recording_source_id: "a".into(),
2343            visibility: ShareVisibility::Restricted,
2344            invited_emails: Some(vec!["alex@example.com".into()]),
2345            party_masking: None,
2346            show_transcript: None,
2347            show_audio: None,
2348            allow_download: None,
2349            default_mute_local: None,
2350            default_mute_remote: None,
2351            password: None,
2352            expires_at: None,
2353        };
2354        let s = serde_json::to_string(&req).unwrap();
2355        assert!(s.contains("\"visibility\":\"restricted\""), "{s}");
2356        assert!(
2357            s.contains("\"invitedEmails\":[\"alex@example.com\"]"),
2358            "{s}"
2359        );
2360    }
2361
2362    #[test]
2363    fn share_response_parses_platform_shape() {
2364        let raw = r#"{
2365            "visibility": "public",
2366            "token": "Zr7-x9F2k1QpLmN4sT8wYa",
2367            "shareUrl": "https://platform.wavekat.com/voice/s/Zr7-x9F2k1QpLmN4sT8wYa",
2368            "sharedAt": "2026-06-19T10:00:00.000Z"
2369        }"#;
2370        let parsed: ShareRecordingResponse = serde_json::from_str(raw).unwrap();
2371        assert_eq!(parsed.visibility, ShareVisibility::Public);
2372        assert_eq!(parsed.token, "Zr7-x9F2k1QpLmN4sT8wYa");
2373        assert!(parsed.share_url.ends_with(&parsed.token));
2374    }
2375
2376    #[test]
2377    fn share_state_parses_restricted_with_invited_emails() {
2378        // The GET read carries the audience back — this is the field the
2379        // POST reply omits and the desktop "who can open this" panel needs.
2380        let raw = r#"{
2381            "visibility": "restricted",
2382            "token": "Zr7-x9F2k1QpLmN4sT8wYa",
2383            "shareUrl": "https://platform.wavekat.com/voice/s/Zr7-x9F2k1QpLmN4sT8wYa",
2384            "sharedAt": "2026-06-19T10:00:00.000Z",
2385            "invitedEmails": ["bob@example.com", "carol@example.com"],
2386            "partyMasking": "full",
2387            "showTranscript": true,
2388            "showAudio": false,
2389            "allowDownload": false,
2390            "defaultMuteLocal": false,
2391            "defaultMuteRemote": true
2392        }"#;
2393        let parsed: ShareStateResponse = serde_json::from_str(raw).unwrap();
2394        assert_eq!(parsed.visibility, ShareVisibility::Restricted);
2395        assert_eq!(
2396            parsed.invited_emails.as_deref(),
2397            Some(
2398                [
2399                    "bob@example.com".to_string(),
2400                    "carol@example.com".to_string()
2401                ]
2402                .as_slice()
2403            )
2404        );
2405        // The visibility controls ride back on the live-share read.
2406        assert_eq!(parsed.party_masking, Some(PartyMasking::Full));
2407        assert_eq!(parsed.show_transcript, Some(true));
2408        assert_eq!(parsed.show_audio, Some(false));
2409        // Audio hidden here, so download comes back off (platform folds the two).
2410        assert_eq!(parsed.allow_download, Some(false));
2411        // Per-channel playback defaults ride back too.
2412        assert_eq!(parsed.default_mute_local, Some(false));
2413        assert_eq!(parsed.default_mute_remote, Some(true));
2414    }
2415
2416    #[test]
2417    fn share_state_parses_private_with_fields_absent() {
2418        // A never-shared (or revoked) recording reports private with no
2419        // token / url / emails — the optional fields stay None.
2420        let parsed: ShareStateResponse =
2421            serde_json::from_str(r#"{ "visibility": "private" }"#).unwrap();
2422        assert_eq!(parsed.visibility, ShareVisibility::Private);
2423        assert!(parsed.token.is_none());
2424        assert!(parsed.share_url.is_none());
2425        assert!(parsed.shared_at.is_none());
2426        assert!(parsed.invited_emails.is_none());
2427    }
2428
2429    #[test]
2430    fn share_request_rejects_empty_source_id_before_hitting_network() {
2431        // Guarded client-side so an empty id can't produce a path like
2432        // `/api/voice/recordings//share` that 404s confusingly.
2433        let req = ShareRecordingRequest {
2434            recording_source_id: String::new(),
2435            visibility: ShareVisibility::Private,
2436            invited_emails: None,
2437            party_masking: None,
2438            show_transcript: None,
2439            show_audio: None,
2440            allow_download: None,
2441            default_mute_local: None,
2442            default_mute_remote: None,
2443            password: None,
2444            expires_at: None,
2445        };
2446        // We can't call the async method without a runtime here, but the
2447        // guard mirrors `upload_recording_bytes` — assert the precondition
2448        // shape the method checks.
2449        assert!(req.recording_source_id.is_empty());
2450    }
2451
2452    // ---- VoiceAccounts ----
2453
2454    fn sample_account() -> VoiceAccountRecord {
2455        VoiceAccountRecord {
2456            source_id: "11111111-1111-4111-8111-111111111111".into(),
2457            enabled: true,
2458            display_name: "Work line".into(),
2459            username: "alice".into(),
2460            domain: "sip.example.com".into(),
2461            auth_username: Some("alice-auth".into()),
2462            server: Some("sip.example.com".into()),
2463            port: Some(5060),
2464            transport: VoiceTransport::Udp,
2465            register_expires: 60,
2466            keepalive_secs: Some(50),
2467            disclosure_enabled: true,
2468            updated_at: "2026-06-20T10:00:00Z".into(),
2469            deleted_at: None,
2470            envelope: SyncEnvelope::for_endpoint::<VoiceAccounts>(),
2471        }
2472    }
2473
2474    #[test]
2475    fn accounts_marker_resource_is_accounts() {
2476        // Path constant drives the URL in `Client::sync` / `Client::list`;
2477        // a rename here would silently 404 against the platform.
2478        assert_eq!(<VoiceAccounts as SyncEndpoint>::RESOURCE, "accounts");
2479    }
2480
2481    #[test]
2482    fn account_record_serializes_with_camel_case_and_envelope() {
2483        let s = serde_json::to_string(&sample_account()).unwrap();
2484        // Field-by-field wire contract — also what the platform's Zod
2485        // schema expects.
2486        assert!(s.contains("\"sourceId\":"), "{s}");
2487        assert!(s.contains("\"displayName\":\"Work line\""), "{s}");
2488        assert!(s.contains("\"authUsername\":\"alice-auth\""), "{s}");
2489        assert!(s.contains("\"registerExpires\":60"), "{s}");
2490        assert!(s.contains("\"keepaliveSecs\":50"), "{s}");
2491        assert!(s.contains("\"disclosureEnabled\":true"), "{s}");
2492        assert!(s.contains("\"transport\":\"udp\""), "{s}");
2493        assert!(s.contains("\"updatedAt\":\"2026-06-20T10:00:00Z\""), "{s}");
2494        // A live line carries no tombstone.
2495        assert!(!s.contains("deletedAt"), "deletedAt should be omitted: {s}");
2496        // The secret never crosses this wire, by construction.
2497        assert!(!s.contains("password"), "no password field: {s}");
2498        // Envelope flattens to the top, same as the other resources.
2499        assert!(s.contains("\"schemaVersion\":1"), "{s}");
2500    }
2501
2502    #[test]
2503    fn account_tombstone_serializes_deleted_at() {
2504        // A soft-delete rides as an upsert with deletedAt set — the
2505        // delete-propagation mechanism (doc 40).
2506        let mut r = sample_account();
2507        r.deleted_at = Some("2026-06-20T12:00:00Z".into());
2508        let s = serde_json::to_string(&r).unwrap();
2509        assert!(s.contains("\"deletedAt\":\"2026-06-20T12:00:00Z\""), "{s}");
2510    }
2511
2512    #[test]
2513    fn account_record_round_trips_optional_fields() {
2514        // A minimal line — no auth username, server, port, keepalive, or
2515        // tombstone — should parse with those all absent.
2516        let raw = r#"{
2517            "sourceId": "a",
2518            "enabled": false,
2519            "displayName": "Cheap trunk",
2520            "username": "u",
2521            "domain": "d",
2522            "transport": "tcp",
2523            "registerExpires": 120,
2524            "disclosureEnabled": false,
2525            "updatedAt": "2026-06-20T10:00:00Z"
2526        }"#;
2527        let parsed: VoiceAccountRecord = serde_json::from_str(raw).unwrap();
2528        assert!(!parsed.enabled);
2529        assert!(parsed.auth_username.is_none());
2530        assert!(parsed.server.is_none());
2531        assert!(parsed.port.is_none());
2532        assert!(parsed.keepalive_secs.is_none());
2533        assert!(parsed.deleted_at.is_none());
2534        assert_eq!(parsed.transport, VoiceTransport::Tcp);
2535        assert_eq!(parsed.register_expires, 120);
2536    }
2537
2538    #[test]
2539    fn voice_transport_round_trips_via_json() {
2540        for t in [VoiceTransport::Udp, VoiceTransport::Tcp] {
2541            let s = serde_json::to_string(&t).unwrap();
2542            let back: VoiceTransport = serde_json::from_str(&s).unwrap();
2543            assert_eq!(t, back);
2544        }
2545        // Pin the wire strings — the daemon's `TransportKind` and the
2546        // platform's Zod enum both depend on these exact tokens.
2547        assert_eq!(
2548            serde_json::to_string(&VoiceTransport::Udp).unwrap(),
2549            "\"udp\""
2550        );
2551        assert_eq!(
2552            serde_json::to_string(&VoiceTransport::Tcp).unwrap(),
2553            "\"tcp\""
2554        );
2555    }
2556
2557    #[test]
2558    fn accounts_query_omits_unset_and_serializes_include_deleted() {
2559        let empty = serde_json::to_string(&VoiceAccountsQuery::default()).unwrap();
2560        assert_eq!(empty, "{}", "default query should be empty: {empty}");
2561        let with_deleted = serde_json::to_string(&VoiceAccountsQuery {
2562            include_deleted: Some(true),
2563        })
2564        .unwrap();
2565        assert!(
2566            with_deleted.contains("\"includeDeleted\":true"),
2567            "{with_deleted}"
2568        );
2569    }
2570
2571    // ---- VoiceFlows ----
2572
2573    #[test]
2574    fn flows_query_serializes_cursor_and_omits_absent_fields() {
2575        let empty = serde_json::to_string(&VoiceFlowsQuery::default()).unwrap();
2576        assert_eq!(empty, "{}");
2577        let cursored = serde_json::to_string(&VoiceFlowsQuery {
2578            after: Some("flow_abc".into()),
2579            limit: Some(100),
2580            schema_versions: None,
2581        })
2582        .unwrap();
2583        assert!(cursored.contains("\"after\":\"flow_abc\""), "{cursored}");
2584        assert!(cursored.contains("\"limit\":100"), "{cursored}");
2585    }
2586
2587    #[test]
2588    fn flows_query_sends_schema_versions_under_the_servers_name() {
2589        // The struct is camelCase; this parameter is not. A silently
2590        // camelCased key is ignored by the server, which reads exactly
2591        // like an account with no flows in that version — so pin it.
2592        let query = serde_json::to_string(&VoiceFlowsQuery {
2593            schema_versions: Some("1,2".into()),
2594            ..Default::default()
2595        })
2596        .unwrap();
2597        assert_eq!(query, r#"{"schema_versions":"1,2"}"#);
2598    }
2599
2600    // ---- Booking ----
2601
2602    #[test]
2603    fn booking_slots_request_uses_the_routes_snake_case_wire() {
2604        // Unlike the sync resources above, these routes speak snake_case.
2605        // A camelCased body is rejected as a validation error mid-call,
2606        // which the flow can only render as "unavailable".
2607        let body = serde_json::to_string(&BookingSlotsRequest {
2608            source_id: "call_1".into(),
2609            duration_mins: 30,
2610            buffer_mins: 10,
2611            lead_mins: 120,
2612            horizon_days: 14,
2613            schedule: BookingSchedule {
2614                tue: vec![BookingTimeRange {
2615                    open: "09:00".into(),
2616                    close: "17:00".into(),
2617                }],
2618                ..Default::default()
2619            },
2620            timezone: "Pacific/Auckland".into(),
2621            exceptions: Vec::new(),
2622            limit: 3,
2623        })
2624        .unwrap();
2625        assert!(body.contains(r#""source_id":"call_1""#), "{body}");
2626        assert!(body.contains(r#""duration_mins":30"#), "{body}");
2627        assert!(body.contains(r#""timezone":"Pacific/Auckland""#), "{body}");
2628        // Days with no hours, and an empty exception list, stay off the
2629        // wire entirely rather than shipping empty arrays.
2630        assert!(!body.contains("\"mon\""), "{body}");
2631        assert!(!body.contains("exceptions"), "{body}");
2632    }
2633
2634    #[test]
2635    fn booking_slots_response_parses_both_answers() {
2636        let offered: BookingSlotsResponse = serde_json::from_str(
2637            r#"{"slots":[{"start":"2026-08-11T21:00:00Z","end":"2026-08-11T21:30:00Z"}],"timezone":"Pacific/Auckland"}"#,
2638        )
2639        .unwrap();
2640        assert_eq!(offered.slots.len(), 1);
2641        assert_eq!(offered.timezone, "Pacific/Auckland");
2642        assert!(offered.status.is_none());
2643
2644        // The calendar could not be read. Not an error to the caller of
2645        // this crate — the flow has an exit for it.
2646        let down: BookingSlotsResponse =
2647            serde_json::from_str(r#"{"status":"unavailable","reason":"not_connected"}"#).unwrap();
2648        assert!(down.slots.is_empty());
2649        assert_eq!(down.status.as_deref(), Some("unavailable"));
2650        assert_eq!(down.reason.as_deref(), Some("not_connected"));
2651    }
2652
2653    #[test]
2654    fn booking_book_response_parses_every_outcome() {
2655        let booked: BookingBookResponse =
2656            serde_json::from_str(r#"{"status":"booked","start":"2026-08-11T21:00:00Z"}"#).unwrap();
2657        assert_eq!(booked.status, "booked");
2658        assert_eq!(booked.start.as_deref(), Some("2026-08-11T21:00:00Z"));
2659
2660        let taken: BookingBookResponse =
2661            serde_json::from_str(r#"{"status":"slot_taken"}"#).unwrap();
2662        assert_eq!(taken.status, "slot_taken");
2663        assert!(taken.start.is_none());
2664
2665        // A status this build has never heard of still parses: failing
2666        // here would drop a live call over an unknown string.
2667        let future: BookingBookResponse =
2668            serde_json::from_str(r#"{"status":"needs_deposit"}"#).unwrap();
2669        assert_eq!(future.status, "needs_deposit");
2670    }
2671
2672    #[test]
2673    fn flows_page_parses_platform_shape() {
2674        let raw = r#"{
2675            "items": [{
2676                "id": "flow_1",
2677                "name": "Luigi's — after hours",
2678                "version": 3,
2679                "yaml": "schema_version: 1\n",
2680                "publishedAt": "2026-07-13T10:00:00Z"
2681            }],
2682            "nextAfter": null
2683        }"#;
2684        let page: VoiceFlowsPage = serde_json::from_str(raw).unwrap();
2685        assert_eq!(page.items.len(), 1);
2686        let rec = &page.items[0];
2687        assert_eq!(rec.id, "flow_1");
2688        assert_eq!(rec.version, 3);
2689        assert_eq!(rec.published_at, "2026-07-13T10:00:00Z");
2690        assert!(page.next_after.is_none());
2691
2692        // A mid-walk page carries the cursor.
2693        let more: VoiceFlowsPage =
2694            serde_json::from_str(r#"{ "items": [], "nextAfter": "flow_1" }"#).unwrap();
2695        assert_eq!(more.next_after.as_deref(), Some("flow_1"));
2696    }
2697
2698    #[test]
2699    fn flow_assets_manifest_parses_platform_shape() {
2700        // `ref` (a reserved word) maps to `asset_ref`; a null duration is
2701        // accepted (the platform doesn't always know it).
2702        let raw = r#"{
2703            "assets": [{
2704                "ref": "vprompt_ab12cd34",
2705                "format": "ulaw_8000",
2706                "byteSize": 48044,
2707                "durationMs": null,
2708                "contentHash": "9f2c00aa"
2709            }]
2710        }"#;
2711        let page: VoiceFlowAssetsPage = serde_json::from_str(raw).unwrap();
2712        assert_eq!(page.assets.len(), 1);
2713        let asset = &page.assets[0];
2714        assert_eq!(asset.asset_ref, "vprompt_ab12cd34");
2715        assert_eq!(asset.format, "ulaw_8000");
2716        assert_eq!(asset.byte_size, 48044);
2717        assert!(asset.duration_ms.is_none());
2718        assert_eq!(asset.content_hash, "9f2c00aa");
2719
2720        // A text-only version legitimately has no frozen audio.
2721        let empty: VoiceFlowAssetsPage = serde_json::from_str(r#"{ "assets": [] }"#).unwrap();
2722        assert!(empty.assets.is_empty());
2723    }
2724
2725    #[test]
2726    fn account_record_accepts_unknown_extras_for_forward_compat() {
2727        // A newer client shipping a field this platform version lacks a
2728        // column for round-trips via the `extras` envelope.
2729        let raw = r#"{
2730            "sourceId": "a",
2731            "enabled": true,
2732            "displayName": "x",
2733            "username": "u",
2734            "domain": "d",
2735            "transport": "udp",
2736            "registerExpires": 60,
2737            "disclosureEnabled": true,
2738            "updatedAt": "2026-06-20T10:00:00Z",
2739            "schemaVersion": 2,
2740            "extras": { "ringtone": "classic" }
2741        }"#;
2742        let parsed: VoiceAccountRecord = serde_json::from_str(raw).unwrap();
2743        assert_eq!(parsed.envelope.schema_version, Some(2));
2744        let extras = parsed.envelope.extras.as_ref().expect("extras present");
2745        assert_eq!(extras["ringtone"], "classic");
2746    }
2747
2748    #[test]
2749    fn system_flow_record_parses_the_platform_shape() {
2750        // The full wire shape as served by the platform's system flow
2751        // endpoint: all fields present including optionals.
2752        let json = r#"{
2753            "id": "flow_voicemail",
2754            "name": "Voicemail",
2755            "description": "A short greeting.",
2756            "language": "en",
2757            "version": 2,
2758            "yaml": "schema_version: 1\n",
2759            "publishedAt": "2026-08-27 01:02:03",
2760            "access": "open",
2761            "systemTags": ["system", "access:open"]
2762        }"#;
2763        let rec: VoiceSystemFlowRecord = serde_json::from_str(json).unwrap();
2764        assert_eq!(rec.id, "flow_voicemail");
2765        assert_eq!(rec.name, "Voicemail");
2766        assert_eq!(rec.description, "A short greeting.");
2767        assert_eq!(rec.language, "en");
2768        assert_eq!(rec.version, 2);
2769        assert_eq!(rec.yaml, "schema_version: 1\n");
2770        assert_eq!(rec.published_at, Some("2026-08-27 01:02:03".into()));
2771        assert_eq!(rec.access, "open");
2772        assert_eq!(rec.system_tags, vec!["system", "access:open"]);
2773    }
2774
2775    #[test]
2776    fn system_flow_record_tolerates_missing_optionals_and_unknown_fields() {
2777        // Older rows or newer platforms: description, publishedAt,
2778        // systemTags may be absent; unknown fields must be ignored
2779        // (forward compat).
2780        let json = r#"{"id":"f","name":"n","language":"en","version":1,"yaml":"y","access":"account","someFutureField":1}"#;
2781        let rec: VoiceSystemFlowRecord = serde_json::from_str(json).unwrap();
2782        assert_eq!(rec.id, "f");
2783        assert_eq!(rec.name, "n");
2784        assert_eq!(rec.description, "");
2785        assert_eq!(rec.language, "en");
2786        assert_eq!(rec.version, 1);
2787        assert_eq!(rec.yaml, "y");
2788        assert!(rec.published_at.is_none());
2789        assert_eq!(rec.access, "account");
2790        assert!(rec.system_tags.is_empty());
2791    }
2792}