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
711impl Client {
712    /// `GET /api/voice/flows/published` — one page of the caller's
713    /// published flow snapshots (latest version each). Strictly
714    /// creator-scoped server-side; never returns another user's flows.
715    pub async fn published_flows(&self, query: &VoiceFlowsQuery) -> Result<VoiceFlowsPage> {
716        self.get_json_query::<VoiceFlowsPage, _>("/api/voice/flows/published", query)
717            .await
718    }
719
720    /// `GET /api/voice/flows/{id}/versions/{version}/assets` — the frozen
721    /// audio manifest for one published version (docs 16/17). Flow-scoped
722    /// server-side: a version of a flow the caller doesn't own is a 404,
723    /// never another user's assets. An existing, visible version with no
724    /// generated audio returns an empty manifest.
725    pub async fn flow_version_assets(
726        &self,
727        flow_id: &str,
728        version: u32,
729    ) -> Result<VoiceFlowAssetsPage> {
730        let path = format!("/api/voice/flows/{flow_id}/versions/{version}/assets");
731        self.get_json::<VoiceFlowAssetsPage>(&path).await
732    }
733
734    /// `GET /api/voice/flows/{id}/versions/{version}/assets/{ref}/bytes` —
735    /// the immutable frozen copy of one clip, served from the version's own
736    /// asset set (never the mutable library). Returned in memory because a
737    /// clip is tens of KB and the daemon writes it atomically into its
738    /// on-disk cache; same flow-scoped 404 as the manifest.
739    pub async fn flow_version_asset_bytes(
740        &self,
741        flow_id: &str,
742        version: u32,
743        asset_ref: &str,
744    ) -> Result<Vec<u8>> {
745        let path =
746            format!("/api/voice/flows/{flow_id}/versions/{version}/assets/{asset_ref}/bytes");
747        self.get_bytes(&path).await
748    }
749}
750
751// ---- Booking (mid-call, synchronous) ---------------------------------------
752//
753// The action plane of wavekat-platform's docs/30: a `book` step asking
754// "when is this business free?" and then "put the caller in at this
755// time", with the caller on the line.
756//
757// Unlike every other endpoint in this file, these are **synchronous and
758// in-call**. Nothing here is queued, batched or retried: a person is
759// waiting, so the platform answers within seconds or answers
760// `unavailable`, and the flow takes its fallback exit. Callers should
761// give these a short timeout of their own and treat expiry the same way
762// they treat `unavailable`.
763//
764// The calendar credential never reaches this crate. The platform holds
765// the connection and answers in times and outcomes — which is what makes
766// booking a pair of platform calls rather than a Google client in every
767// daemon.
768//
769// Wire note: these routes use `snake_case` bodies, unlike the camelCase
770// sync resources above, so these types carry no `rename_all`.
771
772/// One open window in a business's week, `"HH:MM"` 24-hour local time —
773/// the same shape the flow document's `hours`/`book` steps carry.
774#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
775pub struct BookingTimeRange {
776    pub open: String,
777    pub close: String,
778}
779
780/// Open windows per weekday. A missing or empty day is closed.
781#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
782pub struct BookingSchedule {
783    #[serde(default, skip_serializing_if = "Vec::is_empty")]
784    pub mon: Vec<BookingTimeRange>,
785    #[serde(default, skip_serializing_if = "Vec::is_empty")]
786    pub tue: Vec<BookingTimeRange>,
787    #[serde(default, skip_serializing_if = "Vec::is_empty")]
788    pub wed: Vec<BookingTimeRange>,
789    #[serde(default, skip_serializing_if = "Vec::is_empty")]
790    pub thu: Vec<BookingTimeRange>,
791    #[serde(default, skip_serializing_if = "Vec::is_empty")]
792    pub fri: Vec<BookingTimeRange>,
793    #[serde(default, skip_serializing_if = "Vec::is_empty")]
794    pub sat: Vec<BookingTimeRange>,
795    #[serde(default, skip_serializing_if = "Vec::is_empty")]
796    pub sun: Vec<BookingTimeRange>,
797}
798
799/// A single-date override of the weekly schedule (a holiday, or special
800/// hours).
801#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
802pub struct BookingException {
803    /// `"YYYY-MM-DD"` in the schedule's own timezone.
804    pub date: String,
805    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
806    pub closed: bool,
807    #[serde(default, skip_serializing_if = "Vec::is_empty")]
808    pub ranges: Vec<BookingTimeRange>,
809}
810
811/// Body of `POST /api/voice/booking/slots`.
812///
813/// Everything except `source_id` comes straight off the flow document's
814/// `book` step; the platform holds no per-node configuration of its own.
815#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
816pub struct BookingSlotsRequest {
817    /// The call this offer belongs to (`voice_calls.source_id`). Slots
818    /// are held against it, which is what stops a caller being blocked
819    /// by their own offers — and what stops a second caller being
820    /// offered the same time.
821    pub source_id: String,
822    pub duration_mins: u32,
823    #[serde(default)]
824    pub buffer_mins: u32,
825    #[serde(default)]
826    pub lead_mins: u32,
827    #[serde(default)]
828    pub horizon_days: u32,
829    pub schedule: BookingSchedule,
830    /// IANA zone the schedule is written in.
831    pub timezone: String,
832    #[serde(default, skip_serializing_if = "Vec::is_empty")]
833    pub exceptions: Vec<BookingException>,
834    /// How many times to offer. The answer may be shorter, never longer.
835    pub limit: u32,
836}
837
838/// One offerable appointment, as absolute RFC 3339 instants.
839#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
840pub struct BookingSlot {
841    pub start: String,
842    pub end: String,
843}
844
845/// Answer to `POST /api/voice/booking/slots`.
846///
847/// `slots` empty is a real answer — the calendar is full, or the window
848/// closed — and not an error: the flow takes its no-slots exit.
849#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
850pub struct BookingSlotsResponse {
851    #[serde(default)]
852    pub slots: Vec<BookingSlot>,
853    /// The zone the times should be *spoken* in — the business's, echoed
854    /// back so the caller isn't told a time in the server's zone.
855    #[serde(default)]
856    pub timezone: String,
857    /// Set when the platform could not read the calendar at all
858    /// (`"unavailable"`); `slots` is then empty and the reason is for
859    /// logs, never for a caller.
860    #[serde(default, skip_serializing_if = "Option::is_none")]
861    pub status: Option<String>,
862    #[serde(default, skip_serializing_if = "Option::is_none")]
863    pub reason: Option<String>,
864}
865
866/// Body of `POST /api/voice/booking/book`.
867///
868/// Idempotent on `source_id`: a retried request for a call that already
869/// has an appointment answers `booked` with the existing event's start,
870/// without touching the calendar. A timed-out request is therefore safe
871/// to repeat.
872#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
873pub struct BookingBookRequest {
874    pub source_id: String,
875    /// One of the `start`s `/slots` handed back, verbatim.
876    pub start: String,
877    pub duration_mins: u32,
878    pub timezone: String,
879    /// Who is booking, for the calendar entry. Empty when the call
880    /// carried no caller id.
881    #[serde(default)]
882    pub caller_number: String,
883    #[serde(default, skip_serializing_if = "Option::is_none")]
884    pub caller_name: Option<String>,
885}
886
887/// Answer to `POST /api/voice/booking/book`.
888///
889/// Three outcomes, and the flow does something different with each:
890/// `booked` continues, `slot_taken` can offer again, `unavailable` falls
891/// back. Left as a string rather than an enum so a status added later
892/// deserializes instead of failing the call.
893#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
894pub struct BookingBookResponse {
895    pub status: String,
896    /// Present on `booked` — the instant the appointment actually
897    /// starts, which on an idempotent retry is the *existing* event's
898    /// start and not necessarily the one that was asked for.
899    #[serde(default, skip_serializing_if = "Option::is_none")]
900    pub start: Option<String>,
901    #[serde(default, skip_serializing_if = "Option::is_none")]
902    pub reason: Option<String>,
903}
904
905impl Client {
906    /// `POST /api/voice/booking/slots` — when is this business free?
907    ///
908    /// Writes as well as reads: every time it returns is held for
909    /// `source_id` for a couple of minutes, so a second caller is not
910    /// offered it while this one is still deciding. Re-offering the same
911    /// call refreshes its own holds rather than colliding with them.
912    pub async fn booking_slots(
913        &self,
914        request: &BookingSlotsRequest,
915    ) -> Result<BookingSlotsResponse> {
916        self.post_json::<BookingSlotsResponse, _>("/api/voice/booking/slots", request)
917            .await
918    }
919
920    /// `POST /api/voice/booking/book` — put the caller in at this time.
921    pub async fn booking_book(&self, request: &BookingBookRequest) -> Result<BookingBookResponse> {
922        self.post_json::<BookingBookResponse, _>("/api/voice/booking/book", request)
923            .await
924    }
925}
926
927// ---- Anonymous install heartbeat ------------------------------------------
928//
929// A first-run / per-launch ping the desktop daemon fires *before* (and
930// independently of) any platform sign-in, so the platform can count
931// installs and track version / OS adoption for users who never sign in.
932// It hits the public, unauthenticated `POST /api/voice/installs/heartbeat`
933// and upserts a row keyed by `install_id` alone (no user) — distinct
934// from the authenticated `voice_clients` heartbeat, which is keyed by
935// `(user, install_id)`.
936//
937// The environment fields (os / os_version / arch / locale) are gathered
938// *here*, inside the client crate, rather than on the consumer side:
939// the daemon only owns the two values this crate genuinely cannot
940// discover — the persisted `install_id` and its own app version.
941
942/// Best-effort snapshot of the host environment, detected at call time.
943/// Every field is best-effort; a probe that fails contributes `None`
944/// (or, for the always-available `os` / `arch`, the compile-time
945/// target) rather than failing the heartbeat.
946#[derive(Debug, Clone, PartialEq, Eq)]
947pub struct SystemInfo {
948    /// `std::env::consts::OS` — `"macos"`, `"windows"`, `"linux"`, …
949    pub os: String,
950    /// Human OS version, e.g. `"15.5.0"`. `None` when the OS probe
951    /// can't determine it.
952    pub os_version: Option<String>,
953    /// `std::env::consts::ARCH` — `"aarch64"`, `"x86_64"`, …
954    pub arch: String,
955    /// BCP-47 system locale, e.g. `"en-NZ"`. `None` when unset /
956    /// undetectable (common for GUI-launched apps on some platforms).
957    pub locale: Option<String>,
958}
959
960impl SystemInfo {
961    /// Probe the current host. Cheap enough to call per heartbeat; we
962    /// don't cache so a locale change between launches is reflected.
963    pub fn detect() -> Self {
964        let os_version = match os_info::get().version() {
965            os_info::Version::Unknown => None,
966            v => Some(v.to_string()),
967        };
968        SystemInfo {
969            os: std::env::consts::OS.to_string(),
970            os_version,
971            arch: std::env::consts::ARCH.to_string(),
972            locale: sys_locale::get_locale(),
973        }
974    }
975}
976
977/// Body of `POST /api/voice/installs/heartbeat`. The daemon supplies
978/// `install_id` + `app_version`; [`Client::install_heartbeat`] fills the
979/// environment fields from [`SystemInfo::detect`].
980#[derive(Debug, Clone, Serialize, Deserialize)]
981#[serde(rename_all = "camelCase")]
982pub struct InstallHeartbeatRequest {
983    /// The daemon's persisted install UUID — the platform's upsert key.
984    pub install_id: String,
985    /// WaveKat Voice's own version (`env!("CARGO_PKG_VERSION")` on the
986    /// daemon side) — *not* this crate's version.
987    pub app_version: String,
988    pub os: String,
989    #[serde(default, skip_serializing_if = "Option::is_none")]
990    pub os_version: Option<String>,
991    #[serde(default, skip_serializing_if = "Option::is_none")]
992    pub arch: Option<String>,
993    #[serde(default, skip_serializing_if = "Option::is_none")]
994    pub locale: Option<String>,
995}
996
997/// The platform's view of an install row, echoed back from a heartbeat.
998#[derive(Debug, Clone, Serialize, Deserialize)]
999#[serde(rename_all = "camelCase")]
1000pub struct InstallHeartbeatResponse {
1001    pub id: String,
1002    pub install_id: String,
1003    pub app_version: String,
1004    pub os: String,
1005    pub os_version: Option<String>,
1006    pub arch: Option<String>,
1007    pub locale: Option<String>,
1008    pub first_seen_at: String,
1009    pub last_seen_at: String,
1010}
1011
1012impl Client {
1013    /// `POST /api/voice/installs/heartbeat` — the anonymous, no-auth
1014    /// first-run install ping. Detects the host environment internally
1015    /// and posts it alongside the caller-supplied `install_id` +
1016    /// `app_version`. Associated (not a method) because the endpoint is
1017    /// unauthenticated — there's no token, and at first run there's no
1018    /// signed-in `Client` to hang it off of.
1019    ///
1020    /// Though unauthenticated, the request is **signed** with the release
1021    /// credential `cred` (a per-version Ed25519 key + master-issued
1022    /// certificate the consumer bakes in at build time) so the platform
1023    /// can verify it came from a genuine release and reject forged or
1024    /// replayed pings — see [`Client::post_public_signed_json`] and
1025    /// [`crate::sign`]. The platform needs only the master *public* key to
1026    /// verify.
1027    ///
1028    /// `base_url` is the platform base (e.g. `https://platform.wavekat.com`).
1029    pub async fn install_heartbeat(
1030        base_url: &str,
1031        install_id: &str,
1032        app_version: &str,
1033        cred: &ReleaseCredential,
1034    ) -> Result<InstallHeartbeatResponse> {
1035        let sys = SystemInfo::detect();
1036        let body = InstallHeartbeatRequest {
1037            install_id: install_id.to_string(),
1038            app_version: app_version.to_string(),
1039            os: sys.os,
1040            os_version: sys.os_version,
1041            arch: Some(sys.arch),
1042            locale: sys.locale,
1043        };
1044        Client::post_public_signed_json::<InstallHeartbeatResponse, _>(
1045            base_url,
1046            "/api/voice/installs/heartbeat",
1047            &body,
1048            cred,
1049        )
1050        .await
1051    }
1052}
1053
1054// ---- Client surface for recordings ----------------------------------------
1055//
1056// Recordings don't fit the generic `Client::sync` shape cleanly:
1057//
1058//   - the response carries per-item provenance (the platform-stamped
1059//     `r2Key`, plus whether bytes have already landed) that the
1060//     daemon needs in order to decide which rows still owe a PUT;
1061//   - the bytes upload is its own HTTP call (`PUT
1062//     /api/voice/recordings/{sourceId}/bytes`), not a JSON batch.
1063//
1064// Rather than overloading `SyncEndpoint` to carry these shapes, we
1065// expose two inherent methods on `Client` that compose the existing
1066// JSON / bytes-PUT primitives.
1067
1068impl Client {
1069    /// `POST /api/voice/recordings/sync` — idempotent batch upsert of
1070    /// recording metadata. Returns the per-item `r2Key` the daemon
1071    /// should target for the follow-up bytes PUT, and whether bytes
1072    /// have already landed for each row.
1073    ///
1074    /// Batch sizing rules match [`Client::sync`]: the platform rejects
1075    /// batches over 100 items; the daemon's uploader chunks at 50.
1076    pub async fn sync_recordings(
1077        &self,
1078        items: &[VoiceRecordingRecord],
1079    ) -> Result<VoiceRecordingsSyncResponse> {
1080        let stamped = stamp_schema_version::<VoiceRecordings>(items);
1081        let body = SyncRequest { items: stamped };
1082        self.post_json::<VoiceRecordingsSyncResponse, _>("/api/voice/recordings/sync", &body)
1083            .await
1084    }
1085
1086    /// `PUT /api/voice/recordings/{sourceId}/bytes` — upload the WAV
1087    /// bytes for a recording whose metadata was previously synced via
1088    /// [`Client::sync_recordings`]. The platform refuses (`HTTP 413`)
1089    /// if `bytes.len()` disagrees with the synced `sizeBytes`.
1090    ///
1091    /// `source_id` is path-segmented as-is; callers pass the
1092    /// daemon-side UUID they used for the metadata sync. Empty /
1093    /// path-traversal-shaped ids are not specifically guarded here —
1094    /// the platform's Zod schema rejects them server-side, so a
1095    /// malformed id surfaces as a 4xx via [`Error::Http`].
1096    pub async fn upload_recording_bytes(&self, source_id: &str, bytes: Vec<u8>) -> Result<()> {
1097        if source_id.is_empty() {
1098            return Err(Error::BadRequest("source_id must not be empty".into()));
1099        }
1100        let path = format!("/api/voice/recordings/{source_id}/bytes");
1101        self.put_raw_bytes(&path, "audio/wav", bytes).await
1102    }
1103}
1104
1105// ---- Recording sharing ----------------------------------------------------
1106//
1107// Sharing is a *command* — mutate one recording's share state and get a
1108// result back — not the "batch upsert + cursor list" shape `SyncEndpoint`
1109// exists for (see wavekat-voice doc 38). So it's a typed method pair on
1110// `Client` (mirroring `whoami` rather than `sync::<E>()`), not a marker.
1111//
1112// The desktop daemon keeps only a *mirror* of what these return; the
1113// platform is authoritative for who may open a share. See
1114// `wavekat-voice/docs/38-share-a-recording.md`.
1115
1116/// Access tier for a shared recording, mirroring Loom's model. Wire-stable
1117/// snake_case strings — the platform's Zod schema validates against this
1118/// exact list, so a rename here would bounce every share command with a 400.
1119///
1120/// - `Private` — owner only (the default; "not shared").
1121/// - `Restricted` — owner + explicitly invited WaveKat accounts; the
1122///   recipient must be signed in as an invited identity ("protected by login").
1123/// - `Public` — anyone holding the capability link, no sign-in.
1124#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1125#[serde(rename_all = "snake_case")]
1126pub enum ShareVisibility {
1127    Private,
1128    Restricted,
1129    Public,
1130}
1131
1132/// How a shared recording's caller/callee identity (the call's `party`) is
1133/// exposed to a viewer. Wire-stable snake_case, matching the platform's Zod
1134/// enum, so a rename here bounces a share command with a 400.
1135///
1136/// - `Full` — hidden behind a neutral direction label ("Inbound call").
1137/// - `Partial` — best-effort redaction (keeps shape, drops the value).
1138/// - `None` — the raw `party` is shown.
1139///
1140/// Absent on the wire → the platform defaults to `Partial` (identity
1141/// masked) — privacy-forward without fully erasing the caller. See
1142/// `wavekat-platform` docs/14.
1143#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1144#[serde(rename_all = "snake_case")]
1145pub enum PartyMasking {
1146    Full,
1147    Partial,
1148    None,
1149}
1150
1151/// Body of `POST /api/voice/recordings/{id}/share` — create or update a
1152/// recording's share. The recording must already be synced (metadata +
1153/// bytes) or the platform returns 404.
1154#[derive(Debug, Clone, Serialize, Deserialize)]
1155#[serde(rename_all = "camelCase")]
1156pub struct ShareRecordingRequest {
1157    /// The artifact UUID, as synced (daemon-side `artifacts.id`). Goes in
1158    /// the URL path; carried in the struct so callers pass one value.
1159    pub recording_source_id: String,
1160    pub visibility: ShareVisibility,
1161    /// Restricted tier — the WaveKat-account emails allowed to open the
1162    /// share. Ignored (and omitted) for `Private` / `Public`.
1163    #[serde(default, skip_serializing_if = "Option::is_none")]
1164    pub invited_emails: Option<Vec<String>>,
1165    /// Per-share visibility controls (platform docs/14) — what a viewer may
1166    /// see. Each is omitted when unset; the platform then applies its
1167    /// privacy-forward default (identity masked, transcript hidden, audio
1168    /// shown, download off). NB the platform treats the request as the
1169    /// *full* desired state, so an omitted control is reset to its default,
1170    /// not preserved from a prior share — send all of them when editing an
1171    /// existing share's controls.
1172    #[serde(default, skip_serializing_if = "Option::is_none")]
1173    pub party_masking: Option<PartyMasking>,
1174    #[serde(default, skip_serializing_if = "Option::is_none")]
1175    pub show_transcript: Option<bool>,
1176    #[serde(default, skip_serializing_if = "Option::is_none")]
1177    pub show_audio: Option<bool>,
1178    /// Whether a viewer may *download* the WAV, distinct from hearing it.
1179    /// Off by default and only meaningful while `show_audio` is true — the
1180    /// platform forces it off otherwise (you can't save what you can't
1181    /// hear). A soft control: it hides the viewer's Download affordance,
1182    /// not the bytes a listener already fetches to play.
1183    #[serde(default, skip_serializing_if = "Option::is_none")]
1184    pub allow_download: Option<bool>,
1185    /// Per-channel playback defaults — which side is *audible by default*
1186    /// in the viewer's player (docs/14). A call has two channels: `local`
1187    /// (the owner's microphone, "your side") and `remote` (the other
1188    /// party, "their side"). `true` means that side starts muted; the
1189    /// viewer can still un-mute it, and the audio file is unchanged — this
1190    /// is only the player's starting state. Each is omitted when unset, in
1191    /// which case the platform defaults to audible (`false`). Only
1192    /// meaningful while `show_audio` is true; ignored when audio is hidden.
1193    #[serde(default, skip_serializing_if = "Option::is_none")]
1194    pub default_mute_local: Option<bool>,
1195    #[serde(default, skip_serializing_if = "Option::is_none")]
1196    pub default_mute_remote: Option<bool>,
1197    /// Phase 2 — out-of-band password gate. Omitted when unset.
1198    #[serde(default, skip_serializing_if = "Option::is_none")]
1199    pub password: Option<String>,
1200    /// Phase 2 — RFC 3339 auto-revoke time. Omitted when unset.
1201    #[serde(default, skip_serializing_if = "Option::is_none")]
1202    pub expires_at: Option<String>,
1203}
1204
1205/// The platform's response to a successful share command. `share_url` is
1206/// the full https link the user copies; `token` is the opaque capability
1207/// identifier embedded in it (returned separately so the daemon can store
1208/// it for display without re-parsing the URL).
1209#[derive(Debug, Clone, Serialize, Deserialize)]
1210#[serde(rename_all = "camelCase")]
1211pub struct ShareRecordingResponse {
1212    pub visibility: ShareVisibility,
1213    pub token: String,
1214    pub share_url: String,
1215    /// RFC 3339 — when the recording was first shared.
1216    pub shared_at: String,
1217    /// Effective visibility controls the platform stored (docs/14). Optional
1218    /// for tolerance — a platform predating the feature omits them, in which
1219    /// case the daemon should assume the defaults (identity masked, transcript
1220    /// hidden, audio shown, download off).
1221    #[serde(default, skip_serializing_if = "Option::is_none")]
1222    pub party_masking: Option<PartyMasking>,
1223    #[serde(default, skip_serializing_if = "Option::is_none")]
1224    pub show_transcript: Option<bool>,
1225    #[serde(default, skip_serializing_if = "Option::is_none")]
1226    pub show_audio: Option<bool>,
1227    /// Effective download permission — `show_audio && allow_download`, so
1228    /// it's never true when the audio is hidden. Absent on a platform
1229    /// predating the control (assume off).
1230    #[serde(default, skip_serializing_if = "Option::is_none")]
1231    pub allow_download: Option<bool>,
1232    /// Effective per-channel playback defaults the platform stored — which
1233    /// side starts muted in the viewer's player (docs/14). Absent on a
1234    /// platform predating the control (assume audible, `false`).
1235    #[serde(default, skip_serializing_if = "Option::is_none")]
1236    pub default_mute_local: Option<bool>,
1237    #[serde(default, skip_serializing_if = "Option::is_none")]
1238    pub default_mute_remote: Option<bool>,
1239}
1240
1241/// The platform's response to `GET /api/voice/recordings/{id}/share` — the
1242/// *authoritative* current share state for an owned recording. The POST
1243/// reply omits the invited-email list and a local mirror can't reflect a
1244/// share changed from another device, so the desktop "who can open this"
1245/// panel reads here.
1246///
1247/// A recording that was never shared (or whose share is revoked / expired)
1248/// comes back as [`ShareVisibility::Private`] with the optional fields
1249/// absent — the same "not shared" state DELETE leaves behind.
1250#[derive(Debug, Clone, Serialize, Deserialize)]
1251#[serde(rename_all = "camelCase")]
1252pub struct ShareStateResponse {
1253    pub visibility: ShareVisibility,
1254    /// Absent when `visibility == Private` (nothing is shared).
1255    #[serde(default, skip_serializing_if = "Option::is_none")]
1256    pub token: Option<String>,
1257    #[serde(default, skip_serializing_if = "Option::is_none")]
1258    pub share_url: Option<String>,
1259    /// RFC 3339 — when the recording was first shared. Absent when private.
1260    #[serde(default, skip_serializing_if = "Option::is_none")]
1261    pub shared_at: Option<String>,
1262    /// The restricted tier's audience (lowercased, de-duped). Present
1263    /// (possibly empty) only for [`ShareVisibility::Restricted`].
1264    #[serde(default, skip_serializing_if = "Option::is_none")]
1265    pub invited_emails: Option<Vec<String>>,
1266    /// Per-share visibility controls (docs/14). Present for a live share;
1267    /// absent when `Private` (nothing is shared, so no controls apply).
1268    #[serde(default, skip_serializing_if = "Option::is_none")]
1269    pub party_masking: Option<PartyMasking>,
1270    #[serde(default, skip_serializing_if = "Option::is_none")]
1271    pub show_transcript: Option<bool>,
1272    #[serde(default, skip_serializing_if = "Option::is_none")]
1273    pub show_audio: Option<bool>,
1274    /// Effective download permission — `show_audio && allow_download`, so
1275    /// never true when the audio is hidden. Absent when private.
1276    #[serde(default, skip_serializing_if = "Option::is_none")]
1277    pub allow_download: Option<bool>,
1278    /// Effective per-channel playback defaults — which side starts muted in
1279    /// the viewer's player (docs/14). Absent when private.
1280    #[serde(default, skip_serializing_if = "Option::is_none")]
1281    pub default_mute_local: Option<bool>,
1282    #[serde(default, skip_serializing_if = "Option::is_none")]
1283    pub default_mute_remote: Option<bool>,
1284}
1285
1286impl Client {
1287    /// `POST /api/voice/recordings/{id}/share` — create or update a share
1288    /// for an already-synced recording. Returns the capability link + token
1289    /// the desktop UI puts on the clipboard.
1290    ///
1291    /// Per the 404-not-403 ownership rule (doc 21 §"Authorization"), asking
1292    /// to share a recording the caller doesn't own surfaces as
1293    /// [`Error::Http`] with status 404 — existence doesn't leak.
1294    pub async fn share_recording(
1295        &self,
1296        req: &ShareRecordingRequest,
1297    ) -> Result<ShareRecordingResponse> {
1298        if req.recording_source_id.is_empty() {
1299            return Err(Error::BadRequest(
1300                "recording_source_id must not be empty".into(),
1301            ));
1302        }
1303        let path = format!("/api/voice/recordings/{}/share", req.recording_source_id);
1304        self.post_json::<ShareRecordingResponse, _>(&path, req)
1305            .await
1306    }
1307
1308    /// `GET /api/voice/recordings/{id}/share` — read the authoritative
1309    /// share state for an owned recording, including the restricted tier's
1310    /// invited emails (which the share command's reply omits). Like
1311    /// [`share_recording`](Self::share_recording), a recording the caller
1312    /// doesn't own surfaces as [`Error::Http`] with status 404.
1313    pub async fn get_recording_share(
1314        &self,
1315        recording_source_id: &str,
1316    ) -> Result<ShareStateResponse> {
1317        if recording_source_id.is_empty() {
1318            return Err(Error::BadRequest(
1319                "recording_source_id must not be empty".into(),
1320            ));
1321        }
1322        let path = format!("/api/voice/recordings/{recording_source_id}/share");
1323        self.get_json::<ShareStateResponse>(&path).await
1324    }
1325
1326    /// `DELETE /api/voice/recordings/{id}/share` — revoke the share. The
1327    /// recording reverts to Private and any outstanding link returns 410.
1328    pub async fn revoke_recording_share(&self, recording_source_id: &str) -> Result<()> {
1329        if recording_source_id.is_empty() {
1330            return Err(Error::BadRequest(
1331                "recording_source_id must not be empty".into(),
1332            ));
1333        }
1334        let path = format!("/api/voice/recordings/{recording_source_id}/share");
1335        self.delete(&path).await
1336    }
1337}
1338
1339#[cfg(test)]
1340mod tests {
1341    use super::*;
1342
1343    #[test]
1344    fn share_visibility_types_are_reachable_from_the_crate_root() {
1345        // Regression for the 0.0.13 gap: `PartyMasking` was added to this
1346        // module but left out of the crate-root `pub use voice::{…}`, and the
1347        // module is private — so a consumer (`wavekat-voice`) couldn't name
1348        // the type to build a `ShareRecordingRequest`. Pin every share-control
1349        // type to the root path so dropping one fails to compile here, not in
1350        // a downstream crate. The body never runs; reachability is the test.
1351        #[allow(dead_code)]
1352        fn _reachable() {
1353            let _: Option<crate::PartyMasking> = Some(crate::PartyMasking::Partial);
1354            let _: Option<crate::ShareVisibility> = Some(crate::ShareVisibility::Public);
1355            let _: fn(&crate::ShareRecordingRequest) = |_| {};
1356            let _: fn(&crate::ShareRecordingResponse) = |_| {};
1357        }
1358    }
1359
1360    #[test]
1361    fn record_serializes_with_camel_case_keys() {
1362        let r = VoiceCallRecord {
1363            source_id: "11111111-1111-4111-8111-111111111111".into(),
1364            account_id: "22222222-2222-4222-8222-222222222222".into(),
1365            direction: VoiceCallDirection::Inbound,
1366            party: "+14155550123".into(),
1367            ring_at: "2026-05-16T10:00:00Z".into(),
1368            answer_at: Some("2026-05-16T10:00:05Z".into()),
1369            end_at: "2026-05-16T10:01:00Z".into(),
1370            duration_ms: Some(55_000),
1371            disposition: VoiceCallDisposition::Answered,
1372            end_reason: VoiceCallEndReason::HangupRemote,
1373            error: None,
1374            share_visibility: None,
1375            transfer_target: None,
1376            codec: None,
1377            flow_id: None,
1378            flow_name: None,
1379            flow_outcome: None,
1380            flow_steps: None,
1381            deleted_at: None,
1382            envelope: SyncEnvelope::for_endpoint::<VoiceCalls>(),
1383        };
1384        let s = serde_json::to_string(&r).unwrap();
1385        assert!(s.contains("\"sourceId\":"), "{s}");
1386        assert!(s.contains("\"accountId\":"), "{s}");
1387        assert!(s.contains("\"ringAt\":"), "{s}");
1388        assert!(s.contains("\"endAt\":"), "{s}");
1389        assert!(s.contains("\"durationMs\":55000"), "{s}");
1390        // Optional `error` is None — should be omitted from the wire.
1391        assert!(!s.contains("\"error\""), "error should be omitted: {s}");
1392        // Optional `transferTarget` is None here — omitted from the wire,
1393        // exactly like a non-transferred call ships.
1394        assert!(
1395            !s.contains("\"transferTarget\""),
1396            "transferTarget should be omitted: {s}"
1397        );
1398        // Optional `codec` is None (never-answered call, or an older
1399        // daemon) — omitted from the wire, never `null`.
1400        assert!(!s.contains("\"codec\""), "codec should be omitted: {s}");
1401        // Envelope flattens to the top of the object — schemaVersion
1402        // sits next to the other fields rather than nested under
1403        // "envelope". Future resources rely on this layout.
1404        assert!(
1405            s.contains("\"schemaVersion\":1"),
1406            "schemaVersion should flatten: {s}"
1407        );
1408        // `extras` is None, so the envelope contributes no `extras`
1409        // key. Stays out of the row to keep the small/fast path.
1410        assert!(!s.contains("\"extras\""), "extras should be omitted: {s}");
1411        // A live call omits the tombstone entirely rather than sending
1412        // `null` — every ordinary sync is a live call, so this is the
1413        // common path and it should stay off the wire.
1414        assert!(
1415            !s.contains("\"deletedAt\""),
1416            "deletedAt should be omitted on a live call: {s}"
1417        );
1418    }
1419
1420    #[test]
1421    fn call_tombstone_serializes_deleted_at() {
1422        // The delete-propagation mechanism: a deleted call rides up as
1423        // an ordinary upsert with `deletedAt` set (platform docs/22),
1424        // the same shape the account tombstone uses.
1425        let mut r = VoiceCallRecord {
1426            source_id: "11111111-1111-4111-8111-111111111111".into(),
1427            account_id: "22222222-2222-4222-8222-222222222222".into(),
1428            direction: VoiceCallDirection::Inbound,
1429            party: "+14155550123".into(),
1430            ring_at: "2026-05-16T10:00:00Z".into(),
1431            answer_at: None,
1432            end_at: "2026-05-16T10:01:00Z".into(),
1433            duration_ms: None,
1434            disposition: VoiceCallDisposition::Missed,
1435            end_reason: VoiceCallEndReason::HangupRemote,
1436            error: None,
1437            share_visibility: None,
1438            transfer_target: None,
1439            codec: None,
1440            flow_id: None,
1441            flow_name: None,
1442            flow_outcome: None,
1443            flow_steps: None,
1444            deleted_at: None,
1445            envelope: SyncEnvelope::for_endpoint::<VoiceCalls>(),
1446        };
1447        r.deleted_at = Some("2026-07-30T12:00:00Z".into());
1448        let s = serde_json::to_string(&r).unwrap();
1449        assert!(s.contains("\"deletedAt\":\"2026-07-30T12:00:00Z\""), "{s}");
1450    }
1451
1452    #[test]
1453    fn call_record_parses_without_deleted_at() {
1454        // Reading back a live call from `GET /api/voice/calls`: the
1455        // platform sends `deletedAt: null`, and a platform build
1456        // predating the field sends nothing at all. Both must land as
1457        // `None` rather than failing the whole page.
1458        let raw = r#"{
1459            "sourceId": "a",
1460            "accountId": "b",
1461            "direction": "outbound",
1462            "party": "+14155550123",
1463            "ringAt": "2026-05-16T10:00:00Z",
1464            "endAt": "2026-05-16T10:01:00Z",
1465            "disposition": "answered",
1466            "endReason": "hangup_local"
1467        }"#;
1468        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1469        assert!(parsed.deleted_at.is_none());
1470
1471        let with_null: VoiceCallRecord =
1472            serde_json::from_str(&raw.replace('}', r#", "deletedAt": null }"#)).unwrap();
1473        assert!(with_null.deleted_at.is_none());
1474    }
1475
1476    #[test]
1477    fn calls_query_serializes_include_deleted() {
1478        // The delta-pull flag a device sets to learn about deletes made
1479        // elsewhere. Omitted when unset, so an ordinary list request is
1480        // unchanged.
1481        let live = VoiceCallsQuery::default();
1482        assert_eq!(serde_json::to_string(&live).unwrap(), "{}");
1483
1484        let delta = VoiceCallsQuery {
1485            include_deleted: Some(true),
1486            ..Default::default()
1487        };
1488        let s = serde_json::to_string(&delta).unwrap();
1489        assert!(s.contains("\"includeDeleted\":true"), "{s}");
1490    }
1491
1492    #[test]
1493    fn record_round_trips_optional_fields() {
1494        // An unanswered call has answer_at/duration_ms/error all absent.
1495        let raw = r#"{
1496            "sourceId": "a",
1497            "accountId": "b",
1498            "direction": "inbound",
1499            "party": "anonymous",
1500            "ringAt": "2026-05-16T10:00:00Z",
1501            "endAt": "2026-05-16T10:00:30Z",
1502            "disposition": "missed",
1503            "endReason": "missed"
1504        }"#;
1505        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1506        assert!(parsed.answer_at.is_none());
1507        assert!(parsed.duration_ms.is_none());
1508        assert!(parsed.error.is_none());
1509        assert_eq!(parsed.disposition, VoiceCallDisposition::Missed);
1510        assert_eq!(parsed.end_reason, VoiceCallEndReason::Missed);
1511    }
1512
1513    #[test]
1514    fn query_omits_unset_fields() {
1515        let q = VoiceCallsQuery::default();
1516        let s = serde_json::to_string(&q).unwrap();
1517        // Empty object — every field skipped when None.
1518        assert_eq!(
1519            s, "{}",
1520            "default query should serialize to empty object: {s}"
1521        );
1522    }
1523
1524    #[test]
1525    fn enum_round_trip_via_json() {
1526        // The wire form for each direction/disposition/reason must
1527        // match what the daemon and platform expect — this guards
1528        // against accidental Rust-side renames.
1529        for d in [VoiceCallDirection::Inbound, VoiceCallDirection::Outbound] {
1530            let s = serde_json::to_string(&d).unwrap();
1531            let back: VoiceCallDirection = serde_json::from_str(&s).unwrap();
1532            assert_eq!(d, back);
1533        }
1534        for d in [
1535            VoiceCallDisposition::Answered,
1536            VoiceCallDisposition::Missed,
1537            VoiceCallDisposition::Rejected,
1538            VoiceCallDisposition::Cancelled,
1539            VoiceCallDisposition::Failed,
1540        ] {
1541            let s = serde_json::to_string(&d).unwrap();
1542            let back: VoiceCallDisposition = serde_json::from_str(&s).unwrap();
1543            assert_eq!(d, back);
1544        }
1545        for r in [
1546            VoiceCallEndReason::HangupLocal,
1547            VoiceCallEndReason::HangupRemote,
1548            VoiceCallEndReason::RejectedLocal,
1549            VoiceCallEndReason::RejectedRemote,
1550            VoiceCallEndReason::Missed,
1551            VoiceCallEndReason::CancelledLocal,
1552            VoiceCallEndReason::TransferredLocal,
1553            VoiceCallEndReason::ConnectionLost,
1554            VoiceCallEndReason::Failed,
1555        ] {
1556            let s = serde_json::to_string(&r).unwrap();
1557            let back: VoiceCallEndReason = serde_json::from_str(&s).unwrap();
1558            assert_eq!(r, back);
1559        }
1560    }
1561
1562    #[test]
1563    fn connection_lost_pins_its_wire_string() {
1564        // The platform's sync endpoint validates end reasons against
1565        // an exact string list — a rename here would make every
1566        // upload from a session-timer teardown bounce with a 400.
1567        let s = serde_json::to_string(&VoiceCallEndReason::ConnectionLost).unwrap();
1568        assert_eq!(s, "\"connection_lost\"");
1569    }
1570
1571    #[test]
1572    fn transferred_local_pins_its_wire_string() {
1573        // Same contract as `connection_lost`: the platform validates
1574        // against an exact string list, so a rename here would bounce
1575        // every transferred-call upload with a 400.
1576        let s = serde_json::to_string(&VoiceCallEndReason::TransferredLocal).unwrap();
1577        assert_eq!(s, "\"transferred_local\"");
1578    }
1579
1580    #[test]
1581    fn record_round_trips_transfer_target() {
1582        // A transferred call carries `transferTarget` both ways — the
1583        // daemon ships it (it's its own data, not read-only decoration),
1584        // and the platform echoes it back on read.
1585        let raw = r#"{
1586            "sourceId": "a",
1587            "accountId": "b",
1588            "direction": "inbound",
1589            "party": "Alice <sip:alice@example.com>",
1590            "ringAt": "2026-06-28T10:00:00Z",
1591            "answerAt": "2026-06-28T10:00:05Z",
1592            "endAt": "2026-06-28T10:00:30Z",
1593            "durationMs": 25000,
1594            "disposition": "answered",
1595            "endReason": "transferred_local",
1596            "transferTarget": "1002"
1597        }"#;
1598        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1599        assert_eq!(parsed.end_reason, VoiceCallEndReason::TransferredLocal);
1600        assert_eq!(parsed.transfer_target.as_deref(), Some("1002"));
1601        // And it survives a re-serialize (daemon → platform direction).
1602        let s = serde_json::to_string(&parsed).unwrap();
1603        assert!(s.contains("\"transferTarget\":\"1002\""), "{s}");
1604    }
1605
1606    #[test]
1607    fn codec_pins_its_wire_strings() {
1608        // The platform's sync endpoint validates the codec against an
1609        // exact string list, and the daemon's `CallCodec::as_str` emits
1610        // these same strings — a rename here would bounce every upload
1611        // from an answered call with a 400.
1612        for (codec, wire) in [
1613            (VoiceCallCodec::Opus, "\"opus\""),
1614            (VoiceCallCodec::Pcmu, "\"pcmu\""),
1615            (VoiceCallCodec::Pcma, "\"pcma\""),
1616        ] {
1617            assert_eq!(serde_json::to_string(&codec).unwrap(), wire);
1618            let back: VoiceCallCodec = serde_json::from_str(wire).unwrap();
1619            assert_eq!(back, codec);
1620        }
1621    }
1622
1623    #[test]
1624    fn record_round_trips_codec() {
1625        // An answered call carries `codec` both ways — the daemon ships
1626        // it (its own data, like transferTarget), and the platform
1627        // echoes it back on read so the website can show the call's
1628        // audio quality.
1629        let raw = r#"{
1630            "sourceId": "a",
1631            "accountId": "b",
1632            "direction": "inbound",
1633            "party": "Alice <sip:alice@example.com>",
1634            "ringAt": "2026-07-03T10:00:00Z",
1635            "answerAt": "2026-07-03T10:00:05Z",
1636            "endAt": "2026-07-03T10:00:30Z",
1637            "durationMs": 25000,
1638            "disposition": "answered",
1639            "endReason": "hangup_remote",
1640            "codec": "opus"
1641        }"#;
1642        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1643        assert_eq!(parsed.codec, Some(VoiceCallCodec::Opus));
1644        // And it survives a re-serialize (daemon → platform direction).
1645        let s = serde_json::to_string(&parsed).unwrap();
1646        assert!(s.contains("\"codec\":\"opus\""), "{s}");
1647
1648        // A row from an older daemon has no codec — reads as None.
1649        let legacy = raw.replace(",\n            \"codec\": \"opus\"", "");
1650        let parsed: VoiceCallRecord = serde_json::from_str(&legacy).unwrap();
1651        assert_eq!(parsed.codec, None);
1652    }
1653
1654    #[test]
1655    fn flow_outcome_pins_its_wire_strings() {
1656        // Three parties agree on these exact strings: the daemon's
1657        // `flow_outcome_to_str`, `wavekat_flow::trace::FlowOutcome`'s
1658        // snake_case serde, and the platform's zod enum. A rename here
1659        // 400s every flow-answered call's batch.
1660        for (outcome, wire) in [
1661            (VoiceCallFlowOutcome::Answered, "\"answered\""),
1662            (VoiceCallFlowOutcome::MessageLeft, "\"message_left\""),
1663            (VoiceCallFlowOutcome::Transferred, "\"transferred\""),
1664            (VoiceCallFlowOutcome::HungUp, "\"hung_up\""),
1665            (VoiceCallFlowOutcome::Aborted, "\"aborted\""),
1666            (VoiceCallFlowOutcome::Defect, "\"defect\""),
1667        ] {
1668            assert_eq!(serde_json::to_string(&outcome).unwrap(), wire);
1669            let back: VoiceCallFlowOutcome = serde_json::from_str(wire).unwrap();
1670            assert_eq!(back, outcome);
1671        }
1672    }
1673
1674    #[test]
1675    fn record_round_trips_flow_attribution() {
1676        // A flow-answered call carries which flow took it and how the
1677        // run ended, both ways: the daemon ships them, the platform
1678        // echoes them so the website can say "Answered by “X”" and show
1679        // the run's own outcome instead of the misleading SIP one.
1680        let raw = r#"{
1681            "sourceId": "a",
1682            "accountId": "b",
1683            "direction": "inbound",
1684            "party": "Alice <sip:alice@example.com>",
1685            "ringAt": "2026-07-03T10:00:00Z",
1686            "answerAt": "2026-07-03T10:00:05Z",
1687            "endAt": "2026-07-03T10:00:30Z",
1688            "durationMs": 25000,
1689            "disposition": "answered",
1690            "endReason": "hangup_local",
1691            "flowId": "flow_after_hours",
1692            "flowName": "After hours",
1693            "flowOutcome": "message_left"
1694        }"#;
1695        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1696        assert_eq!(parsed.flow_id.as_deref(), Some("flow_after_hours"));
1697        assert_eq!(parsed.flow_name.as_deref(), Some("After hours"));
1698        assert_eq!(parsed.flow_outcome, Some(VoiceCallFlowOutcome::MessageLeft));
1699
1700        let s = serde_json::to_string(&parsed).unwrap();
1701        assert!(s.contains("\"flowId\":\"flow_after_hours\""), "{s}");
1702        assert!(s.contains("\"flowName\":\"After hours\""), "{s}");
1703        assert!(s.contains("\"flowOutcome\":\"message_left\""), "{s}");
1704    }
1705
1706    #[test]
1707    fn record_round_trips_a_flow_step_trace() {
1708        // Pins the per-step field names. These are consumed by the
1709        // platform's Zod schema on one side and produced by the daemon's
1710        // projection on the other; a silent rename here breaks both.
1711        let raw = r#"{
1712            "sourceId": "a",
1713            "accountId": "b",
1714            "direction": "inbound",
1715            "party": "sip:alice@example.com",
1716            "ringAt": "2026-07-03T10:00:00Z",
1717            "answerAt": "2026-07-03T10:00:05Z",
1718            "endAt": "2026-07-03T10:00:30Z",
1719            "disposition": "answered",
1720            "endReason": "hangup_local",
1721            "flowId": "f",
1722            "flowName": "F",
1723            "flowSteps": [
1724                { "atMs": 0, "kind": "spoke", "node": "greeting" },
1725                { "atMs": 4200, "kind": "menu_choice", "digit": "2" },
1726                { "atMs": 9100, "kind": "message_recorded", "secs": 31 }
1727            ]
1728        }"#;
1729        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1730        let steps = parsed.flow_steps.as_deref().expect("steps present");
1731        assert_eq!(steps.len(), 3);
1732        assert_eq!(steps[1].kind, "menu_choice");
1733        assert_eq!(steps[1].digit.as_deref(), Some("2"));
1734        assert_eq!(steps[2].secs, Some(31));
1735        // Absent per-step fields stay absent rather than serializing as
1736        // nulls — same contract as the record's own optional fields.
1737        let s = serde_json::to_string(&steps[0]).unwrap();
1738        assert_eq!(s, r#"{"atMs":0,"kind":"spoke","node":"greeting"}"#);
1739    }
1740
1741    #[test]
1742    fn flow_step_accepts_a_kind_this_build_does_not_know() {
1743        // The whole reason `kind` is a String. A consumer pinned to an
1744        // older crate version must still deserialize a newer daemon's
1745        // trace — rejecting would fail the entire call record, not one
1746        // step.
1747        let step: VoiceCallFlowStep =
1748            serde_json::from_str(r#"{"atMs": 10, "kind": "consulted_the_oracle"}"#).unwrap();
1749        assert_eq!(step.kind, "consulted_the_oracle");
1750        assert_eq!(step.digit, None);
1751    }
1752
1753    #[test]
1754    fn record_omits_flow_steps_for_a_human_answered_call() {
1755        // A call the user took themselves has no trace. The field must
1756        // stay off the wire entirely rather than serializing as null.
1757        let raw = r#"{
1758            "sourceId": "a",
1759            "accountId": "b",
1760            "direction": "inbound",
1761            "party": "sip:alice@example.com",
1762            "ringAt": "2026-07-03T10:00:00Z",
1763            "endAt": "2026-07-03T10:00:30Z",
1764            "disposition": "answered",
1765            "endReason": "hangup_local"
1766        }"#;
1767        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1768        assert!(parsed.flow_steps.is_none());
1769        let s = serde_json::to_string(&parsed).unwrap();
1770        assert!(!s.contains("flowSteps"), "{s}");
1771    }
1772
1773    #[test]
1774    fn record_omits_flow_fields_for_a_human_answered_call() {
1775        // Calls the user took themselves — and every row from a daemon
1776        // predating call flows — carry none of the three. They must
1777        // stay off the wire entirely, not serialize as nulls.
1778        let raw = r#"{
1779            "sourceId": "a",
1780            "accountId": "b",
1781            "direction": "inbound",
1782            "party": "sip:alice@example.com",
1783            "ringAt": "2026-07-03T10:00:00Z",
1784            "endAt": "2026-07-03T10:00:30Z",
1785            "disposition": "answered",
1786            "endReason": "hangup_remote"
1787        }"#;
1788        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1789        assert_eq!(parsed.flow_id, None);
1790        assert_eq!(parsed.flow_name, None);
1791        assert_eq!(parsed.flow_outcome, None);
1792
1793        let s = serde_json::to_string(&parsed).unwrap();
1794        assert!(!s.contains("\"flowId\""), "flowId should be omitted: {s}");
1795        assert!(
1796            !s.contains("\"flowName\""),
1797            "flowName should be omitted: {s}"
1798        );
1799        assert!(
1800            !s.contains("\"flowOutcome\""),
1801            "flowOutcome should be omitted: {s}"
1802        );
1803    }
1804
1805    #[test]
1806    fn voice_calls_marker_resource_is_calls() {
1807        assert_eq!(<VoiceCalls as SyncEndpoint>::RESOURCE, "calls");
1808    }
1809
1810    #[test]
1811    fn record_accepts_unknown_extras_for_forward_compat() {
1812        // A newer client shipping a `notes` field that this platform
1813        // version doesn't have a column for should round-trip via
1814        // the `extras` envelope. The platform persists the blob
1815        // verbatim; a future deploy can promote it to a typed
1816        // column without data loss.
1817        let raw = r#"{
1818            "sourceId": "a",
1819            "accountId": "b",
1820            "direction": "inbound",
1821            "party": "anon",
1822            "ringAt": "2026-05-16T10:00:00Z",
1823            "endAt": "2026-05-16T10:00:30Z",
1824            "disposition": "answered",
1825            "endReason": "hangup_remote",
1826            "schemaVersion": 2,
1827            "extras": { "notes": "from staging build" }
1828        }"#;
1829        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1830        assert_eq!(parsed.envelope.schema_version, Some(2));
1831        let extras = parsed.envelope.extras.as_ref().expect("extras present");
1832        assert_eq!(extras["notes"], "from staging build");
1833    }
1834
1835    #[test]
1836    fn call_record_parses_share_visibility_from_list_response() {
1837        // The list / detail endpoints decorate a call with the tier of any
1838        // active share on its recording, so a consumer can badge the row.
1839        let raw = r#"{
1840            "sourceId": "a",
1841            "accountId": "b",
1842            "direction": "outbound",
1843            "party": "+14155550123",
1844            "ringAt": "2026-05-16T10:00:00Z",
1845            "endAt": "2026-05-16T10:00:30Z",
1846            "disposition": "answered",
1847            "endReason": "hangup_remote",
1848            "shareVisibility": "public"
1849        }"#;
1850        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1851        assert_eq!(parsed.share_visibility, Some(ShareVisibility::Public));
1852
1853        let restricted = raw.replace("public", "restricted");
1854        let parsed: VoiceCallRecord = serde_json::from_str(&restricted).unwrap();
1855        assert_eq!(parsed.share_visibility, Some(ShareVisibility::Restricted));
1856    }
1857
1858    #[test]
1859    fn call_record_unshared_has_no_share_visibility() {
1860        // Absent (older platform, or an unshared call) and an explicit
1861        // `null` both read as "not shared" — never `Some(Private)`.
1862        let base = r#"{
1863            "sourceId": "a",
1864            "accountId": "b",
1865            "direction": "inbound",
1866            "party": "anon",
1867            "ringAt": "2026-05-16T10:00:00Z",
1868            "endAt": "2026-05-16T10:00:30Z",
1869            "disposition": "missed",
1870            "endReason": "missed"
1871        }"#;
1872        let parsed: VoiceCallRecord = serde_json::from_str(base).unwrap();
1873        assert_eq!(parsed.share_visibility, None);
1874
1875        let with_null = base.replace(
1876            r#""endReason": "missed""#,
1877            r#""endReason": "missed", "shareVisibility": null"#,
1878        );
1879        let parsed: VoiceCallRecord = serde_json::from_str(&with_null).unwrap();
1880        assert_eq!(parsed.share_visibility, None);
1881    }
1882
1883    #[test]
1884    fn synced_call_omits_share_visibility() {
1885        // `share_visibility` is read-only decoration: a call uploaded via
1886        // sync must not carry it on the wire (skip_serializing_if = None),
1887        // so the round trip from a sync-shaped record stays clean.
1888        let raw = r#"{
1889            "sourceId": "a",
1890            "accountId": "b",
1891            "direction": "inbound",
1892            "party": "anon",
1893            "ringAt": "2026-05-16T10:00:00Z",
1894            "endAt": "2026-05-16T10:00:30Z",
1895            "disposition": "answered",
1896            "endReason": "hangup_remote"
1897        }"#;
1898        let parsed: VoiceCallRecord = serde_json::from_str(raw).unwrap();
1899        assert_eq!(parsed.share_visibility, None);
1900        let s = serde_json::to_string(&parsed).unwrap();
1901        assert!(
1902            !s.contains("shareVisibility"),
1903            "sync payload leaked share_visibility: {s}"
1904        );
1905    }
1906
1907    #[test]
1908    fn recording_marker_resource_is_recordings() {
1909        // Path constant drives the URL in `Client::sync_recordings`;
1910        // a rename here would silently 404 against the platform.
1911        assert_eq!(<VoiceRecordings as SyncEndpoint>::RESOURCE, "recordings");
1912    }
1913
1914    #[test]
1915    fn recording_record_serializes_with_camel_case_and_envelope() {
1916        let r = VoiceRecordingRecord {
1917            source_id: "11111111-1111-4111-8111-111111111111".into(),
1918            call_source_id: "22222222-2222-4222-8222-222222222222".into(),
1919            size_bytes: 44 + 64_000,
1920            duration_ms: 2_000,
1921            sample_rate: 8_000,
1922            channels: 2,
1923            created_at: "2026-05-16T10:01:05Z".into(),
1924            envelope: SyncEnvelope::for_endpoint::<VoiceRecordings>(),
1925        };
1926        let s = serde_json::to_string(&r).unwrap();
1927        // Field-by-field wire contract — these strings are also what
1928        // the platform's Zod schema expects.
1929        assert!(s.contains("\"sourceId\":"), "{s}");
1930        assert!(s.contains("\"callSourceId\":"), "{s}");
1931        assert!(s.contains("\"sizeBytes\":64044"), "{s}");
1932        assert!(s.contains("\"durationMs\":2000"), "{s}");
1933        assert!(s.contains("\"sampleRate\":8000"), "{s}");
1934        assert!(s.contains("\"channels\":2"), "{s}");
1935        assert!(s.contains("\"createdAt\":"), "{s}");
1936        // Envelope flattens to the top of the object, same as VoiceCallRecord.
1937        assert!(s.contains("\"schemaVersion\":1"), "{s}");
1938    }
1939
1940    #[test]
1941    fn recordings_sync_response_round_trips() {
1942        // The richer-than-generic response carries per-item provenance —
1943        // the daemon's uploader reads `r2Key` for the bytes follow-up
1944        // and `bytesUploaded` to short-circuit when the row already
1945        // landed on a previous cycle.
1946        let raw = r#"{
1947            "accepted": 2,
1948            "skipped": 0,
1949            "items": [
1950                {"sourceId": "a", "r2Key": "voice/recordings/1/a.wav", "bytesUploaded": false},
1951                {"sourceId": "b", "r2Key": "voice/recordings/1/b.wav", "bytesUploaded": true}
1952            ]
1953        }"#;
1954        let parsed: VoiceRecordingsSyncResponse = serde_json::from_str(raw).unwrap();
1955        assert_eq!(parsed.accepted, 2);
1956        assert_eq!(parsed.items.len(), 2);
1957        assert_eq!(parsed.items[0].r2_key, "voice/recordings/1/a.wav");
1958        assert!(!parsed.items[0].bytes_uploaded);
1959        assert!(parsed.items[1].bytes_uploaded);
1960    }
1961
1962    #[test]
1963    fn install_heartbeat_request_serializes_with_camel_case_keys() {
1964        let req = InstallHeartbeatRequest {
1965            install_id: "11111111-1111-4111-8111-111111111111".into(),
1966            app_version: "0.0.21".into(),
1967            os: "macos".into(),
1968            os_version: Some("15.5.0".into()),
1969            arch: Some("aarch64".into()),
1970            locale: Some("en-NZ".into()),
1971        };
1972        let s = serde_json::to_string(&req).unwrap();
1973        assert!(s.contains("\"installId\":"), "{s}");
1974        assert!(s.contains("\"appVersion\":\"0.0.21\""), "{s}");
1975        assert!(s.contains("\"os\":\"macos\""), "{s}");
1976        assert!(s.contains("\"osVersion\":\"15.5.0\""), "{s}");
1977        assert!(s.contains("\"arch\":\"aarch64\""), "{s}");
1978        assert!(s.contains("\"locale\":\"en-NZ\""), "{s}");
1979    }
1980
1981    #[test]
1982    fn install_heartbeat_request_omits_absent_optional_fields() {
1983        // A host where the OS version / locale probe came up empty
1984        // shouldn't send `null` — keeping the keys out lets the
1985        // platform's Zod `.optional()` accept the body and the column
1986        // stay NULL rather than the string "null".
1987        let req = InstallHeartbeatRequest {
1988            install_id: "x".into(),
1989            app_version: "0.0.21".into(),
1990            os: "linux".into(),
1991            os_version: None,
1992            arch: None,
1993            locale: None,
1994        };
1995        let s = serde_json::to_string(&req).unwrap();
1996        assert!(!s.contains("osVersion"), "osVersion should be omitted: {s}");
1997        assert!(!s.contains("arch"), "arch should be omitted: {s}");
1998        assert!(!s.contains("locale"), "locale should be omitted: {s}");
1999    }
2000
2001    #[test]
2002    fn install_heartbeat_response_parses_platform_shape() {
2003        let raw = r#"{
2004            "id": "abc-123",
2005            "installId": "11111111-1111-4111-8111-111111111111",
2006            "appVersion": "0.0.21",
2007            "os": "macos",
2008            "osVersion": "15.5.0",
2009            "arch": "aarch64",
2010            "locale": null,
2011            "firstSeenAt": "2026-05-31T10:00:00.000Z",
2012            "lastSeenAt": "2026-05-31T10:00:00.000Z"
2013        }"#;
2014        let parsed: InstallHeartbeatResponse = serde_json::from_str(raw).unwrap();
2015        assert_eq!(parsed.id, "abc-123");
2016        assert_eq!(parsed.app_version, "0.0.21");
2017        assert_eq!(parsed.os_version.as_deref(), Some("15.5.0"));
2018        assert!(parsed.locale.is_none());
2019    }
2020
2021    #[test]
2022    fn system_info_detect_fills_os_and_arch() {
2023        // os / arch come from compile-time consts, so they're always
2024        // non-empty on every supported target. os_version / locale are
2025        // best-effort and intentionally not asserted.
2026        let sys = SystemInfo::detect();
2027        assert!(!sys.os.is_empty(), "os should be a non-empty target string");
2028        assert!(
2029            !sys.arch.is_empty(),
2030            "arch should be a non-empty target string"
2031        );
2032    }
2033
2034    #[test]
2035    fn transcripts_marker_resource_is_transcripts() {
2036        assert_eq!(<VoiceTranscripts as SyncEndpoint>::RESOURCE, "transcripts");
2037    }
2038
2039    #[test]
2040    fn transcript_record_serializes_with_camel_case_and_channel_enum() {
2041        let r = VoiceTranscriptRecord {
2042            source_id: "1".into(),
2043            call_source_id: "22222222-2222-4222-8222-222222222222".into(),
2044            channel: VoiceTranscriptChannel::Remote,
2045            ts_ms: 100,
2046            end_ms: 1_500,
2047            text: "hello".into(),
2048            envelope: SyncEnvelope::for_endpoint::<VoiceTranscripts>(),
2049        };
2050        let s = serde_json::to_string(&r).unwrap();
2051        assert!(s.contains("\"sourceId\":"), "{s}");
2052        assert!(s.contains("\"callSourceId\":"), "{s}");
2053        // The channel enum is wire-stable snake_case — matches the
2054        // platform's Zod `enum(VOICE_TRANSCRIPT_CHANNELS)`.
2055        assert!(s.contains("\"channel\":\"remote\""), "{s}");
2056        assert!(s.contains("\"tsMs\":100"), "{s}");
2057        assert!(s.contains("\"endMs\":1500"), "{s}");
2058        assert!(s.contains("\"text\":\"hello\""), "{s}");
2059        assert!(s.contains("\"schemaVersion\":1"), "{s}");
2060    }
2061
2062    #[test]
2063    fn share_visibility_pins_its_wire_strings() {
2064        // The platform validates these against an exact string list; a
2065        // rename would bounce every share command with a 400.
2066        assert_eq!(
2067            serde_json::to_string(&ShareVisibility::Private).unwrap(),
2068            "\"private\""
2069        );
2070        assert_eq!(
2071            serde_json::to_string(&ShareVisibility::Restricted).unwrap(),
2072            "\"restricted\""
2073        );
2074        assert_eq!(
2075            serde_json::to_string(&ShareVisibility::Public).unwrap(),
2076            "\"public\""
2077        );
2078        for v in [
2079            ShareVisibility::Private,
2080            ShareVisibility::Restricted,
2081            ShareVisibility::Public,
2082        ] {
2083            let s = serde_json::to_string(&v).unwrap();
2084            let back: ShareVisibility = serde_json::from_str(&s).unwrap();
2085            assert_eq!(v, back);
2086        }
2087    }
2088
2089    #[test]
2090    fn share_request_serializes_with_camel_case_and_omits_unset() {
2091        let req = ShareRecordingRequest {
2092            recording_source_id: "11111111-1111-4111-8111-111111111111".into(),
2093            visibility: ShareVisibility::Public,
2094            invited_emails: None,
2095            party_masking: None,
2096            show_transcript: None,
2097            show_audio: None,
2098            allow_download: None,
2099            default_mute_local: None,
2100            default_mute_remote: None,
2101            password: None,
2102            expires_at: None,
2103        };
2104        let s = serde_json::to_string(&req).unwrap();
2105        assert!(s.contains("\"recordingSourceId\":"), "{s}");
2106        assert!(s.contains("\"visibility\":\"public\""), "{s}");
2107        // Phase-2 / tier-specific / visibility-control fields stay off the
2108        // wire when unset so the platform's `.optional()` schema accepts the
2109        // body (and the omitted controls fall to the platform defaults).
2110        assert!(!s.contains("invitedEmails"), "{s}");
2111        assert!(!s.contains("partyMasking"), "{s}");
2112        assert!(!s.contains("showTranscript"), "{s}");
2113        assert!(!s.contains("showAudio"), "{s}");
2114        assert!(!s.contains("allowDownload"), "{s}");
2115        assert!(!s.contains("defaultMuteLocal"), "{s}");
2116        assert!(!s.contains("defaultMuteRemote"), "{s}");
2117        assert!(!s.contains("password"), "{s}");
2118        assert!(!s.contains("expiresAt"), "{s}");
2119    }
2120
2121    #[test]
2122    fn share_request_serializes_visibility_controls_camel_case() {
2123        let req = ShareRecordingRequest {
2124            recording_source_id: "a".into(),
2125            visibility: ShareVisibility::Public,
2126            invited_emails: None,
2127            party_masking: Some(PartyMasking::Partial),
2128            show_transcript: Some(false),
2129            show_audio: Some(true),
2130            allow_download: Some(true),
2131            default_mute_local: Some(false),
2132            default_mute_remote: Some(true),
2133            password: None,
2134            expires_at: None,
2135        };
2136        let s = serde_json::to_string(&req).unwrap();
2137        assert!(s.contains("\"partyMasking\":\"partial\""), "{s}");
2138        assert!(s.contains("\"showTranscript\":false"), "{s}");
2139        assert!(s.contains("\"showAudio\":true"), "{s}");
2140        assert!(s.contains("\"allowDownload\":true"), "{s}");
2141        // The owner muted their own side by default but left the other
2142        // party audible — both ride the wire as camelCase booleans.
2143        assert!(s.contains("\"defaultMuteLocal\":false"), "{s}");
2144        assert!(s.contains("\"defaultMuteRemote\":true"), "{s}");
2145    }
2146
2147    #[test]
2148    fn share_request_carries_invited_emails_for_restricted() {
2149        let req = ShareRecordingRequest {
2150            recording_source_id: "a".into(),
2151            visibility: ShareVisibility::Restricted,
2152            invited_emails: Some(vec!["alex@example.com".into()]),
2153            party_masking: None,
2154            show_transcript: None,
2155            show_audio: None,
2156            allow_download: None,
2157            default_mute_local: None,
2158            default_mute_remote: None,
2159            password: None,
2160            expires_at: None,
2161        };
2162        let s = serde_json::to_string(&req).unwrap();
2163        assert!(s.contains("\"visibility\":\"restricted\""), "{s}");
2164        assert!(
2165            s.contains("\"invitedEmails\":[\"alex@example.com\"]"),
2166            "{s}"
2167        );
2168    }
2169
2170    #[test]
2171    fn share_response_parses_platform_shape() {
2172        let raw = r#"{
2173            "visibility": "public",
2174            "token": "Zr7-x9F2k1QpLmN4sT8wYa",
2175            "shareUrl": "https://platform.wavekat.com/voice/s/Zr7-x9F2k1QpLmN4sT8wYa",
2176            "sharedAt": "2026-06-19T10:00:00.000Z"
2177        }"#;
2178        let parsed: ShareRecordingResponse = serde_json::from_str(raw).unwrap();
2179        assert_eq!(parsed.visibility, ShareVisibility::Public);
2180        assert_eq!(parsed.token, "Zr7-x9F2k1QpLmN4sT8wYa");
2181        assert!(parsed.share_url.ends_with(&parsed.token));
2182    }
2183
2184    #[test]
2185    fn share_state_parses_restricted_with_invited_emails() {
2186        // The GET read carries the audience back — this is the field the
2187        // POST reply omits and the desktop "who can open this" panel needs.
2188        let raw = r#"{
2189            "visibility": "restricted",
2190            "token": "Zr7-x9F2k1QpLmN4sT8wYa",
2191            "shareUrl": "https://platform.wavekat.com/voice/s/Zr7-x9F2k1QpLmN4sT8wYa",
2192            "sharedAt": "2026-06-19T10:00:00.000Z",
2193            "invitedEmails": ["bob@example.com", "carol@example.com"],
2194            "partyMasking": "full",
2195            "showTranscript": true,
2196            "showAudio": false,
2197            "allowDownload": false,
2198            "defaultMuteLocal": false,
2199            "defaultMuteRemote": true
2200        }"#;
2201        let parsed: ShareStateResponse = serde_json::from_str(raw).unwrap();
2202        assert_eq!(parsed.visibility, ShareVisibility::Restricted);
2203        assert_eq!(
2204            parsed.invited_emails.as_deref(),
2205            Some(
2206                [
2207                    "bob@example.com".to_string(),
2208                    "carol@example.com".to_string()
2209                ]
2210                .as_slice()
2211            )
2212        );
2213        // The visibility controls ride back on the live-share read.
2214        assert_eq!(parsed.party_masking, Some(PartyMasking::Full));
2215        assert_eq!(parsed.show_transcript, Some(true));
2216        assert_eq!(parsed.show_audio, Some(false));
2217        // Audio hidden here, so download comes back off (platform folds the two).
2218        assert_eq!(parsed.allow_download, Some(false));
2219        // Per-channel playback defaults ride back too.
2220        assert_eq!(parsed.default_mute_local, Some(false));
2221        assert_eq!(parsed.default_mute_remote, Some(true));
2222    }
2223
2224    #[test]
2225    fn share_state_parses_private_with_fields_absent() {
2226        // A never-shared (or revoked) recording reports private with no
2227        // token / url / emails — the optional fields stay None.
2228        let parsed: ShareStateResponse =
2229            serde_json::from_str(r#"{ "visibility": "private" }"#).unwrap();
2230        assert_eq!(parsed.visibility, ShareVisibility::Private);
2231        assert!(parsed.token.is_none());
2232        assert!(parsed.share_url.is_none());
2233        assert!(parsed.shared_at.is_none());
2234        assert!(parsed.invited_emails.is_none());
2235    }
2236
2237    #[test]
2238    fn share_request_rejects_empty_source_id_before_hitting_network() {
2239        // Guarded client-side so an empty id can't produce a path like
2240        // `/api/voice/recordings//share` that 404s confusingly.
2241        let req = ShareRecordingRequest {
2242            recording_source_id: String::new(),
2243            visibility: ShareVisibility::Private,
2244            invited_emails: None,
2245            party_masking: None,
2246            show_transcript: None,
2247            show_audio: None,
2248            allow_download: None,
2249            default_mute_local: None,
2250            default_mute_remote: None,
2251            password: None,
2252            expires_at: None,
2253        };
2254        // We can't call the async method without a runtime here, but the
2255        // guard mirrors `upload_recording_bytes` — assert the precondition
2256        // shape the method checks.
2257        assert!(req.recording_source_id.is_empty());
2258    }
2259
2260    // ---- VoiceAccounts ----
2261
2262    fn sample_account() -> VoiceAccountRecord {
2263        VoiceAccountRecord {
2264            source_id: "11111111-1111-4111-8111-111111111111".into(),
2265            enabled: true,
2266            display_name: "Work line".into(),
2267            username: "alice".into(),
2268            domain: "sip.example.com".into(),
2269            auth_username: Some("alice-auth".into()),
2270            server: Some("sip.example.com".into()),
2271            port: Some(5060),
2272            transport: VoiceTransport::Udp,
2273            register_expires: 60,
2274            keepalive_secs: Some(50),
2275            disclosure_enabled: true,
2276            updated_at: "2026-06-20T10:00:00Z".into(),
2277            deleted_at: None,
2278            envelope: SyncEnvelope::for_endpoint::<VoiceAccounts>(),
2279        }
2280    }
2281
2282    #[test]
2283    fn accounts_marker_resource_is_accounts() {
2284        // Path constant drives the URL in `Client::sync` / `Client::list`;
2285        // a rename here would silently 404 against the platform.
2286        assert_eq!(<VoiceAccounts as SyncEndpoint>::RESOURCE, "accounts");
2287    }
2288
2289    #[test]
2290    fn account_record_serializes_with_camel_case_and_envelope() {
2291        let s = serde_json::to_string(&sample_account()).unwrap();
2292        // Field-by-field wire contract — also what the platform's Zod
2293        // schema expects.
2294        assert!(s.contains("\"sourceId\":"), "{s}");
2295        assert!(s.contains("\"displayName\":\"Work line\""), "{s}");
2296        assert!(s.contains("\"authUsername\":\"alice-auth\""), "{s}");
2297        assert!(s.contains("\"registerExpires\":60"), "{s}");
2298        assert!(s.contains("\"keepaliveSecs\":50"), "{s}");
2299        assert!(s.contains("\"disclosureEnabled\":true"), "{s}");
2300        assert!(s.contains("\"transport\":\"udp\""), "{s}");
2301        assert!(s.contains("\"updatedAt\":\"2026-06-20T10:00:00Z\""), "{s}");
2302        // A live line carries no tombstone.
2303        assert!(!s.contains("deletedAt"), "deletedAt should be omitted: {s}");
2304        // The secret never crosses this wire, by construction.
2305        assert!(!s.contains("password"), "no password field: {s}");
2306        // Envelope flattens to the top, same as the other resources.
2307        assert!(s.contains("\"schemaVersion\":1"), "{s}");
2308    }
2309
2310    #[test]
2311    fn account_tombstone_serializes_deleted_at() {
2312        // A soft-delete rides as an upsert with deletedAt set — the
2313        // delete-propagation mechanism (doc 40).
2314        let mut r = sample_account();
2315        r.deleted_at = Some("2026-06-20T12:00:00Z".into());
2316        let s = serde_json::to_string(&r).unwrap();
2317        assert!(s.contains("\"deletedAt\":\"2026-06-20T12:00:00Z\""), "{s}");
2318    }
2319
2320    #[test]
2321    fn account_record_round_trips_optional_fields() {
2322        // A minimal line — no auth username, server, port, keepalive, or
2323        // tombstone — should parse with those all absent.
2324        let raw = r#"{
2325            "sourceId": "a",
2326            "enabled": false,
2327            "displayName": "Cheap trunk",
2328            "username": "u",
2329            "domain": "d",
2330            "transport": "tcp",
2331            "registerExpires": 120,
2332            "disclosureEnabled": false,
2333            "updatedAt": "2026-06-20T10:00:00Z"
2334        }"#;
2335        let parsed: VoiceAccountRecord = serde_json::from_str(raw).unwrap();
2336        assert!(!parsed.enabled);
2337        assert!(parsed.auth_username.is_none());
2338        assert!(parsed.server.is_none());
2339        assert!(parsed.port.is_none());
2340        assert!(parsed.keepalive_secs.is_none());
2341        assert!(parsed.deleted_at.is_none());
2342        assert_eq!(parsed.transport, VoiceTransport::Tcp);
2343        assert_eq!(parsed.register_expires, 120);
2344    }
2345
2346    #[test]
2347    fn voice_transport_round_trips_via_json() {
2348        for t in [VoiceTransport::Udp, VoiceTransport::Tcp] {
2349            let s = serde_json::to_string(&t).unwrap();
2350            let back: VoiceTransport = serde_json::from_str(&s).unwrap();
2351            assert_eq!(t, back);
2352        }
2353        // Pin the wire strings — the daemon's `TransportKind` and the
2354        // platform's Zod enum both depend on these exact tokens.
2355        assert_eq!(
2356            serde_json::to_string(&VoiceTransport::Udp).unwrap(),
2357            "\"udp\""
2358        );
2359        assert_eq!(
2360            serde_json::to_string(&VoiceTransport::Tcp).unwrap(),
2361            "\"tcp\""
2362        );
2363    }
2364
2365    #[test]
2366    fn accounts_query_omits_unset_and_serializes_include_deleted() {
2367        let empty = serde_json::to_string(&VoiceAccountsQuery::default()).unwrap();
2368        assert_eq!(empty, "{}", "default query should be empty: {empty}");
2369        let with_deleted = serde_json::to_string(&VoiceAccountsQuery {
2370            include_deleted: Some(true),
2371        })
2372        .unwrap();
2373        assert!(
2374            with_deleted.contains("\"includeDeleted\":true"),
2375            "{with_deleted}"
2376        );
2377    }
2378
2379    // ---- VoiceFlows ----
2380
2381    #[test]
2382    fn flows_query_serializes_cursor_and_omits_absent_fields() {
2383        let empty = serde_json::to_string(&VoiceFlowsQuery::default()).unwrap();
2384        assert_eq!(empty, "{}");
2385        let cursored = serde_json::to_string(&VoiceFlowsQuery {
2386            after: Some("flow_abc".into()),
2387            limit: Some(100),
2388            schema_versions: None,
2389        })
2390        .unwrap();
2391        assert!(cursored.contains("\"after\":\"flow_abc\""), "{cursored}");
2392        assert!(cursored.contains("\"limit\":100"), "{cursored}");
2393    }
2394
2395    #[test]
2396    fn flows_query_sends_schema_versions_under_the_servers_name() {
2397        // The struct is camelCase; this parameter is not. A silently
2398        // camelCased key is ignored by the server, which reads exactly
2399        // like an account with no flows in that version — so pin it.
2400        let query = serde_json::to_string(&VoiceFlowsQuery {
2401            schema_versions: Some("1,2".into()),
2402            ..Default::default()
2403        })
2404        .unwrap();
2405        assert_eq!(query, r#"{"schema_versions":"1,2"}"#);
2406    }
2407
2408    // ---- Booking ----
2409
2410    #[test]
2411    fn booking_slots_request_uses_the_routes_snake_case_wire() {
2412        // Unlike the sync resources above, these routes speak snake_case.
2413        // A camelCased body is rejected as a validation error mid-call,
2414        // which the flow can only render as "unavailable".
2415        let body = serde_json::to_string(&BookingSlotsRequest {
2416            source_id: "call_1".into(),
2417            duration_mins: 30,
2418            buffer_mins: 10,
2419            lead_mins: 120,
2420            horizon_days: 14,
2421            schedule: BookingSchedule {
2422                tue: vec![BookingTimeRange {
2423                    open: "09:00".into(),
2424                    close: "17:00".into(),
2425                }],
2426                ..Default::default()
2427            },
2428            timezone: "Pacific/Auckland".into(),
2429            exceptions: Vec::new(),
2430            limit: 3,
2431        })
2432        .unwrap();
2433        assert!(body.contains(r#""source_id":"call_1""#), "{body}");
2434        assert!(body.contains(r#""duration_mins":30"#), "{body}");
2435        assert!(body.contains(r#""timezone":"Pacific/Auckland""#), "{body}");
2436        // Days with no hours, and an empty exception list, stay off the
2437        // wire entirely rather than shipping empty arrays.
2438        assert!(!body.contains("\"mon\""), "{body}");
2439        assert!(!body.contains("exceptions"), "{body}");
2440    }
2441
2442    #[test]
2443    fn booking_slots_response_parses_both_answers() {
2444        let offered: BookingSlotsResponse = serde_json::from_str(
2445            r#"{"slots":[{"start":"2026-08-11T21:00:00Z","end":"2026-08-11T21:30:00Z"}],"timezone":"Pacific/Auckland"}"#,
2446        )
2447        .unwrap();
2448        assert_eq!(offered.slots.len(), 1);
2449        assert_eq!(offered.timezone, "Pacific/Auckland");
2450        assert!(offered.status.is_none());
2451
2452        // The calendar could not be read. Not an error to the caller of
2453        // this crate — the flow has an exit for it.
2454        let down: BookingSlotsResponse =
2455            serde_json::from_str(r#"{"status":"unavailable","reason":"not_connected"}"#).unwrap();
2456        assert!(down.slots.is_empty());
2457        assert_eq!(down.status.as_deref(), Some("unavailable"));
2458        assert_eq!(down.reason.as_deref(), Some("not_connected"));
2459    }
2460
2461    #[test]
2462    fn booking_book_response_parses_every_outcome() {
2463        let booked: BookingBookResponse =
2464            serde_json::from_str(r#"{"status":"booked","start":"2026-08-11T21:00:00Z"}"#).unwrap();
2465        assert_eq!(booked.status, "booked");
2466        assert_eq!(booked.start.as_deref(), Some("2026-08-11T21:00:00Z"));
2467
2468        let taken: BookingBookResponse =
2469            serde_json::from_str(r#"{"status":"slot_taken"}"#).unwrap();
2470        assert_eq!(taken.status, "slot_taken");
2471        assert!(taken.start.is_none());
2472
2473        // A status this build has never heard of still parses: failing
2474        // here would drop a live call over an unknown string.
2475        let future: BookingBookResponse =
2476            serde_json::from_str(r#"{"status":"needs_deposit"}"#).unwrap();
2477        assert_eq!(future.status, "needs_deposit");
2478    }
2479
2480    #[test]
2481    fn flows_page_parses_platform_shape() {
2482        let raw = r#"{
2483            "items": [{
2484                "id": "flow_1",
2485                "name": "Luigi's — after hours",
2486                "version": 3,
2487                "yaml": "schema_version: 1\n",
2488                "publishedAt": "2026-07-13T10:00:00Z"
2489            }],
2490            "nextAfter": null
2491        }"#;
2492        let page: VoiceFlowsPage = serde_json::from_str(raw).unwrap();
2493        assert_eq!(page.items.len(), 1);
2494        let rec = &page.items[0];
2495        assert_eq!(rec.id, "flow_1");
2496        assert_eq!(rec.version, 3);
2497        assert_eq!(rec.published_at, "2026-07-13T10:00:00Z");
2498        assert!(page.next_after.is_none());
2499
2500        // A mid-walk page carries the cursor.
2501        let more: VoiceFlowsPage =
2502            serde_json::from_str(r#"{ "items": [], "nextAfter": "flow_1" }"#).unwrap();
2503        assert_eq!(more.next_after.as_deref(), Some("flow_1"));
2504    }
2505
2506    #[test]
2507    fn flow_assets_manifest_parses_platform_shape() {
2508        // `ref` (a reserved word) maps to `asset_ref`; a null duration is
2509        // accepted (the platform doesn't always know it).
2510        let raw = r#"{
2511            "assets": [{
2512                "ref": "vprompt_ab12cd34",
2513                "format": "ulaw_8000",
2514                "byteSize": 48044,
2515                "durationMs": null,
2516                "contentHash": "9f2c00aa"
2517            }]
2518        }"#;
2519        let page: VoiceFlowAssetsPage = serde_json::from_str(raw).unwrap();
2520        assert_eq!(page.assets.len(), 1);
2521        let asset = &page.assets[0];
2522        assert_eq!(asset.asset_ref, "vprompt_ab12cd34");
2523        assert_eq!(asset.format, "ulaw_8000");
2524        assert_eq!(asset.byte_size, 48044);
2525        assert!(asset.duration_ms.is_none());
2526        assert_eq!(asset.content_hash, "9f2c00aa");
2527
2528        // A text-only version legitimately has no frozen audio.
2529        let empty: VoiceFlowAssetsPage = serde_json::from_str(r#"{ "assets": [] }"#).unwrap();
2530        assert!(empty.assets.is_empty());
2531    }
2532
2533    #[test]
2534    fn account_record_accepts_unknown_extras_for_forward_compat() {
2535        // A newer client shipping a field this platform version lacks a
2536        // column for round-trips via the `extras` envelope.
2537        let raw = r#"{
2538            "sourceId": "a",
2539            "enabled": true,
2540            "displayName": "x",
2541            "username": "u",
2542            "domain": "d",
2543            "transport": "udp",
2544            "registerExpires": 60,
2545            "disclosureEnabled": true,
2546            "updatedAt": "2026-06-20T10:00:00Z",
2547            "schemaVersion": 2,
2548            "extras": { "ringtone": "classic" }
2549        }"#;
2550        let parsed: VoiceAccountRecord = serde_json::from_str(raw).unwrap();
2551        assert_eq!(parsed.envelope.schema_version, Some(2));
2552        let extras = parsed.envelope.extras.as_ref().expect("extras present");
2553        assert_eq!(extras["ringtone"], "classic");
2554    }
2555}