rho-coding-agent 3.3.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
use std::{collections::BTreeMap, path::PathBuf, time::Duration};

use pretty_assertions::assert_eq;
use rho_protocol::{
    display::{Presentation, ToolCard, ToolCardStatus, ToolFamily, ToolHeader},
    AnswerStop, ApprovalAsk, ApprovalSource, Ask, Choice, CompactionId, CompactionStatus,
    CompactionTrigger, ContentBlock, InputAnswer, InputRequest, InputRequestId, InputTimeout,
    JobState, MessageId, Operation, PathScope, Question, QuestionAsk, Replay, Resolution,
    RetryReason, Selection, SessionEvent, SteerId, ToolCallId as WireCallId, ToolCallUpdate,
    ToolStatus, TurnError, TurnErrorKind, TurnId, TurnOutcome,
};
use rho_sdk::{ProviderErrorKind, ProviderStreamResetReason, SteeringId, ToolCallId};

use super::{DaemonEvents, DaemonView, Rest, TurnState};
use crate::tui::{activity::ProviderRetryHint, daemon_inputs::AnswerRefusal, StreamKind};

// Covers: context tokens and cumulative spend have different meanings; a
// later unknown price must clear spend rather than reusing the prior total.
// Title events must survive mapping, including successive renames; a
// replayed rename sets the title without a notice.
// Owner: pure daemon event mapper
#[test]
fn usage_and_title_updates_keep_their_independent_values() {
    let views = map(vec![
        Step::Attached(Vec::new(), JobState::Idle),
        Step::Event(SessionEvent::TitleChanged {
            title: "Replayed title".into(),
        }),
        Step::ReplayEnded,
        Step::Event(SessionEvent::Usage {
            used_tokens: 1200,
            window_tokens: Some(8000),
            cost_usd_micros: Some(4321),
        }),
        Step::Event(SessionEvent::TitleChanged {
            title: "First title".into(),
        }),
        Step::Event(SessionEvent::Usage {
            used_tokens: 900,
            window_tokens: None,
            cost_usd_micros: None,
        }),
        Step::Event(SessionEvent::TitleChanged {
            title: "Renamed live".into(),
        }),
    ]);
    // Compare the state updates, and count the notices rather than lock
    // their UI copy: only the two live renames say so.
    let notices = views
        .iter()
        .filter(|view| matches!(view, DaemonView::Notice(_)))
        .count();
    assert_eq!(notices, 2);
    let updates: Vec<_> = views
        .into_iter()
        .filter(|view| !matches!(view, DaemonView::Notice(_)))
        .collect();
    assert_eq!(
        updates,
        vec![
            DaemonView::Title("Replayed title".into()),
            resting(Rest::Ready),
            DaemonView::Context {
                used_tokens: 1200,
                window_tokens: Some(8000)
            },
            DaemonView::Spend(Some(4321)),
            DaemonView::Title("First title".into()),
            DaemonView::Context {
                used_tokens: 900,
                window_tokens: None
            },
            DaemonView::Spend(None),
            DaemonView::Title("Renamed live".into()),
        ]
    );
}

/// What the session hands the mapper: an event, a reset replay's start, an
/// attach's open requests and its replay's end, or what came of an answer
/// the TUI sent.
enum Step {
    Event(SessionEvent),
    Reset,
    Tail,
    /// An attach that lists these requests open, whose replay ends with the
    /// job in this state, of turn [`TURN`].
    Attached(Vec<InputRequest>, JobState),
    ReplayEnded,
    Answering(InputRequestId),
    Refused(InputRequestId, AnswerRefusal),
}

/// The turn the steps' states and ends are of, unless they name another.
const TURN: &str = "t1";

/// The views one session's mapper makes of `steps`.
fn map(steps: Vec<Step>) -> Vec<DaemonView> {
    let mut events = DaemonEvents::default();
    let mut views = Vec::new();
    for step in steps {
        match step {
            Step::Event(event) => views.extend(events.map(event)),
            Step::Reset => views.push(events.replay(Replay::Reset)),
            Step::Tail => views.push(events.replay(Replay::Tail)),
            Step::Attached(inputs, state) => {
                events.attached(
                    inputs,
                    state,
                    Some(TurnId::new(TURN)),
                    /*turn_since*/ None,
                );
            }
            Step::ReplayEnded => views.extend(events.end_replay()),
            Step::Answering(id) => events.answering(id),
            Step::Refused(id, refusal) => views.extend(events.answer_refused(id, refusal)),
        }
    }
    // The tables compare what text shows, not when it was said; the test
    // below owns `replayed`.
    for view in &mut views {
        if let DaemonView::Text { replayed, .. } = view {
            *replayed = false;
        }
    }
    views
}

// Covers: text the daemon replays is marked as said before, so the TUI
// writes it as history; text after the replay ends is live.
// Owner: tui daemon session events
#[test]
fn replayed_text_is_marked_until_the_replay_ends() {
    let mut events = DaemonEvents::default();
    let chunk = |message: &str| SessionEvent::AgentMessageChunk {
        message: MessageId::new(message),
        text: "text".into(),
    };
    let replayed = |views: Vec<DaemonView>| match views.as_slice() {
        [DaemonView::Text { replayed, .. }] => *replayed,
        other => panic!("expected one text view: {other:?}"),
    };
    events.replay(Replay::Reset);
    events.attached(
        Vec::new(),
        JobState::Running,
        Some(TurnId::new(TURN)),
        /*turn_since*/ None,
    );
    let during = replayed(events.map(chunk("m1")));
    events.end_replay();

    assert_eq!((during, replayed(events.map(chunk("m2")))), (true, false));
}

// Covers: a `/compact` turn is over once its job rests or the next prompt
// arrives, replayed or live, so the TUI stops showing what follows as part
// of it. A reset replays a rested turn's state as history, with no rest to
// show: a later turn's reply was dropped along with the `/compact` reply,
// and a turn the TUI still showed busy must stay a `/compact` turn until the
// replay's end rests it. An automatic compaction starts no such turn.
// Owner: tui daemon session events
#[test]
fn a_compact_turn_is_over_when_its_job_rests_or_the_next_prompt_arrives() {
    let started = |trigger| {
        Step::Event(SessionEvent::Compaction {
            id: CompactionId::new("c1"),
            status: CompactionStatus::Started {
                trigger: Some(trigger),
            },
        })
    };
    let command = || started(CompactionTrigger::Command);
    let opened = |command| DaemonView::CompactionStarted { command };
    let attached = || Step::Attached(Vec::new(), JobState::Idle);
    let cases = [
        (
            "replayed to its rest, which the replay's end shows",
            vec![
                Step::Reset,
                attached(),
                command(),
                state(JobState::Completed),
                Step::ReplayEnded,
            ],
            vec![
                DaemonView::Clear,
                opened(true),
                resting(Rest::Ready),
                DaemonView::CompactTurnOver,
            ],
        ),
        (
            "replayed, a later turn follows its rest",
            vec![
                Step::Reset,
                attached(),
                command(),
                state(JobState::Completed),
                reply("m1", "later"),
            ],
            vec![
                DaemonView::Clear,
                opened(true),
                DaemonView::CompactTurnOver,
                text(StreamKind::Assistant, "later", true),
            ],
        ),
        (
            "replayed, cut short of the rest",
            vec![Step::Reset, attached(), command(), user("next")],
            vec![
                DaemonView::Clear,
                opened(true),
                DaemonView::CompactTurnOver,
                DaemonView::User("next".into()),
            ],
        ),
        (
            "live, after the rest it shows",
            vec![
                command(),
                state(JobState::Running),
                state(JobState::Completed),
            ],
            vec![
                opened(true),
                DaemonView::Turn(TurnState::Running),
                resting(Rest::Ready),
                DaemonView::CompactTurnOver,
            ],
        ),
        (
            "an automatic compaction",
            vec![
                started(CompactionTrigger::Automatic),
                state(JobState::Completed),
            ],
            vec![opened(false), resting(Rest::Ready)],
        ),
    ];
    for (name, steps, views) in cases {
        assert_eq!(map(steps), views, "{name}");
    }
}

// Covers: a live retry says why with the retry hint, a request the provider
// only sends again says just that it retries, and a replayed retry, which is
// history, changes nothing.
// Owner: tui daemon session events
#[test]
fn a_live_retry_says_why_and_a_replayed_one_nothing() {
    let retry = |reason, retry_after_ms| SessionEvent::ProviderRetry {
        reason,
        retry_after_ms,
    };
    let hint = |reason| DaemonView::Retrying(Some(ProviderRetryHint { reason }));
    let mut events = DaemonEvents::default();
    events.replay(Replay::Reset);
    events.attached(
        Vec::new(),
        JobState::Running,
        Some(TurnId::new(TURN)),
        /*turn_since*/ None,
    );
    let replayed = events.map(retry(RetryReason::RateLimit, None));
    events.end_replay();
    let live: Vec<_> = [
        retry(RetryReason::RateLimit, Some(5_000)),
        retry(RetryReason::ProviderError, None),
        retry(RetryReason::RequestFailed, None),
    ]
    .into_iter()
    .flat_map(|event| events.map(event))
    .collect();

    assert_eq!(
        (replayed, live),
        (
            Vec::new(),
            vec![
                hint(ProviderStreamResetReason::RetryableFailure {
                    kind: ProviderErrorKind::RateLimit,
                    retry_after: Some(Duration::from_secs(5)),
                }),
                hint(ProviderStreamResetReason::RetryableFailure {
                    kind: ProviderErrorKind::Other,
                    retry_after: None,
                }),
                DaemonView::Retrying(None),
            ]
        )
    );
}

fn user(text: &str) -> Step {
    Step::Event(SessionEvent::UserMessage {
        message: MessageId::new("u1"),
        content: vec![ContentBlock::Text { text: text.into() }],
        steer: None,
    })
}

fn reply(message: &str, text: &str) -> Step {
    Step::Event(SessionEvent::AgentMessageChunk {
        message: MessageId::new(message),
        text: text.into(),
    })
}

fn thought(message: &str, text: &str) -> Step {
    Step::Event(SessionEvent::ThoughtChunk {
        message: MessageId::new(message),
        text: text.into(),
    })
}

fn tool(status: ToolStatus, display: Option<Presentation>) -> Step {
    Step::Event(SessionEvent::tool_call(ToolCallUpdate {
        id: WireCallId::new("call-1"),
        title: None,
        kind: None,
        status: Some(status),
        raw_input: None,
        content: None,
        locations: None,
        display,
    }))
}

fn answered(text: &str) -> Step {
    Step::Event(SessionEvent::TurnEnded {
        turn: TurnId::new(TURN),
        outcome: TurnOutcome::Answered {
            text: text.into(),
            stop: AnswerStop::EndTurn,
        },
    })
}

fn state(state: JobState) -> Step {
    state_of(TURN, state)
}

/// Turn `turn`'s job is in `state`.
fn state_of(turn: &str, state: JobState) -> Step {
    Step::Event(SessionEvent::State {
        state,
        turn: Some(TurnId::new(turn)),
    })
}

fn ended(outcome: TurnOutcome) -> Step {
    Step::Event(SessionEvent::TurnEnded {
        turn: TurnId::new(TURN),
        outcome,
    })
}

fn provider_failed(message: &str) -> TurnOutcome {
    TurnOutcome::Failed {
        error: TurnError {
            kind: TurnErrorKind::Provider,
            message: message.into(),
        },
    }
}

fn resting(rest: Rest) -> DaemonView {
    DaemonView::Turn(TurnState::Resting(rest))
}

fn steer() -> SteeringId {
    SteeringId::from_string("s1").unwrap()
}

fn read_card(status: ToolCardStatus) -> ToolCard {
    ToolCard::new(
        status,
        ToolFamily::Default,
        ToolHeader::call("read", Some("src/lib.rs".into())),
    )
}

fn text(kind: StreamKind, text: &str, opens: bool) -> DaemonView {
    DaemonView::Text {
        kind,
        text: text.into(),
        opens,
        replayed: false,
    }
}

fn call() -> ToolCallId {
    ToolCallId::from_string("call-1").unwrap()
}

// Covers: a daemon session's replayed or live events reach the transcript as
// rows: one row per message, the daemon's tool cards running then finished, a
// call cut off shown interrupted, an answer completing missing chunks, a tail
// preserving partial rows and cards, and a reset replay starting the session
// over.
// Owner: tui daemon event mapping
#[test]
fn session_events_map_to_transcript_views() {
    let cases = [
        (
            "tail replay finishes the open reply without duplicating its row or answer",
            vec![
                user("hello"),
                reply("m1", "Good "),
                Step::Tail,
                Step::Attached(Vec::new(), JobState::Completed),
                reply("m1", "morning."),
                answered("Good morning."),
                Step::ReplayEnded,
            ],
            vec![
                DaemonView::User("hello".into()),
                text(StreamKind::Assistant, "Good ", true),
                DaemonView::InputsReset,
                text(StreamKind::Assistant, "morning.", false),
                resting(Rest::Ready),
            ],
        ),
        (
            "an empty tail preserves an open call until its live interruption",
            vec![
                tool(
                    ToolStatus::Pending,
                    Some(Presentation::Card(read_card(ToolCardStatus::Running))),
                ),
                Step::Tail,
                Step::Attached(Vec::new(), JobState::Running),
                Step::ReplayEnded,
                tool(ToolStatus::Failed, None),
            ],
            vec![
                DaemonView::ToolRunning {
                    call: call(),
                    card: read_card(ToolCardStatus::Running),
                },
                DaemonView::InputsReset,
                DaemonView::Turn(TurnState::Running),
                DaemonView::ToolFinished {
                    call: call(),
                    presentation: read_card(ToolCardStatus::Interrupted).into(),
                },
            ],
        ),
        (
            "replayed turn with a tool card",
            vec![
                Step::Reset,
                user("read lib.rs"),
                thought("m1", "planning"),
                reply("m2", "Let me "),
                reply("m2", "read it."),
                tool(
                    ToolStatus::Pending,
                    Some(Presentation::Card(read_card(ToolCardStatus::Running))),
                ),
                tool(
                    ToolStatus::Completed,
                    Some(Presentation::Card(read_card(ToolCardStatus::Ok))),
                ),
                reply("m3", "Done."),
                answered("Done."),
            ],
            vec![
                DaemonView::Clear,
                DaemonView::User("read lib.rs".into()),
                text(StreamKind::Reasoning, "planning", true),
                text(StreamKind::Assistant, "Let me ", true),
                text(StreamKind::Assistant, "read it.", false),
                DaemonView::ToolRunning {
                    call: call(),
                    card: read_card(ToolCardStatus::Running),
                },
                DaemonView::ToolFinished {
                    call: call(),
                    presentation: Presentation::Card(read_card(ToolCardStatus::Ok)),
                },
                text(StreamKind::Assistant, "Done.", true),
            ],
        ),
        (
            "a call that closes failed without a card was interrupted",
            vec![
                tool(
                    ToolStatus::InProgress,
                    Some(Presentation::Card(read_card(ToolCardStatus::Running))),
                ),
                tool(ToolStatus::Failed, /*display*/ None),
            ],
            vec![
                DaemonView::ToolRunning {
                    call: call(),
                    card: read_card(ToolCardStatus::Running),
                },
                DaemonView::ToolFinished {
                    call: call(),
                    presentation: Presentation::Card(read_card(ToolCardStatus::Interrupted)),
                },
            ],
        ),
        (
            "the answer completes a reply whose last chunks went missing",
            vec![reply("m1", "Hel"), answered("Hello")],
            vec![
                text(StreamKind::Assistant, "Hel", true),
                text(StreamKind::Assistant, "lo", false),
            ],
        ),
        (
            "the answer completes the reply after the last call, not before",
            vec![
                reply("m1", "Let me read it."),
                tool(
                    ToolStatus::Completed,
                    Some(Presentation::Card(read_card(ToolCardStatus::Ok))),
                ),
                answered("Done."),
            ],
            vec![
                text(StreamKind::Assistant, "Let me read it.", true),
                DaemonView::ToolFinished {
                    call: call(),
                    presentation: Presentation::Card(read_card(ToolCardStatus::Ok)),
                },
                text(StreamKind::Assistant, "Done.", true),
            ],
        ),
        (
            "an answer that is the text before the last call shows once",
            vec![
                reply("m1", "Reading it."),
                tool(
                    ToolStatus::Completed,
                    Some(Presentation::Card(read_card(ToolCardStatus::Ok))),
                ),
                Step::Event(SessionEvent::TurnEnded {
                    turn: TurnId::new(TURN),
                    outcome: TurnOutcome::MaxSteps {
                        text: "Reading it.".into(),
                    },
                }),
            ],
            vec![
                text(StreamKind::Assistant, "Reading it.", true),
                DaemonView::ToolFinished {
                    call: call(),
                    presentation: Presentation::Card(read_card(ToolCardStatus::Ok)),
                },
            ],
        ),
        (
            "an empty answer after calls adds no row",
            vec![
                reply("m1", "Reading it."),
                tool(
                    ToolStatus::Completed,
                    Some(Presentation::Card(read_card(ToolCardStatus::Ok))),
                ),
                Step::Event(SessionEvent::TurnEnded {
                    turn: TurnId::new(TURN),
                    outcome: TurnOutcome::MaxSteps {
                        text: String::new(),
                    },
                }),
            ],
            vec![
                text(StreamKind::Assistant, "Reading it.", true),
                DaemonView::ToolFinished {
                    call: call(),
                    presentation: Presentation::Card(read_card(ToolCardStatus::Ok)),
                },
            ],
        ),
        (
            "a reset replay forgets the open message and running cards",
            vec![
                reply("m1", "old"),
                tool(
                    ToolStatus::InProgress,
                    Some(Presentation::Card(read_card(ToolCardStatus::Running))),
                ),
                Step::Reset,
                // No card survives the reset to close.
                tool(ToolStatus::Failed, /*display*/ None),
                reply("m1", "new"),
            ],
            vec![
                text(StreamKind::Assistant, "old", true),
                DaemonView::ToolRunning {
                    call: call(),
                    card: read_card(ToolCardStatus::Running),
                },
                DaemonView::Clear,
                text(StreamKind::Assistant, "new", true),
            ],
        ),
    ];

    for (name, steps, expected) in cases {
        assert_eq!(map(steps), expected, "{name}");
    }
}

// Covers: the job's state drives the TUI's busy state, a failed turn rests
// with its own reason and never another turn's, a replayed state is history
// unless it is of the turn the replay ends under way (#1777), and a steer's
// delivery and echo carry the id the pending panel keys it by, ahead of its
// user row.
// Owner: tui daemon event mapping
#[test]
fn job_states_and_steers_map_to_turn_views() {
    let cases = [
        (
            "a cancelled turn rests interrupted",
            vec![
                state(JobState::Running),
                reply("m1", "partial"),
                ended(TurnOutcome::Cancelled),
                state(JobState::Cancelled),
            ],
            vec![
                DaemonView::Turn(TurnState::Running),
                text(StreamKind::Assistant, "partial", true),
                DaemonView::Status("model interrupted".into()),
                resting(Rest::Interrupted),
            ],
        ),
        (
            "a failed turn rests with its reason",
            vec![
                state(JobState::Running),
                ended(provider_failed("provider refused the request")),
                state(JobState::Failed),
            ],
            vec![
                DaemonView::Turn(TurnState::Running),
                DaemonView::Error("provider refused the request".into()),
                resting(Rest::Failed {
                    error: "provider refused the request".into(),
                }),
            ],
        ),
        (
            "a failure's reason does not outlive its turn",
            vec![
                ended(provider_failed("provider refused the request")),
                state_of("t2", JobState::Queued),
                state_of("t2", JobState::Failed),
            ],
            vec![
                DaemonView::Error("provider refused the request".into()),
                DaemonView::Turn(TurnState::Running),
                resting(Rest::Failed {
                    error: "the turn failed".into(),
                }),
            ],
        ),
        (
            "a turn waits for input, then completes",
            vec![
                state(JobState::WaitingForInput),
                state(JobState::Running),
                state(JobState::Completed),
                state(JobState::Idle),
            ],
            vec![
                DaemonView::Turn(TurnState::WaitingForInput),
                DaemonView::Turn(TurnState::Running),
                resting(Rest::Ready),
                resting(Rest::Ready),
            ],
        ),
        (
            "a reset's turn that ran and ended shows only where the replay ends",
            vec![
                Step::Reset,
                Step::Attached(Vec::new(), JobState::Completed),
                state(JobState::Running),
                state(JobState::WaitingForInput),
                state(JobState::Completed),
                Step::ReplayEnded,
            ],
            vec![DaemonView::Clear, resting(Rest::Ready)],
        ),
        (
            "a tail's states are news: the turn the TUI watched ends before another's shows",
            vec![
                state(JobState::Running),
                Step::Tail,
                Step::Attached(Vec::new(), JobState::Running),
                state(JobState::Completed),
                state_of("t2", JobState::Running),
                Step::ReplayEnded,
            ],
            vec![
                DaemonView::Turn(TurnState::Running),
                DaemonView::InputsReset,
                resting(Rest::Ready),
                DaemonView::Turn(TurnState::Running),
                DaemonView::Turn(TurnState::Running),
            ],
        ),
        (
            "a reset shows the turn it ends under way from where its rows start, and no earlier turn",
            vec![
                Step::Reset,
                Step::Attached(Vec::new(), JobState::Running),
                state_of("t0", JobState::Running),
                state_of("t0", JobState::Completed),
                state(JobState::Running),
                user("now"),
                Step::ReplayEnded,
            ],
            vec![
                DaemonView::Clear,
                DaemonView::Turn(TurnState::Running),
                DaemonView::User("now".into()),
                DaemonView::Turn(TurnState::Running),
            ],
        ),
        (
            "a steer is delivered, then applies as a user row",
            vec![
                Step::Event(SessionEvent::SteeringDelivered {
                    id: SteerId::new("s1"),
                }),
                Step::Event(SessionEvent::UserMessage {
                    message: MessageId::new("u2"),
                    content: vec![ContentBlock::Text {
                        text: "check the tests too".into(),
                    }],
                    steer: Some(SteerId::new("s1")),
                }),
            ],
            vec![
                DaemonView::SteerDelivered(steer()),
                DaemonView::SteerApplied(steer()),
                DaemonView::User("check the tests too".into()),
            ],
        ),
    ];

    for (name, steps, expected) in cases {
        assert_eq!(map(steps), expected, "{name}");
    }
}

/// A write approval, request `id`.
fn approval(id: u64) -> InputRequest {
    InputRequest {
        id: InputRequestId(id),
        ask: Ask::Approval(ApprovalAsk {
            source: ApprovalSource::BuiltInTool {
                name: "write".into(),
            },
            operation: Operation::WritePath {
                path: PathBuf::from("notes.md"),
                scope: PathScope::Workspace,
            },
            reason: String::new(),
        }),
        tool_call: None,
        timeout: None,
        asker: Default::default(),
    }
}

/// A question, request `id`, that the daemon answers at a timeout.
fn timed_question(id: u64) -> InputRequest {
    InputRequest {
        id: InputRequestId(id),
        ask: Ask::Question(QuestionAsk {
            title: "Colour".into(),
            questions: vec![Question {
                id: "colour".into(),
                prompt: "Pick a colour".into(),
                header: None,
                choices: vec![Choice {
                    value: "red".into(),
                    label: "Red".into(),
                    description: None,
                }],
                selection: Selection::One,
                allow_other: false,
                help: None,
                default: None,
                required: true,
            }],
        }),
        tool_call: None,
        timeout: Some(InputTimeout {
            deadline_ms: 1,
            answer: InputAnswer::Answers {
                answers: BTreeMap::from([("colour".to_owned(), vec!["red".to_owned()])]),
            },
            reason: "red keeps the build going".into(),
        }),
        asker: Default::default(),
    }
}

fn requested(request: InputRequest) -> Step {
    Step::Event(SessionEvent::InputRequested {
        request: Box::new(request),
    })
}

fn resolved(id: u64, resolution: Resolution) -> Step {
    Step::Event(SessionEvent::InputResolved {
        id: InputRequestId(id),
        resolution,
    })
}

fn opened(request: InputRequest) -> DaemonView {
    DaemonView::InputOpened(Box::new(request))
}

// Covers: an input request shows once, whether it opened live or the replay
// left it open (listed by the attach, repeated by the replay, or neither),
// and never when the replay opened and closed it; one another client
// answered, the turn withdrew, or the daemon answered at its timeout closes
// with a notice, one the TUI answered closes silently, and a refused answer
// shows the request again only while it is still open.
// Owner: tui daemon event mapping
#[test]
fn input_requests_show_once_and_close_as_resolved() {
    let held = InputRequest {
        timeout: None,
        ..timed_question(3)
    };
    let cases = [
        (
            "a tail replaces stale requests and shows each still-open request once",
            vec![
                requested(approval(1)),
                requested(approval(2)),
                Step::Tail,
                Step::Attached(vec![approval(3)], JobState::WaitingForInput),
                resolved(1, Resolution::Answered),
                requested(approval(3)),
                requested(approval(4)),
                resolved(4, Resolution::Withdrawn),
                Step::ReplayEnded,
            ],
            vec![
                opened(approval(1)),
                opened(approval(2)),
                DaemonView::InputsReset,
                DaemonView::Turn(TurnState::WaitingForInput),
                opened(approval(3)),
            ],
        ),
        (
            "the replay leaves a request open: it shows once the replay ends",
            vec![
                Step::Attached(vec![approval(1)], JobState::WaitingForInput),
                requested(approval(1)),
                requested(approval(2)),
                Step::ReplayEnded,
            ],
            vec![
                DaemonView::Turn(TurnState::WaitingForInput),
                opened(approval(1)),
                opened(approval(2)),
            ],
        ),
        (
            "the replay opens and closes a request: it never shows",
            vec![
                Step::Attached(Vec::new(), JobState::Running),
                requested(approval(1)),
                resolved(1, Resolution::Answered),
                Step::ReplayEnded,
            ],
            vec![DaemonView::Turn(TurnState::Running)],
        ),
        (
            "a request held during the replay shows without its timeout",
            vec![
                Step::Attached(vec![timed_question(3)], JobState::WaitingForInput),
                Step::Event(SessionEvent::InputHeld {
                    id: InputRequestId(3),
                }),
                Step::ReplayEnded,
            ],
            vec![DaemonView::Turn(TurnState::WaitingForInput), opened(held)],
        ),
        (
            "live requests close as resolved elsewhere",
            vec![
                requested(approval(1)),
                requested(approval(1)),
                resolved(1, Resolution::Answered),
                requested(approval(2)),
                resolved(2, Resolution::Withdrawn),
                requested(timed_question(3)),
                resolved(3, Resolution::TimedOut),
            ],
            vec![
                opened(approval(1)),
                DaemonView::InputClosed {
                    id: InputRequestId(1),
                    notice: "another client answered the approval".into(),
                },
                opened(approval(2)),
                DaemonView::InputClosed {
                    id: InputRequestId(2),
                    notice: "the turn withdrew the approval".into(),
                },
                opened(timed_question(3)),
                DaemonView::InputClosed {
                    id: InputRequestId(3),
                    notice: "timeout fallback: red keeps the build going".into(),
                },
            ],
        ),
        (
            "a request the TUI answered closes silently",
            vec![
                requested(approval(1)),
                Step::Answering(InputRequestId(1)),
                resolved(1, Resolution::Answered),
            ],
            vec![opened(approval(1))],
        ),
        (
            "a refused answer asks again; one no longer open does not",
            vec![
                requested(approval(1)),
                Step::Answering(InputRequestId(1)),
                Step::Refused(
                    InputRequestId(1),
                    AnswerRefusal::Failed("the daemon is busy".into()),
                ),
                requested(approval(2)),
                Step::Answering(InputRequestId(2)),
                Step::Refused(InputRequestId(2), AnswerRefusal::NotOpen),
                resolved(2, Resolution::Answered),
            ],
            vec![
                opened(approval(1)),
                DaemonView::Error("could not answer the request: the daemon is busy".into()),
                opened(approval(1)),
                opened(approval(2)),
                DaemonView::Error("could not answer the request: it is no longer open".into()),
            ],
        ),
    ];

    for (name, steps, expected) in cases {
        assert_eq!(map(steps), expected, "{name}");
    }
}