rpi-cli 0.27.1

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates
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
//! Production dispatcher fixtures: real JSONL reader/writer, harness and tools.
use super::tests::{rpc_test_harness, start_test_rpc};
use super::*;
use base64::{engine::general_purpose::STANDARD, Engine};
use rpi_ai::providers::faux::{faux_assistant_message, FauxProvider, FauxScript, FauxStep};
use serde_json::{json, Value};
use tokio::io::AsyncWriteExt;

async fn send(client: &mut tokio::io::DuplexStream, value: Value) {
    let mut bytes = serde_json::to_vec(&value).unwrap();
    bytes.push(b'\n');
    client.write_all(&bytes).await.unwrap();
}
fn png_block() -> Value {
    let mut bytes = Vec::new();
    {
        let mut encoder = png::Encoder::new(&mut bytes, 1, 1);
        encoder.set_color(png::ColorType::Rgba);
        encoder.set_depth(png::BitDepth::Eight);
        encoder
            .write_header()
            .unwrap()
            .write_image_data(&[4, 8, 16, 255])
            .unwrap();
    }
    json!({"type":"image", "mimeType":"image/png", "data":STANDARD.encode(bytes)})
}
async fn stop(client: &mut tokio::io::DuplexStream, task: tokio::task::JoinHandle<i32>) {
    send(client, json!({"type":"stop","id":"stop"})).await;
    assert_eq!(
        tokio::time::timeout(std::time::Duration::from_secs(3), task)
            .await
            .unwrap()
            .unwrap(),
        0
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn production_legacy_client_gets_no_autonomous_settlement_or_execution_frames() {
    let provider = FauxProvider::new(FauxScript::new().with_text("autonomous").with_text("rpc"));
    let harness = AgentHarness::create(rpi_harness::types::AgentHarnessOptions {
        model: provider.default_model().clone(),
        models: vec![provider],
        ..Default::default()
    })
    .await
    .unwrap();
    let retained = harness.clone();
    let (mut client, output, task) = super::tests::start_test_rpc_with_execution(
        harness,
        rpi_extensions::UiDialogMailbox::new(),
        None,
        false,
    );
    let ready = output.wait_for(|m| m["type"] == "ready").await;
    assert!(ready["semantics"]["executionLifecycle"].is_null());
    assert_eq!(
        ready["semantics"]["executionLifecycleOptIn"]["value"],
        "correlated-v1"
    );
    retained
        .lane("main")
        .send_message(
            rpi_ai::UserMessage::new("plugin kickoff", 0).into(),
            rpi_harness::types::SendMessageOptions {
                trigger_turn: Some(true),
                ..Default::default()
            },
        )
        .await
        .unwrap();
    output.wait_for(|m| m["type"] == "agent_end").await;
    // A normal RPC command still settles exactly once in legacy mode.
    send(
        &mut client,
        json!({"type":"prompt", "id":"legacy", "message":"next"}),
    )
    .await;
    let settled = output
        .wait_for(|m| m["type"] == "agent_settled" && m["requestId"] == "legacy")
        .await;
    assert_eq!(settled["outcome"], "completed");
    stop(&mut client, task).await;
    let messages = output.messages();
    assert!(!messages
        .iter()
        .any(|m| m["type"] == "execution_started" || m["type"] == "execution_released"));
    assert_eq!(
        messages
            .iter()
            .filter(|m| m["type"] == "agent_settled")
            .count(),
        1
    );
    assert!(messages
        .iter()
        .filter(|m| m["type"] == "agent_start")
        .all(|m| m.get("executionId").is_none()));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn production_plugin_execution_settles_without_an_rpc_prompt() {
    let (harness, _) = rpc_test_harness("autonomous", 0.0).await;
    let retained = harness.clone();
    let (mut client, output, task) =
        start_test_rpc(harness, rpi_extensions::UiDialogMailbox::new());
    output.wait_for(|m| m["type"] == "ready").await;
    let result = retained
        .lane("main")
        .send_message(
            rpi_ai::UserMessage::new("plugin kickoff", 0).into(),
            rpi_harness::types::SendMessageOptions {
                trigger_turn: Some(true),
                ..Default::default()
            },
        )
        .await
        .unwrap();
    let rpi_harness::agent_harness::SendMessageResult::Run(run) = result else {
        panic!("plugin must start a run");
    };
    let settled = output.wait_for(|m| m["type"] == "agent_settled").await;
    assert_eq!(settled["runId"], run.run_id);
    assert_eq!(settled["outcome"], "completed");
    assert!(settled["executionId"].is_string());
    assert!(settled["requestId"].is_null());
    stop(&mut client, task).await;
    let messages = output.messages();
    let lifecycle: Vec<_> = messages
        .iter()
        .filter(|event| event["executionId"] == settled["executionId"])
        .filter_map(|event| match event["type"].as_str() {
            Some(kind @ ("execution_started" | "execution_released" | "agent_settled")) => {
                Some(kind)
            }
            _ => None,
        })
        .collect();
    assert_eq!(
        lifecycle,
        ["execution_started", "execution_released", "agent_settled"]
    );
    let started = messages
        .iter()
        .find(|event| event["type"] == "execution_started")
        .unwrap();
    assert!(
        started["runId"].is_null(),
        "durable identity is not known at admission"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn production_terminal_publication_releases_admission_before_next_prompt() {
    use crate::rpc::prompt_content::validation_test_hook::{Gate, ReleaseOnDrop};
    use std::sync::atomic::Ordering;

    let provider = FauxProvider::new(FauxScript::new().with_text("first").with_text("second"));
    let harness = AgentHarness::create(rpi_harness::types::AgentHarnessOptions {
        model: provider.default_model().clone(),
        models: vec![provider.clone()],
        ..Default::default()
    })
    .await
    .unwrap();
    let (mut client, output, task) =
        start_test_rpc(harness, rpi_extensions::UiDialogMailbox::new());
    let mut previous_run = Value::Null;
    // Rejection and settlement are both terminal boundaries. A client may send
    // its next request as soon as either arrives, with no sleep or busy retry.
    for (id, invalid) in [
        ("terminal-invalid", true),
        ("terminal-first", false),
        ("terminal-second", false),
    ] {
        let gate = Gate::register(id);
        let _release = ReleaseOnDrop(gate.clone());
        gate.release();
        let request = if invalid {
            json!({"type":"prompt","id":id,"contentBlocks":[{
                "type":"image","mimeType":"image/png","data":"AAAA"
            }]})
        } else {
            json!({"type":"prompt","id":id,"message":"next run"})
        };
        send(&mut client, request).await;
        let response = output.wait_for(|m| m["id"] == id).await;
        assert_eq!(response["success"], !invalid, "{response}");
        if !invalid {
            let settled = output
                .wait_for(|m| m["type"] == "agent_settled" && m["runId"] != previous_run)
                .await;
            assert_eq!(settled["outcome"], "completed", "{settled}");
            previous_run = settled["runId"].clone();
            assert!(previous_run.is_string());
        }
        tokio::time::timeout(
            std::time::Duration::from_secs(3),
            gate.terminal_observed.cancelled(),
        )
        .await
        .unwrap();
        assert!(
            !gate.terminal_active.load(Ordering::Acquire),
            "terminal publication for {id} must expose idle admission"
        );
    }
    assert_eq!(provider.state().call_count.load(Ordering::SeqCst), 2);
    let messages = output.messages();
    let first = messages
        .iter()
        .position(|m| m["type"] == "agent_settled")
        .unwrap();
    let next = messages
        .iter()
        .position(|m| m["id"] == "terminal-second")
        .unwrap();
    assert!(first < next, "successor acceptance must follow settlement");
    stop(&mut client, task).await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn production_prompt_pixels_and_model_are_checked_before_acceptance_or_persistence() {
    let mut model = FauxProvider::new(FauxScript::new()).default_model().clone();
    model.input = vec![rpi_ai::types::InputModality::Text];
    let provider =
        FauxProvider::with_models(FauxScript::new().with_text("unused"), vec![model.clone()]);
    let harness = AgentHarness::create(rpi_harness::types::AgentHarnessOptions {
        model,
        models: vec![provider.clone()],
        ..Default::default()
    })
    .await
    .unwrap();
    let retained = harness.clone();
    let (mut client, output, task) =
        start_test_rpc(harness, rpi_extensions::UiDialogMailbox::new());
    for (id, image, expected) in [
        (
            1,
            json!({"type":"image","mimeType":"image/png","data":"AAAA"}),
            "contentBlocks[0]",
        ),
        (2, png_block(), "does not support image"),
    ] {
        send(
            &mut client,
            json!({"type":"prompt","id":id,"contentBlocks":[image]}),
        )
        .await;
        let response = output.wait_for(|m| m["id"] == id).await;
        assert_eq!(response["success"], false);
        assert!(
            response["error"].as_str().unwrap().contains(expected),
            "{response}"
        );
    }
    assert_eq!(
        provider
            .state()
            .call_count
            .load(std::sync::atomic::Ordering::SeqCst),
        0
    );
    assert!(retained
        .session()
        .storage()
        .find_entries(&EntryQuery::default())
        .await
        .unwrap()
        .is_empty());
    assert!(!output
        .messages()
        .iter()
        .any(|m| m["type"] == "agent_settled"));
    stop(&mut client, task).await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn production_ordered_blocks_reach_model_and_native_history_unchanged() {
    let blocks = vec![
        png_block(),
        json!({"type":"text","text":"middle"}),
        png_block(),
    ];
    let expected: Vec<Content> = blocks
        .iter()
        .cloned()
        .map(|b| serde_json::from_value(b).unwrap())
        .collect();
    let captured = Arc::new(Mutex::new(Vec::new()));
    let seen = captured.clone();
    let script = FauxScript::new();
    script.set_responses(vec![FauxStep::factory(move |ctx| {
        *seen.lock().unwrap() = ctx.messages.clone();
        faux_assistant_message("done", StopReason::Stop)
    })]);
    let mut model = FauxProvider::new(FauxScript::new()).default_model().clone();
    model.input.push(rpi_ai::types::InputModality::Image);
    let provider = FauxProvider::with_models(script, vec![model.clone()]);
    let harness = AgentHarness::create(rpi_harness::types::AgentHarnessOptions {
        model,
        models: vec![provider],
        ..Default::default()
    })
    .await
    .unwrap();
    let (mut client, output, task) =
        start_test_rpc(harness, rpi_extensions::UiDialogMailbox::new());
    send(
        &mut client,
        json!({"type":"prompt","id":1,"contentBlocks":blocks}),
    )
    .await;
    assert_eq!(
        output.wait_for(|m| m["id"] == 1).await["data"]["accepted"],
        true
    );
    output.wait_for(|m| m["type"] == "agent_settled").await;
    let messages = captured.lock().unwrap().clone();
    assert!(messages
        .iter()
        .any(|m| matches!(m, rpi_ai::types::Message::User(u)
        if u.content == rpi_ai::types::UserContent::Blocks(expected.clone()))));
    send(&mut client, json!({"type":"get_messages","id":2})).await;
    let history = output.wait_for(|m| m["id"] == 2).await;
    assert!(history.to_string().contains("middle"));
    assert!(history
        .to_string()
        .contains(blocks[0]["data"].as_str().unwrap()));
    stop(&mut client, task).await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn production_prompt_alias_precedence_and_bad_block_shape_never_fall_back() {
    let (harness, provider) = rpc_test_harness("done", 0.0).await;
    let (mut client, output, task) =
        start_test_rpc(harness, rpi_extensions::UiDialogMailbox::new());
    for (id, payload) in [
        (1, json!({"message":null,"content":"fallback"})),
        (2, json!({"message":"fallback","contentBlocks":null})),
        (3, json!({"contentBlocks":[{"type":"text","text":42}]})),
    ] {
        let mut command = payload;
        command["type"] = json!("prompt");
        command["id"] = json!(id);
        send(&mut client, command).await;
        assert_eq!(output.wait_for(|m| m["id"] == id).await["success"], false);
    }
    assert_eq!(
        provider
            .state()
            .call_count
            .load(std::sync::atomic::Ordering::SeqCst),
        0
    );
    send(
        &mut client,
        json!({"type":"prompt","id":4,"message":"first","content":"second","prompt":"third"}),
    )
    .await;
    assert_eq!(output.wait_for(|m| m["id"] == 4).await["success"], true);
    output.wait_for(|m| m["type"] == "agent_settled").await;
    stop(&mut client, task).await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn production_file_io_dispatch_reads_unsaved_client_text_and_rejects_active_configuration() {
    let router = Arc::new(rpi_tools::file_io::FileIORouter::new());
    let env = Arc::new(rpi_tools::InMemoryExecutionEnv::new());
    let context =
        rpi_tools::ExecutionToolContext::new(env.clone(), Some(env)).with_file_io(router.clone());
    let provider = FauxProvider::new(
        FauxScript::new()
            .with_tool_call("read", json!({"path":"/workspace/unsaved.txt"}))
            .with_text("done"),
    );
    let harness = AgentHarness::create(rpi_harness::types::AgentHarnessOptions {
        model: provider.default_model().clone(),
        models: vec![provider],
        tools: vec![rpi_harness::types::HarnessTool::new(
            rpi_tools::create_read_tool(&context, None),
        )],
        ..Default::default()
    })
    .await
    .unwrap();
    crate::session::register_file_io_router(&harness, &router);
    let (mut client, output, task) =
        start_test_rpc(harness, rpi_extensions::UiDialogMailbox::new());
    let ready = output.wait_for(|m| m["type"] == "ready").await;
    assert_eq!(ready["fileIO"], crate::rpc::file_io::capabilities());
    assert_eq!(
        ready["promptContent"],
        crate::rpc::prompt_content::prompt_capabilities()
    );
    assert_eq!(ready["semantics"]["messageIds"], "sessionEntryId-v1");
    send(
        &mut client,
        json!({"type":"configure_file_io","id":1,"readText":true,"writeText":false}),
    )
    .await;
    assert_eq!(output.wait_for(|m| m["id"] == 1).await["success"], true);
    send(
        &mut client,
        json!({"type":"prompt","id":2,"message":"read unsaved buffer"}),
    )
    .await;
    let request = output.wait_for(|m| m["type"] == "file_io_request").await;
    assert_eq!(request["path"], "/workspace/unsaved.txt");
    send(
        &mut client,
        json!({"type":"configure_file_io","id":3,"readText":false,"writeText":false}),
    )
    .await;
    assert_eq!(output.wait_for(|m| m["id"] == 3).await["success"], false);
    send(
        &mut client,
        json!({"type":"set_model","id":4,"modelId":"other"}),
    )
    .await;
    assert!(output.wait_for(|m| m["id"] == 4).await["error"]
        .as_str()
        .unwrap()
        .contains("active"));
    send(&mut client, json!({"type":"file_io_response","id":"read-reply","requestId":request["requestId"],"result":{"content":"unsaved client buffer\n"}})).await;
    let reply = output.wait_for(|m| m["id"] == "read-reply").await;
    assert_eq!(reply["command"], "file_io_response");
    assert_eq!(reply["data"]["accepted"], true);
    output
        .wait_for(|m| {
            m["type"] == "file_io_request_closed" && m["requestId"] == request["requestId"]
        })
        .await;
    output.wait_for(|m| m["type"] == "agent_settled").await;
    send(&mut client, json!({"type":"get_messages","id":5})).await;
    assert!(output
        .wait_for(|m| m["id"] == 5)
        .await
        .to_string()
        .contains("unsaved client buffer"));
    send(
        &mut client,
        json!({"type":"configure_file_io","id":6,"readText":false,"writeText":false}),
    )
    .await;
    assert_eq!(output.wait_for(|m| m["id"] == 6).await["success"], true);
    stop(&mut client, task).await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn production_file_io_write_and_edit_use_the_same_client_backend() {
    let router = Arc::new(rpi_tools::file_io::FileIORouter::new());
    let env = Arc::new(rpi_tools::InMemoryExecutionEnv::new());
    let context =
        rpi_tools::ExecutionToolContext::new(env.clone(), Some(env)).with_file_io(router.clone());
    let provider = FauxProvider::new(FauxScript::new()
        .with_tool_call("write", json!({"path":"/workspace/buffer.txt","content":"original"}))
        .with_tool_call("edit", json!({"path":"/workspace/buffer.txt","edits":[{"oldText":"original","newText":"edited"}]}))
        .with_text("done"));
    let harness = AgentHarness::create(rpi_harness::types::AgentHarnessOptions {
        model: provider.default_model().clone(),
        models: vec![provider],
        tools: vec![
            rpi_harness::types::HarnessTool::new(rpi_tools::create_write_tool(&context)),
            rpi_harness::types::HarnessTool::new(rpi_tools::create_edit_tool(&context)),
        ],
        ..Default::default()
    })
    .await
    .unwrap();
    crate::session::register_file_io_router(&harness, &router);
    let (mut client, output, task) =
        start_test_rpc(harness, rpi_extensions::UiDialogMailbox::new());
    send(
        &mut client,
        json!({"type":"configure_file_io","id":1,"readText":true,"writeText":true}),
    )
    .await;
    assert_eq!(output.wait_for(|m| m["id"] == 1).await["success"], true);
    send(
        &mut client,
        json!({"type":"prompt","id":2,"message":"write then edit"}),
    )
    .await;
    let mut previous = Value::Null;
    for (operation, content) in [
        ("write_text_file", Some("original")),
        ("read_text_file", None),
        ("write_text_file", Some("edited")),
    ] {
        let request = output
            .wait_for(|m| {
                m["type"] == "file_io_request"
                    && m["requestId"] != previous
                    && !output.messages().iter().any(|closed| {
                        closed["type"] == "file_io_request_closed"
                            && closed["requestId"] == m["requestId"]
                    })
            })
            .await;
        assert_eq!(request["operation"], operation);
        assert_eq!(request["path"], "/workspace/buffer.txt");
        if let Some(content) = content {
            assert_eq!(request["content"], content);
        }
        let result = if operation == "read_text_file" {
            json!({"content":"original"})
        } else {
            json!({})
        };
        let reply_id = format!("reply-{}", request["requestId"].as_str().unwrap());
        send(
            &mut client,
            json!({"type":"file_io_response","id":reply_id,"requestId":request["requestId"],"result":result}),
        )
        .await;
        let reply = output.wait_for(|m| m["id"] == reply_id).await;
        assert_eq!(reply["command"], "file_io_response");
        assert_eq!(reply["data"]["accepted"], true);
        output
            .wait_for(|m| {
                m["type"] == "file_io_request_closed" && m["requestId"] == request["requestId"]
            })
            .await;
        previous = request["requestId"].clone();
    }
    assert_eq!(
        output.wait_for(|m| m["type"] == "agent_settled").await["outcome"],
        "completed"
    );
    stop(&mut client, task).await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn production_validation_is_responsive_and_root_abort_retains_worker_cleanup() {
    use crate::rpc::prompt_content::validation_test_hook::{Gate, ReleaseOnDrop};
    use rpi_tools::file_io::{FileIOErrorCode, FileIOOperation, FileIOReadRange};
    use std::time::Duration;
    for abort_root in [false, true] {
        let id = if abort_root {
            "validation-root-abort"
        } else {
            "validation-command-abort"
        };
        let gate = Gate::register(id);
        let _release = ReleaseOnDrop(gate.clone());
        let (harness, provider) = rpc_test_harness("unused", 0.0).await;
        let retained = harness.clone();
        let router = Arc::new(rpi_tools::file_io::FileIORouter::new());
        crate::session::register_file_io_router(&harness, &router);
        let ui = rpi_extensions::UiDialogMailbox::new();
        let (mut client, output, task) = start_test_rpc(harness, ui.clone());
        send(&mut client, json!({"type":"configure_file_io","id":"initial-config","readText":true,"writeText":false})).await;
        assert_eq!(
            output.wait_for(|m| m["id"] == "initial-config").await["success"],
            true
        );
        // This snapshot must remain client-authoritative after owner drop.
        let backend = router.select(FileIOOperation::Read).await.unwrap().unwrap();
        send(
            &mut client,
            json!({"type":"prompt","id":id,"contentBlocks":[png_block()]}),
        )
        .await;
        tokio::time::timeout(Duration::from_secs(3), gate.entered.cancelled())
            .await
            .unwrap();
        send(&mut client, json!({"type":"configure_file_io","id":"active-config","readText":false,"writeText":false})).await;
        assert!(
            output.wait_for(|m| m["id"] == "active-config").await["error"]
                .as_str()
                .unwrap()
                .contains("active")
        );
        send(
            &mut client,
            json!({"type":"set_model","id":"active-model","modelId":"other"}),
        )
        .await;
        assert!(
            output.wait_for(|m| m["id"] == "active-model").await["error"]
                .as_str()
                .unwrap()
                .contains("active")
        );
        send(&mut client, json!({"type":"ping","id":"during-validation"})).await;
        assert_eq!(
            output.wait_for(|m| m["id"] == "during-validation").await["success"],
            true
        );
        assert!(!gate.worker_finished.is_cancelled());
        if abort_root {
            task.abort();
            assert!(tokio::time::timeout(Duration::from_secs(3), task)
                .await
                .unwrap()
                .unwrap_err()
                .is_cancelled());
            assert!(!ui.is_attached());
            // Cancelling the root must not drop/abort the run's worker owner.
            assert!(!gate.run_finished.is_cancelled());
            assert!(!gate.worker_finished.is_cancelled());
            gate.release();
            tokio::time::timeout(Duration::from_secs(3), gate.run_finished.cancelled())
                .await
                .unwrap();
        } else {
            send(&mut client, json!({"type":"abort","id":"abort-validation"})).await;
            assert_eq!(
                output.wait_for(|m| m["id"] == "abort-validation").await["success"],
                true
            );
            assert!(!gate.run_finished.is_cancelled());
            gate.release();
            tokio::time::timeout(Duration::from_secs(3), gate.run_finished.cancelled())
                .await
                .unwrap();
            let rejection = output.wait_for(|m| m["id"] == id).await;
            assert_eq!(rejection["success"], false);
            assert!(rejection["error"].as_str().unwrap().contains("aborted"));
            stop(&mut client, task).await;
        }
        assert!(gate.worker_finished.is_cancelled());
        assert_eq!(
            provider
                .state()
                .call_count
                .load(std::sync::atomic::Ordering::SeqCst),
            0
        );
        assert!(retained
            .session()
            .storage()
            .find_entries(&EntryQuery::default())
            .await
            .unwrap()
            .is_empty());
        assert!(retained
            .lane("main")
            .snapshot()
            .await
            .unwrap()
            .active
            .is_none());
        assert!(!output
            .messages()
            .iter()
            .any(|m| m["type"] == "agent_settled"
                || (m["id"] == id && m["data"]["accepted"] == true)));
        assert_eq!(
            backend
                .read_text(
                    "/workspace/no-host-fallback.txt",
                    FileIOReadRange::Complete,
                    &tokio_util::sync::CancellationToken::new()
                )
                .await
                .unwrap_err()
                .code,
            FileIOErrorCode::Disconnected
        );
        // Same router still selects client I/O, never a host fallback.
        assert!(router
            .select(FileIOOperation::Read)
            .await
            .unwrap()
            .is_some());
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn production_correlated_file_io_reply_preserves_unknown_field_rejection() {
    let router = Arc::new(rpi_tools::file_io::FileIORouter::new());
    let env = Arc::new(rpi_tools::InMemoryExecutionEnv::new());
    let context =
        rpi_tools::ExecutionToolContext::new(env.clone(), Some(env)).with_file_io(router.clone());
    let provider = FauxProvider::new(
        FauxScript::new()
            .with_tool_call("read", json!({"path":"/workspace/buffer.txt"}))
            .with_text("done"),
    );
    let harness = AgentHarness::create(rpi_harness::types::AgentHarnessOptions {
        model: provider.default_model().clone(),
        models: vec![provider],
        tools: vec![rpi_harness::types::HarnessTool::new(
            rpi_tools::create_read_tool(&context, None),
        )],
        ..Default::default()
    })
    .await
    .unwrap();
    crate::session::register_file_io_router(&harness, &router);
    let (mut client, output, task) =
        start_test_rpc(harness, rpi_extensions::UiDialogMailbox::new());
    send(
        &mut client,
        json!({"type":"configure_file_io","id":1,"readText":true,"writeText":false}),
    )
    .await;
    assert_eq!(output.wait_for(|m| m["id"] == 1).await["success"], true);
    send(
        &mut client,
        json!({"type":"prompt","id":2,"message":"read buffer"}),
    )
    .await;
    let request = output.wait_for(|m| m["type"] == "file_io_request").await;
    send(
        &mut client,
        json!({"type":"file_io_response","id":"bad-reply","requestId":request["requestId"],
        "result":{"content":"MUST NOT BE PERSISTED"},"unknown":true}),
    )
    .await;
    // A known malformed reply retires its waiter with InvalidResponse; accepted
    // means correlated/consumed, not successful file I/O.
    assert_eq!(
        output.wait_for(|m| m["id"] == "bad-reply").await["data"]["accepted"],
        true
    );
    output.wait_for(|m| m["type"] == "agent_settled").await;
    send(&mut client, json!({"type":"get_messages","id":3})).await;
    let history = output.wait_for(|m| m["id"] == 3).await.to_string();
    assert!(
        history.contains("invalid client file I/O response"),
        "{history}"
    );
    assert!(!history.contains("MUST NOT BE PERSISTED"));
    stop(&mut client, task).await;
}

#[tokio::test]
async fn production_parallel_admission_and_abort_before_validation_are_atomic() {
    let (harness, provider) = rpc_test_harness("unused", 0.0).await;
    let (mut client, output, task) =
        start_test_rpc(harness, rpi_extensions::UiDialogMailbox::new());
    // One buffered read on a current-thread runtime: the run task cannot
    // validate/persist until the dispatcher yields after these control frames.
    client.write_all(b"{\"type\":\"prompt\",\"id\":1,\"contentBlocks\":[{\"type\":\"text\",\"text\":\"first\"}]}\n{\"type\":\"prompt\",\"id\":2,\"message\":\"second\"}\n{\"type\":\"abort\",\"id\":3}\n").await.unwrap();
    assert_eq!(output.wait_for(|m| m["id"] == 2).await["success"], false);
    assert_eq!(output.wait_for(|m| m["id"] == 3).await["success"], true);
    let rejected = output.wait_for(|m| m["id"] == 1).await;
    assert_eq!(rejected["success"], false);
    assert!(rejected["error"].as_str().unwrap().contains("aborted"));
    assert_eq!(
        provider
            .state()
            .call_count
            .load(std::sync::atomic::Ordering::SeqCst),
        0
    );
    assert!(!output
        .messages()
        .iter()
        .any(|m| m["type"] == "agent_settled"));
    stop(&mut client, task).await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn production_command_panic_closes_transport_without_a_successful_settlement() {
    let (harness, _) = rpc_test_harness("must not run", 0.0).await;
    let _callback = harness
        .events()
        .on::<rpi_harness::events::RunStartEvent, _>(|_| {
            panic!("simulated admitted execution failure");
        });
    let (mut client, output, task) =
        start_test_rpc(harness, rpi_extensions::UiDialogMailbox::new());
    output.wait_for(|event| event["type"] == "ready").await;
    send(
        &mut client,
        json!({"type":"prompt", "id":"panic", "message":"hello"}),
    )
    .await;
    assert_eq!(
        tokio::time::timeout(std::time::Duration::from_secs(5), task)
            .await
            .unwrap()
            .unwrap(),
        1
    );
    assert!(!output
        .messages()
        .iter()
        .any(|event| event["type"] == "agent_settled"));
}