heatsync-tui 0.4.0

heat-sorted live multichat in the terminal — twitch, kick + youtube (read-only), real emotes, vim keys
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
//! heatsync tui — heat-sorted live multichat. `heatsync [channels…]` opens the
//! grid (default demo set); `--mock` runs the offline synthetic feed; `log`,
//! `search`, `hot` are headless corpus subcommands.
//! keys: j/k and h/l (or arrows, tab/shift-tab) change channel, space pauses,
//! i composes, o joins, m manages, q quits. chat always follows live — there
//! is no message cursor and no keyboard nav over messages.

mod app;
mod blocks;
mod cli;
mod clock;
mod config;
mod draw;
mod drawlog;
mod emote;
mod feed;
mod fill;
mod followlog;
mod held;
mod hsauth;
mod http;
mod input;
mod intr;
mod key;
mod kick;
mod lang;
mod layout;
mod mentions;
mod modcmd;
mod net;
mod paints;
mod palette;
mod picker;
mod sched;
mod scroll;
mod social;
mod special;
mod streamrow;
mod talk;
mod temp;
mod twitch;

use std::io::{self, IsTerminal};
use std::time::{Duration, Instant};

use app::{App, Feed, InputMode};
use config::TabPos;
use crossterm::event::{self, Event, KeyEventKind};
use draw::{emote_mode, ui};
use emote::fb::FbEmotes;
use emote::render::EmoteStore;
use feed::{
    drain_emotes, drain_feed, drain_history, drain_hs, drain_pins, drain_twitch, pump_loads,
    request_stacks, spawn_emote_fetch, spawn_global_emotes, spawn_history, spawn_pin, tick_advance,
};
use heatsync_core::edit;
use heatsync_core::emote::EmoteSet;
use heatsync_core::i18n::{tr, trf};
use heatsync_core::room::RoomModes;
use heatsync_core::streamev::StreamEvents;
use heatsync_core::TabKind;
use heatsync_core::{mock, Channel, Platform};
use input::{drain_picker, handle_key, Flow};
use net::Sub;
use ratatui::Terminal;

fn main() -> io::Result<()> {
    config::init_lang();
    intr::install();
    let args: Vec<String> = std::env::args().skip(1).collect();
    match args.first().map(String::as_str) {
        Some("log") => return cli::log(&args[1..]),
        Some("search") => return cli::search(&args[1..]),
        Some("hot") | Some("top") => return cli::hot(&args[1..]),
        Some("probe") => return cli::probe(&args[1..]),
        Some("diag") => return cli::diag(&args[1..]),
        Some("render-test") => return cli::render_test(&args[1..]),
        Some("status") => return cli::status(),
        Some("lang") => return lang::run(&args[1..]),
        Some("login") => {
            intr::login_phase();
            // an interactive login drops you into the chat, same as plain `hs`
            let opened = cli::login(args.get(1).map(String::as_str) == Some("kick"))?;
            intr::plain_phase();
            if !opened {
                return Ok(());
            }
            return chat(&[]);
        }
        Some("logout") => return cli::logout(),
        // The two flags every installed binary is asked first. Without them
        // `heatsync-tui --version` fell through to the TUI, tried to connect to
        // three channels, and then panicked out of ratatui because there was no
        // terminal — which is what a fresh `cargo install` looks like when you
        // check what you just installed.
        Some("--version") | Some("-V") => {
            println!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
            return Ok(());
        }
        Some("--help") | Some("-h") | Some("help") => {
            print!("{}", tr("input.main_usage"));
            return Ok(());
        }
        _ => {}
    }
    chat(&args)
}

/// the chat ui, for plain `hs` and for the end of an interactive `hs login`.
fn chat(args: &[String]) -> io::Result<()> {
    // Starting the TUI needs a terminal. Say so plainly instead of panicking
    // out of ratatui's init with `Os { code: 6 }`, which is what a pipe, a cron
    // job or a CI step would otherwise get.
    if !io::stdin().is_terminal() || !io::stdout().is_terminal() {
        eprintln!(
            "{}",
            trf("input.main_no_tty", &[("usage", tr("input.main_usage"))])
        );
        std::process::exit(1);
    }

    let mock_mode = args.iter().any(|a| a == "--mock");
    let chan_args: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect();
    let cfg = config::load();
    heatsync_core::block::load(cfg.blocks.clone());
    let mut app = if mock_mode {
        let (hs_tx, hs_rx) = std::sync::mpsc::channel::<hsauth::Note>();
        let (emote_tx, emote_rx) = std::sync::mpsc::channel();
        let (hist_tx, hist_rx) = std::sync::mpsc::channel();
        let (pick_tx, pick_rx) = std::sync::mpsc::channel();
        App {
            channels: mock::channels(),
            emotes: (0..mock::channels().len())
                .map(|_| EmoteSet::new())
                .collect(),
            globals: EmoteSet::new(),
            focus: 0,
            paused: false,
            feed: Feed::Mock(mock::Driver::new()),
            store: None,
            fb: None,
            mode: InputMode::Normal,
            input: String::new(),
            line: edit::Line::default(),
            status: None,
            out: None,
            twitch_tx: None,
            twitch_notes: None,
            kick_tx: None,
            hs: None,
            hs_tx,
            hs_notes: hs_rx,
            tab_pos: cfg.tab_pos,
            manage_cursor: 0,
            completion: None,
            me: Vec::new(),
            names_rx: std::sync::mpsc::channel().1,
            names_tx: std::sync::mpsc::channel().0,
            stamps: cfg.timestamps,
            emote_tx,
            emote_rx,
            hist_tx,
            hist_rx,
            picker: None,
            pick_cache: picker::Cache(None),
            streams: StreamEvents::new(),
            seen: Default::default(),
            rooms: RoomModes::new(),
            pick_tx,
            pick_rx,
            pick_inflight: false,
            paints: paints::Paints::new(),
            pin_tx: std::sync::mpsc::channel().0,
            pin_rx: std::sync::mpsc::channel().1,
            cursor: 0,
            reply: None,
            view_h: std::cell::Cell::new(0),
            chat_body: Default::default(),
            special: special::State::new(false),
        }
    } else {
        let feed_open = cfg.special.contains(&TabKind::Feed);
        build_live(
            &chan_args,
            cfg.tab_pos,
            cfg.timestamps,
            cfg.channels,
            feed_open,
        )
    };
    // virtual tabs pin left of whatever the channel args / config opened.
    special::restore(&mut app, &cfg.special);
    if !mock_mode {
        blocks::pull(&app);
        app.line.set_history(config::load_history());
    }

    // must probe the terminal for graphics BEFORE raw mode / alt screen.
    let had_fb = app.fb.is_some();
    // init() for raw mode, the alternate screen and the panic hook; the terminal
    // itself runs on the held backend (see held.rs).
    drop(ratatui::init());
    emote::decode::install_hook();
    let mut terminal = Terminal::new(held::HeldBackend::new())?;
    intr::tui_phase();
    let res = run(&mut terminal, app);
    ratatui::restore();
    intr::plain_phase();
    if had_fb {
        // the bare console has no alternate screen to pop back to, so the dead
        // TUI text AND our framebuffer emote pixels would linger behind the
        // shell prompt. a real clear repaints every cell (wiping both).
        use std::io::Write;
        print!("\x1b[2J\x1b[H");
        let _ = io::stdout().flush();
    }
    res
}

/// parse channel args (`name`, `twitch:name`, `kick:name`, `yt:id`, and
/// `a+kick:a+yt:x` merged tabs), fetch emote sets, and start the live feed.
/// prints a one-line loading note before raw mode.
fn build_live(
    chan_args: &[&String],
    tab_pos: TabPos,
    stamps: bool,
    saved: Vec<Vec<Sub>>,
    feed_open: bool,
) -> App {
    // precedence: explicit CLI args → persisted tabs → empty (a clean "press o to
    // join" state; no hardcoded demo channels). first run starts blank; whatever
    // you open persists, so the next launch restores it.
    let tabs: Vec<Vec<Sub>> = if !chan_args.is_empty() {
        chan_args.iter().map(|a| parse_tab(a)).collect()
    } else {
        saved
    };
    let tabs: Vec<Vec<Sub>> = tabs.into_iter().filter(|t| !t.is_empty()).collect();

    eprintln!(
        "{}",
        trf("input.main_connecting", &[("n", &tabs.len().to_string())])
    );
    // pick the emote tier now, while we're still a normal terminal:
    //   1. a graphics-capable emulator (sixel/kitty) → EmoteStore
    //   2. else a bare Linux console with /dev/fb0 → framebuffer tier
    //   3. else text-only
    let store = EmoteStore::new();
    let fb = if store.is_none() {
        let (cols, rows) = crossterm::terminal::size().unwrap_or((80, 24));
        FbEmotes::open(cols, rows)
    } else {
        None
    };
    let tier = match (&store, &fb) {
        (Some(s), _) => s.tier_label(),
        (None, Some(_)) => tr("input.main_tier_fb"),
        _ => tr("input.main_tier_text"),
    };
    eprintln!("{}", trf("input.main_emotes_tier", &[("tier", tier)]));
    if store.is_none() && fb.is_none() {
        eprintln!("  {}", tr("input.main_emote_hint"));
    }
    // channels open immediately with empty emote sets; each set is fetched on a
    // background thread and merged in via emote_rx once it lands (no UI stall).
    let (emote_tx, emote_rx) = std::sync::mpsc::channel();
    let (hist_tx, hist_rx) = std::sync::mpsc::channel();
    let (pin_tx, pin_rx) = std::sync::mpsc::channel();
    let mut channels = Vec::new();
    let mut emotes = Vec::new();
    for tab in &tabs {
        let (platform, name) = &tab[0];
        let mut ch = Channel::new(name, *platform, 200);
        ch.extra = tab[1..].to_vec();
        channels.push(ch);
        emotes.push(EmoteSet::new());
        for (p, n) in tab {
            // youtube has no emote API, and its archive is keyed by broadcaster
            // name (we only know the video id) — both fetches would be dead calls.
            if *p != Platform::Youtube {
                spawn_emote_fetch(&emote_tx, *p, n.clone());
                spawn_history(&hist_tx, *p, n.clone());
                spawn_pin(&pin_tx, *p, n.clone());
            }
        }
    }

    // the heatsync login signs the socket in (whispers, dms, mention hits ride
    // it); HEATSYNC_TOKEN, when set, wins.
    let hs = hsauth::load_client();
    let env_token = std::env::var("HEATSYNC_TOKEN")
        .ok()
        .filter(|t| !t.is_empty());
    let ws_cli = env_token.is_none() && hs.as_ref().and_then(|c| c.socket_token()).is_some();
    let token = env_token.or_else(|| hs.as_ref().and_then(|c| c.socket_token()));
    let subs: Vec<Sub> = tabs.into_iter().flatten().collect();
    let (rx, out) = net::spawn(subs, token, feed_open);
    // direct-to-platform sending if the user supplied their own platform tokens.
    let auth = config::load_auth();
    let me: Vec<String> = auth.twitch_user.iter().cloned().collect();
    let kick_tx = auth.kick_token.clone().map(kick::spawn);
    let (twitch_tx, twitch_notes) = match (auth.twitch_user, auth.twitch_oauth) {
        (Some(u), Some(o)) => {
            let (tx, notes) = twitch::spawn(u, o);
            (Some(tx), Some(notes))
        }
        _ => (None, None),
    };
    spawn_global_emotes(&emote_tx);
    let (hs_tx, hs_rx) = std::sync::mpsc::channel::<hsauth::Note>();
    let (pick_tx, pick_rx) = std::sync::mpsc::channel();
    // my kick login isn't in the local auth — ask the heatsync login once, off-thread.
    let (names_tx, names_rx) = std::sync::mpsc::channel();
    if let Some(c) = hs.clone() {
        let tx = names_tx.clone();
        std::thread::spawn(move || {
            if let Ok(v) = c.me() {
                let _ = tx.send(hsauth::my_names(&v));
            }
        });
    }
    App {
        channels,
        emotes,
        globals: EmoteSet::new(),
        focus: 0,
        paused: false,
        feed: Feed::Live {
            rx,
            start: Instant::now(),
            connected: false,
        },
        store,
        fb,
        mode: InputMode::Normal,
        input: String::new(),
        line: edit::Line::default(),
        status: None,
        out: Some(out),
        twitch_tx,
        twitch_notes,
        kick_tx,
        hs,
        hs_tx,
        hs_notes: hs_rx,
        tab_pos,
        manage_cursor: 0,
        completion: None,
        me,
        names_rx,
        names_tx,
        stamps,
        emote_tx,
        emote_rx,
        hist_tx,
        hist_rx,
        picker: None,
        pick_cache: picker::Cache(None),
        streams: StreamEvents::new(),
        seen: Default::default(),
        rooms: RoomModes::new(),
        pick_tx,
        pick_rx,
        pick_inflight: false,
        paints: paints::Paints::new(),
        pin_tx,
        pin_rx,
        cursor: 0,
        reply: None,
        view_h: std::cell::Cell::new(0),
        chat_body: Default::default(),
        special: special::State::new(ws_cli),
    }
}

/// persist the current tab set + bar position (live mode only — mock is ephemeral).
pub(crate) fn save_state(app: &App) {
    if !matches!(app.feed, Feed::Live { .. }) {
        return;
    }
    config::save(&persisted(app));
}

/// what goes to disk. the temp tab is filtered here, at the only door.
pub(crate) fn persisted(app: &App) -> config::Config {
    let channels = app
        .channels
        .iter()
        .filter(|c| !c.kind.is_special() && !c.temp)
        .map(|c| c.subs().map(|(p, n)| (p, n.to_string())).collect())
        .collect();
    let special = app
        .channels
        .iter()
        .map(|c| c.kind)
        .filter(|k| k.is_special())
        .collect();
    config::Config {
        tab_pos: app.tab_pos,
        timestamps: app.stamps,
        channels,
        special,
        blocks: heatsync_core::block::list(),
        lang: config::lang_setting(),
    }
}

/// one tab spec: `+`-joined subs merge into a single interleaved tab
/// (`nl_kripp+kick:nl_kripp+yt:VIDEOID`). whitespace separates too — channel
/// names never contain spaces, so `a kick:a` typed in the join prompt means
/// the same merge.
pub(crate) fn parse_tab(tok: &str) -> Vec<Sub> {
    let mut subs: Vec<Sub> = Vec::new();
    for part in tok
        .split(|c: char| c == '+' || c.is_whitespace())
        .filter(|s| !s.trim().is_empty())
    {
        let s = parse_sub(part.trim());
        if !s.1.is_empty()
            && !subs
                .iter()
                .any(|(p, n)| *p == s.0 && n.eq_ignore_ascii_case(&s.1))
        {
            subs.push(s);
        }
    }
    subs
}

pub(crate) fn parse_sub(tok: &str) -> Sub {
    if let Some(rest) = tok.strip_prefix("kick:") {
        (Platform::Kick, rest.to_string())
    } else if let Some(rest) = tok
        .strip_prefix("yt:")
        .or_else(|| tok.strip_prefix("youtube:"))
    {
        (Platform::Youtube, yt_video_id(rest))
    } else if tok.contains("youtube.com") || tok.contains("youtu.be") {
        (Platform::Youtube, yt_video_id(tok))
    } else if let Some(rest) = tok.strip_prefix("twitch:") {
        (Platform::Twitch, rest.to_string())
    } else {
        (Platform::Twitch, tok.to_string())
    }
}

/// pull the live VIDEO id out of whatever the user pasted: a bare id, a
/// `watch?v=` url, `youtu.be/id`, or `/live/id`. youtube chat subscribes by
/// video id — a handle url can't be resolved client-side, so the id is the
/// canonical channel name.
pub(crate) fn yt_video_id(tok: &str) -> String {
    let tail = tok
        .split_once("v=")
        .map(|(_, t)| t)
        .or_else(|| tok.split_once("youtu.be/").map(|(_, t)| t))
        .or_else(|| tok.split_once("/live/").map(|(_, t)| t))
        .unwrap_or(tok);
    tail.chars()
        .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
        .collect()
}

fn run(terminal: &mut Terminal<held::HeldBackend>, mut app: App) -> io::Result<()> {
    // data cadence: pull chat + decay heat every `tick`. draw cadence: while an
    // animated emote is on the store, redraw every `anim_frame` (~20fps) so the
    // animation is smooth — ratatui diffs the buffer, so an idle frame re-emits
    // nothing and only the changed emote cells cost anything. text-only / static
    // views stay lazy (redraw only on the tick or a keypress).
    let tick = Duration::from_millis(200);
    let mut last = Instant::now();
    // see the frame loop below: synchronized output is a win everywhere EXCEPT
    // inside tmux with passthrough emotes, where it costs us every emote on screen.
    let sync = std::env::var_os("TMUX").is_none() || app.store.as_ref().is_none_or(|s| s.sync_ok());
    // smoothed cost of one draw. animations run at their authored rate, but never
    // faster than the terminal can actually paint — if a draw starts costing real
    // time (a slow pty, a screenful of sixels), the cadence stretches to match
    // instead of queueing writes the terminal renders as tearing. self-tuning, so
    // no protocol gets a hardcoded fps penalty.
    let mut draw_cost = Duration::ZERO;
    let mut scroller = scroll::Scroller::default();
    let mut dlog = drawlog::DrawLog::from_env();
    let mut gate = sched::ChatGate::default();
    // true when something visible may have changed since the last draw: a key,
    // the data tick, or a batch of chat. the 50ms look-for-chat wakes in between
    // draw nothing, so they cost no bytes on the wire.
    let mut woke = true;
    loop {
        drain_emotes(&mut app);
        drain_history(&mut app);
        drain_pins(&mut app);
        drain_twitch(&mut app);
        drain_hs(&mut app);
        drain_picker(&mut app);
        // the focused tab is on screen — whatever it holds is now seen.
        if let Some(ch) = app.channels.get_mut(app.focus) {
            ch.mark_seen();
        }
        // new chat lines and finished emote loads land on EVERY wake — at the
        // animation cadence that's within one frame of arrival, never parked
        // until the next data tick. the tick below keeps only the slow work
        // (heat decay, the mock driver, the focused-channel prefetch sweep).
        // throttled by the gate (see sched.rs): a burst is applied as one batch
        // per gap, wider while typing, so keys repaint only the input line.
        let now = Instant::now();
        let mut dirty = woke;
        if !app.paused && gate.due(now) && drain_feed(&mut app) {
            gate.mark(now);
            dirty = true;
        }
        pump_loads(&mut app);
        // composer preview: load images for emotes in the draft as it's typed
        // (idempotent per key — a cached emote costs a hash lookup).
        if app.mode == InputMode::Insert && !app.channels.is_empty() {
            let text = app.line.text();
            let focus = app.focus;
            let App {
                store, fb, emotes, ..
            } = &mut app;
            request_stacks(store, fb, &emotes[focus], EmoteSet::none(), &text);
        }
        if dirty || emote_mode(&app).next_flip_in().is_some() {
            // snapshot the animation clock + reset the per-draw blit budget, so every
            // emote in this frame is sampled at the same instant.
            if let Some(store) = &app.store {
                store.begin_frame();
            }
            let drew_at = Instant::now();
            // synchronized output (DECSET 2026): the terminal holds presentation
            // until the frame is complete, so a frame's blits land at once instead
            // of streaming in as visible tearing. foot/kitty/wezterm honour it.
            //
            // NOT inside tmux unless tmux draws the sixel itself. tmux implements
            // it, and its implementation repaints the WHOLE pane when the frame
            // ends. our emotes reach the terminal as passthrough, which tmux cannot
            // see, so that repaint paints tmux's own blank cells straight over
            // every image we just drew. wrapping frames in it inside tmux means no
            // emote ever survives the frame it was drawn in.
            if sync {
                crossterm::execute!(io::stdout(), crossterm::terminal::BeginSynchronizedUpdate)?;
            }
            let drew = terminal.draw(|f| ui(f, &app));
            // the diff is held, not yet written. chat that is just last frame's
            // chat moved up is scrolled for real, so the terminal moves its own
            // pixels and only the new rows are written (see scroll.rs).
            let (plan, area) = match &drew {
                Ok(done) => (
                    scroller.observe(done.buffer, scroll_body(&app, done.area)),
                    Some(done.area),
                ),
                Err(_) => (None, None),
            };
            let drew = drew.map(|_| ());
            let plan = plan.filter(|(s, _)| {
                app.store
                    .as_ref()
                    .is_some_and(|st| st.shift_blits(s.top, s.h, s.k))
            });
            let wrote = match plan {
                Some((s, cells)) => terminal.backend_mut().scroll_then_paint(s, &cells),
                None => terminal.backend_mut().release(),
            };
            // sixels go out after the text, inside the sync window: only the
            // placements that changed (see emote/blit.rs).
            let blit = match (area, &app.store) {
                (Some(area), Some(store)) => store.blit(area, &mut io::stdout()),
                _ => Ok(()),
            };
            if sync {
                crossterm::execute!(io::stdout(), crossterm::terminal::EndSynchronizedUpdate)?;
            }
            drew?;
            wrote?;
            blit?;
            dlog.draw();
            // exponential moving average — one slow frame shouldn't throttle us, a
            // sustained slow terminal should.
            draw_cost = (draw_cost * 3 + drew_at.elapsed()) / 4;
            // console tier: paint emote pixels onto the reserved cells now that the
            // text has flushed. terminal tiers draw inline during the frame above.
            if let Some(fb) = &app.fb {
                fb.blit();
            }
        }

        // sleep until whichever comes first: the data tick, or the exact instant
        // the soonest emote flips to its next frame. that's what makes animations
        // play at their authored fps instead of a fixed cadence — and it means a
        // text-only or all-static view never wakes up early at all.
        let tick_left = tick.saturating_sub(last.elapsed());
        let wait = match emote_mode(&app).next_flip_in() {
            // keep the pty at most ~half busy: never schedule the next frame
            // sooner than twice what the last draws actually cost.
            Some(flip) => flip.max(draw_cost * 2).min(tick_left),
            None => tick_left,
        };
        // wake often enough to pick up chat, but only to look: no draw unless
        // something arrived (see `dirty`).
        woke = false;
        if intr::requested() {
            return Ok(());
        }
        if event::poll(wait.min(sched::POLL))? {
            woke = true;
            if let Event::Key(k) = event::read()? {
                gate.note_key(Instant::now());
                dlog.key();
                if matches!(k.kind, KeyEventKind::Press | KeyEventKind::Repeat)
                    && handle_key(&mut app, k) == Flow::Quit
                {
                    return Ok(());
                }
            }
        }

        if last.elapsed() >= tick {
            if !app.paused {
                tick_advance(&mut app);
            }
            last = Instant::now();
            woke = true;
        }
    }
}

/// the chat body when it may be scrolled for real: sixel emotes that the
/// terminal (or tmux itself) keeps in its own grid, a chat spanning the full
/// width (a scroll region is whole rows, so side tab bars opt out).
fn scroll_body(app: &App, area: ratatui::layout::Rect) -> Option<ratatui::layout::Rect> {
    let body = app.chat_body.get();
    let ok = matches!(emote_mode(app), layout::EmoteMode::Term(s) if s.scroll_ok());
    (ok && body.width == area.width && body.height > 0).then_some(body)
}

#[cfg(test)]
mod spec_tests {
    use super::*;
    use heatsync_core::Platform;

    #[test]
    fn plus_and_whitespace_both_merge() {
        let want = vec![
            (Platform::Twitch, "nl_kripp".to_string()),
            (Platform::Kick, "nl_kripp".to_string()),
            (Platform::Youtube, "4tDC0sKhTnA".to_string()),
        ];
        assert_eq!(parse_tab("nl_kripp+kick:nl_kripp+yt:4tDC0sKhTnA"), want);
        assert_eq!(
            parse_tab("twitch:nl_kripp kick:nl_kripp yt:4tDC0sKhTnA"),
            want
        );
        assert_eq!(
            parse_tab("  nl_kripp  +  kick:nl_kripp "),
            want[..2].to_vec()
        );
    }
}