rho-coding-agent 3.9.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
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
use std::{
    collections::BTreeMap,
    time::{Duration, UNIX_EPOCH},
};

use pretty_assertions::assert_eq;
use rho_protocol::{
    self as wire, ErrorCode, InputAnswer, InputRequestId, QuestionAnswer, Resolution, SecretAsk,
    SecretValue,
};
use rho_sdk::{ApprovalDecision, HostInputRefusal, HostInputResponse, HostInputSource};
use tokio::sync::mpsc;

use super::{Asker, Inputs};
use crate::{
    app::{
        daemon_host::sessions::test_events::{
            approval, approval_withdrawn, elicitation, plan, question, question_id,
            question_with_fallback, question_withdrawn, secret,
        },
        session_runtime::{ApprovalId, PlanApprovalId, SecretAskId, SessionEvent, TurnControl},
    },
    permission::PermissionMode,
    tools::{mcp::secret_tool::SecretOutcome, plan_exit::PlanExitDecision},
};

/// Opens the request `event` asks in `inputs`, returning its id and the
/// channel its answer reaches.
fn open(
    inputs: &mut Inputs,
    event: &SessionEvent,
) -> (InputRequestId, mpsc::UnboundedReceiver<TurnControl>) {
    let (control, answers) = mpsc::unbounded_channel();
    inputs.note(Asker::Turn, &control, event, UNIX_EPOCH);
    (opened(inputs).id, answers)
}

/// The request the last change opened, its only one.
fn opened(inputs: &mut Inputs) -> wire::InputRequest {
    match inputs.take_events().as_slice() {
        [wire::SessionEvent::InputRequested { request }] => (**request).clone(),
        _ => panic!("the event opens a request"),
    }
}

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

fn answers(pairs: &[(&str, &[&str])]) -> InputAnswer {
    InputAnswer::Answers {
        answers: pairs
            .iter()
            .map(|(question, values)| {
                (
                    (*question).to_owned(),
                    values.iter().map(|value| (*value).to_owned()).collect(),
                )
            })
            .collect::<BTreeMap<_, _>>(),
    }
}

/// What the turn got for an answer, or the error code the client did.
#[derive(Debug, PartialEq)]
enum Outcome {
    Turn(TurnControl),
    Refused(ErrorCode),
}

// Covers: each kind of request hands the turn the answer a client gave in
// the runtime's terms (a deny without a reason says the user denied it, a
// plan approval only into a mode it offers, answers only when they fit the
// questions), and refuses an answer meant for another kind, leaving the
// request open.
// Owner: daemon input requests.
#[test]
fn a_request_hands_the_turn_only_the_answers_it_takes() {
    let question_answered = HostInputResponse::new().answer("answer", ["yes"]);
    let cases = [
        (
            approval(0),
            InputAnswer::AllowOnce,
            Outcome::Turn(TurnControl::RespondApproval {
                id: ApprovalId::nth_for_tests(0),
                decision: ApprovalDecision::AllowOnce,
            }),
        ),
        (
            approval(0),
            InputAnswer::Deny { reason: None },
            Outcome::Turn(TurnControl::RespondApproval {
                id: ApprovalId::nth_for_tests(0),
                decision: ApprovalDecision::Deny {
                    reason: "denied by user".into(),
                },
            }),
        ),
        (
            approval(0),
            InputAnswer::KeepPlanning { feedback: None },
            Outcome::Refused(ErrorCode::InvalidParams),
        ),
        (
            plan(0),
            InputAnswer::ApprovePlan {
                mode: wire::PermissionMode::Auto,
                feedback: None,
            },
            Outcome::Turn(TurnControl::AnswerPlan {
                id: PlanApprovalId::nth_for_tests(0),
                answer: PlanExitDecision::approve(PermissionMode::Auto),
            }),
        ),
        (
            plan(0),
            InputAnswer::KeepPlanning {
                feedback: Some("smaller steps".into()),
            },
            Outcome::Turn(TurnControl::AnswerPlan {
                id: PlanApprovalId::nth_for_tests(0),
                answer: PlanExitDecision::keep_planning()
                    .with_feedback(Some("smaller steps".into())),
            }),
        ),
        (
            plan(0),
            InputAnswer::ApprovePlan {
                mode: wire::PermissionMode::Bypass,
                feedback: None,
            },
            Outcome::Refused(ErrorCode::InvalidParams),
        ),
        (
            plan(0),
            InputAnswer::AllowOnce,
            Outcome::Refused(ErrorCode::InvalidParams),
        ),
        (
            question("q"),
            answers(&[("answer", &["yes"])]),
            Outcome::Turn(TurnControl::AnswerQuestion {
                id: question_id("q"),
                answer: Ok(question_answered),
            }),
        ),
        (
            question("q"),
            InputAnswer::Decline,
            Outcome::Turn(TurnControl::AnswerQuestion {
                id: question_id("q"),
                answer: Err(HostInputRefusal::Declined),
            }),
        ),
        (
            question("q"),
            answers(&[("answer", &["no"])]),
            Outcome::Refused(ErrorCode::InvalidParams),
        ),
        (
            question("q"),
            answers(&[("other", &["yes"])]),
            Outcome::Refused(ErrorCode::InvalidParams),
        ),
        (
            question("q"),
            InputAnswer::AllowOnce,
            Outcome::Refused(ErrorCode::InvalidParams),
        ),
        (
            question("q"),
            InputAnswer::Secret {
                value: SecretValue::new("tok"),
            },
            Outcome::Refused(ErrorCode::InvalidParams),
        ),
        (
            secret(0),
            InputAnswer::Decline,
            Outcome::Turn(TurnControl::AnswerSecret {
                id: SecretAskId::nth_for_tests(0),
                outcome: SecretOutcome::Declined,
            }),
        ),
        // A value is stored through `take_secret`, never handed over here.
        (
            secret(0),
            InputAnswer::Secret {
                value: SecretValue::new("tok"),
            },
            Outcome::Refused(ErrorCode::InvalidParams),
        ),
        (
            secret(0),
            InputAnswer::AllowOnce,
            Outcome::Refused(ErrorCode::InvalidParams),
        ),
    ];
    for (index, (event, answer, expected)) in cases.into_iter().enumerate() {
        let mut inputs = Inputs::new(/*question_timeout*/ None);
        let (id, mut turn) = open(&mut inputs, &event);
        let refused = matches!(expected, Outcome::Refused(_));

        let outcome = match inputs.answer(id, answer.clone()) {
            Ok(()) => {
                inputs.send_answers();
                Outcome::Turn(turn.try_recv().expect("the turn got the answer"))
            }
            Err(error) => Outcome::Refused(error.error_code().expect("a known code")),
        };

        assert_eq!(outcome, expected, "case {index}: answered {answer:?}");
        // A refused answer leaves the request open; an accepted one tells
        // clients it was answered.
        let told = if refused {
            Vec::new()
        } else {
            vec![resolved(id, Resolution::Answered)]
        };
        assert_eq!(
            (inputs.waiting(), inputs.take_events()),
            (refused, told),
            "case {index}"
        );
    }
}

/// A subagent's asker: run `run-1`, writing session `child-1`.
fn subagent() -> Asker {
    Asker::Subagent(wire::SubagentRef::new(
        "run-1",
        Some(wire::SessionId::new("child-1")),
    ))
}

/// One answer a session gives through `answer_question`, and what it gets.
struct SessionAnswerRow {
    case: &'static str,
    asker: Asker,
    event: SessionEvent,
    answer: QuestionAnswer,
    /// What the asker's turn gets, or the code that refuses the answer.
    expected: Result<TurnControl, ErrorCode>,
}

// Covers: the path a session answers through takes only a question anyone
// but the user may answer: an approval, a plan approval, and an MCP
// server's elicitation (user-only), the turn's own or one a subagent
// forwards, are refused, stay open for a person, and reach no turn; a
// question hands its turn the answers as a session's and tells clients a
// session answered it.
// Owner: daemon input requests.
#[test]
fn only_a_question_takes_a_sessions_answer() {
    let yes = || QuestionAnswer::Answers {
        answers: [("answer".to_owned(), vec!["yes".to_owned()])].into(),
    };
    let rows = [
        // A person alone answers either kind of approval; both stay, since
        // each is its own request kind that a change could let through alone.
        SessionAnswerRow {
            case: "approval",
            asker: Asker::Turn,
            event: approval(0),
            answer: QuestionAnswer::Decline,
            expected: Err(ErrorCode::InvalidParams),
        },
        SessionAnswerRow {
            case: "plan approval",
            asker: Asker::Turn,
            event: plan(0),
            answer: yes(),
            expected: Err(ErrorCode::InvalidParams),
        },
        SessionAnswerRow {
            case: "secret ask",
            asker: Asker::Turn,
            event: secret(0),
            answer: QuestionAnswer::Decline,
            expected: Err(ErrorCode::InvalidParams),
        },
        SessionAnswerRow {
            case: "elicitation",
            asker: Asker::Turn,
            event: elicitation("q"),
            answer: yes(),
            expected: Err(ErrorCode::InvalidParams),
        },
        SessionAnswerRow {
            case: "a subagent's elicitation",
            asker: subagent(),
            event: elicitation("q"),
            answer: QuestionAnswer::Decline,
            expected: Err(ErrorCode::InvalidParams),
        },
        SessionAnswerRow {
            case: "question",
            asker: Asker::Turn,
            event: question("q"),
            answer: yes(),
            expected: Ok(TurnControl::AnswerQuestion {
                id: question_id("q"),
                answer: Ok(HostInputResponse::new()
                    .answer("answer", ["yes"])
                    .with_source(HostInputSource::Session)),
            }),
        },
    ];
    for row in rows {
        let mut inputs = Inputs::new(/*question_timeout*/ None);
        let (control, mut turn) = mpsc::unbounded_channel();
        inputs.note(row.asker, &control, &row.event, UNIX_EPOCH);
        let id = opened(&mut inputs).id;

        let result = inputs
            .answer_question(id, row.answer)
            .map_err(|error| error.error_code());
        inputs.send_answers();

        let expected = match row.expected {
            Ok(delivered) => (
                Ok(()),
                Some(delivered),
                vec![resolved(id, Resolution::AnsweredBySession)],
                false,
            ),
            Err(code) => (Err(Some(code)), None, Vec::new(), true),
        };
        assert_eq!(
            (
                result,
                turn.try_recv().ok(),
                inputs.take_events(),
                inputs.open.contains_key(&id),
            ),
            expected,
            "{}",
            row.case
        );
    }
}

// Covers: a subagent's question is not the turn's: clients are told whose
// it is, down to the subagent's run and session, the turn's end leaves it
// open, and no turn waits on it, so the job does not wait for input.
// Owner: daemon input requests.
#[test]
fn a_subagents_question_outlives_the_turn() {
    let mut inputs = Inputs::new(/*question_timeout*/ None);
    let (turns, _turn) = open(&mut inputs, &approval(0));
    let (control, _answers) = mpsc::unbounded_channel();
    inputs.note(subagent(), &control, &question("q"), UNIX_EPOCH);
    let asked = opened(&mut inputs);
    let subagents = asked.id;

    inputs.withdraw_turn();

    assert_eq!(
        (
            asked.asker,
            asked.subagent,
            inputs.take_events(),
            inputs.waiting(),
            inputs.answer(subagents, InputAnswer::Decline).is_ok(),
        ),
        (
            wire::InputAsker::Subagent,
            Some(wire::SubagentRef::new(
                "run-1",
                Some(wire::SessionId::new("child-1"))
            )),
            vec![wire::SessionEvent::InputResolved {
                id: turns,
                resolution: Resolution::Withdrawn,
            }],
            false,
            true,
        )
    );
}

// Covers: the first answer takes the request, so a second client's answer,
// or one to a request the turn withdrew, is refused as not open and reaches
// no turn; the answer reaches its turn only once it is sent, after clients
// were told; a withdrawal closes only the request of the model turn that
// asked, and none an answer already closed; an answer to a model turn that
// ended without withdrawing its request is refused and tells clients the
// request was withdrawn; ids stay unique after requests close.
// Owner: daemon input requests.
#[test]
fn only_the_first_answer_to_an_open_request_wins() {
    let code = |error: rho_protocol::RpcError| error.error_code();
    let mut inputs = Inputs::new(/*question_timeout*/ None);
    let (approved, mut turn) = open(&mut inputs, &approval(0));
    let (asked, _asking) = open(&mut inputs, &question("q"));
    let (abandoned, ended) = open(&mut inputs, &approval(1));
    drop(ended);
    // The model turn that asked `asked` withdraws it; another model turn's
    // withdrawal of a request with the same runtime id closes nothing.
    let (other_turn, _) = mpsc::unbounded_channel();
    let (asking_turn, _) = mpsc::unbounded_channel();
    inputs.note(Asker::Turn, &asking_turn, &question("q"), UNIX_EPOCH);
    let reasked = opened(&mut inputs);

    let first = inputs
        .answer(approved, InputAnswer::AllowOnce)
        .map_err(code);
    let second = inputs
        .answer(approved, InputAnswer::Deny { reason: None })
        .map_err(code);
    inputs.note(Asker::Turn, &other_turn, &approval_withdrawn(0), UNIX_EPOCH);
    inputs.note(
        Asker::Turn,
        &other_turn,
        &question_withdrawn("q"),
        UNIX_EPOCH,
    );
    inputs.note(
        Asker::Turn,
        &asking_turn,
        &question_withdrawn("q"),
        UNIX_EPOCH,
    );
    let to_withdrawn = inputs
        .answer(reasked.id, InputAnswer::Decline)
        .map_err(code);
    let to_ended = inputs
        .answer(abandoned, InputAnswer::AllowOnce)
        .map_err(code);
    let before_sending = turn.try_recv().ok();
    inputs.send_answers();
    let delivered = [before_sending, turn.try_recv().ok(), turn.try_recv().ok()];

    assert_eq!(
        (
            first,
            second,
            to_withdrawn,
            to_ended,
            inputs.take_events(),
            delivered,
            inputs.waiting(),
            [approved, asked, abandoned, reasked.id],
        ),
        (
            Ok(()),
            Err(Some(ErrorCode::InputNotOpen)),
            Err(Some(ErrorCode::InputNotOpen)),
            Err(Some(ErrorCode::InputNotOpen)),
            vec![
                resolved(approved, Resolution::Answered),
                resolved(reasked.id, Resolution::Withdrawn),
                resolved(abandoned, Resolution::Withdrawn),
            ],
            [
                None,
                Some(TurnControl::RespondApproval {
                    id: ApprovalId::nth_for_tests(0),
                    decision: ApprovalDecision::AllowOnce,
                }),
                None,
            ],
            // `asked`, whose model turn withdrew nothing, is still open.
            true,
            [
                InputRequestId(0),
                InputRequestId(1),
                InputRequestId(2),
                InputRequestId(3)
            ],
        )
    );
}

/// A session's question timeout in these tests; every request opens at
/// `UNIX_EPOCH`, so one that times out has its deadline this far past it.
const QUESTION_TIMEOUT: Duration = Duration::from_secs(60);

// Covers: only a question whose agent offered fallback answers, in a
// session whose questions time out, gets a timeout: clients see when and
// with what the daemon answers it, and the agent's assumption only when it
// gave one, and the caller is handed the timeout to run.
// Owner: daemon input requests.
#[test]
fn only_a_question_with_fallback_answers_times_out() {
    let times_out = |reason: &str, assumption: Option<&str>| {
        (
            Some(wire::InputTimeout {
                deadline_ms: 60_000,
                queued: false,
                answer: answers(&[("answer", &["yes"])]),
                reason: reason.into(),
                assumption: assumption.map(str::to_owned),
            }),
            vec![(InputRequestId(0), QUESTION_TIMEOUT)],
        )
    };
    let cases = [
        (
            "question with fallback answers and an assumption",
            Some(QUESTION_TIMEOUT),
            question_with_fallback("q", Some("safe default")),
            times_out("safe default", Some("safe default")),
        ),
        (
            "question with fallback answers and no assumption",
            Some(QUESTION_TIMEOUT),
            question_with_fallback("q", None),
            times_out("yes", None),
        ),
        (
            "question without",
            Some(QUESTION_TIMEOUT),
            question("q"),
            (None, Vec::new()),
        ),
        (
            "approval",
            Some(QUESTION_TIMEOUT),
            approval(0),
            (None, Vec::new()),
        ),
        (
            "questions do not time out",
            None,
            question_with_fallback("q", Some("safe default")),
            (None, Vec::new()),
        ),
    ];
    for (case, question_timeout, event, expected) in cases {
        let mut inputs = Inputs::new(question_timeout);
        let (control, _turn) = mpsc::unbounded_channel();
        inputs.note(Asker::Turn, &control, &event, UNIX_EPOCH);
        let request = opened(&mut inputs);

        assert_eq!(
            (request.timeout, inputs.take_timeouts()),
            expected,
            "{case}"
        );
    }
}

/// Something that happens to an open question with a timeout.
#[derive(Clone, Copy, Debug)]
enum Step {
    Answer,
    Hold,
    EndTurn,
    TimeOut,
}

/// What came of a question with a timeout after some steps.
#[derive(Debug, PartialEq)]
struct Played {
    /// The codes of the steps refused.
    refused: Vec<ErrorCode>,
    events: Vec<wire::SessionEvent>,
    turn: Option<TurnControl>,
    open: bool,
}

/// Opens the question `event` asks in a session whose questions time out,
/// plays `steps` on it, and reports what came of it.
fn play(event: &SessionEvent, steps: &[Step]) -> Played {
    let mut inputs = Inputs::new(Some(QUESTION_TIMEOUT));
    let (id, mut turn) = open(&mut inputs, event);
    let mut refused = Vec::new();
    for step in steps {
        let result = match step {
            Step::Answer => inputs.answer(id, InputAnswer::Decline),
            Step::Hold => inputs.hold(id),
            Step::EndTurn => {
                turn.close();
                Ok(())
            }
            Step::TimeOut => {
                inputs.time_out(id);
                Ok(())
            }
        };
        refused.extend(result.err().and_then(|error| error.error_code()));
    }
    inputs.send_answers();
    Played {
        refused,
        events: inputs.take_events(),
        turn: turn.try_recv().ok(),
        open: inputs.waiting(),
    }
}

// Covers: a question still open and not held when its timeout fires hands
// the turn its fallback answers, marked as the fallback, and tells clients
// it timed out; one answered or held first, or whose model turn ended,
// does not time out.
// Owner: daemon input requests.
#[test]
fn a_question_times_out_only_while_open_and_not_held() {
    let id = InputRequestId(0);
    let cases = [
        (
            "nobody answered",
            &[Step::TimeOut][..],
            vec![resolved(id, Resolution::TimedOut)],
            Some(TurnControl::AnswerQuestion {
                id: question_id("q"),
                answer: Ok(HostInputResponse::new()
                    .answer("answer", ["yes"])
                    .with_source(HostInputSource::TimeoutFallback)),
            }),
            false,
        ),
        (
            "answered first",
            &[Step::Answer, Step::TimeOut],
            vec![resolved(id, Resolution::Answered)],
            Some(TurnControl::AnswerQuestion {
                id: question_id("q"),
                answer: Err(HostInputRefusal::Declined),
            }),
            false,
        ),
        (
            "held first",
            &[Step::Hold, Step::TimeOut],
            vec![wire::SessionEvent::InputHeld { id }],
            None,
            true,
        ),
        (
            "model turn ended",
            &[Step::EndTurn, Step::TimeOut],
            vec![resolved(id, Resolution::Withdrawn)],
            None,
            false,
        ),
    ];
    for (case, steps, events, turn, open) in cases {
        let expected = Played {
            refused: Vec::new(),
            events,
            turn,
            open,
        };
        let timed = question_with_fallback("q", Some("safe"));
        assert_eq!(play(&timed, steps), expected, "{case}");
    }
}

// Covers: holding a question stops its timeout once and tells clients;
// holding it again, or one without a timeout, tells nobody; a closed
// question cannot be held.
// Owner: daemon input requests.
#[test]
fn holding_tells_clients_only_when_it_stops_a_timeout() {
    let id = InputRequestId(0);
    let held = wire::SessionEvent::InputHeld { id };
    let timed = question_with_fallback("q", Some("safe"));
    let cases = [
        (
            "held",
            &timed,
            &[Step::Hold][..],
            Vec::new(),
            vec![held.clone()],
        ),
        (
            "held twice",
            &timed,
            &[Step::Hold, Step::Hold],
            Vec::new(),
            vec![held],
        ),
        (
            "without a timeout",
            &question("q"),
            &[Step::Hold],
            Vec::new(),
            Vec::new(),
        ),
        (
            "held after it timed out",
            &timed,
            &[Step::TimeOut, Step::Hold],
            vec![ErrorCode::InputNotOpen],
            vec![resolved(id, Resolution::TimedOut)],
        ),
    ];
    for (case, event, steps, refused, events) in cases {
        let played = play(event, steps);
        assert_eq!((played.refused, played.events), (refused, events), "{case}");
    }
}

/// `seconds` past `UNIX_EPOCH`, the tests' clock.
fn at(seconds: u64) -> std::time::SystemTime {
    UNIX_EPOCH + Duration::from_secs(seconds)
}

fn started(id: u64, deadline_ms: u64) -> wire::SessionEvent {
    wire::SessionEvent::InputTimeoutStarted {
        id: InputRequestId(id),
        deadline_ms,
    }
}

// Covers: a question with a timeout opened behind an older open request is
// queued, with no timer and its earliest deadline, until the requests
// before it close; then it gets its whole timeout from that moment, and a
// question queued behind it waits for it in turn.
// Owner: daemon input requests.
#[test]
fn a_queued_questions_clock_starts_when_it_reaches_the_front() {
    let mut inputs = Inputs::new(Some(QUESTION_TIMEOUT));
    let (approval_id, _approval_turn) = open(&mut inputs, &approval(0));
    let (control, _turn) = mpsc::unbounded_channel();
    let mut queued = Vec::new();
    for asked in ["first", "second"] {
        inputs.note(
            Asker::Turn,
            &control,
            &question_with_fallback(asked, Some("safe")),
            at(0),
        );
        let request = opened(&mut inputs);
        queued.push(
            request
                .timeout
                .map(|timeout| (timeout.queued, timeout.deadline_ms)),
        );
    }
    assert_eq!(
        (queued, inputs.take_timeouts()),
        (vec![Some((true, 60_000)), Some((true, 60_000))], Vec::new()),
    );
    // A stray timer for a queued question answers nothing.
    inputs.time_out(InputRequestId(1));
    inputs.start_front_clock(at(5));
    assert_eq!(inputs.take_events(), Vec::new());

    inputs.answer(approval_id, InputAnswer::AllowOnce).unwrap();
    inputs.start_front_clock(at(10));
    assert_eq!(
        (inputs.take_events(), inputs.take_timeouts()),
        (
            vec![
                resolved(approval_id, Resolution::Answered),
                started(1, 70_000)
            ],
            vec![(InputRequestId(1), QUESTION_TIMEOUT)],
        ),
    );

    inputs.time_out(InputRequestId(1));
    inputs.start_front_clock(at(70));
    assert_eq!(
        (inputs.take_events(), inputs.take_timeouts()),
        (
            vec![
                resolved(InputRequestId(1), Resolution::TimedOut),
                started(2, 130_000)
            ],
            vec![(InputRequestId(2), QUESTION_TIMEOUT)],
        ),
    );
}

// Covers: however the request in front of a queued question closes, its
// clock starts then, unless the question closed with it or was held while
// queued, when it never starts.
// Owner: daemon input requests.
#[test]
fn a_queued_questions_clock_starts_however_the_front_closes() {
    let front = InputRequestId(0);
    let queued = InputRequestId(1);
    type Close = fn(&mut Inputs, &mpsc::UnboundedSender<TurnControl>);
    let cases: [(&str, Close, Vec<wire::SessionEvent>); 4] = [
        (
            "answered",
            |inputs, _| {
                inputs
                    .answer(InputRequestId(0), InputAnswer::AllowOnce)
                    .unwrap()
            },
            vec![resolved(front, Resolution::Answered), started(1, 70_000)],
        ),
        (
            "withdrawn",
            |inputs, control| inputs.note(Asker::Turn, control, &approval_withdrawn(0), at(10)),
            vec![resolved(front, Resolution::Withdrawn), started(1, 70_000)],
        ),
        (
            "turn ended",
            |inputs, _| inputs.withdraw_turn(),
            vec![
                resolved(front, Resolution::Withdrawn),
                resolved(queued, Resolution::Withdrawn),
            ],
        ),
        (
            "held while queued",
            |inputs, _| {
                inputs.hold(InputRequestId(1)).unwrap();
                inputs
                    .answer(InputRequestId(0), InputAnswer::AllowOnce)
                    .unwrap();
            },
            vec![
                wire::SessionEvent::InputHeld { id: queued },
                resolved(front, Resolution::Answered),
            ],
        ),
    ];
    for (case, close, expected) in cases {
        let mut inputs = Inputs::new(Some(QUESTION_TIMEOUT));
        let (control, _turn) = mpsc::unbounded_channel();
        inputs.note(Asker::Turn, &control, &approval(0), at(0));
        inputs.note(
            Asker::Turn,
            &control,
            &question_with_fallback("q", Some("safe")),
            at(0),
        );
        inputs.take_events();
        close(&mut inputs, &control);
        inputs.start_front_clock(at(10));
        assert_eq!(inputs.take_events(), expected, "{case}");
    }
}

// Covers: a loaded session starts a queued question's clock as soon as the
// change that closed the request before it is made, so a later attach sees
// it running, and its timer then answers it at the deadline; a miss leaves
// the question queued forever, never expiring.
// Owner: daemon input requests (`LoadedSession::change_inputs`).
#[tokio::test]
async fn a_change_that_closes_the_front_starts_the_queued_clock() {
    use crate::app::{
        daemon_host::{
            jobs::{JobRegistry, JobStore},
            sessions::{
                test_sessions::{load, Load},
                Sessions,
            },
        },
        pull_requests::ScriptedForge,
    };

    let (root, home) = (
        tempfile::TempDir::new().unwrap(),
        tempfile::TempDir::new().unwrap(),
    );
    let sessions = Sessions::new(
        std::sync::Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap())),
        home.path(),
        ScriptedForge::new(),
    );
    let session = load(&sessions, &root, Load::Busy).await;
    let (control, _turn) = mpsc::unbounded_channel();
    for event in [approval(0), question_with_fallback("q", Some("safe"))] {
        session.change_inputs(|inputs| {
            inputs.note(Asker::Turn, &control, &event, std::time::SystemTime::now());
        });
    }
    let queued = |session: &super::LoadedSession| {
        session
            .feed
            .attach(None)
            .inputs
            .iter()
            .find_map(|request| request.timeout.as_ref().map(|timeout| timeout.queued))
    };
    let before = queued(&session);
    // The session's timers run on the test's clock from here.
    tokio::time::pause();
    session
        .change_inputs(|inputs| inputs.answer(InputRequestId(0), InputAnswer::AllowOnce))
        .unwrap();
    let started = queued(&session);
    let timeout = crate::config::QuestionnaireConfig::default()
        .expiry
        .duration()
        .expect("questions expire by default");
    tokio::time::sleep(timeout + Duration::from_secs(1)).await;

    assert_eq!(
        (before, started, queued(&session)),
        (Some(true), Some(false), None)
    );
}

// Covers: a person's value keeps its secret ask open while the daemon
// stores it, refusing every other answer meanwhile, and names the secret to
// store; a store that fails leaves the ask open for another try; one that
// succeeds answers it, and only that it was stored reaches the turn. Any
// other request refuses a value and stays as it was; clients see the ask as
// the server, name, and destination, never a value.
// Owner: daemon input requests.
#[test]
fn a_secret_ask_resolves_only_once_its_value_is_stored() {
    let mut inputs = Inputs::new(/*question_timeout*/ None);
    let (asked, mut asked_turn) = mpsc::unbounded_channel();
    inputs.note(Asker::Turn, &asked, &secret(0), UNIX_EPOCH);
    let ask = opened(&mut inputs);
    let (question_id, _question_turn) = open(&mut inputs, &question("q"));
    let code =
        |result: Result<(), rho_protocol::RpcError>| result.map_err(|error| error.error_code());

    let refused = code(inputs.begin_secret(question_id).map(drop));
    let slot = inputs.begin_secret(ask.id).unwrap();
    let while_storing = (
        code(inputs.begin_secret(ask.id).map(drop)),
        code(inputs.answer(ask.id, InputAnswer::Decline)),
    );
    inputs.end_secret(ask.id, /*stored*/ false);
    let after_failure = (inputs.take_events(), inputs.open.contains_key(&ask.id));
    inputs.begin_secret(ask.id).unwrap();
    inputs.end_secret(ask.id, /*stored*/ true);
    inputs.send_answers();

    assert_eq!(
        (
            ask.ask,
            refused,
            (slot.server, slot.name),
            while_storing,
            after_failure,
            inputs.take_events(),
            inputs.open.keys().copied().collect::<Vec<_>>(),
            asked_turn.try_recv().ok(),
        ),
        (
            wire::Ask::Secret(SecretAsk {
                server: "probe".into(),
                name: "TOKEN".into(),
                reason: None,
                destination: rho_protocol::SecretDestination::Process {
                    command: "python3".into(),
                    args: vec!["probe.py".into()],
                },
            }),
            Err(Some(ErrorCode::InvalidParams)),
            ("probe".to_owned(), "TOKEN".to_owned()),
            (
                Err(Some(ErrorCode::InvalidParams)),
                Err(Some(ErrorCode::InvalidParams)),
            ),
            (Vec::new(), true),
            vec![resolved(ask.id, Resolution::Answered)],
            vec![question_id],
            Some(TurnControl::AnswerSecret {
                id: SecretAskId::nth_for_tests(0),
                outcome: SecretOutcome::Stored,
            }),
        )
    );
}