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
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
//! Chat screen — projecting AppEvent into the feed (messages, generation, tool blocks, tokens). Part of the [`super`] module; split out of the
//! chat.rs monolith (see docs/history/refactoring-god-objects.md, stage 2).

use super::*;

// Imported here rather than through `super`: `screens` may not depend on `app`
// (FSD), so the jump descriptor comes from `features`, where both layers can
// see it — the `RagProgress` precedent.
use crate::features::chat_search::FeedFocus;

impl ChatScreen {
    /// Marks that the feed content changed (streaming, a new message, a note,
    /// an edit): if the feed contains risk-group glyphs, the next frame is drawn as a **full
    /// redraw** — otherwise legacy terminals leave artifacts from changed
    /// emoji lines. See [`is_risky_glyph`], [`crate::shared::ui::prime_full_redraw`].
    ///
    /// Called by **mutators**, not by render fact: the artifact must not be shown even
    /// for a single frame. Detecting "there's a risk" from a render fact would lag a frame
    /// behind (a cache miss is only visible there), and the artifact would flash —
    /// hiding this behind synchronized output isn't possible, conhost ignores mode 2026.
    ///
    /// The risk flag is cached and **only accumulates**: edits always affect the
    /// last block, so we only check it, while a full feed rebuild
    /// ([`Self::activate_chat`]) recomputes it from scratch. Over-estimating is
    /// safe — an extra redraw isn't visible, a missed one leaves an artifact.
    pub(super) fn mark_feed_changed(&mut self) {
        if !self.feed_has_risky
            && let Some(last) = self.feed.last()
        {
            self.feed_has_risky = feed_msg_has_risky_glyph(last);
        }
        if self.feed_has_risky {
            self.full_redraw = true;
        }
    }

    /// Updates the chat title in the projection (after a manual/auto rename).
    /// Changes the title in the feed header if this is the active chat. The list and the
    /// overlay are additionally updated by the `ChatList` event (`set_chat_list`).
    pub fn rename_chat(&mut self, id: Uuid, title: String) {
        if self.active_chat == Some(id) {
            self.title = title.clone();
        }
        if let Some(c) = self.chats.iter_mut().find(|c| c.id == id) {
            c.title = title;
        }
    }

    /// Rebuilds the feed for a chat. `focus` — a domain message to put the view
    /// on together with the query to highlight inside it
    /// (`AppCommand::OpenChatAt`); `None` — the usual "show the tail", with
    /// nothing highlighted. `feed_view` — the chat's stored collapse state
    /// ("thoughts"/tool calls, spec §11.3). `compaction` — the history-compaction
    /// boundary `(the id of the first message still sent verbatim, the rolling
    /// summary)`, or `None` when nothing is folded (spec §6.7).
    #[allow(clippy::too_many_arguments)]
    pub fn activate_chat(
        &mut self,
        id: Uuid,
        title: String,
        messages: &[Message],
        draft: &str,
        feed_view: FeedView,
        focus: Option<FeedFocus>,
        compaction: Option<(Uuid, String)>,
    ) {
        // Switching chats resets the generation state: "orphaned" chunks of the
        // previous generation must not land in the new chat's feed.
        self.active_chat = Some(id);
        self.title = title;
        self.current_gen = None;
        self.generating = false;
        self.live_turn = None;
        self.background_run = false;
        self.stream_role = FeedRole::Assistant;
        // Only a transcript can grow in place (see `grow_transcript`); a
        // chat's feed is rebuilt by activation alone.
        self.transcript = if self.child.is_some() {
            messages.to_vec()
        } else {
            Vec::new()
        };
        // The token counter belongs to the previous chat — clear it so it doesn't linger
        // in the status line after switching (the status bar hides the counter when
        // `tokens == 0 && context == None`).
        self.gen_tokens = 0;
        self.gen_context = None;
        self.gen_context_exact = false;
        self.gen_reasoning = 0;
        // The collapse state belongs to the chat, so it is applied **before**
        // the feed is built: the block cache is keyed on it (spec §11.3). So is
        // the compaction boundary — both are per-chat rendering inputs.
        self.feed_view.set_view(feed_view);
        self.feed_view.set_compaction(compaction);
        // Which `chat://` references resolve depends on the profile, which the
        // new chat may have changed — a third per-chat rendering input, applied
        // before the feed is built for the same reason (spec §11.3).
        self.refresh_known_chats();
        // The reference picker lists the *previous* chat's links.
        self.chat_links = None;
        // Stitch agentic-loop rounds into one "Assistant:" block with inline tool blocks.
        self.feed = FeedMessage::from_messages(messages);
        // A sub-agent transcript opens with its persona (spec §11.3) — the one
        // thing a reader of one wants first, and a chat never shows.
        if let Some(child) = &self.child {
            self.feed
                .insert(0, FeedMessage::system(child.system_message.clone()));
        }
        // The feed was replaced wholesale — recompute "is there a risk" from scratch (from
        // here on the flag only accumulates based on the last block).
        self.feed_has_risky = self.feed.iter().any(feed_msg_has_risky_glyph);
        self.mark_feed_changed();
        // The anchor and the marker index a feed that no longer exists — drop
        // both, so neither can survive into the wrong chat. (The marker outlives
        // a manual scroll on purpose, so a chat switch is the one place that has
        // to clear it explicitly.)
        // The feed is renumbered under any in-feed search, and `Ctrl+E`/`Ctrl+R`/
        // a rewrite round/a cross-chat jump all arrive here (§1.5) — so close it
        // rather than leave it pointing at messages that moved.
        self.search = None;
        self.search_last.clear();
        self.feed_view.clear_search();
        self.feed_view.clear_focus();
        // A jump asked for by the user wins over the tail; anything else — the
        // usual bottom. An id this chat doesn't contain isn't found, so it falls
        // through to the tail (and `clear_focus` above already dropped the
        // previous highlight). See docs/history/chat-search-stage2.md §4.
        match &focus {
            Some(f)
                if self
                    .feed_view
                    .focus_message(&self.feed, f.message, Some(&f.query)) => {}
            _ => self.feed_view.scroll_to_bottom(),
        }
        // Load the chat's saved draft into the input box (empty for a new chat).
        // Do NOT mark `draft_dirty` — otherwise we'd immediately send it back via the same
        // `SetDraft`; trigger the spellcheck recheck directly instead.
        self.input.set_text(draft);
        self.spell_dirty = true;
        self.last_edit = None;
    }

    /// Updates the history-compaction boundary after a live compaction
    /// (`AppEvent::Compacted`) — `(the id of the first message still sent
    /// verbatim, the rolling summary)`; `None` clears it.
    ///
    /// A feed mutator like any other: the boundary changes the rendered lines,
    /// so a legacy terminal needs the same full-redraw insurance every other
    /// content change takes out (see [`Self::mark_feed_changed`]).
    pub fn set_compaction(&mut self, compaction: Option<(Uuid, String)>) {
        self.feed_view.set_compaction(compaction);
        self.mark_feed_changed();
    }

    /// Returns the text for the input box after deleting the last exchange. If the field
    /// isn't empty, the text is prepended to its start (existing input isn't lost),
    /// separated by a blank line: the restored message is a message of its own,
    /// not a continuation of what is being typed, so the halves must read as two
    /// paragraphs instead of fusing into one. See spec §11.7.
    pub fn restore_input(&mut self, text: String) {
        let existing = self.input.text();
        if existing.is_empty() {
            self.input.set_text(&text);
            self.mark_input_changed();
            return;
        }
        let restored = text.trim_end();
        let combined = if restored.is_empty() {
            // Nothing to prepend — the draft stays exactly as it was typed.
            existing
        } else {
            // Exactly one blank line between the halves, whatever whitespace
            // either side brought with it.
            let draft = existing.trim_start_matches(['\n', '\r']);
            format!("{restored}\n\n{draft}")
        };
        self.input.set_text(&combined);
        self.mark_input_changed();
    }

    pub fn push_user_message(&mut self, text: String) {
        self.feed.push(FeedMessage {
            role: FeedRole::User,
            text,
            thoughts: String::new(),
            tools: Vec::new(),
            streaming: false,
            // The echo carries no id — the domain message is the orchestrator's;
            // the feed picks the ids up on the next activation.
            message_ids: Vec::new(),
            // A user message has no model behind it, in the feed or on disk.
            model: None,
        });
        self.mark_feed_changed();
        // User-initiated: you sent it, you want to see it (§4).
        self.feed_view.scroll_to_bottom();
    }

    /// `model` — the model this turn goes to (`AppEvent::GenerationStarted`),
    /// shown in the streaming bubble's header when `interface.show_model_name`
    /// is on. See spec §11.3.
    pub fn begin_generation(&mut self, generation_id: Uuid, model: Option<String>) {
        self.begin_turn(generation_id, model);
        self.feed.push(FeedMessage {
            role: FeedRole::Assistant,
            text: String::new(),
            thoughts: String::new(),
            tools: Vec::new(),
            streaming: true,
            message_ids: Vec::new(),
            model: self.gen_model.clone(),
        });
        self.mark_feed_changed();
        // User-initiated (you pressed send/regenerate): show the new reply (§4).
        self.feed_view.scroll_to_bottom();
    }

    /// `/continue` (spec §6.4): the turn resumes the last assistant reply, so
    /// the stream goes **into its bubble** — re-opened for streaming, moved
    /// past any notes that landed after it (the "reply was cut short" note now
    /// reads above the reply it described), appended with no separator. With
    /// no assistant bubble to resume (a tool-result tail whose round filed
    /// nothing visible), a fresh bubble opens as for any turn.
    pub fn begin_continuation(&mut self, generation_id: Uuid, model: Option<String>) {
        self.begin_turn(generation_id, model);
        if !self.resume_last_assistant_bubble() {
            self.feed.push(FeedMessage {
                role: FeedRole::Assistant,
                text: String::new(),
                thoughts: String::new(),
                tools: Vec::new(),
                streaming: true,
                message_ids: Vec::new(),
                model: self.gen_model.clone(),
            });
        }
        self.mark_feed_changed();
        // User-initiated (you typed the command): show the resumed reply (§4).
        self.feed_view.scroll_to_bottom();
    }

    /// Re-opens the last assistant bubble for streaming, moved past any notes
    /// that landed after it (the "cut short" note then reads above the reply
    /// it described). `false` — the feed holds no assistant bubble to resume.
    /// Shared by `/continue`'s two entry points: a fresh start
    /// ([`Self::begin_continuation`]) and a mid-turn rebuild (`set_live_turn`).
    pub(super) fn resume_last_assistant_bubble(&mut self) -> bool {
        match self
            .feed
            .iter()
            .rposition(|m| m.role == FeedRole::Assistant)
        {
            Some(idx) => {
                let mut bubble = self.feed.remove(idx);
                bubble.streaming = true;
                self.feed.push(bubble);
                true
            }
            None => false,
        }
    }

    /// The per-turn state both openings share; the bubble is the difference.
    fn begin_turn(&mut self, generation_id: Uuid, model: Option<String>) {
        self.current_gen = Some(generation_id);
        self.generating = true;
        self.stream_role = FeedRole::Assistant;
        self.gen_tokens = 0;
        self.gen_context = None;
        self.gen_context_exact = false;
        self.gen_reasoning = 0;
        self.gen_model = model;
        self.pending_text_sep = false;
        self.pending_thoughts_sep = false;
    }

    /// Appends a tool block to the current assistant message (live, during the turn).
    /// A tool call is about to run (`AppEvent::ToolCallStarted`, spec §11.3):
    /// its card goes into the bubble at once, marked *running*, and
    /// [`Self::push_tool_call`] with the same `call_id` completes it.
    pub fn push_tool_call_started(
        &mut self,
        generation_id: Uuid,
        call_id: String,
        name: String,
        arguments: String,
    ) {
        if self.current_gen != Some(generation_id) {
            return;
        }
        self.ensure_streaming_bubble();
        if let Some(last) = self.feed.last_mut() {
            let text_offset = last.text.len();
            last.tools.push(crate::widgets::message_feed::FeedToolCall {
                name,
                arguments,
                result: String::new(),
                text_offset,
                images: 0,
                call_id: Some(call_id),
                running: true,
            });
            self.mark_feed_changed();
            self.feed_view.scroll_to_bottom_if_following();
        }
    }

    pub fn push_tool_call(
        &mut self,
        generation_id: Uuid,
        call_id: String,
        name: String,
        arguments: String,
        result: String,
        images: usize,
    ) {
        if self.current_gen == Some(generation_id)
            && let Some(last) = self.feed.last_mut()
        {
            // The card this call opened, if it did — completed in place, so
            // the result lands where the *running…* was.
            if let Some(card) = last
                .tools
                .iter_mut()
                .find(|t| t.running && t.call_id.as_deref() == Some(call_id.as_str()))
            {
                card.result = result;
                card.images = images;
                card.running = false;
            } else {
                // The call happened after response text had already accumulated — record the
                // position, so the tool block lands at the call site, not in the "header".
                let text_offset = last.text.len();
                last.tools.push(crate::widgets::message_feed::FeedToolCall {
                    name,
                    arguments,
                    result,
                    text_offset,
                    images,
                    call_id: Some(call_id),
                    running: false,
                });
            }
            // Separate the next round's text/thoughts with a separator (matching a reload).
            self.pending_text_sep = true;
            self.pending_thoughts_sep = true;
            self.mark_feed_changed();
            // Arrives on its own mid-turn — must not yank a reader away (§4).
            self.feed_view.scroll_to_bottom_if_following();
        }
    }

    /// The assistant wrote a message and is continuing with a second one (the
    /// `send_followup_message` tool): finish the current bubble and add a new
    /// streaming assistant bubble — the next round's text will go into it.
    /// This way the live feed matches a reload (`from_messages` doesn't merge a
    /// message with `new_bubble`). See spec §9.3.
    pub fn continue_assistant(&mut self, generation_id: Uuid) {
        if self.current_gen != Some(generation_id) {
            return;
        }
        if let Some(last) = self.feed.last_mut() {
            last.streaming = false;
        }
        self.pending_text_sep = false;
        self.pending_thoughts_sep = false;
        self.feed.push(FeedMessage {
            role: FeedRole::Assistant,
            text: String::new(),
            thoughts: String::new(),
            tools: Vec::new(),
            streaming: true,
            message_ids: Vec::new(),
            // Same turn, same model — and the same answer the second message's
            // own metadata will carry once it is stored.
            model: self.gen_model.clone(),
        });
        self.mark_feed_changed();
        // Arrives on its own (the model chose to write another message) — §4.
        self.feed_view.scroll_to_bottom_if_following();
    }

    /// The assistant decided to rewrite the current message (the
    /// `rewrite_current_message` tool): discard the current bubble's already-accumulated
    /// text/thoughts/calls — the rewritten reply will go into the same bubble. See spec §9.3.
    pub fn rewrite_assistant(&mut self, generation_id: Uuid) {
        if self.current_gen != Some(generation_id) {
            return;
        }
        if let Some(last) = self.feed.last_mut() {
            last.text.clear();
            last.thoughts.clear();
            last.tools.clear();
            last.streaming = true;
        }
        self.pending_text_sep = false;
        self.pending_thoughts_sep = false;
        self.mark_feed_changed();
        // Arrives on its own (the model chose to rewrite) — §4.
        self.feed_view.scroll_to_bottom_if_following();
    }

    /// Guarantees that `last` is a streaming assistant bubble (the target for chunks).
    /// If a note slipped into the feed mid-generation (e.g. an `AppEvent::Error`
    /// about hitting the round limit before the final synthesis), `last` ends up being
    /// a note — in that case open a new assistant bubble, otherwise the stream would go
    /// into the note and render as plain text with no markdown.
    fn ensure_streaming_bubble(&mut self) {
        let ok = matches!(
            self.feed.last(),
            Some(m) if m.role == self.stream_role && m.streaming
        );
        if !ok {
            self.feed.push(FeedMessage {
                role: self.stream_role,
                text: String::new(),
                thoughts: String::new(),
                tools: Vec::new(),
                streaming: true,
                message_ids: Vec::new(),
                model: self.gen_model.clone(),
            });
        }
    }

    /// The open dialogue transcript's next line (`AppEvent::TranscriptLine`,
    /// spec §9.13): the coming stream draws on `role`'s side. An empty
    /// streaming bubble is retargeted in place; otherwise the next chunk
    /// opens a bubble of that side.
    pub fn set_transcript_line(
        &mut self,
        generation_id: Uuid,
        role: crate::entities::message::MessageRole,
    ) {
        if self.current_gen != Some(generation_id) {
            return;
        }
        let role = match role {
            crate::entities::message::MessageRole::User => FeedRole::User,
            _ => FeedRole::Assistant,
        };
        self.set_stream_role(role);
    }

    /// Sets the current stream's side and retargets an empty streaming
    /// bubble in place (a bubble mid-content keeps its side; the next chunk
    /// after a role change opens a new one).
    pub(super) fn set_stream_role(&mut self, role: FeedRole) {
        self.stream_role = role;
        if let Some(last) = self.feed.last_mut()
            && last.streaming
            && last.role != role
            && last.text.is_empty()
            && last.thoughts.is_empty()
            && last.tools.is_empty()
        {
            last.role = role;
            self.mark_feed_changed();
        }
    }

    /// Shows the "retrying" chip, or clears it when a retry produced content.
    ///
    /// The chip is transient by construction: every path that ends the wait —
    /// content ([`Self::push_chunk`]/[`Self::push_thoughts`]) or the turn finishing
    /// ([`Self::finish_generation`]) — clears it, so it cannot outlive what it
    /// describes. Stale generations are dropped, as everywhere (spec §4.4).
    pub fn set_retrying(&mut self, generation_id: Uuid, attempt: u32, max: u32, delay_secs: u64) {
        if self.current_gen != Some(generation_id) {
            return;
        }
        self.retrying = Some(self.loc.tf(
            "ui.chat.bg.retry",
            &[
                ("attempt", &attempt.to_string()),
                ("max", &max.to_string()),
                ("secs", &delay_secs.to_string()),
            ],
        ));
    }

    /// Clears the retry chip: whatever it was waiting for has happened.
    fn clear_retrying(&mut self) {
        self.retrying = None;
    }

    /// The sub-agent chip (`AppEvent::SubagentProgress`, spec §9.3.2): worded
    /// here in the interface language; `None` clears it. Guarded by the
    /// generation id like every streaming event.
    pub fn set_subagent_progress(
        &mut self,
        generation_id: Uuid,
        run: Uuid,
        progress: Option<crate::app::events::SubagentProgress>,
    ) {
        if self.current_gen != Some(generation_id) && self.live_turn != Some(generation_id) {
            return;
        }
        // One line per running run, keyed by its id: a report replaces the
        // run's line (and moves it last — the chip names the latest), its
        // `None` removes it. Several runs at once are the parallel group.
        self.subagents.retain(|(id, _)| *id != run);
        let Some(label) = progress.map(|p| {
            use crate::app::events::RunProgressKind;
            let round = p.round.to_string();
            match p.kind {
                RunProgressKind::DialogueLine => self.loc.tf(
                    "ui.chat.bg.dialogue",
                    &[("name", &p.name), ("line", &round)],
                ),
                RunProgressKind::DialogueDirector => self
                    .loc
                    .tf("ui.chat.bg.dialogue_director", &[("name", &p.name)]),
                RunProgressKind::Subagent => match p.tool {
                    Some(tool) => self.loc.tf(
                        "ui.chat.bg.subagent_tool",
                        &[("name", &p.name), ("round", &round), ("tool", &tool)],
                    ),
                    None => self.loc.tf(
                        "ui.chat.bg.subagent",
                        &[("name", &p.name), ("round", &round)],
                    ),
                },
            }
        }) else {
            return;
        };
        self.subagents.push((run, label));
    }

    pub fn push_chunk(&mut self, generation_id: Uuid, text: &str) {
        if self.current_gen != Some(generation_id) {
            return;
        }
        self.clear_retrying();
        self.ensure_streaming_bubble();
        if let Some(last) = self.feed.last_mut() {
            // The round's first text after a tool call gets an empty-line
            // separator (matching `FeedMessage::from_messages`).
            if self.pending_text_sep {
                self.pending_text_sep = false;
                if !last.text.is_empty() {
                    last.text.push_str("\n\n");
                }
            }
            last.text.push_str(text);
        }
        self.mark_feed_changed();
    }

    pub fn push_thoughts(&mut self, generation_id: Uuid, text: &str) {
        if self.current_gen != Some(generation_id) {
            return;
        }
        self.clear_retrying();
        self.ensure_streaming_bubble();
        if let Some(last) = self.feed.last_mut() {
            if self.pending_thoughts_sep {
                self.pending_thoughts_sep = false;
                if !last.thoughts.is_empty() {
                    last.thoughts.push('\n');
                }
            }
            last.thoughts.push_str(text);
        }
        self.mark_feed_changed();
    }

    /// Updates the token counter of the current generation (live). Ignores stale
    /// events (by `generation_id`). Updates the context (the conversation) only when it's
    /// set (`Some`), remembering whether it's an exact number or an estimate.
    pub fn set_token_usage(
        &mut self,
        generation_id: Uuid,
        completion: u64,
        context: Option<u64>,
        context_exact: bool,
        reasoning: Option<u32>,
    ) {
        if self.current_gen == Some(generation_id) {
            self.gen_tokens = completion;
            if let Some(c) = context {
                self.gen_context = Some(c);
                self.gen_context_exact = context_exact;
            }
            // Reasoning tokens are only known from `usage` (Some) — otherwise leave them be.
            if let Some(r) = reasoning {
                self.gen_reasoning = r;
            }
        }
    }

    pub fn finish_generation(
        &mut self,
        generation_id: Uuid,
        reason: FinishReason,
        continuable: bool,
    ) {
        // A transcript view of the turn that just ended: the chip goes, the
        // feed is not the turn's (docs/subagent-live.md §3.4).
        if self.live_turn == Some(generation_id) && self.current_gen.is_none() {
            self.live_turn = None;
            self.subagents.clear();
            return;
        }
        if self.current_gen != Some(generation_id) {
            return;
        }
        // A transcript's own stream ending leaves the turn's chip guard alone:
        // the turn goes on, and its chip is cleared by its own events.
        if self.live_turn == Some(generation_id) {
            self.live_turn = None;
        }
        if let Some(last) = self.feed.last_mut() {
            last.streaming = false;
            // A card still running when the turn ended (cancelled, timed out
            // mid-call) must not say *running…* forever.
            for card in last.tools.iter_mut().filter(|t| t.running) {
                card.running = false;
            }
        }
        self.generating = false;
        self.current_gen = None;
        // The run's stream ended — whatever the outcome, the stop key stops
        // nothing now, so the footer must stop advertising it (spec §11.2).
        self.background_run = false;
        self.clear_retrying();
        self.subagents.clear();
        // The interruption notes name `/continue` only when it would actually
        // work (`continuable` — fork F9); `Length` gets a note at all only
        // since the command existed to make one actionable (spec §6.4). A
        // cancelled turn always answers; a length-cut reply used to stop
        // mid-sentence with nothing on screen saying why. So did a reply the
        // provider's content filter stopped, which is never continuable
        // (docs/research/content-filter-finish.md).
        let note = match (reason, continuable) {
            (FinishReason::Cancelled, true) => Some("ui.chat.gen_cancelled_continuable"),
            (FinishReason::Cancelled, false) => Some("ui.chat.gen_cancelled"),
            (FinishReason::Length, true) => Some("ui.err.reply_truncated_continuable"),
            (FinishReason::Length, false) => Some("ui.err.reply_truncated"),
            (FinishReason::Filtered, _) => Some("ui.err.reply_filtered"),
            _ => None,
        };
        if let Some(key) = note {
            self.push_note(self.loc.t(key));
        }
    }

    pub fn push_error(&mut self, message: &str) {
        let warn = self.palette.glyphs().warn;
        self.push_note(&format!("{warn} {message}"));
    }

    /// Appends a neutral note to the feed (e.g. a confirmation of a chat-list
    /// operation once the list screen is already closed — a late auto-title/copy reply).
    pub fn push_note(&mut self, text: &str) {
        self.feed.push(FeedMessage::note(text));
        self.mark_feed_changed();
        // Arrives on its own (an error, a late list-operation reply) — §4.
        self.feed_view.scroll_to_bottom_if_following();
    }

    /// The agentic loop is asking whether to run a dangerous tool call
    /// (spec §9.8). Opens the modal popup; the answer leaves as
    /// [`ChatIntent::ConfirmTool`].
    pub fn request_tool_confirm(
        &mut self,
        generation_id: Uuid,
        call_id: String,
        name: String,
        arguments: String,
        inputs: Option<crate::features::chat_inputs::ConfirmInputs>,
    ) {
        self.tool_confirm = Some(ToolConfirm {
            generation_id,
            call_id,
            name,
            arguments,
            inputs,
        });
    }
}

/// A character whose rendering on legacy terminals (conhost/Command Prompt) diverges
/// from `ratatui`'s model enough that changing the content leaves "hanging"
/// artifacts — halves of wide glyphs, pieces of the backdrop, drifted rows.
///
/// Risk classes (all about emoji, not CJK: terminals render width-2 ideographs
/// consistently, so there's no point triggering a full redraw over them):
/// - **VS16** (U+FE0F) — `🗂️`: `ratatui` sends this cluster's trailing cell
///   separately, see [`crate::shared::ui::prime_full_redraw`];
/// - **ZWJ** (U+200D) — `👨‍👩‍👧`: a composite cluster, the model's and the terminal's widths
///   diverge the most (a deliberate boundary, see the `shared/wrap.rs` doc);
/// - **skin-tone modifiers** (U+1F3FB..=U+1F3FF) — `👍🏽`;
/// - **supplementary-plane pictographs** (≥ U+1F000) — `😀`, `🔥`;
/// - **width-2 BMP emoji symbols** (`✅`, `⭐`, `✨`) — ordinary arrows/typography
///   from the same width-1 blocks don't fall into this.
pub(super) fn is_risky_glyph(c: char) -> bool {
    use crate::shared::wrap::char_width;
    matches!(c, '\u{FE0F}' | '\u{200D}')
        || ('\u{1F3FB}'..='\u{1F3FF}').contains(&c)
        || c >= '\u{1F000}'
        || (('\u{2190}'..='\u{2BFF}').contains(&c) && char_width(c) == 2)
}

/// Whether a feed item contains a risk-group glyph (in the text, "thoughts", or
/// tool-call arguments/result) — in that case a content change or
/// scroll requires a full redraw. See [`is_risky_glyph`].
pub(super) fn feed_msg_has_risky_glyph(m: &FeedMessage) -> bool {
    let has = |s: &str| s.chars().any(is_risky_glyph);
    has(&m.text) || has(&m.thoughts) || m.tools.iter().any(|t| has(&t.arguments) || has(&t.result))
}