trusty-common 0.45.3

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
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
//! The memory TUI event loop: poll, render, handle input, drain SSE events.
//!
//! Why: keeping the async I/O — daemon polling, SSE subscription, recall
//! requests, drawer fetches — in a dedicated module separates it from the
//! pure state and rendering, making both easier to test independently.
//! What: [`run_loop`] is the inner loop called by `run_with_socket`; the other
//! functions are async helpers for specific operations (polling, recall,
//! SSE event application, drawer fetches).
//! Test: the pure pieces (state, log, rendering helpers) are unit-tested;
//! the async I/O glue is exercised by launching the UI.

use std::time::Instant;

use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};

use crate::monitor::memory_client::{
    ActivityFeed, MemoryClient, MemoryEvent, RecallHit, resolve_memory_socket,
};
use crate::monitor::memory_tui::MemoryFocus;
use crate::monitor::memory_tui::MemoryTuiState;
use crate::monitor::memory_tui::render::render;
use crate::monitor::memory_tui::state::{DRAWER_PAGE_SIZE, RECALL_TOP_K};
use crate::monitor::memory_tui::view::navigate_down_visible;
use crate::monitor::memory_tui::view::navigate_up_visible;
use crate::monitor::utils::DaemonStatus;

/// Data-refresh interval: how often the daemon is polled.
const REFRESH_INTERVAL: std::time::Duration = std::time::Duration::from_millis(2000);

/// Input-poll interval: how often the keyboard is checked.
const INPUT_POLL: std::time::Duration = std::time::Duration::from_millis(50);

/// Poll the trusty-memory daemon and fold the result into `state`.
///
/// Why: keeps the per-poll I/O out of the event loop so the loop can re-poll
/// on demand as well as on its timer.
/// What: re-resolves the socket when the daemon is offline, calls `fetch_all`,
/// and updates the status, aggregate stats, palace list, and selection clamp.
/// Test: thin I/O glue; the pure clamp is unit-tested.
pub(crate) async fn poll_daemon(state: &mut MemoryTuiState, client: &mut MemoryClient) {
    if !state.daemon_status.is_online()
        && let Ok(resolved) = resolve_memory_socket()
        && resolved != client.socket()
    {
        state.daemon_addr = resolved.display().to_string();
        client.set_socket(resolved);
    }
    match client.fetch_all().await {
        Ok(data) => {
            state.daemon_status = DaemonStatus::Online {
                version: data.version.clone(),
                uptime_secs: 0,
            };
            state.palaces = data.palaces.clone();
            state.status = Some(data);
            state.clamp_selection();
        }
        Err(e) => {
            state.daemon_status = DaemonStatus::Offline {
                last_error: e.to_string(),
            };
        }
    }
}

/// Run a recall and append the hits to the activity log.
///
/// Why: pressing `[Enter]` in the recall bar runs a memory recall; the
/// operator sees the results inline in the ACTIVITY panel. The recall endpoint
/// is inherently cross-palace, so when a single palace is selected the hits
/// are filtered to that palace; when "All palaces" is selected every hit is
/// shown.
/// What: calls `client.recall`, then — for the "All" selection — appends a
/// daemon-wide `recall "<q>" → N results` summary plus one `palace_id`-scoped
/// `· [palace] snippet` continuation per hit. For a single palace it appends a
/// palace-scoped summary counting only that palace's hits and a continuation
/// per kept hit. An empty query is a no-op; transport errors are logged scoped
/// to the selection.
/// Test: thin I/O glue; result projection is tested in `memory_client`.
async fn run_recall(state: &mut MemoryTuiState, client: &MemoryClient) {
    let query = state.input.trim().to_string();
    if query.is_empty() {
        return;
    }
    let scope = state.selected_id().map(str::to_string);
    match client.recall(&query, RECALL_TOP_K).await {
        Ok(hits) => match &scope {
            // "All palaces": one daemon-wide summary, each hit scoped to its
            // own palace so the per-palace feed still shows it.
            None => {
                state
                    .log
                    .push(format!("recall \"{query}\" (all) → {} results", hits.len()));
                for hit in &hits {
                    let palace = if hit.palace_id.is_empty() {
                        "?"
                    } else {
                        hit.palace_id.as_str()
                    };
                    state
                        .log
                        .push_raw_scoped(palace, format!("  · [{palace}] {}", hit.snippet));
                }
            }
            // A single palace: keep only that palace's hits.
            Some(id) => {
                let kept: Vec<&RecallHit> = hits.iter().filter(|h| h.palace_id == *id).collect();
                state
                    .log
                    .push_scoped(id, format!("recall \"{query}\" → {} results", kept.len()));
                for hit in kept {
                    state
                        .log
                        .push_raw_scoped(id, format!("  · {}", hit.snippet));
                }
            }
        },
        Err(e) => match &scope {
            None => state
                .log
                .push(format!("recall \"{query}\" (all) failed: {e}")),
            Some(id) => state
                .log
                .push_scoped(id, format!("recall \"{query}\" failed: {e}")),
        },
    }
    state.input.clear();
}

/// Append a streamed `/sse` event to the activity log, scoped to its palace.
///
/// Why: the SSE task forwards [`MemoryEvent`]s through a channel; the event
/// loop drains them and this turns each into a human-readable log entry. The
/// drawer events concern one palace, so they are tagged with its id and the
/// per-palace activity feed keeps only its own events.
/// What: `DreamCompleted` records a daemon-wide header plus an indented
/// merge/prune/compact line; `DrawerAdded` / `DrawerDeleted` record a single
/// line each scoped to `palace_id`; `PalaceCreated` records a daemon-wide line
/// (the new palace has no id yet on the wire).
/// Test: `test_log_append_dream`, `test_apply_memory_event`.
pub fn apply_memory_event(state: &mut MemoryTuiState, event: MemoryEvent) {
    match event {
        MemoryEvent::DreamCompleted {
            merged,
            pruned,
            compacted,
        } => {
            state.log.push("SSE: dream_completed");
            state.log.push_raw(format!(
                "  merged: {merged}  pruned: {pruned}  compacted: {compacted}"
            ));
        }
        MemoryEvent::DrawerAdded {
            palace_id,
            drawer_count,
            content_preview,
        } => {
            // Prefer a content preview when the daemon provided one; fall
            // back to the legacy "(<count>)" format so older daemons still
            // render a useful line.
            let line = if content_preview.is_empty() {
                format!("SSE: drawer added → {palace_id} ({drawer_count})")
            } else {
                format!("SSE: drawer added → {palace_id} ({drawer_count}): \"{content_preview}\"")
            };
            state.log.push_scoped(&palace_id, line);
        }
        MemoryEvent::DrawerDeleted {
            palace_id,
            drawer_count,
        } => {
            state.log.push_scoped(
                &palace_id,
                format!("SSE: drawer deleted → {palace_id} ({drawer_count})"),
            );
        }
        MemoryEvent::PalaceCreated { name } => {
            state.log.push(format!("SSE: palace created → {name}"));
        }
    }
}

/// Fetch the drawer page for the current selection and fold the result into
/// [`MemoryTuiState::drawer_list`].
///
/// Why: the activity panel needs a live page slice for whichever palace is
/// selected; isolating the fetch keeps the event loop free of per-trigger
/// branching and makes the loading / error transitions easy to reason about.
/// What: when no single palace is selected, clears the drawer slice and
/// returns. Otherwise issues `client.list_drawers` for the stored offset and
/// either replaces `drawers` or records the error. Always flips
/// `loading = false` so the renderer drops the in-flight badge.
/// Test: thin I/O glue; pure projection is tested in `memory_client`.
pub(crate) async fn fetch_drawer_page(state: &mut MemoryTuiState, client: &MemoryClient) {
    let Some(palace_id) = state.selected_id().map(str::to_string) else {
        // "All palaces" or no selection — clear the drawer slice; the panel
        // falls back to the aggregate activity log.
        state.drawer_list.palace_id = None;
        state.drawer_list.drawers.clear();
        state.drawer_list.offset = 0;
        state.drawer_list.loading = false;
        state.drawer_list.last_error = None;
        return;
    };

    state.drawer_list.palace_id = Some(palace_id.clone());
    state.drawer_list.loading = true;
    match client
        .list_drawers(&palace_id, DRAWER_PAGE_SIZE, state.drawer_list.offset)
        .await
    {
        Ok(rows) => {
            state.drawer_list.drawers = rows;
            state.drawer_list.last_error = None;
        }
        Err(e) => {
            state.drawer_list.last_error = Some(e.to_string());
            state.drawer_list.drawers.clear();
        }
    }
    state.drawer_list.loading = false;
}

/// Fetch the full memory detail for the drawer-detail modal (issue #215).
///
/// Why: when the operator presses `Enter` in the drawer pane the modal must
/// open with the verbatim drawer body. The activity-panel rows only carry
/// the truncated snippet, so we re-fetch the drawer list from the daemon —
/// which serialises every drawer's full `content` — and store the result in
/// `state.drawer_detail_memories`.
/// What: when no palace is selected, leaves the modal closed and returns.
/// Otherwise issues `client.fetch_drawer_detail` for the current scope and
/// either replaces the memories or records the failure on the log. Always
/// flips `drawer_detail_loading = false` so the modal drops its in-flight
/// label.
/// Test: thin I/O glue; pure projection is tested via `parse_memory_details`.
async fn fetch_drawer_detail(state: &mut MemoryTuiState, client: &MemoryClient) {
    let Some(palace_id) = state.selected_id().map(str::to_string) else {
        // No single palace selected — close the modal so it can't render
        // stale memories from a previous scope.
        state.close_drawer_detail();
        return;
    };
    state.drawer_detail_loading = true;
    // Use a generous limit so the modal can show the entire drawer page (the
    // pane page size is 20, but the modal lets the operator scroll through
    // every memory the daemon returns).
    match client.fetch_drawer_detail(&palace_id, 50).await {
        Ok(memories) => {
            state.drawer_detail_memories = memories;
            // Clamp the selected index to the loaded set in case the page
            // shrank between key-press and fetch completion.
            if state.drawer_detail_idx >= state.drawer_detail_memories.len() {
                state.drawer_detail_idx = state.drawer_detail_memories.len().saturating_sub(1);
            }
        }
        Err(e) => {
            // Surface the error on the activity log so the operator sees why
            // the modal stayed empty. The modal itself shows a `Loading…`
            // placeholder until either a fetch succeeds or it is closed.
            state
                .log
                .push_scoped(&palace_id, format!("drawer detail fetch failed: {e}"));
            state.drawer_detail_memories.clear();
        }
    }
    state.drawer_detail_loading = false;
}

/// The memory TUI event loop: poll, render, handle input, drain SSE events.
///
/// Why: kept separate from `run_with_socket` so terminal setup/teardown wraps it
/// cleanly.
/// What: polls the daemon immediately, then renders every frame while polling
/// the keyboard every 50 ms; on the 2 s timer it re-polls the status AND reads
/// the activity rows past its cursor (#6286 — `/sse` is retired, so events
/// arrive on the tick rather than as they happen). `[d]` triggers a dream
/// cycle, `[Enter]` runs a recall; `Tab`, arrows, `?`, `q`/`Esc`, and `Ctrl-C`
/// behave per [`KEY_HINT`].
/// Carry the feed across one tick, reporting whether it held the log for the
/// interval this tick's poll covers.
///
/// Why it returns the answer rather than the caller computing it (#6286 review,
/// finding 1): this function both READS the feed's state and REPLACES the feed,
/// and the reader must run first. When the caller captured the state itself,
/// the capture sat above a death check that reassigns `feed` — and moving it
/// below, or reading `feed` again after the re-open, silently produced a live
/// feed and a discarded poll. Returning the captured value makes that ordering
/// impossible to express wrongly: there is no post-re-open state to read,
/// because the only answer the caller gets is the one taken before.
///
/// What, in order: capture whether the feed is live; take and render a lag
/// notice from a feed that still is; on a feed that has stopped, report why and
/// drop it; then re-open if there is nothing attached, so a restarted daemon
/// re-attaches with no operator action.
///
/// Test: the ordering is structural — the return value cannot come from after
/// the re-open. What the caller does with it is pinned by
/// `poll_renders_the_death_window_even_though_the_feed_reopened`; the feed's own
/// lag and death reporting by `monitor::memory_client::feed::tests`.
async fn rotate_feed(
    state: &mut MemoryTuiState,
    client: &MemoryClient,
    feed: &mut Option<ActivityFeed>,
) -> bool {
    let was_healthy = feed.as_ref().is_some_and(ActivityFeed::is_live);

    // A lag notice arrives on a feed that is still working, so it is taken
    // every tick rather than only when the stream dies. Taking clears it, so
    // each notice renders once.
    if was_healthy && let Some(hole) = feed.as_ref().and_then(ActivityFeed::take_last_error) {
        state.log.push_raw(format!("activity stream: {hole}"));
    }

    if feed.as_ref().is_some_and(|f| !f.is_live()) {
        let reason = feed
            .as_ref()
            .and_then(ActivityFeed::take_last_error)
            .unwrap_or_else(|| "the activity stream ended".to_string());
        state
            .log
            .push_raw(format!("activity stream lost ({reason}); polling"));
        *feed = None;
    }
    if feed.is_none() {
        *feed = open_activity_feed(state, client).await;
    }

    was_healthy
}

/// What the activity log does with one poll's events.
///
/// Why it is a type rather than a bool (#6286): the three outcomes are not two.
/// Seeding and cursor-only both render nothing but for different reasons, and
/// conflating them is how the first read's whole page of history nearly went
/// into the log. Naming them also makes the handover testable without a
/// terminal — see [`poll_disposition`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PollDisposition {
    /// First read: seed the cursor, render nothing. Dumping a page of history
    /// into the log the moment the TUI opens is a worse answer than an empty
    /// log.
    Seed,
    /// The stream already delivered this interval's events. Advance the cursor
    /// so a later fallback resumes rather than replaying.
    CursorOnly,
    /// The stream is not carrying the log for this interval. Render them.
    Render,
}

/// Decide what this tick's poll does, given the feed's state at the START of
/// the tick.
///
/// Why `feed_was_healthy` and not the feed's current state (#6286 review,
/// finding 1): the tick re-opens a dead feed before the poll runs, so by then
/// the feed is live again — and a re-subscribed `broadcast::Receiver` replays
/// nothing. Judging on the post-re-open state discards exactly the events the
/// fallback exists to catch, while the cursor advances past them. Every event
/// emitted in the death window would then reach neither source.
///
/// What: `Seed` on the first read; `CursorOnly` when the feed carried the
/// interval; `Render` otherwise. A feed that died mid-interval and re-opened on
/// this tick yields `Render`, so its events are rendered from the poll. That
/// can duplicate a row the stream had already delivered before it died, which
/// is the accepted cost: a duplicate is visible and a gap is not.
///
/// Test: `poll_seeds_the_cursor_on_the_first_read`,
/// `poll_advances_only_while_the_feed_carried_the_interval`,
/// `poll_renders_the_death_window_even_though_the_feed_reopened`.
fn poll_disposition(seeded_events: bool, feed_was_healthy: bool) -> PollDisposition {
    if !seeded_events {
        PollDisposition::Seed
    } else if feed_was_healthy {
        PollDisposition::CursorOnly
    } else {
        PollDisposition::Render
    }
}

/// Open the live activity feed, saying so either way (#6286).
///
/// Why: this replaces a 2-second poll, and a silent failure to attach would
/// leave the log looking like an idle daemon rather than a degraded TUI. Both
/// outcomes go in the log so an operator reading it knows which source the
/// events are coming from.
/// What: `Some` on success; `None` when the daemon is not serving the method —
/// which is what a daemon predating it, and one that is not running, both look
/// like. The caller polls in that case.
/// Test: the feed's own contract is covered by
/// `monitor::memory_client::feed::tests`; this is the wiring.
async fn open_activity_feed(
    state: &mut MemoryTuiState,
    client: &MemoryClient,
) -> Option<ActivityFeed> {
    match ActivityFeed::open(client.socket()).await {
        Ok(feed) => {
            state.log.push_raw("activity stream attached".to_string());
            Some(feed)
        }
        Err(e) => {
            state
                .log
                .push_raw(format!("activity stream unavailable ({e}); polling"));
            None
        }
    }
}

/// Test: the pure pieces (state, log, rendering helpers) are unit-tested.
pub(crate) async fn run_loop<B: ratatui::backend::Backend>(
    terminal: &mut ratatui::Terminal<B>,
    state: &mut MemoryTuiState,
    client: &mut MemoryClient,
) -> anyhow::Result<()> {
    poll_daemon(state, client).await;
    let mut last_poll = Instant::now();

    // #6286: the activity log's two sources. The live stream is what `/sse`
    // was; the poll is the fallback, kept because a daemon that predates
    // `memory.activity_stream` — or one that restarts under this TUI — must
    // leave the log working rather than blank.
    let mut feed = open_activity_feed(state, client).await;

    // The poll's cursor. `0` means "everything the first read finds is new";
    // the first read therefore seeds it rather than replaying the whole page
    // into the log. It advances on every poll whether or not the feed is live,
    // so a fallback picks up where the stream left off instead of replaying.
    let mut event_cursor: u64 = 0;
    let mut seeded_events = false;

    // Issue #184: every time the palace selection changes, refresh the
    // drawer panel. Tracking the previously-shown scope avoids re-fetching
    // on every render tick.
    let mut last_drawer_scope: Option<String> = None;

    loop {
        terminal.draw(|f| render(f, state))?;
        // `terminal.draw` requires `state` mutably (the renderer scrolls the
        // palace list); the closure reborrows it for the rest of the loop.

        let key = if event::poll(INPUT_POLL)? {
            match event::read()? {
                Event::Key(key) => Some(key),
                _ => None,
            }
        } else {
            None
        };
        if let Some(key) = key
            && key.kind != KeyEventKind::Release
        {
            // Ctrl-C always quits, regardless of focus or the help overlay.
            if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
                return Ok(());
            }
            if state.show_help {
                if matches!(key.code, KeyCode::Char('?') | KeyCode::Esc) {
                    state.show_help = false;
                } else if key.code == KeyCode::Char('q') {
                    return Ok(());
                }
                continue;
            }
            // Issue #215: drawer-detail modal owns the keyboard while open —
            // `Esc`/`q` close it; `↑`/`↓` scroll its body; everything else is
            // swallowed so the underlying UI never reacts under the modal.
            if state.drawer_detail_open {
                match key.code {
                    KeyCode::Esc | KeyCode::Char('q') => state.close_drawer_detail(),
                    KeyCode::Up => {
                        state.drawer_detail_scroll = state.drawer_detail_scroll.saturating_sub(1);
                    }
                    KeyCode::Down => {
                        state.drawer_detail_scroll = state.drawer_detail_scroll.saturating_add(1);
                    }
                    _ => {}
                }
                continue;
            }
            match (state.focus, key.code) {
                // Filter-active bindings come first — they capture characters,
                // backspace, Esc, and Enter before the general List handlers.
                (MemoryFocus::List, KeyCode::Esc) if state.filter_active => {
                    // Keep the filter text so the user can re-activate.
                    state.filter_active = false;
                }
                (MemoryFocus::List, KeyCode::Enter) if state.filter_active => {
                    state.filter_active = false;
                }
                (MemoryFocus::List, KeyCode::Backspace) if state.filter_active => {
                    state.filter.pop();
                    state.clamp_to_visible();
                }
                (MemoryFocus::List, KeyCode::Char(c)) if state.filter_active => {
                    state.filter.push(c);
                    state.clamp_to_visible();
                }
                // Tab is a no-op while the filter is active — otherwise it
                // would steal focus away from the list and break filter input.
                (MemoryFocus::List, KeyCode::Tab) if state.filter_active => {}
                (_, KeyCode::Char('?')) => state.show_help = true,
                // Issue #215: Tab cycles through every focusable zone.
                (_, KeyCode::Tab) => state.cycle_focus(),
                // Esc on the drawer pane returns focus to the palace list
                // (with the drawer cursor cleared); on every other zone Esc
                // still quits, matching the legacy behaviour.
                (MemoryFocus::DrawerPane, KeyCode::Esc) => {
                    state.focus = MemoryFocus::List;
                    state.drawer_cursor = 0;
                }
                (_, KeyCode::Esc) => return Ok(()),
                // List-focus bindings.
                (MemoryFocus::List, KeyCode::Char('q')) => return Ok(()),
                (MemoryFocus::List, KeyCode::Up) => navigate_up_visible(state),
                (MemoryFocus::List, KeyCode::Down) => navigate_down_visible(state),
                // Drawer-page navigation in the ACTIVITY panel — only when a
                // single palace is selected. `←` previous page, `→` next.
                (MemoryFocus::List, KeyCode::Left) if state.selected_id().is_some() => {
                    state.drawer_list.prev_page();
                    fetch_drawer_page(state, client).await;
                    state.clamp_drawer_cursor();
                }
                (MemoryFocus::List, KeyCode::Right) if state.selected_id().is_some() => {
                    state.drawer_list.next_page();
                    fetch_drawer_page(state, client).await;
                    state.clamp_drawer_cursor();
                }
                (MemoryFocus::List, KeyCode::Char('/')) => {
                    state.filter_active = true;
                    state.filter.clear();
                }
                (MemoryFocus::List, KeyCode::Char('s')) => {
                    state.sort_key = state.sort_key.next();
                }
                (MemoryFocus::List, KeyCode::Char('g')) => {
                    state.group_by_project = !state.group_by_project;
                }
                (MemoryFocus::List, KeyCode::Char('d')) => {
                    let now = Instant::now();
                    if !state.dream_backoff.ready(now) {
                        let remaining = state.dream_backoff.remaining(now);
                        tracing::debug!(
                            "dream cycle suppressed by backoff: {}s remaining",
                            remaining.as_secs()
                        );
                        // Only echo the cooldown once per quiet period — log a
                        // single hint line the first time the operator hits
                        // [d] inside the window, then stay silent on repeats.
                    } else {
                        state.log.push("dream cycle triggered");
                        match client.dream_run().await {
                            Ok(stats) => {
                                state.log.push_raw(format!(
                                    "  merged: {}  pruned: {}  compacted: {}",
                                    stats.merged, stats.pruned, stats.compacted
                                ));
                                state.dream_backoff.record_success();
                            }
                            Err(e) => {
                                let should_log = state.dream_backoff.record_failure(Instant::now());
                                if should_log {
                                    let next = state.dream_backoff.remaining(Instant::now());
                                    state.log.push(format!(
                                        "dream failed: {e} (next attempt in {}s)",
                                        next.as_secs()
                                    ));
                                } else {
                                    tracing::debug!(
                                        "dream failed (suppressed, {} consecutive failures): {e}",
                                        state.dream_backoff.consecutive_failures()
                                    );
                                }
                            }
                        }
                        poll_daemon(state, client).await;
                        last_poll = Instant::now();
                    }
                }
                // DrawerPane bindings (issue #215). `↑`/`↓` move the drawer
                // cursor through the current page; `Enter` opens the detail
                // modal for the highlighted drawer; `←`/`→` continue to do
                // page navigation so the operator can step through pages
                // without switching focus back to the list.
                (MemoryFocus::DrawerPane, KeyCode::Up) => {
                    state.drawer_cursor_up();
                }
                (MemoryFocus::DrawerPane, KeyCode::Down) => {
                    state.drawer_cursor_down();
                }
                (MemoryFocus::DrawerPane, KeyCode::Left) if state.selected_id().is_some() => {
                    state.drawer_list.prev_page();
                    fetch_drawer_page(state, client).await;
                    state.clamp_drawer_cursor();
                }
                (MemoryFocus::DrawerPane, KeyCode::Right) if state.selected_id().is_some() => {
                    state.drawer_list.next_page();
                    fetch_drawer_page(state, client).await;
                    state.clamp_drawer_cursor();
                }
                (MemoryFocus::DrawerPane, KeyCode::Enter)
                    if !state.drawer_list.drawers.is_empty()
                        && state.drawer_cursor < state.drawer_list.drawers.len() =>
                {
                    state.drawer_detail_open = true;
                    state.drawer_detail_idx = state.drawer_cursor;
                    state.drawer_detail_scroll = 0;
                    state.drawer_detail_memories.clear();
                    fetch_drawer_detail(state, client).await;
                }
                (MemoryFocus::DrawerPane, KeyCode::Char('q')) => return Ok(()),
                // Input-focus bindings.
                (MemoryFocus::Input, KeyCode::Enter) => {
                    run_recall(state, client).await;
                }
                (MemoryFocus::Input, KeyCode::Backspace) => {
                    state.input.pop();
                }
                (MemoryFocus::Input, KeyCode::Char(c)) => state.input.push(c),
                _ => {}
            }
        }

        // #6286: events the live stream pushed, taken every render tick rather
        // than every poll tick — that latency is the whole reason the stream
        // exists. Draining never blocks.
        if let Some(live) = feed.as_mut() {
            for event in live.drain() {
                apply_memory_event(state, event);
            }
        }

        if last_poll.elapsed() >= REFRESH_INTERVAL {
            poll_daemon(state, client).await;

            let feed_was_healthy = rotate_feed(state, client, &mut feed).await;

            // The poll. It runs on every tick regardless, and
            // `poll_disposition` decides what to do with what it found.
            if let Ok((cursor, events)) = client.recent_events(event_cursor).await {
                if poll_disposition(seeded_events, feed_was_healthy) == PollDisposition::Render {
                    for event in events {
                        apply_memory_event(state, event);
                    }
                }
                seeded_events = true;
                event_cursor = cursor;
            }
            // Refresh the drawer page in lock-step with the daemon poll so
            // new drawers appear in the activity panel without needing a
            // key press (issue #184: "Real-time updates when new drawers
            // are added while viewing").
            if state.selected_id().is_some() {
                fetch_drawer_page(state, client).await;
                state.clamp_drawer_cursor();
            }
            last_poll = Instant::now();
        }

        // Detect a palace-selection change after key handling and refresh
        // the drawer slice. Comparing the stored scope means we only fire
        // the fetch on real changes, not on every render tick.
        let current_scope = state.selected_id().map(str::to_string);
        if current_scope != last_drawer_scope {
            state.drawer_list.reset_for(current_scope.clone());
            fetch_drawer_page(state, client).await;
            // Issue #215: palace change resets the drawer cursor; the modal
            // (if open) should also close since its memories belong to the
            // previous scope.
            state.drawer_cursor = 0;
            state.close_drawer_detail();
            last_drawer_scope = current_scope;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{PollDisposition, poll_disposition};

    /// Why: the first read finds every row past a zero cursor, so rendering it
    /// would dump the whole activity table into the log the moment the TUI
    /// opens. It seeds the cursor instead — and it does so whether or not the
    /// stream attached, because the reason is the cursor, not the feed.
    /// Test: itself.
    #[test]
    fn poll_seeds_the_cursor_on_the_first_read() {
        assert_eq!(poll_disposition(false, true), PollDisposition::Seed);
        assert_eq!(poll_disposition(false, false), PollDisposition::Seed);
    }

    /// Why: a live stream already put this interval's events in the log. The
    /// poll still runs, so the cursor keeps pace and a later fallback resumes
    /// where the stream left off instead of replaying from wherever it last
    /// polled.
    /// Test: itself.
    #[test]
    fn poll_advances_only_while_the_feed_carried_the_interval() {
        assert_eq!(poll_disposition(true, true), PollDisposition::CursorOnly);
    }

    /// Why (#6286 review, finding 1): this is the handover, and it is where the
    /// gap was. The tick that notices a dead feed also RE-OPENS it, so by the
    /// time the poll runs the feed is live again — and a re-subscribed
    /// `broadcast::Receiver` replays nothing. Judged on the post-re-open state,
    /// the disposition was `CursorOnly`: this tick's events were discarded and
    /// the cursor advanced past them, so every event emitted while the stream
    /// was down reached neither source.
    ///
    /// The fix is that the decision reads the feed's state at the START of the
    /// tick, which is what this pins. A duplicate row on the death tick is the
    /// accepted cost — a duplicate is visible, a gap is not.
    /// Test: itself.
    #[test]
    fn poll_renders_the_death_window_even_though_the_feed_reopened() {
        // `false` is `feed_was_healthy`, captured before the re-open. The feed
        // is live again by the time the poll runs; the disposition must not
        // care.
        assert_eq!(poll_disposition(true, false), PollDisposition::Render);
    }

    /// Why: a TUI running with no stream at all — a daemon predating
    /// `memory.activity_stream`, or one that is not running — has the poll as
    /// its only source, and must render every tick after the first.
    /// Test: itself.
    #[test]
    fn poll_renders_every_tick_when_no_stream_ever_attached() {
        let mut seeded = false;
        let mut rendered = 0;
        for _ in 0..3 {
            if poll_disposition(seeded, false) == PollDisposition::Render {
                rendered += 1;
            }
            seeded = true;
        }
        assert_eq!(rendered, 2, "the first tick seeds, every one after renders");
    }
}