mindfork 0.11.0

A terminal AI chat written in Rust: local models via llama.cpp or OpenAI, Anthropic, Gemini and Grok in the cloud, with persistent memory, notes, RAG and tools.
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
//! Orchestrator tests — impersonation (request building + streaming). Part of the [`super`]
//! module (fixtures in mod.rs). See docs/history/refactoring-god-objects.md, stage 3.

use super::*;

#[test]
fn impersonation_request_swaps_roles_and_sets_system() {
    let profile = Profile::new("P", "sys ассистента");
    let mut chat = Chat::from_profile(&profile, "c");
    chat.push_message(Message::assistant("Привет! Чем помочь?"));
    chat.push_message(Message::user("Расскажи о Rust"));
    chat.push_message(Message::assistant("Rust — системный язык…"));

    let req = build_impersonation_request(
        &chat,
        None,
        "Ты — пользователь".into(),
        "",
        SamplingConfig::default(),
        None,
        crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru),
    );

    assert_eq!(req.system.as_deref(), Some("Ты — пользователь"));
    assert!(req.tools.is_empty());
    // Roles are swapped: assistant↔user.
    assert_eq!(req.messages.len(), 3);
    assert_eq!(
        req.messages[0].role,
        crate::shared::api::contract::ApiRole::User
    );
    assert_eq!(req.messages[0].content, "Привет! Чем помочь?");
    assert_eq!(
        req.messages[1].role,
        crate::shared::api::contract::ApiRole::Assistant
    );
    assert_eq!(req.messages[1].content, "Расскажи о Rust");
    assert_eq!(
        req.messages[2].role,
        crate::shared::api::contract::ApiRole::User
    );
}

#[test]
fn impersonation_request_disables_reasoning() {
    // Impersonation discards "thoughts", so the request must suppress reasoning —
    // otherwise models with thinking "baked into" the template (Gemma/Qwen) spend their whole
    // budget on reasoning_content, and the reply text comes back empty (an empty preview).
    let profile = Profile::new("P", "sys");
    let chat = Chat::from_profile(&profile, "c");
    let req = build_impersonation_request(
        &chat,
        None,
        "Ты — пользователь".into(),
        "",
        // The user left "thoughts" enabled in the impersonation sampling —
        // the request must still turn them off.
        SamplingConfig {
            thinking: Some(true),
            ..Default::default()
        },
        None,
        crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru),
    );
    assert_eq!(req.sampling.thinking, Some(false));
    assert_eq!(req.sampling.reasoning_budget, Some(0));
    assert_eq!(
        req.sampling.reasoning_effort,
        Some(crate::entities::sampling::ReasoningEffort::None)
    );
}

#[test]
fn impersonation_request_with_seed_adds_continuation_hint() {
    let profile = Profile::new("P", "sys");
    let chat = Chat::from_profile(&profile, "c");
    let req = build_impersonation_request(
        &chat,
        None,
        "Ты — пользователь".into(),
        "Мне нужно ",
        SamplingConfig::default(),
        None,
        crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru),
    );
    let system = req.system.unwrap();
    assert!(system.contains("Ты — пользователь"));
    assert!(
        system.contains("Мне нужно"),
        "the seed made it into the instruction"
    );
}

#[test]
fn impersonation_request_includes_user_hint() {
    let profile = Profile::new("P", "sys");
    let chat = Chat::from_profile(&profile, "c");
    let req = build_impersonation_request(
        &chat,
        None,
        "Ты — пользователь".into(),
        "",
        SamplingConfig::default(),
        Some("Известное о человеке: черты — скептик"),
        crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru),
    );
    let system = req.system.unwrap();
    assert!(system.contains("Ты — пользователь"));
    // The interlocutor model is mixed into the impersonation system prompt.
    assert!(system.contains("черты — скептик"));
}

/// A chat whose older half is folded away, plus the view over it. Shaped like a
/// real one: the greeting, two exchanges folded, one exchange verbatim — and the
/// boundary on a `User` message, which is what `plan_cut` guarantees.
fn compacted_chat() -> Chat {
    let profile = Profile::new("P", "sys");
    let mut chat = Chat::from_profile(&profile, "c");
    chat.push_message(Message::assistant("Привет! Чем помочь?"));
    chat.push_message(Message::user("Первый вопрос"));
    chat.push_message(Message::assistant("Первый ответ"));
    chat.push_message(Message::user("Второй вопрос"));
    chat.push_message(Message::assistant("Второй ответ"));
    let boundary = 3; // The second user message — a cut always lands on a User one.
    chat.compaction = Some(crate::entities::chat::Compaction {
        summary: "Ранее: обсудили первый вопрос.".into(),
        upto: boundary,
        boundary_id: chat.messages[boundary].id,
        compacted_at: chrono::Utc::now(),
        rolls: 1,
    });
    chat
}

#[test]
fn impersonation_folds_the_compacted_prefix_and_carries_the_summary() {
    let chat = compacted_chat();
    let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru);
    let req = build_impersonation_request(
        &chat,
        chat.compaction_view(true),
        "Ты — пользователь".into(),
        "",
        SamplingConfig::default(),
        None,
        loc,
    );

    // Only the verbatim tail is sent, and the folded part is not in it. The
    // tail is messages[3..]: the cut's user message, swapped into a leading
    // assistant turn, moves into the persona (gemma-impersonation §3.1); the
    // reply after it is the one turn sent.
    assert_eq!(
        req.messages.len(),
        1,
        "the tail is messages[3..], its opening folded"
    );
    let sent: Vec<&str> = req.messages.iter().map(|m| m.content.as_str()).collect();
    assert_eq!(sent, vec!["Второй ответ"]);
    assert!(
        !sent.iter().any(|t| t.contains("Первый")),
        "the folded exchange must not be sent verbatim: {sent:?}"
    );
    // …and what replaced it is in the system prompt, after the persona and
    // before the opening the swap moved there.
    let system = req.system.unwrap();
    assert!(system.starts_with("Ты — пользователь"));
    assert!(system.contains("Ранее: обсудили первый вопрос."));
    assert!(
        system.contains("Второй вопрос"),
        "the opening, in the persona: {system}"
    );
    assert!(
        system.find("Ранее: обсудили").unwrap() < system.find("Второй вопрос").unwrap(),
        "the summary before the opening"
    );
}

/// Impersonation has **no** tools, so the block must tell the model to work from
/// the summary rather than point it at `history_read`/`history_search` it cannot
/// call — the dead-end wording the whole S12 gate exists to prevent.
#[test]
fn impersonation_summary_block_does_not_offer_the_read_back_tools() {
    let chat = compacted_chat();
    let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru);
    let req = build_impersonation_request(
        &chat,
        chat.compaction_view(true),
        "Ты — пользователь".into(),
        "",
        SamplingConfig::default(),
        None,
        loc,
    );
    let system = req.system.unwrap();
    assert!(req.tools.is_empty(), "impersonation never offers tools");
    assert!(system.contains(loc.t("compaction.block.no_tools")));
    assert!(
        !system.contains("history_read") && !system.contains("history_search"),
        "must not name tools this request does not carry: {system}"
    );
}

/// The master switch off (or nothing folded) → byte-for-byte the request that
/// was built before compression existed.
#[test]
fn impersonation_is_unchanged_when_compaction_is_off() {
    let chat = compacted_chat();
    let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru);
    let build = |view| {
        build_impersonation_request(
            &chat,
            view,
            "Ты — пользователь".into(),
            "",
            SamplingConfig::default(),
            None,
            loc,
        )
    };
    let off = build(chat.compaction_view(false));
    assert_eq!(off.system.as_deref(), Some("Ты — пользователь"));
    assert_eq!(off.messages.len(), 5, "the whole history is sent");
    // The stored summary is dormant, not discarded: switching back brings it
    // in — the tail's two messages, the cut's opening folded into the persona.
    assert_eq!(build(chat.compaction_view(true)).messages.len(), 1);
}

/// A cut always lands on a `User` message, and impersonation **swaps** roles —
/// so the request used to start with an assistant turn: accepted by Anthropic,
/// native Gemini and OpenAI Responses, refused by Gemma 3's template with a
/// `400` (docs/research/gemma-impersonation.md §2.1). The opening is folded
/// into the persona now and the list opens with the assistant's reply. The
/// tail matters as much as the head: Anthropic treats a **trailing** assistant
/// turn as a prefill and answers with nothing. Both are what a future change
/// to the cut could reintroduce silently — hence this test rather than a
/// comment.
#[test]
fn compacted_impersonation_opens_with_user_and_ends_with_user() {
    use crate::shared::api::contract::ApiRole;
    let chat = compacted_chat();
    let req = build_impersonation_request(
        &chat,
        chat.compaction_view(true),
        "Ты — пользователь".into(),
        "",
        SamplingConfig::default(),
        None,
        crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru),
    );
    assert_eq!(req.messages.first().unwrap().role, ApiRole::User);
    assert_eq!(
        req.messages.last().unwrap().role,
        ApiRole::User,
        "a trailing assistant turn reads as a prefill — the model would continue it instead of \
         writing the next message"
    );
}

/// A chat the user opened — nearly every chat — swaps into a conversation
/// that opens with an assistant turn, which Gemma 3's template refuses and
/// which drops the persona there (docs/research/gemma-impersonation.md
/// §2.1). The opening line moves into the persona as one sentence and the
/// list opens with the assistant's first reply; order and content are what
/// they were.
#[test]
fn a_user_opened_chat_folds_its_opening_into_the_persona() {
    use crate::shared::api::contract::ApiRole;
    let profile = Profile::new("P", "sys");
    let mut chat = Chat::from_profile(&profile, "c");
    chat.push_message(Message::user("Ищу книгу о маяках."));
    chat.push_message(Message::assistant("Художественную или историческую?"));
    chat.push_message(Message::user("Историческую."));
    chat.push_message(Message::assistant("Тогда «Маячные Стивенсоны». Найти?"));
    let req = build_impersonation_request(
        &chat,
        None,
        "Ты — пользователь".into(),
        "",
        SamplingConfig::default(),
        Some("Подсказка о пользователе"),
        crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru),
    );
    let roles: Vec<ApiRole> = req.messages.iter().map(|m| m.role).collect();
    assert_eq!(
        roles,
        vec![ApiRole::User, ApiRole::Assistant, ApiRole::User]
    );
    let sent: Vec<&str> = req.messages.iter().map(|m| m.content.as_str()).collect();
    assert_eq!(
        sent,
        vec![
            "Художественную или историческую?",
            "Историческую.",
            "Тогда «Маячные Стивенсоны». Найти?"
        ]
    );
    let system = req.system.unwrap();
    assert!(system.starts_with("Ты — пользователь"));
    assert!(
        system.ends_with("Ищу книгу о маяках."),
        "the opening closes the persona: {system}"
    );
    assert!(
        system.find("Подсказка о пользователе").unwrap() < system.find("Ищу книгу").unwrap(),
        "the user hint before the opening"
    );
}

/// The seed's hint comes after the opening: the persona, who the human is,
/// what the human first said, what to continue.
#[test]
fn the_seed_hint_follows_the_folded_opening() {
    let profile = Profile::new("P", "sys");
    let mut chat = Chat::from_profile(&profile, "c");
    chat.push_message(Message::user("Ищу книгу о маяках."));
    chat.push_message(Message::assistant("Художественную или историческую?"));
    let req = build_impersonation_request(
        &chat,
        None,
        "Ты — пользователь".into(),
        "Истори",
        SamplingConfig::default(),
        None,
        crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru),
    );
    let system = req.system.unwrap();
    assert!(
        system.find("Ищу книгу").unwrap() < system.find("Истори»").unwrap(),
        "{system}"
    );
    assert_eq!(req.messages.len(), 1);
}

/// Two same-role turns in a row — the human wrote twice with no reply
/// between, or a reply that was tool calls only fell out of the swap — are
/// one turn for a template that insists on alternation (§3.1, fork F3), in
/// either role; a chat the assistant opened is otherwise untouched.
#[test]
fn adjacent_same_role_turns_are_merged() {
    use crate::shared::api::ApiMessage;
    use crate::shared::api::contract::ApiRole;
    let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::En);
    let mut system = String::from("persona");
    let out = super::super::impersonation::alternate_for_template(
        vec![
            ApiMessage::user("first reply"),
            ApiMessage::user("second reply"),
            ApiMessage::assistant("one"),
            ApiMessage::assistant("two"),
            ApiMessage::user("third reply"),
        ],
        &mut system,
        loc,
    );
    let sent: Vec<(ApiRole, &str)> = out.iter().map(|m| (m.role, m.content.as_str())).collect();
    assert_eq!(
        sent,
        vec![
            (ApiRole::User, "first reply\n\nsecond reply"),
            (ApiRole::Assistant, "one\n\ntwo"),
            (ApiRole::User, "third reply"),
        ]
    );
    assert_eq!(
        system, "persona",
        "no leading assistant turn: nothing folded"
    );

    // Merged first, then folded: two opening lines of the human become one
    // sentence of the persona.
    let mut system = String::from("persona");
    let out = super::super::impersonation::alternate_for_template(
        vec![
            ApiMessage::assistant("hello"),
            ApiMessage::assistant("anyone there?"),
            ApiMessage::user("yes"),
        ],
        &mut system,
        loc,
    );
    assert_eq!(out.len(), 1);
    assert_eq!(out[0].role, ApiRole::User);
    assert!(system.ends_with("hello\n\nanyone there?"), "{system}");
}

/// A chat with only the user's opening swaps into a lone assistant turn,
/// which both templates accept and the model continues — left as it is
/// (§3.3, fork F4).
#[test]
fn the_opening_only_chat_stays_a_lone_assistant_turn() {
    use crate::shared::api::contract::ApiRole;
    let profile = Profile::new("P", "sys");
    let mut chat = Chat::from_profile(&profile, "c");
    chat.push_message(Message::user("Ищу книгу о маяках."));
    let req = build_impersonation_request(
        &chat,
        None,
        "Ты — пользователь".into(),
        "",
        SamplingConfig::default(),
        None,
        crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru),
    );
    assert_eq!(req.messages.len(), 1);
    assert_eq!(req.messages[0].role, ApiRole::Assistant);
    assert_eq!(req.system.as_deref(), Some("Ты — пользователь"));
}

#[test]
fn swap_role_skips_system_tool_and_empty() {
    assert!(swap_role_message(&Message::new(MessageRole::System, "x")).is_none());
    assert!(swap_role_message(&Message::new(MessageRole::Tool, "x")).is_none());
    assert!(swap_role_message(&Message::user("   ")).is_none());
}

#[tokio::test]
async fn impersonate_streams_into_preview_and_finishes() {
    // The first request (send) → a reply; the second (impersonation) → a message.
    let backend = Arc::new(MockBackend::sequence(vec![
        vec![
            ChatChunk::Text("ответ".into()),
            ChatChunk::Finished(FinishReason::Stop),
        ],
        vec![
            ChatChunk::Text("моя реплика".into()),
            ChatChunk::Finished(FinishReason::Stop),
        ],
    ])) as Arc<dyn EngineBackend>;
    let (_d, cmd_tx, mut evt_rx, handle) = spawn_orch(Some(backend));
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
        .await
        .unwrap();

    // Need at least one message in the history.
    cmd_tx
        .send(AppCommand::SendMessage("привет".into()))
        .unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();

    cmd_tx
        .send(AppCommand::Impersonate {
            seed: String::new(),
        })
        .unwrap();
    // Impersonation starts.
    wait_for(&mut evt_rx, |e| {
        matches!(e, AppEvent::ImpersonationStarted { .. })
    })
    .await
    .unwrap();
    // The message text arrives in deltas.
    let chunk = wait_for(&mut evt_rx, |e| {
        matches!(e, AppEvent::ImpersonationChunk { .. })
    })
    .await
    .unwrap();
    assert!(matches!(chunk, AppEvent::ImpersonationChunk { text, .. } if text == "моя реплика"));
    // Finishes with Stop.
    let fin = wait_for(&mut evt_rx, |e| {
        matches!(e, AppEvent::ImpersonationFinished { .. })
    })
    .await
    .unwrap();
    assert!(matches!(
        fin,
        AppEvent::ImpersonationFinished {
            reason: FinishReason::Stop,
            ..
        }
    ));

    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();
}

/// The user persona is resolved through the assistant profile's reference into
/// `config.impersonation_profiles`; every miss falls back to the default text.
#[test]
fn impersonation_system_resolves_through_the_profile_reference() {
    let (_d, mut orch) = bare_orch();
    let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru);
    let default_text = loc.t("prompt.impersonation.default");

    let imp = crate::shared::config::ImpersonationProfile::new("Юзер", "Ты — Владимир.");
    let imp_id = imp.id;
    orch.config.impersonation_profiles = vec![imp];

    let mut profile = Profile::new("P", "sys");
    // No reference — the default.
    assert_eq!(orch.impersonation_system(Some(&profile), loc), default_text);
    // A reference — the persona's message.
    profile.impersonation_profile_id = Some(imp_id);
    assert_eq!(
        orch.impersonation_system(Some(&profile), loc),
        "Ты — Владимир."
    );
    // A dangling reference (the persona was deleted) — the default, not an empty prompt.
    profile.impersonation_profile_id = Some(uuid::Uuid::new_v4());
    assert_eq!(orch.impersonation_system(Some(&profile), loc), default_text);
    // A blank persona message — also the default.
    profile.impersonation_profile_id = Some(imp_id);
    orch.config.impersonation_profiles[0].system_message = "   ".into();
    assert_eq!(orch.impersonation_system(Some(&profile), loc), default_text);
}

/// Impersonation on the shared engine records its exact usage beside the
/// estimate its reservation was priced from, under its own kind
/// (docs/research/title-impersonation-usage.md §3.2): the budget's
/// `Impersonation` ratio moves, the turn's does not.
#[tokio::test]
async fn impersonation_records_its_usage_under_its_own_kind() {
    use crate::shared::api::contract::TokenUsage;
    use crate::shared::session_budget::Shape;
    let (_d, mut orch, _rx, chat_id) = bare_with_chat(vec![
        Message::user("Привет!"),
        Message::assistant("Здравствуйте. Чем помочь?"),
    ]);
    orch.active_id = Some(chat_id);
    orch.engines.backend = Some(Arc::new(MockBackend::scripted(vec![
        ChatChunk::Text("Расскажи о себе.".into()),
        ChatChunk::Usage(TokenUsage {
            prompt_tokens: 50_000,
            completion_tokens: 4,
            reasoning_tokens: 0,
            prefill: None,
        }),
        ChatChunk::Finished(FinishReason::Stop),
    ])) as Arc<dyn EngineBackend>);
    let budget = orch.session_budget();
    assert_eq!(budget.density(Shape::Impersonation), 1.0);

    orch.handle_impersonate(String::new());
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    while budget.density(Shape::Impersonation) == 1.0 && std::time::Instant::now() < deadline {
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
    }
    assert!(
        budget.density(Shape::Impersonation) > 1.0,
        "50 000 exact over a small estimate: {}",
        budget.density(Shape::Impersonation)
    );
    assert_eq!(
        budget.density(Shape::Turn),
        1.0,
        "impersonation's record is impersonation's"
    );
}

/// Impersonation's prompt is the session's largest — the whole conversation,
/// roles swapped, under its own system, processed cold — and on the shared
/// engine its timing rides the task's landing to the slow-prefill rule
/// (docs/research/oneshot-samples.md §3.1): `ImpersonationFinished` first,
/// the note after it.
#[tokio::test]
async fn impersonations_landing_offers_its_sample_on_the_shared_engine() {
    use crate::shared::api::contract::{Prefill, TokenUsage};
    let (_d, mut orch, mut rx, chat_id) = bare_with_chat(vec![
        Message::user("Привет!"),
        Message::assistant("Здравствуйте. Чем помочь?"),
    ]);
    orch.active_id = Some(chat_id);
    orch.config.engine.mode = crate::shared::config::ServerMode::External;
    orch.engines.backend = Some(Arc::new(MockBackend::scripted(vec![
        ChatChunk::Text("Расскажи о себе.".into()),
        ChatChunk::Usage(TokenUsage {
            prompt_tokens: 10_642,
            completion_tokens: 4,
            reasoning_tokens: 0,
            prefill: Some(Prefill {
                tokens: 10_642,
                ms: 280_000,
            }),
        }),
        ChatChunk::Finished(FinishReason::Stop),
    ])) as Arc<dyn EngineBackend>);
    let (done_tx, mut done_rx) = tokio::sync::mpsc::unbounded_channel();
    orch.imp_done_tx = done_tx;
    while rx.try_recv().is_ok() {}

    orch.handle_impersonate(String::new());
    let done = tokio::time::timeout(std::time::Duration::from_secs(5), done_rx.recv())
        .await
        .expect("the task landed")
        .unwrap();
    assert_eq!(
        done.prefill.map(|p| p.tokens),
        Some(10_642),
        "the shared engine's sample rides the landing"
    );
    orch.handle_imp_done(done);
    let events: Vec<AppEvent> = std::iter::from_fn(|| rx.try_recv().ok()).collect();
    let finished = events
        .iter()
        .position(|e| matches!(e, AppEvent::ImpersonationFinished { .. }))
        .expect("the landing");
    let note = events
        .iter()
        .position(|e| matches!(e, AppEvent::Notice(t) if t.contains("-b 256 -ub 256")))
        .expect("the note");
    assert!(finished < note, "the landing first, the note after it");
}

/// The sample is kept under the record's own condition — a budget, which is
/// the shared engine (fork F3): a separate impersonation server is another
/// server, with its own batch and session, and the task keeps nothing there;
/// and a stream that ended before its usage chunk carries nothing anywhere.
#[tokio::test]
async fn a_separate_server_or_a_cut_stream_lands_no_sample() {
    use crate::shared::api::contract::{Prefill, TokenUsage};
    let (_d, mut orch, _rx, _chat_id) = bare_with_chat(vec![]);
    let request = || crate::shared::api::ChatRequest {
        continue_final: false,
        system: Some("persona".into()),
        messages: vec![crate::shared::api::ApiMessage::user("hello")],
        sampling: crate::entities::sampling::SamplingConfig::default(),
        tools: Vec::new(),
    };
    let timed = || {
        Arc::new(MockBackend::scripted(vec![
            ChatChunk::Text("reply".into()),
            ChatChunk::Usage(TokenUsage {
                prompt_tokens: 400,
                completion_tokens: 1,
                reasoning_tokens: 0,
                prefill: Some(Prefill {
                    tokens: 400,
                    ms: 10_000,
                }),
            }),
            ChatChunk::Finished(FinishReason::Stop),
        ])) as Arc<dyn EngineBackend>
    };
    let (evt_tx, _evt_rx) = tokio::sync::mpsc::unbounded_channel();

    // A separate server: no budget, no sample.
    let (done_tx, mut done_rx) = tokio::sync::mpsc::unbounded_channel();
    super::super::impersonation::spawn_impersonation(
        timed(),
        request(),
        Uuid::new_v4(),
        tokio_util::sync::CancellationToken::new(),
        orch.ui_locale(),
        evt_tx.clone(),
        done_tx,
        None,
    );
    let done = tokio::time::timeout(std::time::Duration::from_secs(5), done_rx.recv())
        .await
        .expect("landed")
        .unwrap();
    assert_eq!(done.reason, FinishReason::Stop);
    assert!(
        done.prefill.is_none(),
        "another server: no sample for this one's rule"
    );

    // The shared engine, a stream cut before its usage: nothing to carry.
    let cut = Arc::new(MockBackend::scripted(vec![
        ChatChunk::Text("reply".into()),
        ChatChunk::Finished(FinishReason::Stop),
    ])) as Arc<dyn EngineBackend>;
    let (done_tx, mut done_rx) = tokio::sync::mpsc::unbounded_channel();
    super::super::impersonation::spawn_impersonation(
        cut,
        request(),
        Uuid::new_v4(),
        tokio_util::sync::CancellationToken::new(),
        orch.ui_locale(),
        evt_tx.clone(),
        done_tx,
        Some(orch.session_budget()),
    );
    let done = tokio::time::timeout(std::time::Duration::from_secs(5), done_rx.recv())
        .await
        .expect("landed")
        .unwrap();
    assert!(done.prefill.is_none(), "no usage chunk, no sample");

    // The shared engine with the chunk: the sample.
    let (done_tx, mut done_rx) = tokio::sync::mpsc::unbounded_channel();
    super::super::impersonation::spawn_impersonation(
        timed(),
        request(),
        Uuid::new_v4(),
        tokio_util::sync::CancellationToken::new(),
        orch.ui_locale(),
        evt_tx,
        done_tx,
        Some(orch.session_budget()),
    );
    let done = tokio::time::timeout(std::time::Duration::from_secs(5), done_rx.recv())
        .await
        .expect("landed")
        .unwrap();
    assert_eq!(done.prefill.map(|p| p.tokens), Some(400));
}