mindfork 0.10.2

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
//! Orchestrator tests — auto-titling a chat. Part of the [`super`] module
//! (fixtures in mod.rs). See docs/history/refactoring-god-objects.md, stage 3.

use super::*;

/// One scripted engine reply: stream `text`, then finish. Every e2e test here
/// scripts a few of these, and the four-line `vec![Text, Finished]` blocks
/// were sliding duplicates of each other and of the impersonation suite's —
/// hoisting the plumbing keeps each script to one line (docs/lessons.md §2).
fn script(text: &str) -> Vec<ChatChunk> {
    vec![
        ChatChunk::Text(text.into()),
        ChatChunk::Finished(FinishReason::Stop),
    ]
}

/// Spawns the orchestrator over a `MockBackend::sequence` of `scripts` and
/// waits out the initial activation — the shared opening of every e2e test in
/// this file: a fixture, not a test (docs/lessons.md §2). `sequence` repeats
/// its **last** entry once the rest are consumed, so a one-entry list serves
/// every request the same script.
async fn orch_with_scripts(
    scripts: Vec<Vec<ChatChunk>>,
    cfg: AppConfig,
) -> (
    tempfile::TempDir,
    UnboundedSender<AppCommand>,
    UnboundedReceiver<AppEvent>,
    tokio::task::JoinHandle<()>,
    Uuid,
) {
    let backend = Arc::new(MockBackend::sequence(scripts)) as Arc<dyn EngineBackend>;
    let (d, cmd_tx, mut evt_rx, handle) = spawn_orch_cfg(Some(backend), cfg);
    let active = wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatActivated { .. }))
        .await
        .unwrap();
    let chat_id = match active {
        AppEvent::ChatActivated { id, .. } => id,
        _ => unreachable!(),
    };
    (d, cmd_tx, evt_rx, handle, chat_id)
}

/// The next `ChatRenamed` event's payload.
async fn wait_renamed(evt_rx: &mut UnboundedReceiver<AppEvent>) -> (Uuid, String) {
    match wait_for(evt_rx, |e| matches!(e, AppEvent::ChatRenamed { .. }))
        .await
        .unwrap()
    {
        AppEvent::ChatRenamed { id, title } => (id, title),
        _ => unreachable!(),
    }
}

/// A [`TitleResult`] as the background task would deliver it.
fn title_result(chat_id: Uuid, text: Result<&str, &str>, origin: TitleOrigin) -> TitleResult {
    TitleResult {
        chat_id,
        text: text.map(str::to_string).map_err(str::to_string),
        origin,
        prefill: None,
    }
}

#[tokio::test]
async fn auto_rename_sets_title_from_model() {
    // The first script answers the send; the second — the requested title.
    let (_d, cmd_tx, mut evt_rx, handle, chat_id) = orch_with_scripts(
        vec![script("ответ"), script("«Тема разговора»")],
        no_auto_cfg(),
    )
    .await;

    // Need at least one reply, otherwise there's nothing to title.
    cmd_tx
        .send(AppCommand::SendMessage("привет".into()))
        .unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::ChatList(_)))
        .await
        .unwrap();

    cmd_tx.send(AppCommand::AutoRenameChat(chat_id)).unwrap();
    let (id, title) = wait_renamed(&mut evt_rx).await;
    assert_eq!(id, chat_id);
    assert_eq!(title, "Тема разговора", "the model's quotes are stripped");

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

#[test]
fn salvage_prefers_text_else_last_thought_line() {
    // There's a primary reply — take it.
    assert_eq!(
        salvage_title_source("Заголовок".into(), "мысли".into()),
        "Заголовок"
    );
    // The reply is empty — salvage the last substantive line of the reasoning.
    assert_eq!(
        salvage_title_source("  ".into(), "рассуждаю\nитог: Планы\n\n".into()),
        "итог: Планы"
    );
    // Entirely empty — an empty string (clean_generated_title returns None → an error).
    assert_eq!(salvage_title_source(String::new(), String::new()), "");
}

#[test]
fn auto_rename_without_messages_emits_error() {
    let (_d, mut orch, mut rx, chat_id) = bare_with_chat(vec![]);

    orch.handle_auto_rename(chat_id);
    // An empty chat → an error into the chat-list area, the background task doesn't start.
    let ev = rx.try_recv().unwrap();
    assert!(matches!(ev, AppEvent::ChatListError(_)));
}

/// The automatic trigger end-to-end with the **default** config (spec §11.2):
/// the first reply titles the chat with no command from anyone, and the second
/// exchange does not re-title — the first fire is the positive control that
/// makes the absence assertion meaningful (docs/lessons.md §2).
#[tokio::test]
async fn first_reply_titles_the_chat_automatically() {
    // The second script serves the automatic title task — and every later
    // request too, being the sequence's last entry.
    let (_d, cmd_tx, mut evt_rx, handle, chat_id) = orch_with_scripts(
        vec![script("ответ"), script("«Планы на дачу»")],
        AppConfig::default(),
    )
    .await;

    cmd_tx
        .send(AppCommand::SendMessage("привет".into()))
        .unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();
    // No AutoRenameChat was sent — the rename arrives on its own.
    let (id, title) = wait_renamed(&mut evt_rx).await;
    assert_eq!(id, chat_id);
    assert_eq!(title, "Планы на дачу");

    // The second exchange must not re-title: the conversation already has its
    // first reply. Drain to the channel's end (after Quit) so a late rename
    // cannot hide behind the assertion.
    cmd_tx
        .send(AppCommand::SendMessage("ещё вопрос".into()))
        .unwrap();
    wait_for(&mut evt_rx, |e| matches!(e, AppEvent::Finished { .. }))
        .await
        .unwrap();
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();
    let mut late_renames = 0;
    while let Ok(ev) = evt_rx.try_recv() {
        if matches!(ev, AppEvent::ChatRenamed { .. }) {
            late_renames += 1;
        }
    }
    assert_eq!(late_renames, 0, "the second exchange must not re-title");
}

/// The `AfterUserMessage` timing: the title task starts on send, without
/// waiting for the reply.
#[tokio::test]
async fn after_user_mode_titles_on_send() {
    // One script served to every request: both the reply and the racing title
    // task read the same text, so the assertion does not depend on which of
    // the two concurrent requests lands first.
    let mut cfg = AppConfig::default();
    cfg.interface.auto_title = crate::shared::config::AutoTitleMode::AfterUserMessage;
    let (_d, cmd_tx, mut evt_rx, handle, chat_id) =
        orch_with_scripts(vec![script("Дачный сезон")], cfg).await;

    cmd_tx
        .send(AppCommand::SendMessage("привет".into()))
        .unwrap();
    let (id, title) = wait_renamed(&mut evt_rx).await;
    assert_eq!(id, chat_id);
    assert_eq!(title, "Дачный сезон");
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();
}

/// Regenerating the first reply re-fires the trigger (design D2): the
/// truncation removed the conversation's only reply, so the next one is again
/// the first — and the title follows what the exchange actually became.
#[tokio::test]
async fn regenerating_the_first_reply_retitles() {
    let (_d, cmd_tx, mut evt_rx, handle, _chat) = orch_with_scripts(
        vec![
            script("ответ №1"),
            script("«Первое имя»"),
            script("ответ №2"),
            script("«Второе имя»"),
        ],
        AppConfig::default(),
    )
    .await;

    cmd_tx
        .send(AppCommand::SendMessage("привет".into()))
        .unwrap();
    // Wait the first title out before regenerating, so the two title tasks
    // cannot race each other for scripts.
    let (_, first) = wait_renamed(&mut evt_rx).await;
    assert_eq!(first, "Первое имя");

    cmd_tx.send(AppCommand::RegenerateLast).unwrap();
    let (_, second) = wait_renamed(&mut evt_rx).await;
    assert_eq!(second, "Второе имя");
    cmd_tx.send(AppCommand::Quit).unwrap();
    handle.await.unwrap();
}

/// A manual rename wins over the automatic path at both ends (spec §11.2, D1):
/// the flag it sets blocks a later trigger, and an automatic result arriving
/// *after* the rename is dropped — while a requested one still applies, which
/// is the positive control for both absences.
#[test]
fn manual_rename_outranks_the_automatic_title() {
    let (_d, mut orch, mut rx, chat_id) = bare_with_chat(vec![
        Message::user("привет"),
        Message::assistant("здравствуйте"),
    ]);

    orch.handle_rename(chat_id, "Моё имя".into());
    assert!(
        orch.chats[0].renamed_manually,
        "a manual rename must set the flag"
    );
    while rx.try_recv().is_ok() {} // drop the rename's own events

    // An automatic result that lost the race to the rename: dropped silently.
    orch.handle_title_result(title_result(
        chat_id,
        Ok("«Модельное имя»"),
        TitleOrigin::Auto,
    ));
    assert_eq!(orch.chats[0].title, "Моё имя");
    assert!(rx.try_recv().is_err(), "an automatic result must be silent");

    // The requested path (the chat-list action) still applies: the user asked
    // for this title moments ago, so last write wins.
    orch.handle_title_result(title_result(
        chat_id,
        Ok("«Модельное имя»"),
        TitleOrigin::Requested,
    ));
    assert_eq!(orch.chats[0].title, "Модельное имя");
    assert!(matches!(
        rx.try_recv().unwrap(),
        AppEvent::ChatList(_) | AppEvent::ChatRenamed { .. }
    ));
}

/// The same rule for a sub-agent transcript (spec §11.2, D1): an automatic
/// result arriving after the transcript was renamed by hand is dropped —
/// silently, so the list is not told of a title that never landed — while a
/// requested one still applies, the positive control.
#[test]
fn manual_rename_outranks_the_automatic_title_on_a_transcript() {
    let run = crate::entities::subagent::SubagentRun::fixture("Критик", &["x", "y"]);
    let run_id = run.id;
    let mut carrier = Message::assistant("делегировал");
    carrier.tool_calls = vec![run.on_record()];
    let (_d, mut orch, mut rx, chat_id) = bare_with_chat(vec![Message::user("привет"), carrier]);

    orch.handle_rename(run_id, "Моё имя".into());
    assert!(orch.chats[0].child(run_id).unwrap().renamed_manually);
    while rx.try_recv().is_ok() {} // drop the rename's own events

    orch.handle_title_result(title_result(
        run_id,
        Ok("«Модельное имя»"),
        TitleOrigin::Auto,
    ));
    assert_eq!(orch.chats[0].child(run_id).unwrap().title, "Моё имя");
    assert!(rx.try_recv().is_err(), "an automatic result must be silent");

    orch.handle_title_result(title_result(
        run_id,
        Ok("«Модельное имя»"),
        TitleOrigin::Requested,
    ));
    assert_eq!(orch.chats[0].child(run_id).unwrap().title, "Модельное имя");
    assert!(matches!(
        rx.try_recv().unwrap(),
        AppEvent::ChatList(_) | AppEvent::ChatRenamed { .. }
    ));
    // The parent keeps its own title throughout.
    assert_eq!(orch.chats[0].title, "Новый чат");
    assert_eq!(orch.chats[0].id, chat_id);
}

/// Failures are reported where their origin belongs (design D4): an automatic
/// run logs and stays out of the UI, a requested one lands in the chat-list
/// overlay — the loud arm proving the quiet arm's silence is deliberate.
#[test]
fn automatic_title_failures_are_quiet_requested_ones_are_loud() {
    let (_d, mut orch, mut rx, chat_id) = bare_with_chat(vec![]); // empty: no digest

    // Trigger-side: an empty digest on the automatic path says nothing.
    orch.maybe_auto_title(
        chat_id,
        crate::shared::config::AutoTitleMode::AfterAssistantReply,
    );
    assert!(
        rx.try_recv().is_err(),
        "the automatic path must not emit UI events"
    );
    // Result-side: an error outcome on the automatic path says nothing either.
    orch.handle_title_result(title_result(
        chat_id,
        Err("engine exploded"),
        TitleOrigin::Auto,
    ));
    assert!(
        rx.try_recv().is_err(),
        "an automatic failure must be silent"
    );

    // The requested path reports both the same conditions.
    orch.handle_auto_rename(chat_id);
    assert!(matches!(rx.try_recv().unwrap(), AppEvent::ChatListError(_)));
    orch.handle_title_result(title_result(
        chat_id,
        Err("engine exploded"),
        TitleOrigin::Requested,
    ));
    assert!(matches!(rx.try_recv().unwrap(), AppEvent::ChatListError(_)));
}

#[test]
fn auto_rename_when_server_not_ready_errors_into_chat_list() {
    // The server is still connecting: the readiness error must go into the chat-list
    // overlay (`ChatListError`), not the chat feed (`Error`) — otherwise the
    // full-screen list overlay would hide it.
    let (_d, mut orch, mut rx, chat_id) = bare_with_chat(vec![
        Message::user("привет"),
        Message::assistant("здравствуйте"),
    ]);
    orch.engines.server_status = ServerStatus::Connecting;

    orch.handle_auto_rename(chat_id);
    let ev = rx.try_recv().unwrap();
    assert!(
        matches!(ev, AppEvent::ChatListError(_)),
        "a not-ready error during auto-titling must go into the chat list, got: {ev:?}"
    );
}

/// The title 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 `Title` ratio moves, the turn's does not.
#[tokio::test]
async fn the_title_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.engines.backend = Some(Arc::new(MockBackend::scripted(vec![
        ChatChunk::Text("Названия".into()),
        ChatChunk::Usage(TokenUsage {
            prompt_tokens: 50_000,
            completion_tokens: 2,
            reasoning_tokens: 0,
            prefill: None,
        }),
        ChatChunk::Finished(FinishReason::Stop),
    ])) as Arc<dyn EngineBackend>);
    let budget = orch.session_budget();
    assert_eq!(budget.density(Shape::Title), 1.0);

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

/// The title's stream is a cold prompt on the chat server — its own system
/// over the digest, processed whole — and its timing is offered to the
/// slow-prefill rule after the title's own landing
/// (docs/research/oneshot-samples.md §3.2): the rename first, the note after
/// it; the second sample on the same server says nothing.
#[test]
fn the_titles_landing_offers_its_sample() {
    let (_d, mut orch, mut rx, chat_id) =
        bare_with_chat(vec![crate::entities::message::Message::user("Привет!")]);
    orch.config.engine.mode = crate::shared::config::ServerMode::External;
    while rx.try_recv().is_ok() {}
    let cold = Some(crate::shared::api::contract::Prefill {
        tokens: 1000,
        ms: 26_000,
    });
    let mut res = title_result(chat_id, Ok("«Имя»"), TitleOrigin::Requested);
    res.prefill = cold;
    orch.handle_title_result(res);
    let events: Vec<AppEvent> = std::iter::from_fn(|| rx.try_recv().ok()).collect();
    let renamed = events
        .iter()
        .position(|e| matches!(e, AppEvent::ChatRenamed { .. }))
        .expect("the rename landed");
    let note = events
        .iter()
        .position(|e| matches!(e, AppEvent::Notice(t) if t.contains("-b 256 -ub 256")))
        .expect("the note");
    assert!(renamed < note, "the landing first, the note after it");

    let mut again = title_result(chat_id, Ok("«Ещё имя»"), TitleOrigin::Requested);
    again.prefill = cold;
    orch.handle_title_result(again);
    let notes = std::iter::from_fn(|| rx.try_recv().ok())
        .filter(|e| matches!(e, AppEvent::Notice(_)))
        .count();
    assert_eq!(notes, 0, "one note per server session");
}

/// An error result's prompt was processed all the same: the landing reports
/// the failure, then offers the sample (§3.2).
#[test]
fn a_failed_titles_prompt_was_processed_all_the_same() {
    let (_d, mut orch, mut rx, chat_id) =
        bare_with_chat(vec![crate::entities::message::Message::user("Привет!")]);
    orch.config.engine.mode = crate::shared::config::ServerMode::External;
    while rx.try_recv().is_ok() {}
    let mut res = title_result(chat_id, Err("boom"), TitleOrigin::Auto);
    res.prefill = Some(crate::shared::api::contract::Prefill {
        tokens: 1000,
        ms: 26_000,
    });
    orch.handle_title_result(res);
    let notes: Vec<String> = std::iter::from_fn(|| rx.try_recv().ok())
        .filter_map(|e| match e {
            AppEvent::Notice(t) => Some(t),
            _ => None,
        })
        .collect();
    assert_eq!(notes.len(), 1, "{notes:?}");
    assert!(notes[0].contains("-b 256 -ub 256"), "{}", notes[0]);
}