bcode_cli 0.0.1-alpha.0

Command-line 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
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
//! IPC regression coverage for scripted timeout cancellation.

use super::*;

async fn hello_peer(listener: &bcode_ipc::LocalIpcListener) -> bcode_ipc::LocalIpcStream {
    let mut stream = listener.accept().await.unwrap();
    let hello = bcode_ipc::recv_envelope(&mut stream).await.unwrap();
    let daemon = bcode_ipc::DaemonStatus {
        namespace: bcode_ipc::daemon_namespace(),
        protocol_version: u32::from(bcode_ipc::CURRENT_PROTOCOL_VERSION),
        artifact_id: Some(bcode_ipc::ArtifactId::current()),
        executable_digest: Some(
            bcode_daemon_lifecycle::current_executable_identity()
                .unwrap()
                .1,
        ),
        build_fingerprint: bcode_ipc::BUILD_FINGERPRINT.into(),
        storage_writer_epoch: Some(bcode_ipc::CURRENT_SESSION_STORAGE_WRITER_EPOCH),
        session_event_schema_version: Some(
            bcode_session_models::CURRENT_SESSION_EVENT_SCHEMA_VERSION,
        ),
        state_location_id: Some(bcode_ipc::state_location_id()),
        ..Default::default()
    };
    reply(
        &mut stream,
        hello.request_id,
        bcode_ipc::ResponsePayload::Hello {
            protocol_version: bcode_ipc::ProtocolVersion(bcode_ipc::CURRENT_PROTOCOL_VERSION),
            client_id: bcode_session_models::ClientId::new(),
            daemon,
        },
    )
    .await;
    stream
}

async fn reply(
    stream: &mut bcode_ipc::LocalIpcStream,
    id: u64,
    payload: bcode_ipc::ResponsePayload,
) {
    bcode_ipc::send_envelope(
        stream,
        &bcode_ipc::response_envelope(id, &bcode_ipc::Response::Ok(payload)).unwrap(),
    )
    .await
    .unwrap();
}

async fn attach_peer(watch: &mut bcode_ipc::LocalIpcStream, session_id: SessionId) {
    let attach = bcode_ipc::recv_envelope(watch).await.unwrap();
    assert!(
        matches!(bcode_ipc::decode_request(&attach.payload).unwrap(),
        bcode_ipc::Request::AttachSessionRecent { session_id: id, .. } if id == session_id)
    );
    let session = serde_json::from_value(serde_json::json!({
        "id": session_id, "name": null, "client_count": 0,
        "created_at_ms": 0, "updated_at_ms": 0, "working_directory": "/tmp",
    }))
    .unwrap();
    reply(
        watch,
        attach.request_id,
        bcode_ipc::ResponsePayload::Attached {
            session_id,
            session,
            history: Vec::new(),
            input_history: Vec::new(),
            usage_summary: None,
            import_warnings: Vec::new(),
            draft: None,
            runtime_selection: bcode_session_models::SessionRuntimeSelection::default(),
            projection_window: None,
        },
    )
    .await;
}

#[tokio::test]
async fn observation_failure_without_timeout_authority_performs_no_transport_work() {
    for timeout_error in [false, true] {
        let directory = tempfile::tempdir().unwrap();
        let endpoint = bcode_ipc::IpcEndpoint::unix_socket(directory.path().join("n.sock"));
        let listener = bcode_ipc::LocalIpcListener::bind(&endpoint).unwrap();
        let session_id = SessionId::new();
        let server = tokio::spawn(async move {
            let mut watch = hello_peer(&listener).await;
            attach_peer(&mut watch, session_id).await;
            (listener, watch)
        });
        let client = BcodeClient::new(endpoint);
        let mut watcher = client.watch_session(session_id, 1).await.unwrap();
        let (listener, mut peer) = server.await.unwrap();
        let receipt = bcode_session_models::TurnReceipt::from_accepted_event(session_id, 17);
        let timeout = std::time::Duration::from_millis(20);
        let options = TurnObservationOptions {
            timeout,
            cancellation_grace: (!timeout_error).then_some(timeout),
        };
        let error = if timeout_error {
            ClientError::RequestTimeout { timeout }
        } else {
            ClientError::UnexpectedResponse
        };
        let result = report_observation_failure(
            &client,
            session_id,
            &receipt,
            Some(&options),
            error,
            &mut watcher,
        )
        .await;
        assert!(result.is_err());
        assert!(
            tokio::time::timeout(timeout, listener.accept())
                .await
                .is_err()
        );
        assert!(
            tokio::time::timeout(timeout, bcode_ipc::recv_envelope(&mut peer))
                .await
                .is_err()
        );
    }
}

#[tokio::test]
async fn cancellation_recovery_deadline_preserves_original_timeout_without_retry() {
    let directory = tempfile::tempdir().unwrap();
    let endpoint = bcode_ipc::IpcEndpoint::unix_socket(directory.path().join("d.sock"));
    let listener = bcode_ipc::LocalIpcListener::bind(&endpoint).unwrap();
    let session_id = SessionId::new();
    let server = tokio::spawn(async move {
        let mut watch = hello_peer(&listener).await;
        attach_peer(&mut watch, session_id).await;
        let mut cancel = hello_peer(&listener).await;
        let request = bcode_ipc::recv_envelope(&mut cancel).await.unwrap();
        reply(
            &mut cancel,
            request.request_id,
            bcode_ipc::ResponsePayload::TurnCancellationRequested { cancelled: true },
        )
        .await;
        let history = bcode_ipc::recv_envelope(&mut watch).await.unwrap();
        assert!(matches!(
            bcode_ipc::decode_request(&history.payload).unwrap(),
            bcode_ipc::Request::SessionHistoryPage { .. }
        ));
        // Keep the response unanswered without closing the original subscription.
        (listener, watch)
    });
    let client =
        BcodeClient::new(endpoint).with_request_timeout(std::time::Duration::from_secs(30));
    let mut watcher = client.watch_session(session_id, 1).await.unwrap();
    let receipt = bcode_session_models::TurnReceipt::from_accepted_event(session_id, 17);
    let original = std::time::Duration::from_secs(7);
    let options = TurnObservationOptions {
        timeout: original,
        // Include fresh cancellation-connection executable verification under load.
        // This remains shorter than the transport timeout, and history stays unanswered.
        cancellation_grace: Some(std::time::Duration::from_secs(5)),
    };
    let result = tokio::time::timeout(
        std::time::Duration::from_secs(15),
        report_observation_failure(
            &client,
            session_id,
            &receipt,
            Some(&options),
            ClientError::RequestTimeout { timeout: original },
            &mut watcher,
        ),
    )
    .await
    .expect("recovery grace must expire before the 30-second transport timeout");
    assert!(
        matches!(result, Err(CliError::Client(ClientError::RequestTimeout { timeout })) if timeout == original)
    );
    let (listener, mut peer) = server.await.unwrap();
    let bound = std::time::Duration::from_millis(50);
    assert!(
        tokio::time::timeout(bound, listener.accept())
            .await
            .is_err()
    );
    assert!(
        tokio::time::timeout(bound, bcode_ipc::recv_envelope(&mut peer))
            .await
            .is_err()
    );
}

#[tokio::test]
async fn unanswered_cancellation_is_bounded_by_recovery_grace() {
    let directory = tempfile::tempdir().unwrap();
    let endpoint = bcode_ipc::IpcEndpoint::unix_socket(directory.path().join("grace.sock"));
    let listener = bcode_ipc::LocalIpcListener::bind(&endpoint).unwrap();
    let session_id = SessionId::new();
    let server = tokio::spawn(async move {
        let mut watch = hello_peer(&listener).await;
        attach_peer(&mut watch, session_id).await;
        let mut cancel = hello_peer(&listener).await;
        let request = bcode_ipc::recv_envelope(&mut cancel).await.unwrap();
        assert!(matches!(
            bcode_ipc::decode_request(&request.payload).unwrap(),
            bcode_ipc::Request::CancelSessionTurn {
                clear_queue: false,
                ..
            }
        ));
        (listener, watch, cancel)
    });
    let client =
        BcodeClient::new(endpoint).with_request_timeout(std::time::Duration::from_secs(30));
    let mut watcher = client.watch_session(session_id, 1).await.unwrap();
    let receipt = bcode_session_models::TurnReceipt::from_accepted_event(session_id, 17);
    let original = std::time::Duration::from_secs(7);
    let options = TurnObservationOptions {
        timeout: original,
        cancellation_grace: Some(std::time::Duration::from_millis(100)),
    };
    let result = tokio::time::timeout(
        std::time::Duration::from_secs(2),
        report_observation_failure(
            &client,
            session_id,
            &receipt,
            Some(&options),
            ClientError::RequestTimeout { timeout: original },
            &mut watcher,
        ),
    )
    .await
    .expect("cancellation must not wait for the 30-second transport timeout");
    assert!(
        matches!(result, Err(CliError::Client(ClientError::RequestTimeout { timeout })) if timeout == original)
    );
    let (listener, mut watch, mut cancel) = server.await.unwrap();
    assert!(bcode_ipc::recv_envelope(&mut cancel).await.is_err());
    let bound = std::time::Duration::from_millis(50);
    assert!(
        tokio::time::timeout(bound, listener.accept())
            .await
            .is_err()
    );
    assert!(
        tokio::time::timeout(bound, bcode_ipc::recv_envelope(&mut watch))
            .await
            .is_err()
    );
}

#[tokio::test]
async fn delayed_acknowledgement_does_not_restart_recovery_grace() {
    let directory = tempfile::tempdir().unwrap();
    let endpoint = bcode_ipc::IpcEndpoint::unix_socket(directory.path().join("shared.sock"));
    let listener = bcode_ipc::LocalIpcListener::bind(&endpoint).unwrap();
    let session_id = SessionId::new();
    let server = tokio::spawn(async move {
        let mut watch = hello_peer(&listener).await;
        attach_peer(&mut watch, session_id).await;
        let mut cancel = hello_peer(&listener).await;
        let request = bcode_ipc::recv_envelope(&mut cancel).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(600)).await;
        reply(
            &mut cancel,
            request.request_id,
            bcode_ipc::ResponsePayload::TurnCancellationRequested { cancelled: true },
        )
        .await;
        let history = bcode_ipc::recv_envelope(&mut watch).await.unwrap();
        assert!(matches!(
            bcode_ipc::decode_request(&history.payload).unwrap(),
            bcode_ipc::Request::SessionHistoryPage { .. }
        ));
        (listener, watch)
    });
    let client =
        BcodeClient::new(endpoint).with_request_timeout(std::time::Duration::from_secs(30));
    let mut watcher = client.watch_session(session_id, 1).await.unwrap();
    let receipt = bcode_session_models::TurnReceipt::from_accepted_event(session_id, 17);
    let original = std::time::Duration::from_secs(7);
    let options = TurnObservationOptions {
        timeout: original,
        cancellation_grace: Some(std::time::Duration::from_secs(1)),
    };
    // A fresh recovery budget after the delayed acknowledgement would take at
    // least 1.6 seconds. The shared budget must finish before that, allowing
    // scheduler slack without treating acknowledgement as terminal success.
    let result = tokio::time::timeout(
        std::time::Duration::from_millis(1400),
        report_observation_failure(
            &client,
            session_id,
            &receipt,
            Some(&options),
            ClientError::RequestTimeout { timeout: original },
            &mut watcher,
        ),
    )
    .await
    .expect("acknowledgement must consume the recovery budget");
    assert!(
        matches!(result, Err(CliError::Client(ClientError::RequestTimeout { timeout })) if timeout == original)
    );
    let (listener, mut watch) = server.await.unwrap();
    let bound = std::time::Duration::from_millis(50);
    assert!(
        tokio::time::timeout(bound, listener.accept())
            .await
            .is_err()
    );
    assert!(
        tokio::time::timeout(bound, bcode_ipc::recv_envelope(&mut watch))
            .await
            .is_err()
    );
}

#[tokio::test]
async fn headless_permission_wait_fails_without_answering_it() {
    let directory = tempfile::tempdir().unwrap();
    let endpoint = bcode_ipc::IpcEndpoint::unix_socket(directory.path().join("permission.sock"));
    let listener = bcode_ipc::LocalIpcListener::bind(&endpoint).unwrap();
    let session_id = SessionId::new();
    let server = tokio::spawn(async move {
        let mut watch = hello_peer(&listener).await;
        attach_peer(&mut watch, session_id).await;
        let history = bcode_ipc::recv_envelope(&mut watch).await.unwrap();
        reply(
            &mut watch,
            history.request_id,
            bcode_ipc::ResponsePayload::SessionHistoryPage {
                page: bcode_session_models::SessionHistoryPage {
                    session_id,
                    events: Vec::new(),
                    compatibility_issues: Vec::new(),
                    next_cursor: None,
                    has_more: false,
                },
            },
        )
        .await;
        let mut permissions = hello_peer(&listener).await;
        let request = bcode_ipc::recv_envelope(&mut permissions).await.unwrap();
        assert!(matches!(
            bcode_ipc::decode_request(&request.payload).unwrap(),
            bcode_ipc::Request::ListPermissions
        ));
        let permission = serde_json::from_value(serde_json::json!({
            "permission_id": "checkpoint", "session_id": session_id,
            "tool_call_id": "tool", "tool_name": "test", "arguments_json": "{}", "agent_id": "build",
        })).unwrap();
        reply(
            &mut permissions,
            request.request_id,
            bcode_ipc::ResponsePayload::PermissionList {
                permissions: vec![permission],
            },
        )
        .await;
        (listener, watch)
    });
    let client = BcodeClient::new(endpoint);
    let mut watcher = client.watch_session(session_id, 1).await.unwrap();
    let receipt = bcode_session_models::TurnReceipt::from_accepted_event(session_id, 17);
    let result = headless::observe(
        &client,
        &mut watcher,
        session_id,
        &receipt,
        std::time::Duration::from_secs(1),
    )
    .await;
    assert!(
        matches!(result, Err(ClientError::Protocol(message)) if message.contains("requires permission"))
    );
    let (listener, _watch) = server.await.unwrap();
    assert!(
        tokio::time::timeout(std::time::Duration::from_millis(50), listener.accept())
            .await
            .is_err()
    );
}

#[tokio::test]
async fn headless_observes_authoritative_success_and_failure() {
    use bcode_session_models::{ModelTurnOutcome, SessionEvent, SessionEventKind, TurnReceipt};
    for outcome in [ModelTurnOutcome::Completed, ModelTurnOutcome::Cancelled] {
        let directory = tempfile::tempdir().unwrap();
        let endpoint = bcode_ipc::IpcEndpoint::unix_socket(directory.path().join("terminal.sock"));
        let listener = bcode_ipc::LocalIpcListener::bind(&endpoint).unwrap();
        let session_id = SessionId::new();
        let receipt = TurnReceipt::from_accepted_event(session_id, 17);
        let expected = receipt.clone();
        let server = tokio::spawn(async move {
            let mut watch = hello_peer(&listener).await;
            attach_peer(&mut watch, session_id).await;
            let history = bcode_ipc::recv_envelope(&mut watch).await.unwrap();
            assert!(matches!(
                bcode_ipc::decode_request(&history.payload).unwrap(),
                bcode_ipc::Request::SessionHistoryPage { .. }
            ));
            reply(
                &mut watch,
                history.request_id,
                bcode_ipc::ResponsePayload::SessionHistoryPage {
                    page: bcode_session_models::SessionHistoryPage {
                        session_id,
                        compatibility_issues: Vec::new(),
                        next_cursor: None,
                        has_more: false,
                        events: vec![SessionEvent {
                            schema_version: 1,
                            session_id,
                            sequence: 18,
                            timestamp_ms: 0,
                            provenance: None,
                            kind: SessionEventKind::ModelTurnFinished {
                                turn_id: expected.turn_id.to_string(),
                                outcome,
                                message: None,
                            },
                        }],
                    },
                },
            )
            .await;
            // Retain transport until the observer settles the recovered terminal event.
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        });
        let client = BcodeClient::new(endpoint);
        let mut watcher = client.watch_session(session_id, 1).await.unwrap();
        let observed = headless::observe(
            &client,
            &mut watcher,
            session_id,
            &receipt,
            std::time::Duration::from_secs(1),
        )
        .await
        .unwrap();
        assert_eq!(observed, outcome);
        assert_eq!(
            write_terminal_turn_result(session_id, &receipt, observed).is_ok(),
            outcome == ModelTurnOutcome::Completed
        );
        server.await.unwrap();
    }
}

#[tokio::test]
async fn headless_lost_admission_response_is_unknown_and_never_replayed() {
    let directory = tempfile::tempdir().unwrap();
    let endpoint = bcode_ipc::IpcEndpoint::unix_socket(directory.path().join("lost.sock"));
    let listener = bcode_ipc::LocalIpcListener::bind(&endpoint).unwrap();
    let session_id = SessionId::new();
    let server = tokio::spawn(async move {
        let mut watch = hello_peer(&listener).await;
        attach_peer(&mut watch, session_id).await;
        let mut admission = hello_peer(&listener).await;
        let request = bcode_ipc::recv_envelope(&mut admission).await.unwrap();
        assert!(
            matches!(bcode_ipc::decode_request(&request.payload).unwrap(),
            bcode_ipc::Request::SubmitTurn { session_id: id, .. } if id == session_id)
        );
        // The peer may have committed admission. Losing the response is not rejection.
        drop(admission);
        (listener, watch)
    });
    // Compatibility verification hashes the real test executable. Leave setup slack
    // under the parallel library suite; the lost response, not elapsed time, drives failure.
    let client = BcodeClient::new(endpoint);
    let result = send_message_observed(
        &client,
        session_id,
        scripted_send_options(),
        Some(tokio::time::Instant::now() + std::time::Duration::from_secs(30)),
    )
    .await;
    assert!(result.is_err());
    let (listener, _watch) = server.await.unwrap();
    assert!(
        tokio::time::timeout(std::time::Duration::from_millis(50), listener.accept())
            .await
            .is_err()
    );
}

#[tokio::test]
async fn headless_subscription_uses_total_budget_not_transport_timeout() {
    let directory = tempfile::tempdir().unwrap();
    let endpoint = bcode_ipc::IpcEndpoint::unix_socket(directory.path().join("subscribe.sock"));
    let listener = bcode_ipc::LocalIpcListener::bind(&endpoint).unwrap();
    let session_id = SessionId::new();
    let server = tokio::spawn(async move {
        let mut watch = hello_peer(&listener).await;
        let _request = bcode_ipc::recv_envelope(&mut watch).await.unwrap();
        (listener, watch)
    });
    let client =
        BcodeClient::new(endpoint).with_request_timeout(std::time::Duration::from_secs(30));
    // Compatibility verification hashes the test executable before subscription.
    // Leave setup slack; the total budget still must beat the 30-second transport timeout.
    let result = tokio::time::timeout(
        std::time::Duration::from_secs(5),
        send_message_observed(
            &client,
            session_id,
            scripted_send_options(),
            Some(tokio::time::Instant::now() + std::time::Duration::from_secs(2)),
        ),
    )
    .await
    .unwrap();
    assert!(result.is_err());
    let (listener, _watch) = server.await.unwrap();
    assert!(
        tokio::time::timeout(std::time::Duration::from_millis(50), listener.accept())
            .await
            .is_err()
    );
}

#[tokio::test]
async fn invalid_prompt_never_connects_or_submits() {
    let directory = tempfile::tempdir().unwrap();
    let endpoint = bcode_ipc::IpcEndpoint::unix_socket(directory.path().join("input.sock"));
    let listener = bcode_ipc::LocalIpcListener::bind(&endpoint).unwrap();
    let client = BcodeClient::new(endpoint);
    let invalid_utf8 = directory.path().join("invalid.txt");
    std::fs::write(&invalid_utf8, [0xff]).unwrap();
    let inputs = [
        PromptInput {
            message: Some(String::new()),
            file: None,
            stdin: false,
        },
        PromptInput {
            message: Some("x".repeat(MAX_CLI_PROMPT_BYTES + 1)),
            file: None,
            stdin: false,
        },
        PromptInput {
            message: None,
            file: Some(invalid_utf8),
            stdin: false,
        },
        PromptInput {
            message: None,
            file: Some(directory.path().join("missing")),
            stdin: false,
        },
        PromptInput {
            message: None,
            file: Some(directory.path().to_path_buf()),
            stdin: false,
        },
        PromptInput {
            message: None,
            file: None,
            stdin: false,
        },
        PromptInput {
            message: Some("conflicting sources".into()),
            file: None,
            stdin: true,
        },
    ];
    for input in inputs {
        let mut options = scripted_send_options();
        options.input = input;
        let result = send_message_with_client(&client, SessionId::new(), options).await;
        assert!(matches!(
            result,
            Err(CliError::InvalidArguments(_) | CliError::Signal(_))
        ));
    }
    assert!(
        tokio::time::timeout(std::time::Duration::from_millis(50), listener.accept())
            .await
            .is_err()
    );
}

async fn admit_prompt(
    listener: &bcode_ipc::LocalIpcListener,
    session_id: SessionId,
    receipt: &bcode_session_models::TurnReceipt,
) {
    let mut stream = hello_peer(listener).await;
    let request = bcode_ipc::recv_envelope(&mut stream).await.unwrap();
    let bcode_ipc::Request::SubmitTurn {
        session_id: id,
        text,
        admission,
    } = bcode_ipc::decode_request(&request.payload).unwrap()
    else {
        panic!("expected admission")
    };
    assert_eq!(id, session_id);
    assert_eq!(text, "$(touch never)\n具体");
    assert_eq!(admission.idempotency_key.as_deref(), Some("job-1"));
    assert_eq!(admission.origin.unwrap().producer, "ci.test");
    reply(
        &mut stream,
        request.request_id,
        bcode_ipc::ResponsePayload::TurnAdmission {
            admission: bcode_session_models::TurnAdmission::Accepted(receipt.clone()),
        },
    )
    .await;
}

fn scripted_send_options() -> SendOptions {
    SendOptions {
        input: PromptInput {
            message: Some("$(touch never)\n具体".into()),
            file: None,
            stdin: false,
        },
        placement: None,
        producer: "ci.test".into(),
        idempotency_key: Some("job-1".into()),
        background: false,
        json: true,
        observation: Some(TurnObservationOptions {
            timeout: std::time::Duration::from_millis(50),
            cancellation_grace: Some(std::time::Duration::from_secs(1)),
        }),
        launch_options: bcode_tui::TuiLaunchOptions::default(),
    }
}

#[tokio::test]
async fn send_timeout_recovers_terminal_outcome_after_false_or_lost_ack() {
    use bcode_session_models::{ModelTurnOutcome, SessionEvent, SessionEventKind, TurnReceipt};
    for acknowledged in [Some(false), Some(true), None] {
        for outcome in [ModelTurnOutcome::Completed, ModelTurnOutcome::Cancelled] {
            let directory = tempfile::tempdir().unwrap();
            let endpoint = bcode_ipc::IpcEndpoint::unix_socket(directory.path().join("r.sock"));
            let listener = bcode_ipc::LocalIpcListener::bind(&endpoint).unwrap();
            let session_id = SessionId::new();
            let receipt = TurnReceipt::from_accepted_event(session_id, 17);
            let expected = receipt.clone();
            let server = tokio::spawn(async move {
                let mut watch = hello_peer(&listener).await;
                attach_peer(&mut watch, session_id).await;
                admit_prompt(&listener, session_id, &expected).await;
                let initial = bcode_ipc::recv_envelope(&mut watch).await.unwrap();
                assert!(matches!(
                    bcode_ipc::decode_request(&initial.payload).unwrap(),
                    bcode_ipc::Request::SessionHistoryPage { .. }
                ));
                reply(
                    &mut watch,
                    initial.request_id,
                    bcode_ipc::ResponsePayload::SessionHistoryPage {
                        page: bcode_session_models::SessionHistoryPage {
                            session_id,
                            events: Vec::new(),
                            compatibility_issues: Vec::new(),
                            next_cursor: None,
                            has_more: false,
                        },
                    },
                )
                .await;
                let mut cancel = hello_peer(&listener).await;
                let request = bcode_ipc::recv_envelope(&mut cancel).await.unwrap();
                assert_eq!(
                    bcode_ipc::decode_request(&request.payload).unwrap(),
                    bcode_ipc::Request::CancelSessionTurn {
                        session_id,
                        expected_turn_id: Some(expected.turn_id.to_string()),
                        clear_queue: false,
                    }
                );
                if let Some(cancelled) = acknowledged {
                    reply(
                        &mut cancel,
                        request.request_id,
                        bcode_ipc::ResponsePayload::TurnCancellationRequested { cancelled },
                    )
                    .await;
                }
                drop(cancel);
                let history = bcode_ipc::recv_envelope(&mut watch).await.unwrap();
                assert!(
                    matches!(bcode_ipc::decode_request(&history.payload).unwrap(),
                    bcode_ipc::Request::SessionHistoryPage { session_id: id, .. } if id == session_id)
                );
                reply(
                    &mut watch,
                    history.request_id,
                    bcode_ipc::ResponsePayload::SessionHistoryPage {
                        page: bcode_session_models::SessionHistoryPage {
                            session_id,
                            compatibility_issues: Vec::new(),
                            next_cursor: None,
                            has_more: false,
                            events: vec![SessionEvent {
                                schema_version: 1,
                                sequence: 18,
                                timestamp_ms: 0,
                                session_id,
                                provenance: None,
                                kind: SessionEventKind::ModelTurnFinished {
                                    turn_id: expected.turn_id.to_string(),
                                    outcome,
                                    message: None,
                                },
                            }],
                        },
                    },
                )
                .await;
                listener
            });
            let client =
                BcodeClient::new(endpoint).with_request_timeout(std::time::Duration::from_secs(1));
            let result =
                send_message_with_client(&client, session_id, scripted_send_options()).await;
            assert_eq!(result.is_ok(), outcome == ModelTurnOutcome::Completed);
            let listener = server.await.unwrap();
            assert!(
                tokio::time::timeout(std::time::Duration::from_millis(50), listener.accept())
                    .await
                    .is_err()
            );
        }
    }
}

#[test]
fn cancellation_acknowledgement_never_claims_terminal_success() {
    let session_id = SessionId::new();
    let receipt = bcode_session_models::TurnReceipt::from_accepted_event(session_id, 17);
    for (requested, acknowledged) in [
        (false, None),
        (true, None),
        (true, Some(false)),
        (true, Some(true)),
    ] {
        let mut output = Vec::new();
        write_unverified_observation(&mut output, session_id, &receipt, requested, acknowledged)
            .unwrap();
        let result: serde_json::Value = serde_json::from_slice(&output).unwrap();
        assert_eq!(
            result,
            serde_json::json!({
                "schema_version": 1,
                "session_id": session_id,
                "receipt": receipt,
                "outcome": null,
                "observation": "unverified",
                "cancellation_requested": requested,
                "cancellation_acknowledged": acknowledged,
            })
        );
    }
}

#[test]
fn unverified_observation_propagates_output_and_flush_failures() {
    struct FailingOutput {
        fail_write: bool,
    }
    impl std::io::Write for FailingOutput {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            if self.fail_write {
                Err(std::io::Error::other("write failed"))
            } else {
                Ok(bytes.len())
            }
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Err(std::io::Error::other("flush failed"))
        }
    }
    let session_id = SessionId::new();
    let receipt = bcode_session_models::TurnReceipt::from_accepted_event(session_id, 17);
    for fail_write in [true, false] {
        assert!(
            write_unverified_observation(
                &mut FailingOutput { fail_write },
                session_id,
                &receipt,
                true,
                Some(true),
            )
            .is_err()
        );
    }
}

#[tokio::test]
async fn timeout_cancellation_preserves_exact_target_and_unknown_acknowledgement() {
    for acknowledged in [Some(false), Some(true), None] {
        let directory = tempfile::tempdir().unwrap();
        let endpoint = bcode_ipc::IpcEndpoint::unix_socket(directory.path().join("c.sock"));
        let listener = bcode_ipc::LocalIpcListener::bind(&endpoint).unwrap();
        let session_id = SessionId::new();
        let server = tokio::spawn(async move {
            let mut stream = listener.accept().await.unwrap();
            let hello = bcode_ipc::recv_envelope(&mut stream).await.unwrap();
            let daemon = bcode_ipc::DaemonStatus {
                namespace: bcode_ipc::daemon_namespace(),
                protocol_version: u32::from(bcode_ipc::CURRENT_PROTOCOL_VERSION),
                artifact_id: Some(bcode_ipc::ArtifactId::current()),
                executable_digest: Some(
                    bcode_daemon_lifecycle::current_executable_identity()
                        .unwrap()
                        .1,
                ),
                build_fingerprint: bcode_ipc::BUILD_FINGERPRINT.into(),
                storage_writer_epoch: Some(bcode_ipc::CURRENT_SESSION_STORAGE_WRITER_EPOCH),
                session_event_schema_version: Some(
                    bcode_session_models::CURRENT_SESSION_EVENT_SCHEMA_VERSION,
                ),
                state_location_id: Some(bcode_ipc::state_location_id()),
                ..Default::default()
            };
            let response = bcode_ipc::Response::Ok(bcode_ipc::ResponsePayload::Hello {
                protocol_version: bcode_ipc::ProtocolVersion(bcode_ipc::CURRENT_PROTOCOL_VERSION),
                client_id: bcode_session_models::ClientId::new(),
                daemon,
            });
            bcode_ipc::send_envelope(
                &mut stream,
                &bcode_ipc::response_envelope(hello.request_id, &response).unwrap(),
            )
            .await
            .unwrap();
            let request = bcode_ipc::recv_envelope(&mut stream).await.unwrap();
            assert_eq!(
                bcode_ipc::decode_request(&request.payload).unwrap(),
                bcode_ipc::Request::CancelSessionTurn {
                    session_id,
                    expected_turn_id: Some("turn-具体".to_owned()),
                    clear_queue: false,
                }
            );
            if let Some(cancelled) = acknowledged {
                let response = bcode_ipc::Response::Ok(
                    bcode_ipc::ResponsePayload::TurnCancellationRequested { cancelled },
                );
                bcode_ipc::send_envelope(
                    &mut stream,
                    &bcode_ipc::response_envelope(request.request_id, &response).unwrap(),
                )
                .await
                .unwrap();
            }
            // EOF before acknowledgement models an uncertain transport outcome.
            drop(stream);
            listener
        });
        let client =
            BcodeClient::new(endpoint).with_request_timeout(std::time::Duration::from_secs(1));
        assert_eq!(
            request_observation_cancellation(&client, session_id, "turn-具体".to_owned(), true,)
                .await,
            acknowledged
        );
        let listener = server.await.unwrap();
        // No retry, session-wide cancellation, or resubmission follows an error.
        assert!(
            tokio::time::timeout(std::time::Duration::from_millis(50), listener.accept(),)
                .await
                .is_err()
        );
        assert_eq!(
            request_observation_cancellation(&client, session_id, "turn-具体".to_owned(), false,)
                .await,
            None
        );
        assert!(
            tokio::time::timeout(std::time::Duration::from_millis(50), listener.accept(),)
                .await
                .is_err()
        );
    }
}