semora-proto 1.2.0

Shared API types and websocket messages for Semora
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
//! Shared API types and websocket messages for Semora.
//!
//! Every HTTP response body and websocket frame exchanged between
//! `semora-server`, `semora` (the CLI) and the browser is defined here.

use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};
use serde_json::Value;
use time::OffsetDateTime;

/// The guide for people and agents, served at `/docs` and printed by `semora skill`.
pub const GUIDE: &str = include_str!("../guide.md");
/// A deleted document is kept this many days, then purged. The server purges by it, and the
/// CLI, the guide and the pages state it.
pub const DELETED_RETENTION_DAYS: i64 = 7;

/// Websocket subprotocol spoken on `/ws/d/{id}`.
pub const SUBPROTOCOL: &str = "semora.v1";
/// Prefix of every API route.
pub const API_PREFIX: &str = "/api/v1";
/// Largest websocket frame either side may send.
pub const MAX_WS_MESSAGE: usize = 64 * 1024;
/// Largest `data` payload of a `page_event`.
pub const MAX_PAGE_EVENT_DATA: usize = 64 * 1024;
/// Largest screenshot attachment.
pub const MAX_ATTACHMENT: usize = 5 * 1024 * 1024;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DocKind {
    Md,
    Html,
    Bundle,
}

impl DocKind {
    pub fn as_str(self) -> &'static str {
        match self {
            DocKind::Md => "md",
            DocKind::Html => "html",
            DocKind::Bundle => "bundle",
        }
    }
}

impl fmt::Display for DocKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for DocKind {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "md" => Ok(DocKind::Md),
            "html" => Ok(DocKind::Html),
            "bundle" => Ok(DocKind::Bundle),
            other => Err(format!("unknown document kind `{other}`")),
        }
    }
}

/// What a person may do in a project. The order is the order of power:
/// `Viewer < Reviewer < Editor < Owner`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Level {
    Viewer,
    Reviewer,
    Editor,
    Owner,
}

impl Level {
    pub fn as_str(self) -> &'static str {
        match self {
            Level::Viewer => "viewer",
            Level::Reviewer => "reviewer",
            Level::Editor => "editor",
            Level::Owner => "owner",
        }
    }

    /// The word the UI shows: `Viewer`, `Reviewer`, `Editor`, `Owner`.
    pub fn label(self) -> &'static str {
        match self {
            Level::Viewer => "Viewer",
            Level::Reviewer => "Reviewer",
            Level::Editor => "Editor",
            Level::Owner => "Owner",
        }
    }
}

impl fmt::Display for Level {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for Level {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "viewer" => Ok(Level::Viewer),
            "reviewer" => Ok(Level::Reviewer),
            "editor" => Ok(Level::Editor),
            "owner" => Ok(Level::Owner),
            other => Err(format!("unknown level `{other}`")),
        }
    }
}

/// A serde default for a sender that predates levels, which could only be the owner.
pub fn owner_level() -> Level {
    Level::Owner
}

/// Who a piece of feedback, a message or a revision is from.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Person {
    pub id: i64,
    pub name: String,
}

/// API key scopes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Scope {
    #[serde(rename = "docs:write")]
    DocsWrite,
    #[serde(rename = "docs:read")]
    DocsRead,
    #[serde(rename = "events")]
    Events,
}

impl Scope {
    pub fn all() -> Vec<Scope> {
        vec![Scope::DocsWrite, Scope::DocsRead, Scope::Events]
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Scope::DocsWrite => "docs:write",
            Scope::DocsRead => "docs:read",
            Scope::Events => "events",
        }
    }

    /// Parses a comma-separated scope list such as `docs:write,events`.
    pub fn parse_list(s: &str) -> Result<Vec<Scope>, String> {
        s.split(',')
            .map(str::trim)
            .filter(|p| !p.is_empty())
            .map(Scope::from_str)
            .collect()
    }

    pub fn join(scopes: &[Scope]) -> String {
        scopes
            .iter()
            .map(|s| s.as_str())
            .collect::<Vec<_>>()
            .join(",")
    }
}

impl FromStr for Scope {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "docs:write" => Ok(Scope::DocsWrite),
            "docs:read" => Ok(Scope::DocsRead),
            "events" => Ok(Scope::Events),
            other => Err(format!("unknown scope `{other}`")),
        }
    }
}

/// A relative link inside a pushed document that points at a file the bundle lacks.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BrokenLink {
    /// The file containing the link.
    pub from: String,
    /// The link target as written.
    pub href: String,
}

/// Returned by every create or replace.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PushResponse {
    pub id: String,
    pub rev: i64,
    pub kind: DocKind,
    pub url: String,
    pub ws_url: String,
    pub files: usize,
    pub title: String,
    /// True when the files, entry page and kind equal the current revision's: the push made no
    /// revision, `rev` is the current one, and open pages were not reloaded. The title, tags
    /// and meta of the push still applied. An older server leaves it out, which reads as false.
    #[serde(default)]
    pub unchanged: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub broken_links: Vec<BrokenLink>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
    /// The project id, when the document is in a project.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    /// The document's path inside the project.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    /// The path link: `{server}/p/{project}/{path}`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path_url: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DocSummary {
    pub id: String,
    pub title: String,
    pub kind: DocKind,
    pub tags: Vec<String>,
    pub rev: i64,
    /// Number of stored revisions (older ones are pruned).
    pub revision_count: i64,
    pub url: String,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: OffsetDateTime,
    /// The project id, when the document is in a project.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    /// The document's path inside the project.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    /// The path link: `{server}/p/{project}/{path}`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path_url: Option<String>,
    /// The caller's level on the document. Set by list and detail.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub level: Option<Level>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ListResponse {
    pub docs: Vec<DocSummary>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
}

/// A project as the API returns it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProjectInfo {
    /// The project id people type and see in links.
    pub slug: String,
    /// The display name.
    pub name: String,
    /// The project page.
    pub url: String,
    /// Live documents in the project.
    pub documents: i64,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
    /// The newest live document's time, else the project's own.
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: OffsetDateTime,
    /// The caller's level in the project. A server that predates collaboration only listed the
    /// caller's own projects.
    #[serde(default = "owner_level")]
    pub level: Level,
    /// The owner's display name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub owner: Option<String>,
}

/// `POST /api/v1/projects`: create a project, or link your existing one with that id.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CreateProject {
    pub slug: String,
    /// Defaults to the slug. Ignored when linking an existing project.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Link a project you collaborate on but don't own. Without it that is a 409
    /// ([`JoinNeeded`]): anyone can be added to a project without being asked, so linking
    /// one, and publishing into it, is the person's own choice.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub join: bool,
}

/// The 409 of `POST /api/v1/projects` for a project you collaborate on, when you didn't ask
/// to join it. `error` is `join_needed`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct JoinNeeded {
    pub error: String,
    pub message: String,
    /// The owner's display name.
    pub owner: String,
    /// Your level in the project.
    pub level: Level,
}

/// `PATCH /api/v1/projects/{slug}`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PatchProject {
    pub name: String,
    /// A new project id. Left out, the id stays. The old id becomes an alias for as long as
    /// the server's alias setting says, so old links and checkouts still find the project.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slug: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProjectList {
    pub projects: Vec<ProjectInfo>,
}

/// One mapping rule: documents whose path matches `pattern` show inside `folder`
/// in the project's tree. `folder` is `/` for the project root.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Mapping {
    pub pattern: String,
    pub folder: String,
}

/// A project's mapping rules, in order. The first match wins.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MappingList {
    pub mappings: Vec<Mapping>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileInfo {
    pub path: String,
    pub size: u64,
    pub mime: String,
    pub hash: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RevisionInfo {
    pub rev: i64,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    pub files: usize,
    /// Name of the API key that pushed the revision, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub created_by: Option<String>,
    /// The person who pushed the revision.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pushed_by: Option<Person>,
    /// Where the revision was pushed from: machine name and git branch.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origin: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DocDetail {
    #[serde(flatten)]
    pub summary: DocSummary,
    pub entry_path: String,
    pub ws_url: String,
    pub files: Vec<FileInfo>,
    pub revisions: Vec<RevisionInfo>,
    #[serde(default)]
    pub meta: Value,
}

/// `PATCH /api/v1/docs/{id}`: change metadata without a new revision.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct PatchDoc {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Replace the full tag set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub add_tags: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub remove_tags: Vec<String>,
    /// Merged into the stored meta object; `null` values remove keys.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<Value>,
}

/// `GET /api/v1/docs/{id}/view`: a freshly signed content URL for the viewer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ViewResponse {
    pub content_url: String,
    pub rev: i64,
    pub path: String,
    #[serde(with = "time::serde::rfc3339")]
    pub expires_at: OffsetDateTime,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UserInfo {
    pub id: i64,
    pub email: String,
    pub display_name: String,
    pub is_admin: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct KeyInfo {
    pub id: i64,
    pub name: String,
    pub prefix: String,
    pub scopes: Vec<Scope>,
    pub created_via: String,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
    #[serde(
        default,
        with = "time::serde::rfc3339::option",
        skip_serializing_if = "Option::is_none"
    )]
    pub last_used_at: Option<OffsetDateTime>,
    #[serde(
        default,
        with = "time::serde::rfc3339::option",
        skip_serializing_if = "Option::is_none"
    )]
    pub expires_at: Option<OffsetDateTime>,
    #[serde(
        default,
        with = "time::serde::rfc3339::option",
        skip_serializing_if = "Option::is_none"
    )]
    pub revoked_at: Option<OffsetDateTime>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WhoAmI {
    pub server: String,
    /// The id `.semora` files name this server by. `None` from a server older than this field.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub server_id: Option<String>,
    pub user: UserInfo,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub key: Option<KeyInfo>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CreateKeyRequest {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scopes: Option<Vec<Scope>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_in_days: Option<u32>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CreatedKey {
    pub key: KeyInfo,
    /// The full key. Its owner can also copy it later from the account page.
    pub secret: String,
}

/// `POST /api/v1/cli/device`: the CLI asks to sign in.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CliDeviceRequest {
    /// Name for the key the sign-in creates, e.g. `cli@hostname`.
    #[serde(default)]
    pub name: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CliDeviceResponse {
    /// The secret the CLI polls `/api/v1/cli/token` with. It never leaves the CLI.
    pub device_code: String,
    /// The short code the person checks in the browser, like `ABCD-EFGH`.
    pub user_code: String,
    /// The page that asks for the code.
    pub verification_uri: String,
    /// The same page with the code filled in.
    pub verification_uri_complete: String,
    /// Seconds until the sign-in is forgotten.
    pub expires_in: u64,
    /// Seconds to wait between polls.
    pub interval: u64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CliTokenRequest {
    pub device_code: String,
}

/// What a poll of `/api/v1/cli/token` finds. `Approved` is answered once.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum CliTokenResponse {
    /// Nobody has decided yet; poll again.
    Pending,
    Approved {
        api_key: String,
        name: String,
        user: UserInfo,
    },
    Denied,
    /// Unknown, already used, or older than `expires_in`.
    Expired,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApiErrorBody {
    pub error: String,
    pub message: String,
}

// ---------------------------------------------------------------------------
// Feedback events and websocket messages
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EventKind {
    Comment,
    Drawing,
    PageEvent,
    Message,
    /// A message from an agent to the page. Stored for the feed, never delivered to agents.
    Say,
}

impl EventKind {
    pub fn as_str(self) -> &'static str {
        match self {
            EventKind::Comment => "comment",
            EventKind::Drawing => "drawing",
            EventKind::PageEvent => "page_event",
            EventKind::Message => "message",
            EventKind::Say => "say",
        }
    }

    /// Kinds that come from the page and are delivered to agents.
    pub fn feedback() -> [EventKind; 4] {
        [
            EventKind::Comment,
            EventKind::Drawing,
            EventKind::PageEvent,
            EventKind::Message,
        ]
    }

    pub fn parse_list(s: &str) -> Result<Vec<EventKind>, String> {
        s.split(',')
            .map(str::trim)
            .filter(|p| !p.is_empty())
            .map(EventKind::from_str)
            .collect()
    }
}

impl FromStr for EventKind {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "comment" => Ok(EventKind::Comment),
            "drawing" => Ok(EventKind::Drawing),
            "page_event" => Ok(EventKind::PageEvent),
            "message" => Ok(EventKind::Message),
            "say" => Ok(EventKind::Say),
            other => Err(format!("unknown event kind `{other}`")),
        }
    }
}

impl fmt::Display for EventKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Where a comment points: a W3C text-quote selector plus a CSS selector and
/// the nearest heading, so an agent can find the spot without line numbers.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Anchor {
    pub path: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quote: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prefix: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub suffix: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub selector: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub heading: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Size {
    pub width: u32,
    pub height: u32,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Point {
    pub x: i64,
    pub y: i64,
}

/// A stored feedback event as delivered to an agent.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EventOut {
    pub id: i64,
    pub doc_id: String,
    pub kind: EventKind,
    pub rev: i64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    pub payload: Value,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attachment_url: Option<String>,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
    /// Who sent it. Absent when that account is gone.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub from: Option<Person>,
}

/// A message from an agent shown in the page.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SayOut {
    pub id: i64,
    pub text: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reply_to: Option<i64>,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
    /// Who sent it. Absent when that account is gone.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub from: Option<Person>,
    /// Sent when a page connects, replaying recent messages for the feed.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub backlog: bool,
}

/// A comment, drawing or message as the page's margin shows it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NoteOut {
    pub event: EventOut,
    /// The name of the first key that acked it. Absent while no agent has it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delivered_to: Option<String>,
    /// Sent when a page connects, replaying recent entries for the margin.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub backlog: bool,
}

/// `POST /api/v1/docs/{id}/events`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SayRequest {
    pub text: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reply_to: Option<i64>,
}

/// `GET /api/v1/docs/{id}/events`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EventsResponse {
    pub events: Vec<EventOut>,
}

/// `POST /api/v1/docs/{id}/attachments`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AttachmentResponse {
    pub attachment_id: String,
}

/// Messages sent by the server on a document channel.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ServerMsg {
    Hello {
        doc_id: String,
        rev: i64,
        agents: usize,
        browsers: usize,
    },
    Revision {
        rev: i64,
        changed: Vec<String>,
    },
    Presence {
        agents: usize,
        browsers: usize,
    },
    Event(EventOut),
    Say(SayOut),
    /// To pages: a comment, drawing or message that someone at a page sent.
    Note(NoteOut),
    /// To pages: an agent's key acked the event `id`; `to` is the key's name.
    Delivered {
        id: i64,
        to: String,
    },
    Error {
        message: String,
    },
}

/// Messages sent by browsers and agents on a document channel.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ClientMsg {
    // Browser → server
    Comment {
        anchor: Anchor,
        text: String,
    },
    Drawing {
        path: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        note: Option<String>,
        attachment_id: String,
        viewport: Size,
        scroll: Point,
    },
    PageEvent {
        name: String,
        #[serde(default)]
        data: Value,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        path: Option<String>,
    },
    Message {
        text: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        path: Option<String>,
    },
    // Agent → server
    Ack {
        id: i64,
    },
    Say {
        text: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reply_to: Option<i64>,
    },
}