bcode_tui 0.0.1-alpha.0

Terminal user interface for bcode
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
//! Exclusive renderer-neutral transcript to terminal-document adaptation boundary.

use std::collections::{BTreeMap, BTreeSet};

use bcode_session_view_models::{SessionViewSnapshot, TranscriptViewItemId, ViewRevision};

use crate::transcript::{
    TranscriptStreamIntegrity, apply_stream_integrity, terminal_item_from_shared,
};

use super::{TranscriptDocument, TranscriptDocumentDamage};

/// Adapts canonical `SessionView` transcript items into terminal-native items.
///
/// This is the only production module allowed to mutate `TranscriptDocument`.
#[derive(Debug, Clone, Default)]
pub struct SessionViewTerminalAdapter {
    document_revision: Option<ViewRevision>,
    item_revisions: BTreeMap<TranscriptViewItemId, ViewRevision>,
    stream_statuses:
        BTreeMap<TranscriptViewItemId, bcode_session_view_models::TextStreamViewStatus>,
}

const fn stream_integrity(
    status: Option<bcode_session_view_models::TextStreamViewStatus>,
) -> Option<TranscriptStreamIntegrity> {
    match status {
        Some(bcode_session_view_models::TextStreamViewStatus::Incomplete) => {
            Some(TranscriptStreamIntegrity::Incomplete)
        }
        Some(bcode_session_view_models::TextStreamViewStatus::Degraded) => {
            Some(TranscriptStreamIntegrity::Degraded)
        }
        Some(
            bcode_session_view_models::TextStreamViewStatus::Healthy
            | bcode_session_view_models::TextStreamViewStatus::Terminal(_),
        )
        | None => None,
    }
}

impl SessionViewTerminalAdapter {
    pub fn reset(&mut self) {
        self.document_revision = None;
        self.item_revisions.clear();
        self.stream_statuses.clear();
    }

    pub fn apply(
        &mut self,
        snapshot: &SessionViewSnapshot,
        target: &mut TranscriptDocument,
    ) -> TranscriptDocumentDamage {
        let source = &snapshot.transcript;
        let source_items = source.items.iter().filter(|item| {
            snapshot.thinking.visible
                || !matches!(
                    item.kind,
                    bcode_session_view_models::TranscriptViewItemKind::ReasoningMessage { .. }
                        | bcode_session_view_models::TranscriptViewItemKind::ReasoningActivity { .. }
                )
        });
        if !target.source_index_is_consistent() {
            target.replace_from_shared(
                source_items
                    .clone()
                    .map(|item| {
                        apply_stream_integrity(
                            terminal_item_from_shared(item),
                            snapshot.text_streams.get(&item.id),
                        )
                    })
                    .collect(),
            );
            self.item_revisions = source_items
                .clone()
                .map(|item| (item.id.clone(), item.revision))
                .collect();
            self.stream_statuses = snapshot
                .text_streams
                .iter()
                .filter(|(id, _)| source_items.clone().any(|item| item.id == **id))
                .map(|(id, state)| (id.clone(), state.status))
                .collect();
            self.document_revision = Some(source.revision);
            return TranscriptDocumentDamage::FullReset;
        }
        let ordered_source_ids = source_items
            .clone()
            .map(|item| item.id.clone())
            .collect::<Vec<_>>();
        let source_ids = ordered_source_ids.iter().cloned().collect::<BTreeSet<_>>();
        let previous_ids = self.item_revisions.keys().cloned().collect::<BTreeSet<_>>();
        let structural = source_ids != previous_ids;
        let mut changed = BTreeSet::new();
        target.retain_from_shared(&source_ids);
        self.item_revisions.retain(|id, _| source_ids.contains(id));
        self.stream_statuses.retain(|id, _| source_ids.contains(id));
        for item in source_items {
            let target_has_item = target.source_index(&item.id).is_some();
            let stream_status = snapshot
                .text_streams
                .get(&item.id)
                .map(|state| state.status);
            if !target_has_item || self.item_revisions.get(&item.id) != Some(&item.revision) {
                target.upsert_from_shared(apply_stream_integrity(
                    terminal_item_from_shared(item),
                    snapshot.text_streams.get(&item.id),
                ));
                changed.insert(item.id.clone());
            } else if self.stream_statuses.get(&item.id).copied() != stream_status
                && target.set_stream_integrity(&item.id, stream_integrity(stream_status))
            {
                changed.insert(item.id.clone());
            }
            self.item_revisions.insert(item.id.clone(), item.revision);
            if let Some(status) = stream_status {
                self.stream_statuses.insert(item.id.clone(), status);
            } else {
                self.stream_statuses.remove(&item.id);
            }
        }
        target.reorder_from_shared(&ordered_source_ids);
        self.document_revision = Some(source.revision);
        if structural {
            TranscriptDocumentDamage::Structural
        } else if changed.is_empty() {
            TranscriptDocumentDamage::None
        } else {
            TranscriptDocumentDamage::Items(changed)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bcode_session_view_models::{
        ChatMessageView, TextStreamViewState, TranscriptViewItem, TranscriptViewItemKind,
    };

    fn assistant_snapshot(
        revision: u64,
        status: bcode_session_view_models::TextStreamViewStatus,
    ) -> SessionViewSnapshot {
        let mut snapshot = SessionViewSnapshot::empty();
        let id = TranscriptViewItemId::new("assistant-stream");
        snapshot.transcript.items.push(TranscriptViewItem {
            id: id.clone(),
            revision,
            sequence: None,
            timestamp_ms: None,
            output_location: None,
            streaming: true,
            kind: TranscriptViewItemKind::AssistantMessage {
                message: ChatMessageView::markdown("answer"),
            },
        });
        snapshot.transcript.revision = revision;
        snapshot.text_streams.insert(
            id,
            TextStreamViewState {
                generation: 0,
                revision,
                accepted_bytes: 6,
                truncated: matches!(
                    status,
                    bcode_session_view_models::TextStreamViewStatus::Incomplete
                ),
                status,
            },
        );
        snapshot
    }

    #[test]
    fn hidden_reasoning_is_removed_without_reinterpreting_shared_items() {
        let mut snapshot = SessionViewSnapshot::empty();
        snapshot.thinking.visible = true;
        snapshot.transcript.items = vec![
            TranscriptViewItem {
                id: TranscriptViewItemId::new("reasoning"),
                revision: 1,
                sequence: Some(1),
                timestamp_ms: None,
                output_location: None,
                streaming: false,
                kind: TranscriptViewItemKind::ReasoningMessage {
                    message: ChatMessageView::markdown("private reasoning"),
                },
            },
            TranscriptViewItem {
                id: TranscriptViewItemId::new("answer"),
                revision: 1,
                sequence: Some(2),
                timestamp_ms: None,
                output_location: None,
                streaming: false,
                kind: TranscriptViewItemKind::AssistantMessage {
                    message: ChatMessageView::markdown("answer"),
                },
            },
        ];
        snapshot.transcript.revision = 1;
        let mut adapter = SessionViewTerminalAdapter::default();
        let mut document = TranscriptDocument::default();

        adapter.apply(&snapshot, &mut document);
        assert_eq!(document.items().len(), 2);

        snapshot.thinking.visible = false;
        snapshot.transcript.revision = 2;
        assert_eq!(
            adapter.apply(&snapshot, &mut document),
            TranscriptDocumentDamage::Structural
        );
        assert_eq!(document.items().len(), 1);
        assert_eq!(document.items()[0].text(), "answer");

        snapshot.thinking.visible = true;
        snapshot.transcript.revision = 3;
        assert_eq!(
            adapter.apply(&snapshot, &mut document),
            TranscriptDocumentDamage::Structural
        );
        assert_eq!(document.items().len(), 2);
    }

    #[test]
    fn integrity_only_change_updates_one_terminal_item() {
        let mut adapter = SessionViewTerminalAdapter::default();
        let mut document = TranscriptDocument::default();
        let healthy =
            assistant_snapshot(1, bcode_session_view_models::TextStreamViewStatus::Healthy);
        assert_eq!(
            adapter.apply(&healthy, &mut document),
            TranscriptDocumentDamage::Structural
        );
        let item_revision = document.items()[0].revision();

        let degraded =
            assistant_snapshot(1, bcode_session_view_models::TextStreamViewStatus::Degraded);
        assert_eq!(
            adapter.apply(&degraded, &mut document),
            TranscriptDocumentDamage::Items(BTreeSet::from([TranscriptViewItemId::new(
                "assistant-stream",
            )]))
        );
        assert_eq!(document.items()[0].text(), "answer");
        assert_eq!(
            document.items()[0].stream_integrity(),
            Some(TranscriptStreamIntegrity::Degraded)
        );
        assert!(document.items()[0].revision() > item_revision);
    }

    fn notice(text: &str) -> crate::transcript::TranscriptItem {
        crate::transcript::TranscriptItem::with_format(
            "System",
            text.to_owned(),
            bcode_session_view_models::TextFormat::PlainText,
        )
    }

    fn visible_text(document: &TranscriptDocument) -> Vec<&str> {
        document
            .iter()
            .map(crate::transcript::TranscriptItem::text)
            .collect()
    }

    fn message_snapshot(items: &[(&str, u64, u64, &str)], thinking: bool) -> SessionViewSnapshot {
        let mut snapshot = SessionViewSnapshot::empty();
        snapshot.thinking.visible = thinking;
        snapshot.transcript.items = items
            .iter()
            .map(|(id, revision, sequence, text)| TranscriptViewItem {
                id: TranscriptViewItemId::new(*id),
                revision: *revision,
                sequence: Some(*sequence),
                timestamp_ms: Some(*sequence),
                output_location: None,
                streaming: false,
                kind: TranscriptViewItemKind::AssistantMessage {
                    message: ChatMessageView::markdown(*text),
                },
            })
            .collect();
        // The adapter tracks per-item revisions, so the document revision only needs to advance.
        snapshot.transcript.revision = items
            .iter()
            .map(|(_, revision, _, _)| *revision)
            .sum::<u64>();
        snapshot
    }

    #[test]
    fn reasoning_visibility_toggle_does_not_disturb_interleaved_notices() {
        let mut snapshot = SessionViewSnapshot::empty();
        snapshot.thinking.visible = true;
        snapshot.transcript.items = vec![
            TranscriptViewItem {
                id: TranscriptViewItemId::new("answer-one"),
                revision: 1,
                sequence: Some(1),
                timestamp_ms: Some(1),
                output_location: None,
                streaming: false,
                kind: TranscriptViewItemKind::AssistantMessage {
                    message: ChatMessageView::markdown("first"),
                },
            },
            TranscriptViewItem {
                id: TranscriptViewItemId::new("reasoning"),
                revision: 1,
                sequence: Some(2),
                timestamp_ms: Some(2),
                output_location: None,
                streaming: false,
                kind: TranscriptViewItemKind::ReasoningMessage {
                    message: ChatMessageView::markdown("private reasoning"),
                },
            },
        ];
        snapshot.transcript.revision = 1;
        let mut adapter = SessionViewTerminalAdapter::default();
        let mut document = TranscriptDocument::default();
        adapter.apply(&snapshot, &mut document);
        document.push_ephemeral("bcode.tui".to_owned(), notice("local"));
        assert_eq!(
            visible_text(&document),
            vec!["first", "private reasoning", "local"]
        );

        snapshot.thinking.visible = false;
        snapshot.transcript.revision = 2;
        adapter.apply(&snapshot, &mut document);

        assert_eq!(
            visible_text(&document),
            vec!["first", "local"],
            "hiding reasoning removes only the canonical reasoning entry"
        );

        snapshot.thinking.visible = true;
        snapshot.transcript.revision = 3;
        adapter.apply(&snapshot, &mut document);

        assert_eq!(
            visible_text(&document),
            vec!["first", "private reasoning", "local"],
            "restoring reasoning keeps the notice at its recorded boundary"
        );
        assert!(document.source_index_is_consistent());
    }

    #[test]
    fn canonical_stream_updates_before_and_after_a_notice_keep_its_position() {
        let mut adapter = SessionViewTerminalAdapter::default();
        let mut document = TranscriptDocument::default();
        adapter.apply(
            &message_snapshot(&[("a", 1, 1, "first")], false),
            &mut document,
        );
        document.push_ephemeral("bcode.tui".to_owned(), notice("local"));
        adapter.apply(
            &message_snapshot(&[("a", 1, 1, "first"), ("b", 1, 2, "second")], false),
            &mut document,
        );
        assert_eq!(visible_text(&document), vec!["first", "local", "second"]);

        adapter.apply(
            &message_snapshot(&[("a", 2, 1, "first edited"), ("b", 1, 2, "second")], false),
            &mut document,
        );
        assert_eq!(
            visible_text(&document),
            vec!["first edited", "local", "second"],
            "updating the entry before the notice does not move it"
        );

        adapter.apply(
            &message_snapshot(
                &[("a", 2, 1, "first edited"), ("b", 2, 2, "second edited")],
                false,
            ),
            &mut document,
        );
        assert_eq!(
            visible_text(&document),
            vec!["first edited", "local", "second edited"],
            "updating the entry after the notice does not move it"
        );
        assert!(document.source_index_is_consistent());
    }

    #[test]
    fn adapter_full_reset_recovery_rebuilds_canonical_entries_around_notices() {
        let mut adapter = SessionViewTerminalAdapter::default();
        let mut document = TranscriptDocument::default();
        adapter.apply(
            &message_snapshot(&[("a", 1, 1, "first"), ("b", 1, 2, "second")], false),
            &mut document,
        );
        document.push_ephemeral("bcode.tui".to_owned(), notice("local"));
        assert_eq!(visible_text(&document), vec!["first", "second", "local"]);

        document.corrupt_source_index_for_test(TranscriptViewItemId::new("a"), 9);
        assert!(!document.source_index_is_consistent());

        assert_eq!(
            adapter.apply(
                &message_snapshot(&[("a", 1, 1, "first"), ("b", 1, 2, "second")], false),
                &mut document,
            ),
            TranscriptDocumentDamage::FullReset
        );

        assert_eq!(
            visible_text(&document),
            vec!["first", "second", "local"],
            "full-reset recovery rebuilds canonical entries and retains the notice"
        );
        assert!(document.source_index_is_consistent());
    }
}