synaps-engine 0.10.1

Runtime engine — streaming, tools, MCP, skills, extensions, sidecar
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
//! Interrupted turns are recorded as REAL history plus one interruption
//! marker — never as a recap folded into the next user message (the old
//! "ABORT CONTEXT", which current models refuse as a prompt injection).
//!
//! Each test drives the production actor → runtime → Anthropic transport
//! against a loopback SSE stub and asserts the adopted history, the marker,
//! and — for caching — the exact request bytes the provider sees next.

mod session_actor_common;
use session_actor_common::*;

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use agent_engine::engine::interrupt::{is_interruption_marker, InterruptReason};
use agent_engine::session::display::is_event_payload;
use agent_engine::session::{
    ClientKind, ClientMeta, ClientTransport, LocalTransport, SessionCommand, SessionConfig,
    SessionEventWire,
};
use agent_engine::{LlmEvent, SessionEvent, StreamEvent};
use axum::response::IntoResponse;
use futures::StreamExt;
use serde_json::{json, Value};
use serial_test::serial;

// ── fixtures ─────────────────────────────────────────────────────────────────

/// One complete assistant round that calls `name` with `input` (JSON text).
fn sse_tool(id: &str, name: &str, input: &str) -> &'static str {
    let escaped = serde_json::to_string(input).unwrap();
    Box::leak(
        format!(
            concat!(
                "data: {{\"type\":\"message_start\",\"message\":{{\"id\":\"msg_{id}\",\"type\":\"message\",",
                "\"role\":\"assistant\",\"content\":[],\"model\":\"claude-sonnet-4-5\",\"stop_reason\":null,",
                "\"stop_sequence\":null,\"usage\":{{\"input_tokens\":10,\"output_tokens\":0,",
                "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}}}}}\n\n",
                "data: {{\"type\":\"content_block_start\",\"index\":0,",
                "\"content_block\":{{\"type\":\"tool_use\",\"id\":\"{id}\",\"name\":\"{name}\"}}}}\n\n",
                "data: {{\"type\":\"content_block_delta\",\"index\":0,",
                "\"delta\":{{\"type\":\"input_json_delta\",\"partial_json\":{escaped}}}}}\n\n",
                "data: {{\"type\":\"content_block_stop\",\"index\":0}}\n\n",
                "data: {{\"type\":\"message_delta\",\"delta\":{{\"stop_reason\":\"tool_use\",",
                "\"stop_sequence\":null}},\"usage\":{{\"input_tokens\":10,\"output_tokens\":5,",
                "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}}}\n\n",
                "data: {{\"type\":\"message_stop\"}}\n\n",
            ),
            id = id,
            name = name,
            escaped = escaped,
        )
        .into_boxed_str(),
    )
}

fn sse_read_missing() -> &'static str {
    sse_tool(
        "toolu_read",
        "read",
        r#"{"path":"/nonexistent/synaps-interrupt-fixture"}"#,
    )
}

type Bodies = Arc<Mutex<Vec<Value>>>;

/// Sequenced stub (hit `i` serves `bodies[min(i, len-1)]`) that records
/// every request body. Only hit `endless` (if any) keeps the connection open
/// with keep-alives after its body — the cancel fixture; every other body
/// closes (the SSE parser reads until the connection ends).
async fn capture_stub(
    bodies: &'static [&'static str],
    endless: Option<usize>,
) -> (String, Arc<AtomicUsize>, Bodies) {
    let hits = Arc::new(AtomicUsize::new(0));
    let seen: Bodies = Arc::new(Mutex::new(Vec::new()));
    let (hits_c, seen_c) = (Arc::clone(&hits), Arc::clone(&seen));
    let app = axum::Router::new().fallback(move |body: axum::body::Bytes| {
        let (hits, seen) = (Arc::clone(&hits_c), Arc::clone(&seen_c));
        async move {
            let i = hits.fetch_add(1, Ordering::SeqCst);
            if let Ok(v) = serde_json::from_slice::<Value>(&body) {
                seen.lock().unwrap().push(v);
            }
            let idx = i.min(bodies.len() - 1);
            let body = bodies[idx];
            if endless == Some(i) {
                let stream = futures::stream::once(async move {
                    Ok::<_, std::io::Error>(axum::body::Bytes::from(body))
                })
                .chain(futures::stream::unfold((), |()| async {
                    tokio::time::sleep(Duration::from_millis(200)).await;
                    Some((Ok(axum::body::Bytes::from(": keep-alive\n\n")), ()))
                }));
                return axum::response::Response::builder()
                    .status(200)
                    .header("content-type", "text/event-stream")
                    .body(axum::body::Body::from_stream(stream))
                    .unwrap();
            }
            (
                axum::http::StatusCode::OK,
                [("content-type", "text/event-stream")],
                body.to_string(),
            )
                .into_response()
        }
    });
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
    (format!("http://{addr}"), hits, seen)
}

async fn attach(handle: &agent_engine::session::SessionHandle) -> LocalTransport {
    let (mut t, _) = LocalTransport::attach(handle.clone(), ClientMeta::new(ClientKind::Test))
        .await
        .unwrap();
    until(&mut t, |e| {
        matches!(e, SessionEventWire::ClientJoined { .. })
    })
    .await;
    t
}

fn is_text(e: &SessionEventWire) -> bool {
    matches!(
        e,
        SessionEventWire::Stream(StreamEvent::Llm(LlmEvent::Text(_)))
    )
}

/// Cancel, then collect through the cancel's `Idle`.
async fn cancel(t: &mut LocalTransport) -> Vec<agent_engine::session::Envelope> {
    t.send(SessionCommand::Cancel).await.unwrap();
    until(t, |e| matches!(e, SessionEventWire::Idle)).await
}

fn aborted(seen: &[agent_engine::session::Envelope]) -> Vec<bool> {
    seen.iter()
        .filter_map(|e| match e.event {
            SessionEventWire::Aborted { context_saved } => Some(context_saved),
            _ => None,
        })
        .collect()
}

fn text_of(m: &Value) -> String {
    match &m["content"] {
        Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

/// Every `tool_use` id has exactly one `tool_result` later in history.
fn assert_tools_paired(msgs: &[Arc<Value>]) {
    let blocks = |ty: &'static str, key: &'static str| -> Vec<String> {
        msgs.iter()
            .filter_map(|m| m["content"].as_array())
            .flat_map(|b| b.iter())
            .filter(|b| b["type"] == ty)
            .map(|b| b[key].as_str().unwrap_or("").to_string())
            .collect()
    };
    let mut uses = blocks("tool_use", "id");
    let mut results = blocks("tool_result", "tool_use_id");
    uses.sort();
    results.sort();
    assert_eq!(uses, results, "tool_use/tool_result pairing");
}

fn assert_no_recap(msgs: &[Arc<Value>]) {
    let all = serde_json::to_string(msgs).unwrap();
    assert!(!all.contains("ABORT CONTEXT"), "no recap in history: {all}");
}

fn strip_cache_control(v: &Value) -> Value {
    match v {
        Value::Object(o) => Value::Object(
            o.iter()
                .filter(|(k, _)| k.as_str() != "cache_control")
                .map(|(k, v)| (k.clone(), strip_cache_control(v)))
                .collect(),
        ),
        Value::Array(a) => Value::Array(a.iter().map(strip_cache_control).collect()),
        other => other.clone(),
    }
}

// ── tests ────────────────────────────────────────────────────────────────────

/// Esc mid-reply: the partial reply stays as a REAL assistant message, the
/// marker follows, usage for the interrupted round is billed, nothing is
/// folded into the next message.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn cancel_mid_reply_keeps_the_partial_reply_and_appends_the_marker() {
    let _h = Home::new();
    let (url, _) = stub(SSE_PREFIX, true).await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);
    let host = host().await;
    let handle = host.create_session(cfg()).await.unwrap();
    let mut a = attach(&handle).await;

    a.send(submit("hello")).await.unwrap();
    until(&mut a, is_text).await;
    let seen = cancel(&mut a).await;

    assert_eq!(aborted(&seen), vec![true], "one Aborted, partial work kept");
    let conv = last_conversation(&seen);
    let msgs = &conv.api_messages;
    assert_eq!(msgs.len(), 3, "{msgs:#?}");
    assert_eq!(msgs[0]["content"], "hello");
    assert_eq!(msgs[1]["role"], "assistant");
    assert_eq!(msgs[1]["content"], json!([{"type": "text", "text": "hi"}]));
    assert_eq!(msgs[2]["role"], "user");
    assert_eq!(msgs[2]["content"], InterruptReason::User.marker());
    assert!(conv.abort_context.is_none());
    assert!(
        conv.tokens.input > 0,
        "the interrupted round's usage is billed"
    );
    assert_no_recap(msgs);
    end(&mut a).await;
}

/// A steer typed mid-reply and not yet delivered when Esc lands is DEQUEUED
/// (the UI shows "dequeued: …") — it never enters history after the cancel,
/// whichever point of the turn the cancel interrupts.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn undelivered_steer_is_dequeued_not_slipped_into_history() {
    let _h = Home::new();
    let (url, _) = stub(SSE_PREFIX, true).await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);
    let host = host().await;
    let handle = host.create_session(cfg()).await.unwrap();
    let mut a = attach(&handle).await;

    a.send(submit("hello")).await.unwrap();
    until(&mut a, is_text).await;
    a.send(SessionCommand::Steer {
        text: "actually do Y".into(),
    })
    .await
    .unwrap();
    until(&mut a, |e| matches!(e, SessionEventWire::Steered { .. })).await;
    let seen = cancel(&mut a).await;

    assert!(
        seen.iter().any(|e| matches!(
            &e.event,
            SessionEventWire::Dequeued { text } if text == "actually do Y"
        )),
        "the undelivered steer is dequeued"
    );
    let conv = last_conversation(&seen);
    assert!(conv.queued_message.is_none());
    let texts: Vec<String> = conv.api_messages.iter().map(|m| text_of(m)).collect();
    assert!(
        !texts.iter().any(|t| t.contains("actually do Y")),
        "a dequeued steer never enters history: {texts:?}"
    );
    assert_eq!(texts.last().unwrap(), InterruptReason::User.marker());
    end(&mut a).await;
}

/// The old recap dropped every completed tool round of the aborted turn.
/// Now the round is kept verbatim.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn cancel_after_a_tool_round_keeps_the_round() {
    let _h = Home::new();
    let bodies: &'static [&'static str] = Box::leak(Box::new([sse_read_missing(), SSE_PREFIX]));
    let (url, hits) = stub_seq_endless_last(bodies).await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);
    let host = host().await;
    let handle = host.create_session(cfg()).await.unwrap();
    let mut a = attach(&handle).await;

    a.send(submit("look at the file")).await.unwrap();
    until(&mut a, is_text).await; // second round is streaming
    let seen = cancel(&mut a).await;

    assert_eq!(hits.load(Ordering::SeqCst), 2);
    let msgs = last_conversation(&seen).api_messages;
    let roles: Vec<&str> = msgs.iter().map(|m| m["role"].as_str().unwrap()).collect();
    assert_eq!(
        roles,
        ["user", "assistant", "user", "assistant", "user"],
        "{msgs:#?}"
    );
    assert_eq!(msgs[1]["content"][0]["type"], "tool_use");
    assert_eq!(msgs[2]["content"][0]["type"], "tool_result");
    assert_eq!(msgs[3]["content"], json!([{"type": "text", "text": "hi"}]));
    assert_eq!(msgs[4]["content"], InterruptReason::User.marker());
    assert_tools_paired(&msgs);
    assert_no_recap(&msgs);
    end(&mut a).await;
}

/// Prompt caching: the first request after an abort re-sends, byte for byte
/// (modulo the single moving cache marker), everything the cancelled
/// request sent — tools, system, and its whole message list — and only
/// appends after it. (The old path restarted from the turn's first user
/// message, so the tool round fell out of the shared prefix.)
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn next_request_after_cancel_extends_the_cancelled_requests_prefix() {
    let _h = Home::new();
    let bodies: &'static [&'static str] =
        Box::leak(Box::new([sse_read_missing(), SSE_PREFIX, SSE_HI]));
    // Hits: 0 = tool round, 1 = cancelled round (held open), 2 = next turn.
    let (url, hits, seen_bodies) = capture_stub(bodies, Some(1)).await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);
    let host = host().await;
    let handle = host.create_session(cfg()).await.unwrap();
    let mut a = attach(&handle).await;

    a.send(submit("look at the file")).await.unwrap();
    until(&mut a, is_text).await;
    cancel(&mut a).await;
    a.send(submit("actually, do Y")).await.unwrap();
    until(&mut a, |e| {
        matches!(
            e,
            SessionEventWire::Stream(StreamEvent::Session(SessionEvent::Done))
        )
    })
    .await;
    until(&mut a, |e| matches!(e, SessionEventWire::Idle)).await;

    assert_eq!(hits.load(Ordering::SeqCst), 3);
    let reqs = seen_bodies.lock().unwrap().clone();
    let (cancelled, next) = (&reqs[1], &reqs[2]);
    assert_eq!(
        next["system"], cancelled["system"],
        "system prefix identical"
    );
    assert_eq!(next["tools"], cancelled["tools"], "tools prefix identical");

    let before = cancelled["messages"].as_array().unwrap();
    let after = next["messages"].as_array().unwrap();
    assert!(after.len() > before.len());
    for (i, (b, n)) in before.iter().zip(after).enumerate() {
        assert_eq!(
            strip_cache_control(b),
            strip_cache_control(n),
            "message {i} changed between the cancelled request and the next one"
        );
    }
    // Appended: the partial reply, then marker + new prompt (the Anthropic
    // path merges adjacent user turns into one message).
    let tail = &after[before.len()..];
    assert_eq!(tail[0]["role"], "assistant");
    assert_eq!(
        strip_cache_control(&tail[0]["content"]),
        json!([{"type": "text", "text": "hi"}])
    );
    let last = strip_cache_control(tail.last().unwrap());
    assert_eq!(last["role"], "user");
    assert_eq!(
        last["content"],
        json!([
            {"type": "text", "text": InterruptReason::User.marker()},
            {"type": "text", "text": "actually, do Y"}
        ])
    );
    assert!(!serde_json::to_string(next)
        .unwrap()
        .contains("ABORT CONTEXT"));
    end(&mut a).await;
}

/// The cost cap cancels from INSIDE the stream handler. The drain must not
/// re-check the cap (no recursive cancel) and records its own marker.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn cost_cap_interrupts_once_with_its_own_marker() {
    let _h = Home::new();
    let bodies: &'static [&'static str] = Box::leak(Box::new([sse_read_missing(), SSE_PREFIX]));
    let (url, _) = stub_seq_endless_last(bodies).await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);
    let host = host().await;
    let handle = host
        .create_session(SessionConfig {
            max_session_cost: Some(1e-9),
            ..cfg()
        })
        .await
        .unwrap();
    let mut a = attach(&handle).await;

    a.send(submit("spend")).await.unwrap();
    let seen = until(&mut a, |e| matches!(e, SessionEventWire::Idle)).await;
    // Anything still in flight after the first Idle.
    let late = drain_for(&mut a, Duration::from_millis(1500)).await;
    let all: Vec<_> = seen.iter().chain(late.iter()).cloned().collect();

    let caps = all
        .iter()
        .filter(|e| matches!(e.event, SessionEventWire::CostCapReached { .. }))
        .count();
    assert_eq!(caps, 1, "exactly one cost-cap breach");
    assert_eq!(
        aborted(&all).len(),
        1,
        "exactly one Aborted (no recursive cancel)"
    );
    let msgs = last_conversation(&all).api_messages;
    assert_eq!(
        msgs.last().unwrap()["content"],
        InterruptReason::CostCap.marker(),
        "{msgs:#?}"
    );
    assert_eq!(
        msgs[1]["content"][0]["type"], "tool_use",
        "the round survives"
    );
    assert_tools_paired(&msgs);
    assert_no_recap(&msgs);
    end(&mut a).await;
}

/// A tool blocked on a host prompt: cancel answers it `None`, the turn
/// unwinds, the prompt is resolved for clients, history stays paired.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn pending_prompt_is_resolved_and_the_turn_unwinds() {
    let _h = Home::new();
    let bodies: &'static [&'static str] = Box::leak(Box::new([SSE_PROMPT_TOOL_USE, SSE_HI]));
    let (url, hits) = stub_seq(bodies).await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);
    let host = prompt_host().await;
    let handle = host.create_session(cfg()).await.unwrap();
    let mut a = attach(&handle).await;

    a.send(submit("needs a secret")).await.unwrap();
    let seen = until(&mut a, |e| matches!(e, SessionEventWire::Prompt(_))).await;
    let id = prompt_id(seen.last().unwrap()).unwrap();
    let started = std::time::Instant::now();
    let seen = cancel(&mut a).await;

    assert!(
        started.elapsed() < Duration::from_secs(5),
        "cancel must not hang on the prompt ({:?})",
        started.elapsed()
    );
    assert!(seen.iter().any(|e| matches!(
        e.event,
        SessionEventWire::PromptResolved { prompt_id } if prompt_id == id
    )));
    assert_eq!(aborted(&seen).len(), 1);
    assert_eq!(
        hits.load(Ordering::SeqCst),
        1,
        "no follow-up request after cancel"
    );
    let conv = last_conversation(&seen);
    assert_tools_paired(&conv.api_messages);
    assert_eq!(tool_results(&conv).len(), 1);
    assert_eq!(
        conv.api_messages.last().unwrap()["content"],
        InterruptReason::User.marker()
    );
    end(&mut a).await;
}

/// A tool canceled mid-execution after streaming output: the partial output
/// is kept but labelled — it must never read as a completed result.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn tool_canceled_mid_output_is_labelled_partial() {
    let _h = Home::new();
    let bash = sse_tool(
        "toolu_bash",
        "bash",
        r#"{"command":"printf 'partial-out\\n'; sleep 30"}"#,
    );
    let bodies: &'static [&'static str] = Box::leak(Box::new([bash, SSE_HI]));
    let (url, _) = stub_seq(bodies).await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);
    let host = host().await;
    let handle = host.create_session(cfg()).await.unwrap();
    let mut a = attach(&handle).await;

    a.send(submit("run it")).await.unwrap();
    until(&mut a, |e| {
        matches!(
            e,
            SessionEventWire::Stream(StreamEvent::Llm(LlmEvent::ToolResultDelta { delta, .. }))
                if delta.contains("partial-out")
        )
    })
    .await;
    let seen = cancel(&mut a).await;

    let conv = last_conversation(&seen);
    let results = tool_results(&conv);
    assert_eq!(results.len(), 1, "{:#?}", conv.api_messages);
    let r = &results[0];
    assert!(r.starts_with("partial-out"), "partial output kept: {r}");
    assert!(
        r.contains("Canceled by user before the tool finished; the output above is partial."),
        "labelled partial: {r}"
    );
    assert_eq!(
        conv.api_messages.last().unwrap()["content"],
        InterruptReason::User.marker()
    );
    end(&mut a).await;
}

/// Steers an event into the running turn, then stalls until cancelled.
struct EventThenStallTool;

#[async_trait::async_trait]
impl agent_engine::Tool for EventThenStallTool {
    fn name(&self) -> &str {
        "event_then_stall"
    }
    fn description(&self) -> &str {
        "pushes an event then waits"
    }
    fn parameters(&self) -> Value {
        json!({"type": "object"})
    }
    fn origin(&self) -> agent_engine::tools::ToolOrigin {
        agent_engine::tools::ToolOrigin::Builtin
    }
    async fn execute(
        &self,
        _params: Value,
        ctx: agent_engine::ToolContext,
    ) -> agent_engine::Result<String> {
        let queue = ctx.capabilities.event_queue.expect("runtime event queue");
        queue
            .push(agent_engine::events::Event::simple(
                "watcher",
                "build finished: 3 warnings",
                None,
            ))
            .expect("push");
        tokio::time::sleep(Duration::from_secs(60)).await;
        Ok("unreachable".into())
    }
}

/// An event steered into the stream but never drained by the engine (it
/// only drains at round boundaries) used to die with the steering channel on
/// cancel. It now lands in history right after the marker.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn steered_event_the_engine_never_drained_is_kept_after_the_marker() {
    let _h = Home::new();
    let tool = sse_tool("toolu_evt", "event_then_stall", "{}");
    let bodies: &'static [&'static str] = Box::leak(Box::new([tool, SSE_HI]));
    let (url, _) = stub_seq(bodies).await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);
    let host = host().await;
    host.parts()
        .tools
        .write()
        .await
        .register(Arc::new(EventThenStallTool));
    let handle = host
        .create_session(SessionConfig {
            // No auto-turn after the cancel: we only inspect history.
            ..cfg()
        })
        .await
        .unwrap();
    let mut a = attach(&handle).await;

    a.send(submit("wait for the build")).await.unwrap();
    until(&mut a, |e| matches!(e, SessionEventWire::External(_))).await;
    let seen = cancel(&mut a).await;

    let msgs = last_conversation(&seen).api_messages;
    let n = msgs.len();
    assert!(n >= 5, "{msgs:#?}");
    assert!(is_interruption_marker(&text_of(&msgs[n - 2])), "{msgs:#?}");
    let event = text_of(&msgs[n - 1]);
    assert!(is_event_payload(&event), "{event}");
    assert!(event.contains("build finished: 3 warnings"), "{event}");
    assert_tools_paired(&msgs);
    end(&mut a).await;
}

/// A session saved by an older Synaps with an `abort_context` recap is
/// migrated on `--continue`: recap dropped, marker appended, and the next
/// request carries no recap.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn legacy_abort_context_session_is_migrated_on_continue() {
    let _h = Home::new();
    let (url, _, seen_bodies) = capture_stub(Box::leak(Box::new([SSE_HI])), None).await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);

    let mut legacy = agent_engine::core::session::Session::new(MODEL, "low", None);
    legacy.api_messages = vec![Arc::new(json!({"role": "user", "content": "do X"}))];
    legacy.abort_context = Some(
        "(System note — ABORT CONTEXT: your previous response was interrupted …)\n\
         - you had started writing: Let me"
            .into(),
    );
    legacy.save().await.unwrap();

    let host = host().await;
    let handle = host
        .create_session(SessionConfig {
            continue_session: Some(Some(legacy.id.clone())),
            persist: true,
            ..cfg()
        })
        .await
        .unwrap();
    let (mut a, snap) = LocalTransport::attach(handle.clone(), ClientMeta::new(ClientKind::Test))
        .await
        .unwrap();
    let msgs = &snap.conversation.api_messages;
    assert_eq!(msgs.len(), 2, "{msgs:#?}");
    assert_eq!(msgs[1]["content"], InterruptReason::Unknown.marker());
    assert!(snap.conversation.abort_context.is_none());

    a.send(submit("carry on")).await.unwrap();
    until(&mut a, |e| matches!(e, SessionEventWire::Idle)).await;
    let body = seen_bodies.lock().unwrap().last().cloned().unwrap();
    let wire = serde_json::to_string(&body).unwrap();
    assert!(!wire.contains("ABORT CONTEXT"), "{wire}");
    assert!(wire.contains(InterruptReason::Unknown.marker()), "{wire}");

    // Saved back without the legacy field.
    let saved = agent_engine::core::session::Session::load(&legacy.id).unwrap();
    assert!(saved.abort_context.is_none());
    end(&mut a).await;
}

/// `on_message_complete` handler that holds the engine between "the final
/// response came back" and "the turn ended" until released: the exact
/// window in which Esc lands a moment too late.
struct GateHook {
    entered: tokio::sync::Notify,
    release: tokio::sync::Notify,
}

#[async_trait::async_trait]
impl agent_engine::extensions::runtime::ExtensionHandler for GateHook {
    fn id(&self) -> &str {
        "gate-hook"
    }
    async fn handle(
        &self,
        _event: &agent_engine::extensions::hooks::events::HookEvent,
    ) -> agent_engine::extensions::hooks::events::HookResult {
        self.entered.notify_one();
        self.release.notified().await;
        agent_engine::extensions::hooks::events::HookResult::Continue
    }
    async fn shutdown(&self) {}
}

/// Esc a moment too late: the answer was complete (the engine is past the
/// provider call, in the `on_message_complete` hook) when the cancel reached
/// the turn. The complete answer is kept with NO interruption marker, and
/// clients get the turn's `Done`, not `Aborted`. (Review finding: the drain
/// used to append "[Request interrupted by user]" after a finished answer.)
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn cancel_that_races_a_finished_answer_marks_nothing() {
    use agent_engine::extensions::hooks::events::HookKind;
    let _h = Home::new();
    let (url, _) = stub(SSE_HI, false).await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);
    let host = host().await;
    let gate = Arc::new(GateHook {
        entered: tokio::sync::Notify::new(),
        release: tokio::sync::Notify::new(),
    });
    let mut perms = agent_engine::extensions::permissions::PermissionSet::new();
    perms.grant(HookKind::OnMessageComplete.required_permission());
    host.parts()
        .hook_bus
        .subscribe(HookKind::OnMessageComplete, gate.clone(), None, None, perms)
        .await
        .unwrap();
    let handle = host.create_session(cfg()).await.unwrap();
    let mut a = attach(&handle).await;

    a.send(submit("hello")).await.unwrap();
    tokio::time::timeout(Duration::from_secs(10), gate.entered.notified())
        .await
        .expect("the engine reached on_message_complete");
    a.send(SessionCommand::Cancel).await.unwrap();
    // Let the actor cancel the token and start draining, then let the
    // engine finish its (already complete) turn inside the drain budget.
    tokio::time::sleep(Duration::from_millis(150)).await;
    gate.release.notify_one();
    let seen = until(&mut a, |e| matches!(e, SessionEventWire::Idle)).await;

    assert!(aborted(&seen).is_empty(), "not an interruption: {seen:#?}");
    assert!(
        seen.iter().any(|e| matches!(
            e.event,
            SessionEventWire::Stream(StreamEvent::Session(SessionEvent::Done))
        )),
        "clients get the turn's Done"
    );
    let msgs = last_conversation(&seen).api_messages;
    assert_eq!(msgs.len(), 2, "{msgs:#?}");
    assert_eq!(msgs[1]["role"], "assistant");
    assert_eq!(msgs[1]["content"], json!([{"type": "text", "text": "hi"}]));
    assert!(!msgs.iter().any(|m| m["content"]
        .as_str()
        .is_some_and(is_interruption_marker)));
    end(&mut a).await;
}

/// A cancel that was not the user's says so in the canceled tool result:
/// a reload's checkpoint cuts a running tool and the result reads "Canceled
/// (Synaps restarted)…", matching the marker — never "Canceled by user".
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn a_tool_cut_by_a_reload_says_so_not_by_user() {
    use agent_engine::session::CheckpointReason;
    let _h = Home::new();
    let bash = sse_tool(
        "toolu_bash",
        "bash",
        r#"{"command":"printf 'partial-out\\n'; sleep 30"}"#,
    );
    let bodies: &'static [&'static str] = Box::leak(Box::new([bash, SSE_HI]));
    let (url, _) = stub_seq(bodies).await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);
    let host = host().await;
    let handle = host.create_session(cfg()).await.unwrap();
    let mut a = attach(&handle).await;

    a.send(submit("run it")).await.unwrap();
    until(&mut a, |e| {
        matches!(
            e,
            SessionEventWire::Stream(StreamEvent::Llm(LlmEvent::ToolResultDelta { delta, .. }))
                if delta.contains("partial-out")
        )
    })
    .await;
    a.send(SessionCommand::Checkpoint {
        reason: CheckpointReason::Reload,
    })
    .await
    .unwrap();
    let seen = until(&mut a, |e| matches!(e, SessionEventWire::Idle)).await;

    let conv = last_conversation(&seen);
    let results = tool_results(&conv);
    assert_eq!(results.len(), 1, "{:#?}", conv.api_messages);
    let r = &results[0];
    assert!(r.starts_with("partial-out"), "partial output kept: {r}");
    assert!(
        r.contains("[Canceled (Synaps restarted) before the tool finished; the output above is partial."),
        "the cause, not the user: {r}"
    );
    assert!(!r.contains("by user"), "{r}");
    assert_eq!(
        conv.api_messages.last().unwrap()["content"],
        InterruptReason::Restart.marker()
    );
    end(&mut a).await;
}

/// Every OTHER attached client learns the prompt that started a user turn
/// (`TurnStarted.user_text`): a mirror never saw it, and the next reply's
/// text glued onto the previous one. The attach replay's copy carries none
/// (the snapshot's history already has it).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn every_client_learns_the_prompt_of_a_user_turn() {
    let _h = Home::new();
    let (url, _) = stub(SSE_PREFIX, true).await;
    std::env::set_var("SYNAPS_ANTHROPIC_BASE_URL", &url);
    let host = host().await;
    let handle = host.create_session(cfg()).await.unwrap();
    let mut a = attach(&handle).await;
    let mut b = attach(&handle).await;

    a.send(submit("hello from A")).await.unwrap();
    let seen = until(&mut b, |e| matches!(e, SessionEventWire::TurnStarted { .. })).await;
    match &seen.last().unwrap().event {
        SessionEventWire::TurnStarted { user_text, .. } => {
            assert_eq!(user_text.as_deref(), Some("hello from A"));
        }
        _ => unreachable!(),
    }
    until(&mut a, is_text).await;
    let (_c, snap) = LocalTransport::attach(handle.clone(), ClientMeta::new(ClientKind::Test))
        .await
        .unwrap();
    let replayed = snap
        .replay
        .iter()
        .find_map(|e| match &e.event {
            SessionEventWire::TurnStarted { user_text, .. } => Some(user_text.clone()),
            _ => None,
        })
        .expect("the turn start is replayed");
    assert_eq!(replayed, None, "the replay does not repeat the prompt");
    drop(b);
    end(&mut a).await;
}