devsandbox 0.11.1

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
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
//! A thread's feed (docs/architecture/inbox/threads-and-feed.md, *Feed*): what happened on an
//! owner thread, in first-insert order. The owner's **messages**, the user's
//! **replies** and **actions**, and host-recorded **markers** (done/reopen by
//! the user, state/status changes by the owner). The header (`thread put`)
//! is not in the feed; a put only leaves a marker when its state or status
//! changes.
//!
//! A message may carry a form (`form.rs`): its lifecycle and draft live on
//! the message item ([`ItemKind::Message::form`]), and the user's answers
//! join the feed as a **submission**.
//!
//! Every user item records the client that made it (`tui`, `cli`,
//! `api:<name>`) for the user's own audit. It stays in the store: events and
//! the API never carry it, so an owner can't tell clients apart.
//!
//! The rules that shape the feed ([`push`]: status markers collapse; [`cap`]:
//! what goes first past [`MAX_FEED`]) are pure functions over the item list.

use serde::{Deserialize, Serialize};

use std::collections::BTreeMap;

use super::form::{self, Answer, Form, FormRecord};
use super::State;

/// Feed items kept per thread; past it, [`cap`] drops the least valuable.
pub const MAX_FEED: usize = 300;

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FeedItem {
    /// Arrival order across the whole Inbox (like `Note::id`).
    pub seq: u64,
    /// Unix seconds of first insert (a merged status marker: of its last
    /// change).
    pub at: u64,
    pub kind: ItemKind,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum ItemKind {
    /// From the owner. `id` is its idempotency key, unique in the thread.
    Message {
        id: String,
        blocks: Vec<Block>,
        /// Replaced in place since it was first inserted.
        #[serde(default)]
        edited: bool,
        /// The owner took it back; kept so the story stays readable.
        #[serde(default)]
        withdrawn: bool,
        /// Set once the message has carried a form: its state and draft.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        form: Option<FormRecord>,
    },
    /// The user's free text from the composer.
    Reply { text: String, client: String },
    /// The user submitted form `form` of message `message`: the complete
    /// answers, as the owner's event carried them.
    Submission { message: String, form: String, answers: BTreeMap<String, Answer>, client: String },
    /// The user pressed a header button: its id and its label at the time.
    Action { action: String, label: String, client: String },
    Marker(Marker),
}

/// A message block (docs/architecture/inbox/threads-and-feed.md, *`thread send`*). Serialized in the
/// same shape `thread send` takes, so `thread ls --feed` hands an owner back
/// what it sent.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Block {
    Markdown { text: String },
    /// A compact key/value list.
    Fields { items: Vec<Field> },
    /// Questions for the user (`form.rs`); at most one per message.
    Form(Form),
}

/// One row of a [`Block::Fields`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Field {
    pub label: String,
    pub value: String,
}

/// A one-line feed item. Done/Reopen are the user's (with the client),
/// State/Status the owner's put changing those fields.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "marker", rename_all = "lowercase")]
pub enum Marker {
    Done { client: String },
    Reopen { client: String },
    State { from: State, to: State },
    Status { from: Option<String>, to: Option<String> },
}

impl FeedItem {
    /// A message of one markdown block, for tests.
    #[cfg(test)]
    pub fn markdown(seq: u64, at: u64, id: &str, text: &str) -> FeedItem {
        let blocks = vec![Block::Markdown { text: text.to_string() }];
        let kind = ItemKind::Message { id: id.to_string(), blocks, edited: false, withdrawn: false, form: None };
        FeedItem { seq, at, kind }
    }

    fn is_marker(&self) -> bool {
        matches!(self.kind, ItemKind::Marker(_))
    }

    fn is_message(&self) -> bool {
        matches!(self.kind, ItemKind::Message { .. })
    }

    /// A message whose form still waits for the user: [`cap`] never drops it.
    fn has_open_form(&self) -> bool {
        matches!(&self.kind, ItemKind::Message { form: Some(r), .. } if r.is_open())
    }
}

/// Message `id`'s form and its record, when it has a form block.
pub fn form_of<'a>(feed: &'a [FeedItem], id: &str) -> Option<(&'a Form, &'a FormRecord)> {
    feed.iter().find_map(|i| match &i.kind {
        ItemKind::Message { id: have, blocks, form: Some(record), .. } if have == id => {
            form::form_in(blocks).map(|f| (f, record))
        }
        _ => None,
    })
}

/// Message `id`'s form record, to change it.
pub fn form_record_mut<'a>(feed: &'a mut [FeedItem], id: &str) -> Option<&'a mut FormRecord> {
    feed.iter_mut().find_map(|i| match &mut i.kind {
        ItemKind::Message { id: have, form: Some(record), .. } if have == id => Some(record),
        _ => None,
    })
}

/// A message's markdown blocks joined by a blank line (other blocks left
/// out): a message's one-line summary.
pub fn markdown_of(blocks: &[Block]) -> String {
    blocks
        .iter()
        .filter_map(|b| match b {
            Block::Markdown { text } => Some(text.as_str()),
            Block::Fields { .. } | Block::Form(_) => None,
        })
        .collect::<Vec<_>>()
        .join("\n\n")
}

/// What a `thread send` did to the feed ([`send`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Sent {
    /// Same id, same blocks, not withdrawn: nothing to do.
    Unchanged,
    /// Same id, replaced in place (`edited`), or a withdrawn one sent again.
    /// `form_opened`: it brought a form where none was open (news, like an
    /// insert).
    Edited { form_opened: bool },
    /// A new id, appended.
    Inserted,
}

/// Apply owner message `id` with `blocks` (docs/architecture/inbox/threads-and-feed.md,
/// *`thread send`*): the id is the owner's idempotency key, so the same content is
/// a no-op, other content replaces the message in place (its `seq`, `at` and
/// feed position stay: order is first-insert order) and tags it `edited`.
/// A withdrawn message sent again comes back, replaced and `edited` even with
/// the same blocks: it was gone from the reader's view, so it changed. `seq`
/// is only called for an insert, so a no-op mints no id.
///
/// A form block moves the message's form record ([`form::resend`]): a
/// re-send while open replaces the form and prunes the draft, one without
/// the form withdraws it, and a **submitted form is frozen**: the re-send's
/// form block is ignored and the stored form keeps its answers, so a
/// dispatcher re-asserting its original message stays a no-op.
pub fn send(feed: &mut Vec<FeedItem>, id: &str, blocks: Vec<Block>, seq: impl FnOnce() -> u64, at: u64) -> Sent {
    let existing = feed.iter_mut().find_map(|i| match &mut i.kind {
        ItemKind::Message { id: have, blocks, edited, withdrawn, form } if have == id => {
            Some((blocks, edited, withdrawn, form))
        }
        _ => None,
    });
    match existing {
        Some((have, edited, withdrawn, record)) => {
            let resent = form::resend(have, record.as_ref(), blocks);
            if resent.blocks == *have && resent.record == *record && !*withdrawn {
                return Sent::Unchanged;
            }
            *have = resent.blocks;
            *record = resent.record;
            *edited = true;
            *withdrawn = false;
            Sent::Edited { form_opened: resent.opened }
        }
        None => {
            let form = form::form_in(&blocks).map(|f| FormRecord::open(&f.id));
            let kind = ItemKind::Message { id: id.to_string(), blocks, edited: false, withdrawn: false, form };
            push(feed, FeedItem { seq: seq(), at, kind });
            Sent::Inserted
        }
    }
}

/// Withdraw owner message `id`: tagged `withdrawn` and kept, so the story
/// stays readable; an open form on it is withdrawn too (a submitted one
/// keeps its answers). Whether anything changed (an unknown or already
/// withdrawn id is a no-op).
pub fn withdraw(feed: &mut [FeedItem], id: &str) -> bool {
    feed.iter_mut().any(|i| match &mut i.kind {
        ItemKind::Message { id: have, withdrawn, form, .. } if have == id && !*withdrawn => {
            *withdrawn = true;
            if let Some(record) = form {
                record.withdraw();
            }
            true
        }
        _ => false,
    })
}

/// Append `item`, collapsing status changes: a status marker right after
/// another status marker (nothing in between) merges into it, keeping the
/// earlier `from` and taking the new `to` and `at`; a merge that lands back
/// where it started (`from == to`) leaves no marker at all. State markers
/// never merge: a state change is always news.
pub fn push(feed: &mut Vec<FeedItem>, item: FeedItem) {
    let back_to_start = match (&item.kind, feed.last().map(|l| &l.kind)) {
        (ItemKind::Marker(Marker::Status { to, .. }), Some(ItemKind::Marker(Marker::Status { from, .. }))) => from == to,
        _ => {
            feed.push(item);
            return;
        }
    };
    if back_to_start {
        feed.pop();
        return;
    }
    let (Some(last), ItemKind::Marker(Marker::Status { to, .. })) = (feed.last_mut(), item.kind) else { return };
    if let ItemKind::Marker(Marker::Status { to: prev_to, .. }) = &mut last.kind {
        *prev_to = to;
    }
    last.at = item.at;
}

/// Bring `feed` down to `max` items: the oldest markers go first, then the
/// oldest messages, then the oldest replies, actions and submissions (the
/// user's own words outlast the owner's narration, which it can re-send).
/// A message whose form is open is never dropped: it is still waiting on
/// the user. Past only those, the cap goes soft.
pub fn cap(feed: &mut Vec<FeedItem>, max: usize) {
    while feed.len() > max {
        let pos = feed
            .iter()
            .position(FeedItem::is_marker)
            .or_else(|| feed.iter().position(|i| i.is_message() && !i.has_open_form()))
            .or_else(|| feed.iter().position(|i| !i.has_open_form()));
        let Some(pos) = pos else { return };
        feed.remove(pos);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn status(seq: u64, from: Option<&str>, to: Option<&str>) -> FeedItem {
        let (from, to) = (from.map(str::to_string), to.map(str::to_string));
        FeedItem { seq, at: seq * 10, kind: ItemKind::Marker(Marker::Status { from, to }) }
    }

    fn state(seq: u64, from: State, to: State) -> FeedItem {
        FeedItem { seq, at: seq * 10, kind: ItemKind::Marker(Marker::State { from, to }) }
    }

    fn reply(seq: u64) -> FeedItem {
        FeedItem { seq, at: seq * 10, kind: ItemKind::Reply { text: format!("r{seq}"), client: "tui".into() } }
    }

    fn statuses(feed: &[FeedItem]) -> Vec<(u64, u64, Option<&str>, Option<&str>)> {
        feed.iter()
            .filter_map(|i| match &i.kind {
                ItemKind::Marker(Marker::Status { from, to }) => Some((i.seq, i.at, from.as_deref(), to.as_deref())),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn consecutive_status_markers_merge() {
        let mut feed = Vec::new();
        push(&mut feed, status(1, None, Some("a")));
        push(&mut feed, status(2, Some("a"), Some("b")));
        push(&mut feed, status(3, Some("b"), Some("c")));
        assert_eq!(feed.len(), 1);
        // The earlier `from` and seq, the new `to` and time.
        assert_eq!(statuses(&feed), [(1, 30, None, Some("c"))]);
    }

    #[test]
    fn a_merge_back_to_the_start_leaves_nothing() {
        let mut feed = vec![reply(1)];
        push(&mut feed, status(2, Some("a"), Some("b")));
        push(&mut feed, status(3, Some("b"), Some("a")));
        assert_eq!(feed, [reply(1)]);
        // Also from and to both absent.
        push(&mut feed, status(4, None, Some("x")));
        push(&mut feed, status(5, Some("x"), None));
        assert_eq!(feed, [reply(1)]);
    }

    #[test]
    fn anything_in_between_stops_the_merge() {
        for between in [reply(2), state(2, State::Active, State::NeedsYou), FeedItem::markdown(2, 20, "m", "hi")] {
            let mut feed = Vec::new();
            push(&mut feed, status(1, Some("a"), Some("b")));
            push(&mut feed, between.clone());
            push(&mut feed, status(3, Some("b"), Some("c")));
            assert_eq!(feed.len(), 3, "{between:?}");
            assert_eq!(statuses(&feed), [(1, 10, Some("a"), Some("b")), (3, 30, Some("b"), Some("c"))]);
        }
    }

    #[test]
    fn state_markers_never_merge() {
        let mut feed = Vec::new();
        push(&mut feed, state(1, State::Active, State::NeedsYou));
        push(&mut feed, state(2, State::NeedsYou, State::Active));
        assert_eq!(feed.len(), 2);
        // A status marker after a state marker starts fresh, too.
        push(&mut feed, status(3, None, Some("x")));
        assert_eq!(feed.len(), 3);
    }

    #[test]
    fn cap_drops_markers_then_messages_then_user_items() {
        let mut feed = vec![
            reply(1),
            FeedItem::markdown(2, 20, "m1", "one"),
            state(3, State::Active, State::NeedsYou),
            FeedItem::markdown(4, 40, "m2", "two"),
            status(5, None, Some("s")),
            reply(6),
        ];
        let seqs = |feed: &[FeedItem]| feed.iter().map(|i| i.seq).collect::<Vec<_>>();
        cap(&mut feed, 6);
        assert_eq!(seqs(&feed), [1, 2, 3, 4, 5, 6], "within the cap: untouched");
        cap(&mut feed, 4);
        assert_eq!(seqs(&feed), [1, 2, 4, 6], "markers first, oldest first");
        cap(&mut feed, 3);
        assert_eq!(seqs(&feed), [1, 4, 6], "then the oldest message");
        cap(&mut feed, 1);
        assert_eq!(seqs(&feed), [6], "then the oldest replies");
    }

    fn md(text: &str) -> Vec<Block> {
        vec![Block::Markdown { text: text.into() }]
    }

    fn message(feed: &[FeedItem], id: &str) -> (u64, u64, Vec<Block>, bool, bool) {
        feed.iter()
            .find_map(|i| match &i.kind {
                ItemKind::Message { id: have, blocks, edited, withdrawn, .. } if have == id => {
                    Some((i.seq, i.at, blocks.clone(), *edited, *withdrawn))
                }
                _ => None,
            })
            .unwrap()
    }

    #[test]
    fn send_inserts_edits_in_place_and_ignores_repeats() {
        let mut feed = vec![reply(1)];
        assert_eq!(send(&mut feed, "a", md("one"), || 2, 20), Sent::Inserted);
        assert_eq!(send(&mut feed, "b", md("two"), || 3, 30), Sent::Inserted);
        // Same content: nothing, and no id minted.
        assert_eq!(send(&mut feed, "a", md("one"), || panic!("minted"), 40), Sent::Unchanged);
        // New content: replaced in place, first-insert seq/time/position kept.
        assert_eq!(send(&mut feed, "a", md("uno"), || panic!("minted"), 50), Sent::Edited { form_opened: false });
        assert_eq!(message(&feed, "a"), (2, 20, md("uno"), true, false));
        assert_eq!(feed.iter().map(|i| i.seq).collect::<Vec<_>>(), [1, 2, 3]);
        // The edited content again is a no-op too.
        assert_eq!(send(&mut feed, "a", md("uno"), || panic!("minted"), 60), Sent::Unchanged);
    }

    #[test]
    fn withdraw_keeps_the_message_and_a_resend_brings_it_back() {
        let mut feed = Vec::new();
        send(&mut feed, "a", md("one"), || 1, 10);
        assert!(!withdraw(&mut feed, "nope"), "an unknown id is a no-op");
        assert!(withdraw(&mut feed, "a"));
        assert!(!withdraw(&mut feed, "a"), "already withdrawn");
        assert_eq!(message(&feed, "a"), (1, 10, md("one"), false, true));
        // Sent again, same blocks: back, in place, and tagged edited.
        assert_eq!(send(&mut feed, "a", md("one"), || panic!("minted"), 20), Sent::Edited { form_opened: false });
        assert_eq!(message(&feed, "a"), (1, 10, md("one"), true, false));
        assert_eq!(feed.len(), 1);
    }

    fn with_form(text: &str) -> Vec<Block> {
        vec![Block::Markdown { text: text.into() }, Block::Form(form::tests::mixed())]
    }

    fn record(feed: &[FeedItem], id: &str) -> Option<FormRecord> {
        feed.iter().find_map(|i| match &i.kind {
            ItemKind::Message { id: have, form, .. } if have == id => Some(form.clone()),
            _ => None,
        })?
    }

    #[test]
    fn a_form_opens_with_its_message_and_withdraws_with_it() {
        let mut feed = Vec::new();
        assert_eq!(send(&mut feed, "a", with_form("one"), || 1, 10), Sent::Inserted);
        assert_eq!(record(&feed, "a"), Some(FormRecord::open("f")));
        assert_eq!(form_of(&feed, "a").map(|(f, _)| f.id.as_str()), Some("f"));
        assert!(form_of(&feed, "nope").is_none());
        // Re-asserted: nothing. A changed markdown block: an edit, form open.
        assert_eq!(send(&mut feed, "a", with_form("one"), || panic!(), 11), Sent::Unchanged);
        assert_eq!(send(&mut feed, "a", with_form("uno"), || panic!(), 12), Sent::Edited { form_opened: false });
        // Withdrawing the message withdraws the open form.
        assert!(withdraw(&mut feed, "a"));
        assert_eq!(record(&feed, "a").unwrap().state, form::FormState::Withdrawn);
        // Sent again: back, with a fresh open form (news).
        assert_eq!(send(&mut feed, "a", with_form("uno"), || panic!(), 13), Sent::Edited { form_opened: true });
        assert_eq!(record(&feed, "a"), Some(FormRecord::open("f")));
        // A form added to a message that had none.
        send(&mut feed, "b", md("two"), || 2, 20);
        assert_eq!(record(&feed, "b"), None);
        assert_eq!(send(&mut feed, "b", with_form("two"), || panic!(), 21), Sent::Edited { form_opened: true });
        // The form dropped while open: withdrawn, a quiet edit.
        assert_eq!(send(&mut feed, "b", md("two"), || panic!(), 22), Sent::Edited { form_opened: false });
        assert_eq!(record(&feed, "b").unwrap().state, form::FormState::Withdrawn);
        assert!(form_of(&feed, "b").is_none(), "no form block left");
        assert_eq!(send(&mut feed, "b", md("two"), || panic!(), 23), Sent::Unchanged);
    }

    #[test]
    fn a_submitted_form_survives_resends_and_withdrawal() {
        let mut feed = Vec::new();
        send(&mut feed, "a", with_form("one"), || 1, 10);
        let answers: BTreeMap<String, Answer> = [("note".to_string(), Answer::Text("hi".into()))].into();
        let submitted = form::FormState::Submitted { at: 11, answers, client: "tui".into() };
        form_record_mut(&mut feed, "a").unwrap().state = submitted.clone();
        // The original again: invisible.
        assert_eq!(send(&mut feed, "a", with_form("one"), || panic!(), 12), Sent::Unchanged);
        // Other blocks change, the stored form doesn't, whatever was sent.
        let other = vec![Block::Markdown { text: "uno".into() }, Block::Form(form::tests::example())];
        assert_eq!(send(&mut feed, "a", other.clone(), || panic!(), 13), Sent::Edited { form_opened: false });
        assert_eq!(message(&feed, "a").2, with_form("uno"));
        assert_eq!(record(&feed, "a").unwrap().state, submitted);
        assert_eq!(send(&mut feed, "a", other, || panic!(), 14), Sent::Unchanged, "frozen re-sends settle");
        // Withdrawn: the answers stay.
        withdraw(&mut feed, "a");
        assert_eq!(record(&feed, "a").unwrap().state, submitted);
    }

    #[test]
    fn cap_never_drops_an_open_form() {
        let open = |seq: u64, id: &str| {
            let mut feed = Vec::new();
            send(&mut feed, id, with_form("q"), || seq, seq * 10);
            feed.pop().unwrap()
        };
        let mut done = open(3, "m3");
        if let ItemKind::Message { form: Some(r), .. } = &mut done.kind {
            r.withdraw();
        }
        let mut feed = vec![open(1, "m1"), reply(2), done, FeedItem::markdown(4, 40, "m4", "x"), status(5, None, Some("s"))];
        let seqs = |feed: &[FeedItem]| feed.iter().map(|i| i.seq).collect::<Vec<_>>();
        cap(&mut feed, 4);
        assert_eq!(seqs(&feed), [1, 2, 3, 4], "markers first");
        cap(&mut feed, 2);
        assert_eq!(seqs(&feed), [1, 2], "then messages, skipping the open form; a withdrawn one goes");
        cap(&mut feed, 1);
        assert_eq!(seqs(&feed), [1], "then user items, still skipping it");
        cap(&mut feed, 0);
        assert_eq!(seqs(&feed), [1], "only open forms left: the cap goes soft");
    }

    #[test]
    fn markdown_of_skips_fields() {
        let blocks = vec![
            Block::Markdown { text: "a".into() },
            Block::Fields { items: vec![Field { label: "Head".into(), value: "36b1".into() }] },
            Block::Markdown { text: "b".into() },
        ];
        assert_eq!(markdown_of(&blocks), "a\n\nb");
    }

    #[test]
    fn store_shape_round_trips() {
        let fields = vec![Block::Fields { items: vec![Field { label: "Head".into(), value: "36b1".into() }] }];
        let feed = vec![
            FeedItem { seq: 8, at: 80, kind: ItemKind::Message { id: "f".into(), blocks: fields, edited: true, withdrawn: false, form: None } },
            FeedItem {
                seq: 9,
                at: 90,
                kind: ItemKind::Message {
                    id: "q".into(),
                    blocks: vec![Block::Form(form::tests::mixed())],
                    edited: false,
                    withdrawn: false,
                    form: Some(FormRecord { draft: [("note".to_string(), Answer::Text("n".into()))].into(), ..FormRecord::open("f") }),
                },
            },
            FeedItem {
                seq: 10,
                at: 100,
                kind: ItemKind::Submission {
                    message: "q".into(),
                    form: "f".into(),
                    answers: [("sure".to_string(), Answer::Confirm(true))].into(),
                    client: "tui".into(),
                },
            },
            FeedItem::markdown(1, 10, "m", "hi"),
            reply(2),
            FeedItem { seq: 3, at: 30, kind: ItemKind::Action { action: "go".into(), label: "Go".into(), client: "api:x".into() } },
            FeedItem { seq: 4, at: 40, kind: ItemKind::Marker(Marker::Done { client: "cli".into() }) },
            FeedItem { seq: 5, at: 50, kind: ItemKind::Marker(Marker::Reopen { client: "tui".into() }) },
            state(6, State::Done, State::Active),
            status(7, None, Some("s")),
        ];
        let json = serde_json::to_string(&feed).unwrap();
        assert!(json.contains(r#""kind":{"type":"marker","marker":"done","client":"cli"}"#), "{json}");
        assert!(json.contains(r#""blocks":[{"type":"fields","items":[{"label":"Head","value":"36b1"}]}]"#), "{json}");
        assert_eq!(serde_json::from_str::<Vec<FeedItem>>(&json).unwrap(), feed);
    }
}