broll 0.4.0

Terminal session recorder with searchable, timestamped output
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
use anyhow::{Context, Result};
use chrono::Utc;
use portable_pty::{CommandBuilder, NativePtySystem, PtySize, PtySystem};
use std::io::{Read, Write};
use std::sync::atomic::{AtomicBool, AtomicU16, Ordering};
use std::sync::{mpsc, Arc};
use std::time::{Duration, Instant};
use uuid::Uuid;

use crate::filter;
use crate::storage::models::{Chunk, ChunkKind, Session};
use crate::storage::Database;

/// Marker env var so we can detect nested sessions and stop gracefully.
const SESSION_ENV_VAR: &str = "BROLL_SESSION_ID";

/// Unique markers emitted by shell hooks to delimit command output.
/// Uses OSC sequences that terminals silently ignore.
/// PRECMD marker = prompt is about to be shown (command finished).
/// PREEXEC marker = command is about to execute (contains the command text, percent-encoded).
/// Format: \x1b]777;broll-exec;ENCODED_COMMAND\x07
const PREEXEC_MARKER_PREFIX: &str = "\x1b]777;broll-exec;";
const PREEXEC_MARKER_END: char = '\x07';
/// Prefix shared by every broll OSC marker.
const MARKER_COMMON: &str = "\x1b]777;broll";
/// Working directory of the command about to run: `\x1b]777;broll-cwd;<path>\x07`.
const CWD_MARKER_PREFIX: &str = "\x1b]777;broll-cwd;";
/// Exit code of the command that just finished: `\x1b]777;broll-exit;<code>\x07`.
const EXIT_MARKER_PREFIX: &str = "\x1b]777;broll-exit;";
/// Body of the precmd marker (the `\x1b]777;broll-cmd` part, without the BEL).
const PRECMD_MARKER_BODY: &str = "\x1b]777;broll-cmd";

/// A parsed broll marker (its BEL-stripped body classified by type).
#[derive(Debug, PartialEq)]
enum Marker<'a> {
    /// Command about to run, carrying the command text.
    Exec(&'a str),
    /// Working directory for the next command.
    Cwd(&'a str),
    /// Exit code of the command that just finished.
    Exit(&'a str),
    /// Prompt is about to be shown (command output finished).
    Precmd,
}

/// Classify a marker body (text between the common prefix start and the BEL).
fn classify_marker(body: &str) -> Option<Marker<'_>> {
    if let Some(cmd) = body.strip_prefix(PREEXEC_MARKER_PREFIX) {
        Some(Marker::Exec(cmd))
    } else if let Some(cwd) = body.strip_prefix(CWD_MARKER_PREFIX) {
        Some(Marker::Cwd(cwd))
    } else if let Some(code) = body.strip_prefix(EXIT_MARKER_PREFIX) {
        Some(Marker::Exit(code))
    } else if body == PRECMD_MARKER_BODY {
        Some(Marker::Precmd)
    } else {
        None
    }
}

/// Strip broll OSC markers from a byte stream destined for the screen.
///
/// Operates on raw bytes (markers are ASCII) so multi-byte UTF-8 characters are
/// never split and corrupted. Any trailing bytes that form a complete-or-partial
/// marker are moved into `carry` so a marker split across two reads is still
/// stripped instead of leaking its tail to the terminal. Returns the bytes that
/// are safe to write now.
fn strip_markers_for_display(combined: &[u8], carry: &mut Vec<u8>) -> Vec<u8> {
    // Every broll marker shares this OSC prefix and ends with a BEL, so we can
    // strip them uniformly without enumerating each marker type.
    let common = MARKER_COMMON.as_bytes();
    let bel = PREEXEC_MARKER_END as u8;

    let mut out = Vec::with_capacity(combined.len());
    let mut i = 0;
    while i < combined.len() {
        if combined[i] != 0x1b {
            out.push(combined[i]);
            i += 1;
            continue;
        }
        let rest = &combined[i..];
        // Not enough bytes to know whether this ESC starts our marker.
        if rest.len() < common.len() {
            if common.starts_with(rest) {
                carry.extend_from_slice(rest); // partial common prefix at end
                return out;
            }
            out.push(combined[i]); // ESC, but not ours
            i += 1;
            continue;
        }
        if !rest.starts_with(common) {
            out.push(combined[i]); // ESC, but not ours
            i += 1;
            continue;
        }
        // A broll marker: strip everything through the next BEL.
        match rest.iter().position(|&b| b == bel) {
            Some(belpos) => i += belpos + 1,
            None => {
                carry.extend_from_slice(rest); // incomplete marker, finish next read
                return out;
            }
        }
    }
    out
}

/// Decode bytes as UTF-8, carrying a trailing incomplete multi-byte sequence over
/// to the next call so characters split across read boundaries aren't turned into
/// replacement chars. Genuinely invalid bytes are replaced and skipped.
fn decode_with_carry(carry: &mut Vec<u8>, data: &[u8]) -> String {
    carry.extend_from_slice(data);
    let mut out = String::new();
    loop {
        match std::str::from_utf8(carry) {
            Ok(s) => {
                out.push_str(s);
                carry.clear();
                return out;
            }
            Err(e) => {
                let valid = e.valid_up_to();
                // carry[..valid] is valid UTF-8, so this conversion is lossless.
                out.push_str(&String::from_utf8_lossy(&carry[..valid]));
                match e.error_len() {
                    Some(n) => {
                        out.push('\u{FFFD}'); // genuinely invalid bytes
                        carry.drain(..valid + n);
                    }
                    None => {
                        carry.drain(..valid); // incomplete trailing sequence: keep it
                        return out;
                    }
                }
            }
        }
    }
}

/// RAII guard that restores terminal from raw mode on drop.
struct RawModeGuard;

impl RawModeGuard {
    fn enable() -> Result<Self> {
        crossterm::terminal::enable_raw_mode()?;
        Ok(Self)
    }
}

impl Drop for RawModeGuard {
    fn drop(&mut self) {
        let _ = crossterm::terminal::disable_raw_mode();
    }
}

/// How long to wait for more data before flushing an incomplete line to DB.
const INCOMPLETE_LINE_TIMEOUT: Duration = Duration::from_secs(2);

/// Create a temporary rc file that sources the user's config then installs hooks.
/// The preexec hook emits the command text directly inside the OSC marker.
/// Only BEL (\x07) could break the marker, so we strip it with parameter expansion.
fn create_hook_rc(shell_name: &str) -> Option<tempfile::TempDir> {
    // Use broll's data directory for temp files to avoid system TMPDIR permission issues
    let broll_data = dirs::data_dir()?.join("broll");
    std::fs::create_dir_all(&broll_data).ok()?;
    let tmp_dir = tempfile::Builder::new()
        .prefix("broll-")
        .tempdir_in(&broll_data)
        .ok()?;

    let hook_code = match shell_name {
        "zsh" => {
            let user_zshrc = dirs::home_dir()
                .map(|h| h.join(".zshrc"))
                .filter(|p| p.exists());
            let source_line = user_zshrc
                .map(|p| format!("[[ -f \"{}\" ]] && source \"{0}\"\n", p.display()))
                .unwrap_or_default();

            let rc_path = tmp_dir.path().join(".zshrc");
            // zsh preexec receives the command line as $1
            // Strip BEL chars to avoid breaking the OSC sequence
            let content = format!(
                concat!(
                    "{}", // source user's zshrc
                    "_broll_preexec() {{\n",
                    "  local cmd=\"${{1//$'\\a'/}}\"\n",
                    "  printf '\\e]777;broll-cwd;%s\\a' \"${{PWD//$'\\a'/}}\"\n",
                    "  printf '\\e]777;broll-exec;%s\\a' \"$cmd\"\n",
                    "}}\n",
                    // Capture $? first; it is the exit code of the command that just ran.
                    "_broll_precmd() {{\n",
                    "  local ec=$?\n",
                    "  printf '\\e]777;broll-exit;%d\\a' \"$ec\"\n",
                    "  printf '\\e]777;broll-cmd\\a'\n",
                    "}}\n",
                    "autoload -Uz add-zsh-hook\n",
                    "add-zsh-hook preexec _broll_preexec\n",
                    "add-zsh-hook precmd _broll_precmd\n",
                ),
                source_line,
            );
            std::fs::write(&rc_path, content).ok()?;
            Some(())
        }
        "bash" => {
            let user_bashrc = dirs::home_dir()
                .map(|h| h.join(".bashrc"))
                .filter(|p| p.exists());
            let source_line = user_bashrc
                .map(|p| format!("[[ -f \"{}\" ]] && source \"{0}\"\n", p.display()))
                .unwrap_or_default();

            let rc_path = tmp_dir.path().join(".bashrc");
            // bash: emit the last command in precmd (before the precmd marker)
            // using fc -ln -1 to get the full command line
            let content = format!(
                concat!(
                    "{}", // source user's bashrc
                    "_broll_last_hist=\"\"\n",
                    "_broll_precmd() {{\n",
                    // Capture $? first; any other command below would clobber it.
                    "  local ec=$?\n",
                    "  local cmd\n",
                    "  cmd=$(fc -ln -1 2>/dev/null | sed 's/^[[:space:]]*//')\n",
                    "  cmd=\"${{cmd//$'\\a'/}}\"\n",
                    "  if [[ -n \"$cmd\" && \"$cmd\" != \"$_broll_last_hist\" ]]; then\n",
                    "    _broll_last_hist=\"$cmd\"\n",
                    "    printf '\\e]777;broll-cwd;%s\\a' \"${{PWD//$'\\a'/}}\"\n",
                    "    printf '\\e]777;broll-exec;%s\\a' \"$cmd\"\n",
                    "    printf '\\e]777;broll-exit;%d\\a' \"$ec\"\n",
                    "  fi\n",
                    "  printf '\\e]777;broll-cmd\\a'\n",
                    "}}\n",
                    "PROMPT_COMMAND=\"_broll_precmd;${{PROMPT_COMMAND}}\"\n",
                ),
                source_line,
            );
            std::fs::write(&rc_path, content).ok()?;
            Some(())
        }
        _ => None,
    };

    hook_code.map(|_| tmp_dir)
}

/// States for tracking what part of the PTY output we're in.
#[derive(PartialEq)]
enum CaptureState {
    /// Between precmd (prompt shown) and preexec (command started).
    /// This is prompt + user typing — skip this.
    Idle,
    /// Between preexec (command started) and precmd (command finished).
    /// This is real command output — capture this.
    Capturing,
}

/// Start a recording session by spawning a sub-shell in a PTY.
pub fn start_session(
    name: Option<String>,
    tag: Option<String>,
    group: Option<String>,
    no_filter: bool,
    dir: Option<std::path::PathBuf>,
) -> Result<()> {
    if std::env::var(SESSION_ENV_VAR).is_ok() {
        anyhow::bail!("Already inside a broll session. Run `exit` or `broll stop` first.");
    }

    let session_id = Uuid::new_v4().to_string();
    let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".into());
    let terminal_label = format!("term-{}", &session_id[..8]);
    let tags = tag.map(|t| vec![t]).unwrap_or_default();

    let session = Session {
        id: session_id.clone(),
        name: name.clone(),
        started_at: Utc::now(),
        ended_at: None,
        group,
        terminal_label: terminal_label.clone(),
        tags,
        shell: shell.clone(),
    };

    let db = Database::open()?;
    db.create_session(&session)?;

    // Session label for display
    let session_label = name.as_deref().unwrap_or(&session_id[..8]);

    // Set terminal title to indicate recording
    eprint!("\x1b]0;broll recording - {}\x1b\\", session_label);

    // Styled recording banner
    eprintln!(
        "\x1b[48;5;52m\x1b[97;1m broll recording - {} \x1b[0m",
        session_label,
    );
    eprintln!("\x1b[2m  exit the shell or run `broll stop` to end recording\x1b[0m");

    let (cols, rows) = crossterm::terminal::size().unwrap_or((80, 24));

    let pty_system = NativePtySystem::default();
    let pair = pty_system
        .openpty(PtySize {
            rows,
            cols,
            pixel_width: 0,
            pixel_height: 0,
        })
        .context("Failed to open PTY")?;

    let shell_name = std::path::Path::new(&shell)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("sh")
        .to_string();

    let mut cmd = CommandBuilder::new(&shell);
    cmd.env(SESSION_ENV_VAR, &session_id);
    cmd.env("BROLL_SESSION", session_label);

    // Set working directory (defaults to current directory)
    let work_dir = dir.unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| "/".into()));
    cmd.cwd(&work_dir);

    // Create temp rc file with hooks; keep _tmp_dir alive until session ends
    let _tmp_dir = create_hook_rc(&shell_name);
    let has_hooks = _tmp_dir.is_some();
    if let Some(ref tmp) = _tmp_dir {
        match shell_name.as_str() {
            "zsh" => {
                cmd.env("ZDOTDIR", tmp.path().to_str().unwrap_or("/tmp"));
            }
            "bash" => {
                let rc_path = tmp.path().join(".bashrc");
                cmd.args(["--rcfile", rc_path.to_str().unwrap_or("/tmp/.bashrc")]);
            }
            _ => {}
        }
    }

    let mut child = pair.slave.spawn_command(cmd)?;
    drop(pair.slave);

    let mut reader = pair.master.try_clone_reader()?;
    let writer = pair.master.take_writer()?;

    let _raw_guard = RawModeGuard::enable()?;

    let resize_flag = Arc::new(AtomicBool::new(false));
    signal_hook::flag::register(signal_hook::consts::SIGWINCH, Arc::clone(&resize_flag))?;

    let term_cols = Arc::new(AtomicU16::new(cols));
    let term_cols_storage = Arc::clone(&term_cols);

    let (tx, rx) = mpsc::channel::<Vec<u8>>();

    // Spawn thread to forward stdin -> PTY
    let mut pty_writer = writer;
    let _stdin_handle = std::thread::spawn(move || {
        let mut stdin = std::io::stdin();
        let mut buf = [0u8; 1024];
        loop {
            match stdin.read(&mut buf) {
                Ok(0) | Err(_) => break,
                Ok(n) => {
                    if pty_writer.write_all(&buf[..n]).is_err() {
                        break;
                    }
                }
            }
        }
    });

    // Spawn storage thread. Uses markers to only capture real command output.
    // Renders output through a virtual terminal (vt100) to preserve column layout.
    let storage_session_id = session_id.clone();
    let storage_handle = std::thread::spawn(move || {
        let mut raw_buf = String::new();
        // Holds a trailing partial UTF-8 sequence split across reads.
        let mut utf8_carry: Vec<u8> = Vec::new();
        let mut last_data_at = Instant::now();
        let mut state = CaptureState::Idle;
        // Accumulate raw bytes for current command output to render through vt100
        let mut cmd_output_bytes: Vec<u8> = Vec::new();
        // Working directory for the next command, stashed from a cwd marker.
        let mut pending_cwd: Option<String> = None;
        // Row id of the command (input) chunk currently running, for exit-code update.
        let mut current_command_id: Option<i64> = None;

        /// Render raw terminal bytes through a virtual terminal and return plain text lines.
        fn render_vt(raw: &[u8], term_cols: u16) -> String {
            // Estimate rows needed: at least one row per newline, with a reasonable minimum.
            // This avoids the previous hardcoded 500-row limit that silently lost output.
            let newline_count = raw.iter().filter(|&&b| b == b'\n').count();
            let estimated_rows = (newline_count + 1).max(500) as u16;
            // vt100 panics on a zero-width screen; a terminal that reports no size
            // (or a PTY with no winsize) must not take the capture thread down.
            let cols = term_cols.max(1);
            let mut parser = vt100::Parser::new(estimated_rows, cols, 0);
            parser.process(raw);
            let screen = parser.screen();
            let mut lines: Vec<String> = Vec::new();
            for row in 0..screen.size().0 {
                let line = screen.contents_between(
                    row, 0,
                    row, screen.size().1 - 1,
                );
                lines.push(line.trim_end().to_string());
            }
            // Trim trailing empty lines
            while lines.last().is_some_and(|l: &String| l.is_empty()) {
                lines.pop();
            }
            lines.join("\n")
        }

        /// Lines emitted by macOS zsh session save/restore — not real command output.
        fn is_shell_noise(line: &str) -> bool {
            let trimmed = line.trim();
            trimmed == "Saving session..."
                || trimmed.starts_with("...saving history...")
                || trimmed.starts_with("...copying shared history...")
                || trimmed.starts_with("...completed.")
                || trimmed.starts_with("Deleting expired sessions...")
        }

        let store_chunk = |content_raw: &str,
                           kind: ChunkKind,
                           cwd: Option<String>,
                           db: &Database,
                           sid: &str,
                           no_filt: bool|
         -> Option<i64> {
            let content: String = content_raw
                .lines()
                .filter(|l| !is_shell_noise(l))
                .collect::<Vec<_>>()
                .join("\n");
            let content = if no_filt {
                content
            } else {
                filter::redact(&content)
            };
            let trimmed = content.trim();
            if trimmed.is_empty() {
                return None;
            }

            let chunk = Chunk {
                id: 0,
                session_id: sid.to_string(),
                timestamp: Utc::now(),
                content,
                kind,
                cwd,
                exit_code: None,
            };
            match db.insert_chunk(&chunk) {
                Ok(id) => Some(id),
                Err(e) => {
                    eprintln!("broll: failed to store chunk: {e}");
                    None
                }
            }
        };

        if let Ok(db) = Database::open() {
            loop {
                match rx.recv_timeout(INCOMPLETE_LINE_TIMEOUT) {
                    Ok(data) => {
                        last_data_at = Instant::now();
                        let text = decode_with_carry(&mut utf8_carry, &data);
                        raw_buf.push_str(&text);

                        if has_hooks {
                            // Process the buffer one marker at a time. Bytes before a
                            // marker are command output while Capturing, prompt noise
                            // while Idle. A trailing (possibly partial) marker is kept
                            // for the next read so it is never split or leaked.
                            loop {
                                let Some(start) = raw_buf.find(MARKER_COMMON) else {
                                    // No marker present: flush all but a small tail that
                                    // could be the start of a marker split across reads.
                                    let keep = MARKER_COMMON.len();
                                    let flush_to = raw_buf.len().saturating_sub(keep);
                                    if flush_to > 0 {
                                        if state == CaptureState::Capturing {
                                            cmd_output_bytes
                                                .extend_from_slice(&raw_buf.as_bytes()[..flush_to]);
                                        }
                                        raw_buf.drain(..flush_to);
                                    }
                                    break;
                                };

                                let Some(bel_rel) = raw_buf[start..].find(PREEXEC_MARKER_END) else {
                                    // Marker started but not yet terminated: emit the
                                    // output before it and keep the partial marker.
                                    if state == CaptureState::Capturing {
                                        cmd_output_bytes.extend_from_slice(&raw_buf.as_bytes()[..start]);
                                    }
                                    raw_buf.drain(..start);
                                    break;
                                };
                                let bel = start + bel_rel;

                                // Output before the marker (ignored while Idle).
                                if state == CaptureState::Capturing {
                                    cmd_output_bytes.extend_from_slice(&raw_buf.as_bytes()[..start]);
                                }

                                let body = raw_buf[start..bel].to_string();
                                raw_buf.drain(..bel + 1); // drain through the BEL

                                match classify_marker(&body) {
                                    Some(Marker::Cwd(cwd)) => {
                                        pending_cwd = Some(cwd.to_string());
                                    }
                                    Some(Marker::Exec(cmd)) => {
                                        current_command_id = store_chunk(
                                            cmd,
                                            ChunkKind::Input,
                                            pending_cwd.take(),
                                            &db,
                                            &storage_session_id,
                                            no_filter,
                                        );
                                        cmd_output_bytes.clear();
                                        state = CaptureState::Capturing;
                                    }
                                    Some(Marker::Exit(code)) => {
                                        if let (Some(cid), Ok(ec)) =
                                            (current_command_id, code.trim().parse::<i64>())
                                        {
                                            let _ = db.set_chunk_exit_code(cid, ec);
                                        }
                                    }
                                    Some(Marker::Precmd) => {
                                        if state == CaptureState::Capturing {
                                            let rendered = render_vt(
                                                &cmd_output_bytes,
                                                term_cols_storage.load(Ordering::Relaxed),
                                            );
                                            store_chunk(
                                                &rendered,
                                                ChunkKind::Output,
                                                None,
                                                &db,
                                                &storage_session_id,
                                                no_filter,
                                            );
                                            cmd_output_bytes.clear();
                                        }
                                        state = CaptureState::Idle;
                                        current_command_id = None;
                                    }
                                    None => {} // unknown broll marker: already drained
                                }
                            }
                        } else {
                            // No hooks: accumulate output, render through vt100
                            // on newlines to preserve column layout
                            cmd_output_bytes.extend_from_slice(raw_buf.as_bytes());
                            raw_buf.clear();
                        }
                    }
                    Err(mpsc::RecvTimeoutError::Timeout) => {
                        // Flush accumulated output on timeout
                        if last_data_at.elapsed() >= INCOMPLETE_LINE_TIMEOUT {
                            cmd_output_bytes.extend_from_slice(raw_buf.as_bytes());
                            raw_buf.clear();
                            if !cmd_output_bytes.is_empty() {
                                if !has_hooks || state == CaptureState::Capturing {
                                    let rendered = render_vt(&cmd_output_bytes, term_cols_storage.load(Ordering::Relaxed));
                                    store_chunk(
                                        &rendered,
                                        ChunkKind::Output,
                                        None,
                                        &db,
                                        &storage_session_id,
                                        no_filter,
                                    );
                                }
                                cmd_output_bytes.clear();
                            }
                        }
                    }
                    Err(mpsc::RecvTimeoutError::Disconnected) => {
                        cmd_output_bytes.extend_from_slice(raw_buf.as_bytes());
                        if !cmd_output_bytes.is_empty()
                            && (!has_hooks || state == CaptureState::Capturing)
                        {
                            let rendered = render_vt(&cmd_output_bytes, term_cols_storage.load(Ordering::Relaxed));
                            store_chunk(
                                &rendered,
                                ChunkKind::Output,
                                None,
                                &db,
                                &storage_session_id,
                                no_filter,
                            );
                        }
                        break;
                    }
                }
            }
        }
    });

    // Main thread: read PTY output -> stdout + send to storage
    let mut stdout = std::io::stdout();
    // Ensure cursor is on a fresh line after the "recording started" messages,
    // so the shell's first prompt renders correctly in raw mode.
    let _ = stdout.write_all(b"\r\n");
    let _ = stdout.flush();
    let mut buf = [0u8; 4096];
    // Holds bytes of a marker split across two reads, so its tail never leaks.
    let mut stdout_carry: Vec<u8> = Vec::new();

    loop {
        if resize_flag.swap(false, Ordering::Relaxed)
            && let Ok((cols, rows)) = crossterm::terminal::size()
        {
            term_cols.store(cols, Ordering::Relaxed);
            let _ = pair.master.resize(PtySize {
                rows,
                cols,
                pixel_width: 0,
                pixel_height: 0,
            });
        }

        match reader.read(&mut buf) {
            Ok(0) => break,
            Ok(n) => {
                let raw = &buf[..n];

                // Send original bytes (with markers) to storage for processing.
                let _ = tx.send(raw.to_vec());

                // Strip markers before writing to stdout so they stay invisible.
                // Prepend any carried-over partial marker from the previous read.
                let mut combined = std::mem::take(&mut stdout_carry);
                combined.extend_from_slice(raw);
                let cleaned = strip_markers_for_display(&combined, &mut stdout_carry);
                stdout.write_all(&cleaned)?;
                stdout.flush()?;
            }
            Err(_) => break,
        }
    }

    drop(tx);

    let _ = child.wait();

    // Drop raw mode BEFORE printing the exit message so \n works normally
    drop(_raw_guard);

    // Don't join stdin_handle — it blocks on stdin.read() until user presses a key.
    // It will be cleaned up when the process exits.
    let _ = storage_handle.join();

    db.end_session(&session_id)?;

    // Restore terminal title
    eprint!("\x1b]0;\x1b\\");

    eprintln!("broll: session {} ended", &session_id[..8]);

    Ok(())
}

/// Stop the current recording session (called from within a sub-shell).
pub fn stop_session() -> Result<()> {
    match std::env::var(SESSION_ENV_VAR) {
        Ok(_id) => {
            println!("broll: stopping session, exit the shell to finalize.");
            std::process::exit(0);
        }
        Err(_) => {
            anyhow::bail!("Not inside a broll recording session.");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Feed input through the stripper one slice at a time (simulating reads) and
    /// return the concatenated emitted output.
    fn strip_streamed(reads: &[&[u8]]) -> Vec<u8> {
        let mut carry = Vec::new();
        let mut out = Vec::new();
        for r in reads {
            let mut combined = std::mem::take(&mut carry);
            combined.extend_from_slice(r);
            out.extend_from_slice(&strip_markers_for_display(&combined, &mut carry));
        }
        out
    }

    #[test]
    fn strips_complete_markers_in_one_read() {
        let input = b"before\x1b]777;broll-cmd\x07after";
        assert_eq!(strip_streamed(&[input]), b"beforeafter");
    }

    #[test]
    fn strips_variable_length_exec_marker() {
        let input = b"a\x1b]777;broll-exec;ls%20-la\x07b";
        assert_eq!(strip_streamed(&[input]), b"ab");
    }

    #[test]
    fn precmd_marker_split_across_reads_does_not_leak() {
        // Split right in the middle of the precmd marker.
        let full = b"out\x1b]777;broll-cmd\x07end";
        for split in 1..full.len() {
            let (a, b) = full.split_at(split);
            assert_eq!(strip_streamed(&[a, b]), b"outend", "split at {split}");
        }
    }

    #[test]
    fn exec_marker_split_across_reads_does_not_leak() {
        let full = b"x\x1b]777;broll-exec;cmd\x07y";
        for split in 1..full.len() {
            let (a, b) = full.split_at(split);
            assert_eq!(strip_streamed(&[a, b]), b"xy", "split at {split}");
        }
    }

    #[test]
    fn strips_cwd_and_exit_markers() {
        let input = b"\x1b]777;broll-cwd;/home/u\x07ls\x1b]777;broll-exit;0\x07";
        assert_eq!(strip_streamed(&[input]), b"ls");
    }

    #[test]
    fn cwd_and_exit_markers_split_across_reads_do_not_leak() {
        for full in [
            b"a\x1b]777;broll-cwd;/tmp/x\x07b".as_slice(),
            b"a\x1b]777;broll-exit;127\x07b".as_slice(),
        ] {
            for split in 1..full.len() {
                let (x, y) = full.split_at(split);
                assert_eq!(strip_streamed(&[x, y]), b"ab", "split at {split}");
            }
        }
    }

    #[test]
    fn classify_marker_recognizes_each_type() {
        assert_eq!(classify_marker("\x1b]777;broll-exec;ls -la"), Some(Marker::Exec("ls -la")));
        assert_eq!(classify_marker("\x1b]777;broll-cwd;/home"), Some(Marker::Cwd("/home")));
        assert_eq!(classify_marker("\x1b]777;broll-exit;0"), Some(Marker::Exit("0")));
        assert_eq!(classify_marker("\x1b]777;broll-cmd"), Some(Marker::Precmd));
        assert_eq!(classify_marker("\x1b]777;broll-bogus"), None);
    }

    #[test]
    fn passes_through_unrelated_escape_sequences() {
        let input = b"\x1b[31mred\x1b[0m";
        assert_eq!(strip_streamed(&[input]), input);
    }

    #[test]
    fn keeps_osc_that_is_not_a_broll_marker() {
        let input = b"\x1b]0;window title\x07text";
        assert_eq!(strip_streamed(&[input]), input);
    }

    #[test]
    fn decode_with_carry_handles_split_multibyte() {
        // "héllo" — 'é' is 0xC3 0xA9. Split between its two bytes.
        let bytes = "héllo".as_bytes().to_vec();
        let split = 2; // after 'h' and the first byte of 'é'
        let (a, b) = bytes.split_at(split);
        let mut carry = Vec::new();
        let mut out = decode_with_carry(&mut carry, a);
        out.push_str(&decode_with_carry(&mut carry, b));
        assert_eq!(out, "héllo");
        assert!(carry.is_empty());
    }

    #[test]
    fn decode_with_carry_replaces_invalid_bytes() {
        let mut carry = Vec::new();
        let out = decode_with_carry(&mut carry, &[0x68, 0xFF, 0x69]); // h <invalid> i
        assert_eq!(out, "h\u{FFFD}i");
    }
}