rustimal 0.6.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
//! A pane: one shell process, its terminal state, and its animation state.

use std::borrow::Cow;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Instant, SystemTime};

use alacritty_terminal::event::{Event as TermEvent, EventListener, WindowSize};
use alacritty_terminal::event_loop::{EventLoop, EventLoopSender, Msg};
use alacritty_terminal::grid::Dimensions;
use alacritty_terminal::index::{Column, Line, Point, Side};
use alacritty_terminal::selection::{Selection, SelectionType};
use alacritty_terminal::sync::FairMutex;
use alacritty_terminal::term::cell::Flags;
use alacritty_terminal::term::{Config as TermConfig, Term, TermMode};
use alacritty_terminal::tty::{self, Options, Shell};
use winit::event_loop::EventLoopProxy;

use crate::anim::Tween;
use crate::claude::{self, Status};
use crate::editing::{self, Move};
use crate::inject::{Injector, Outcome};
use crate::layout::{PaneId, Rect};
use crate::links::Target;
use crate::search::Search;

/// Something that just finished running in a pane, worth telling the user about.
pub struct Done {
    pub what: String,
    pub secs: f32,
}

pub enum TitleSignal {
    None,
    Pick(PathBuf),
    Done(Done),
    /// The shell's `review` or `pr`: the folder it was typed in, and the arguments.
    Review { cwd: PathBuf, args: String },
    /// The shell's `t3`: the folder to show, and which conversation (empty for the latest).
    T3 { cwd: PathBuf, args: String },
    /// The shell's `do`: the folder, and which agent. The task is in [`Pane::take_task`].
    Do { cwd: PathBuf, agent: String },
}

pub enum UserEvent {
    Term(PaneId, TermEvent),
    /// The global hotkey was pressed.
    Hotkey,
    /// The config file changed on disk.
    ConfigChanged,
    /// A review job finished.
    Review(Box<crate::review_ui::Message>),
    /// The T3 Code page for a pane's folder was looked up.
    T3Page { pane: PaneId, dir: PathBuf, page: Result<crate::t3::Page, String> },
    /// A message from the T3 Code view in a pane.
    T3Message(PaneId, String),
    /// News from the agent working for a pane's conversation.
    Chat { pane: PaneId, run: u64, update: crate::chat::Update },
}

#[derive(Clone)]
pub struct Listener {
    id: PaneId,
    proxy: EventLoopProxy<UserEvent>,
}

impl EventListener for Listener {
    fn send_event(&self, event: TermEvent) {
        let _ = self.proxy.send_event(UserEvent::Term(self.id, event));
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct GridSize {
    pub cols: usize,
    pub rows: usize,
}

impl Dimensions for GridSize {
    fn total_lines(&self) -> usize {
        self.rows
    }
    fn screen_lines(&self) -> usize {
        self.rows
    }
    fn columns(&self) -> usize {
        self.cols
    }
}

pub struct Pane {
    pub id: PaneId,
    pub term: Arc<FairMutex<Term<Listener>>>,
    sender: EventLoopSender,
    pub grid: GridSize,
    pending_grid: Option<(GridSize, Instant)>,
    cell: (f32, f32),

    /// Where the layout wants the pane.
    pub target: Rect,
    /// Where the pane is drawn this frame (sampled from `rect_anim`).
    pub rect: Rect,
    /// 0..1 focus highlight.
    pub focus: f32,
    /// 0..1 overall opacity (fades in on spawn, out on close).
    pub opacity: f32,
    /// 0..1 visual bell flash.
    pub bell: f32,
    pub rect_anim: Tween<Rect>,
    pub focus_anim: Tween<f32>,
    pub opacity_anim: Tween<f32>,
    pub bell_anim: Tween<f32>,
    pub title: String,
    pub cwd: Option<PathBuf>,
    pub scroll_accum: f32,
    /// Claude Code is running in this pane (started through the shell integration).
    pub claude: bool,
    /// Topic Claude puts in the terminal title.
    pub claude_title: String,
    /// Latest Claude status line data, and bookkeeping for reading it.
    pub claude_status: Option<Status>,
    status_key: String,
    status_mtime: Option<SystemTime>,
    /// A secret only this pane's shell knows; see [`review_request`].
    review_token: String,
    /// Find-in-scrollback state while the search bar is open.
    pub search: Option<Search>,
    /// The `do` conversation, kept (hidden) once started so it can be returned to.
    pub chat: Option<Box<crate::chat::Chat>>,
    /// Link under the mouse while Ctrl is held: `(grid line, first column, end column)`.
    pub link: Option<(i32, usize, usize)>,
    /// The command now running (its start time and text), reported by the shell integration.
    cmd: Option<(Instant, String)>,
    /// When Claude's title last showed its "working" spinner.
    claude_busy: Option<Instant>,
    /// The shell loads rustimal's integration, so its prompt ends the way `cursor_at_prompt` expects.
    integrated: bool,
    /// A command being typed into the shell for a click on a listing entry.
    injector: Option<Injector>,
    /// Part of the command line selected with the keyboard (Shift+arrows, Ctrl+A).
    pub kb_sel: Option<KbSel>,
    /// The mouse is down on the command line: where it started and where the cursor is now.
    pub drag: Option<KbSel>,
    /// Whether that drag selects (a double click) or only moves the cursor (a single click).
    drag_selects: bool,
}

/// A selection made with the keyboard on the command line. Positions are characters into it.
#[derive(Clone, Debug)]
pub struct KbSel {
    /// The command line when it was made; the selection ends if the line changes.
    pub text: String,
    pub anchor: usize,
    /// Where the shell's cursor is (or is on its way to).
    pub head: usize,
}

impl Pane {
    #[allow(clippy::too_many_arguments)]
    pub fn spawn(
        id: PaneId,
        proxy: EventLoopProxy<UserEvent>,
        shell: (String, Vec<String>),
        extra_env: &[(String, String)],
        cwd: Option<PathBuf>,
        scrollback: usize,
        grid: GridSize,
        cell: (f32, f32),
        rect: Rect,
    ) -> std::io::Result<Self> {
        let integrated = extra_env.iter().any(|(k, _)| k == "PROMPT_COMMAND");
        let listener = Listener { id, proxy };
        let mut env: HashMap<String, String> = [
            ("TERM", "xterm-256color"),
            ("COLORTERM", "truecolor"),
            ("TERM_PROGRAM", "rustimal"),
            // Keep Git Bash in the directory we start it in.
            ("CHERE_INVOKING", "1"),
        ]
        .into_iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
        // Current PATH and friends from the registry, not the (possibly stale) inherited ones.
        for (k, v) in crate::winenv::fresh() {
            env.entry(k).or_insert(v);
        }
        env.extend(extra_env.iter().cloned());
        // Unique across rustimal windows, so concurrent instances don't share status files.
        let status_key = format!("{}-{id}", std::process::id());
        env.insert("RUSTIMAL_PANE".into(), status_key.clone());
        let review_token = new_token();
        env.insert("RUSTIMAL_REVIEW_TOKEN".into(), review_token.clone());
        let opts = Options {
            shell: Some(Shell::new(shell.0, shell.1)),
            working_directory: cwd.clone(),
            drain_on_exit: false,
            env,
            escape_args: true,
        };
        let pty = tty::new(&opts, window_size(grid, cell), id)?;
        let config = TermConfig { scrolling_history: scrollback, ..Default::default() };
        let term = Arc::new(FairMutex::new(Term::new(config, &grid, listener.clone())));
        let event_loop = EventLoop::new(term.clone(), listener, pty, false, false)?;
        let sender = event_loop.channel();
        event_loop.spawn();

        Ok(Self {
            id,
            term,
            sender,
            grid,
            pending_grid: None,
            cell,
            target: rect,
            rect,
            focus: 0.0,
            opacity: 0.0,
            bell: 0.0,
            rect_anim: Tween::new(rect),
            focus_anim: Tween::new(0.0),
            opacity_anim: Tween::new(0.0),
            bell_anim: Tween::new(0.0),
            title: String::new(),
            cwd,
            scroll_accum: 0.0,
            claude: false,
            claude_title: String::new(),
            claude_status: None,
            status_key,
            status_mtime: None,
            review_token,
            search: None,
            chat: None,
            link: None,
            cmd: None,
            claude_busy: None,
            integrated,
            injector: None,
            kb_sel: None,
            drag: None,
            drag_selects: true,
        })
    }

    /// Can a command be typed into this pane's shell? Only with the shell integration (whose
    /// prompt rustimal recognises), outside Claude and full-screen programs, and not while a
    /// command has been running for a while: then the click should just open the item.
    pub fn can_type(&self) -> bool {
        const BUSY: std::time::Duration = std::time::Duration::from_secs(3);
        self.integrated
            && !self.claude
            && !self.term.lock().mode().contains(TermMode::ALT_SCREEN)
            && self.cmd.as_ref().is_none_or(|(started, _)| started.elapsed() < BUSY)
    }

    /// Start typing `cmd` into the shell; see `Injector`. `target` is opened if that fails.
    pub fn start_typing(&mut self, cmd: String, target: Option<Target>) {
        self.injector = Some(Injector::new(cmd, target, Instant::now()));
    }

    /// The cursor is at an empty prompt (nothing typed, no program running).
    pub fn at_empty_prompt(&self) -> bool {
        cursor_at_prompt(&self.term.lock())
    }

    /// Is a command line being edited here, so editor keys (Shift+arrows, Ctrl+A) make sense?
    /// Only with the shell integration, whose prompt marks where the command starts; programs
    /// that have the screen (vim, Claude) get every key untouched.
    pub fn edit_ready(&self) -> bool {
        self.integrated && !self.claude && self.injector.is_none() && command_line(&self.term.lock()).is_some()
    }

    /// The keyboard selection, if the command line is still as it was when it was made.
    fn live_selection(&self, cl: &CmdLine) -> Option<KbSel> {
        let sel = self.kb_sel.as_ref()?;
        let shown = self.term.lock().selection.is_some();
        (shown && sel.anchor != sel.head && sel.text == cl.text()).then(|| sel.clone())
    }

    pub fn has_selection(&mut self) -> bool {
        // The guard must be gone before `live_selection`, which locks the terminal again.
        let cl = command_line(&self.term.lock());
        let live = cl.and_then(|cl| self.live_selection(&cl));
        if live.is_none() {
            self.kb_sel = None;
        }
        live.is_some()
    }

    pub fn clear_selection(&mut self) {
        if self.kb_sel.take().is_some() {
            self.term.lock().selection = None;
        }
    }

    /// Extend the selection by a move (Shift+Left, Ctrl+Shift+Right, Shift+Home...), moving the
    /// shell's cursor with it. Returns false if there is nothing typed to select.
    pub fn extend_selection(&mut self, mv: Move) -> bool {
        let (cl, app) = {
            let term = self.term.lock();
            (command_line(&term), term.mode().contains(TermMode::APP_CURSOR))
        };
        let Some(cl) = cl.filter(|cl| !cl.cells.is_empty()) else { return false };
        let live = self.live_selection(&cl);
        // While a selection grows quickly, the screen's cursor lags the keys sent; go by where
        // the selection says it is.
        let cursor = live.as_ref().map_or(cl.cursor, |s| s.head);
        let anchor = live.as_ref().map_or(cursor, |s| s.anchor);
        let to = editing::target(&cl.chars(), cursor, mv);
        self.write(editing::move_keys(cursor, to, app));
        self.kb_sel = Some(KbSel { text: cl.text(), anchor, head: to });
        show_selection(&mut self.term.lock(), &cl, anchor.min(to), anchor.max(to));
        true
    }

    /// Select the whole command line, with the cursor at its end.
    pub fn select_command_line(&mut self) -> bool {
        let (cl, app) = {
            let term = self.term.lock();
            (command_line(&term), term.mode().contains(TermMode::APP_CURSOR))
        };
        let Some(cl) = cl.filter(|cl| !cl.cells.is_empty()) else { return false };
        let cursor = self.live_selection(&cl).map_or(cl.cursor, |s| s.head);
        let n = cl.cells.len();
        self.write(editing::move_keys(cursor, n, app));
        self.kb_sel = Some(KbSel { text: cl.text(), anchor: 0, head: n });
        show_selection(&mut self.term.lock(), &cl, 0, n);
        true
    }

    /// The mouse went down at `col` on grid line `line`: if that is on the command line being
    /// typed, put the shell's cursor there and start following the mouse (see `drag_to`).
    /// With `select` true, dragging also selects what the cursor passes.
    pub fn press_cursor(&mut self, line: i32, col: usize, right: bool, select: bool) -> bool {
        if !self.edit_ready() {
            return false;
        }
        let (cl, app) = {
            let term = self.term.lock();
            (command_line(&term), term.mode().contains(TermMode::APP_CURSOR))
        };
        let Some(cl) = cl.filter(|cl| cl.line == line) else { return false };
        let at = cl.index_at(col, right);
        self.write(editing::move_keys(cl.cursor, at, app));
        self.clear_selection();
        self.term.lock().selection = None;
        self.drag = Some(KbSel { text: cl.text(), anchor: at, head: at });
        self.drag_selects = select;
        true
    }

    /// The mouse moved with the button down after `press_cursor`: the cursor follows it, and
    /// the text between where it went down and the cursor is selected (only if the drag was
    /// started with a double click; a single click's drag just moves the cursor).
    pub fn drag_to(&mut self, col: usize, right: bool) {
        let Some(drag) = self.drag.clone() else { return };
        let (cl, app) = {
            let term = self.term.lock();
            (command_line(&term), term.mode().contains(TermMode::APP_CURSOR))
        };
        // The line changed under the mouse (output, a program started): stop following.
        let Some(cl) = cl.filter(|cl| cl.text() == drag.text) else {
            self.drag = None;
            return;
        };
        let at = cl.index_at(col, right);
        if at == drag.head {
            return;
        }
        self.write(editing::move_keys(drag.head, at, app));
        self.drag = Some(KbSel { head: at, ..drag.clone() });
        if !self.drag_selects {
            return;
        }
        if at == drag.anchor {
            self.clear_selection();
            self.term.lock().selection = None;
        } else {
            self.kb_sel = Some(KbSel { text: drag.text, anchor: drag.anchor, head: at });
            show_selection(&mut self.term.lock(), &cl, drag.anchor.min(at), drag.anchor.max(at));
        }
    }

    /// Left or right with a selection: the cursor goes to that end of it, and it is gone.
    pub fn collapse_selection(&mut self, to_end: bool) -> bool {
        let (cl, app) = {
            let term = self.term.lock();
            (command_line(&term), term.mode().contains(TermMode::APP_CURSOR))
        };
        let Some(sel) = cl.as_ref().and_then(|cl| self.live_selection(cl)) else { return false };
        let to = if to_end { sel.anchor.max(sel.head) } else { sel.anchor.min(sel.head) };
        self.write(editing::move_keys(sel.head, to, app));
        self.clear_selection();
        true
    }

    /// Delete the selected text from the command line.
    pub fn delete_selection(&mut self) -> bool {
        let (cl, app) = {
            let term = self.term.lock();
            (command_line(&term), term.mode().contains(TermMode::APP_CURSOR))
        };
        let Some(sel) = cl.as_ref().and_then(|cl| self.live_selection(cl)) else { return false };
        let (lo, hi) = (sel.anchor.min(sel.head), sel.anchor.max(sel.head));
        self.write(editing::delete_keys(lo, hi, sel.head, app));
        self.clear_selection();
        true
    }

    pub fn is_typing(&self) -> bool {
        self.injector.is_some()
    }

    /// Carry on typing a command. Returns the target to open if typing it failed.
    pub fn pump(&mut self) -> Option<Target> {
        let mut injector = self.injector.take()?;
        let (writes, outcome) = injector.tick(&self.term.lock(), Instant::now());
        for bytes in writes {
            self.write(bytes);
        }
        match outcome {
            Outcome::Pending => {
                self.injector = Some(injector);
                None
            }
            Outcome::Done => None,
            Outcome::GiveUp => injector.target,
        }
    }

    pub fn write(&self, bytes: impl Into<Cow<'static, [u8]>>) {
        let bytes: Cow<'static, [u8]> = bytes.into();
        // An empty write would wedge the terminal's writer: it never finishes "writing" nothing,
        // and every later key queues up behind it. (Ctrl+A with the cursor already at the end of
        // the line has no keys to send.)
        if bytes.is_empty() {
            return;
        }
        let _ = self.sender.send(Msg::Input(bytes));
    }

    /// Request a new grid size. Applied after a short debounce so that
    /// animations and key-repeat don't spam the shell with resizes.
    pub fn request_grid(&mut self, grid: GridSize, cell: (f32, f32), immediate: bool) {
        let cell_changed = cell != self.cell;
        self.cell = cell;
        if grid == self.grid && !cell_changed {
            self.pending_grid = None;
            return;
        }
        if immediate {
            self.apply_grid(grid);
        } else {
            self.pending_grid = Some((grid, Instant::now()));
        }
    }

    /// Returns true if a pending resize is still waiting.
    pub fn flush_grid(&mut self, debounce: std::time::Duration) -> bool {
        if let Some((grid, at)) = self.pending_grid {
            if at.elapsed() >= debounce {
                self.apply_grid(grid);
            } else {
                return true;
            }
        }
        false
    }

    fn apply_grid(&mut self, grid: GridSize) {
        self.pending_grid = None;
        self.grid = grid;
        self.term.lock().resize(grid);
        let _ = self.sender.send(Msg::Resize(window_size(grid, self.cell)));
    }

    pub fn window_size(&self) -> WindowSize {
        window_size(self.grid, self.cell)
    }

    /// Handle a title change. The shell integration uses titles as a side channel:
    /// "rustimal:<dir>" at every prompt, "__rustimal_pick__:<dir>" to request the
    /// Claude picker, and "__rustimal_claude__" right before Claude starts.
    /// Plain Git Bash titles look like "MINGW64:/c/some/dir".
    pub fn set_title(&mut self, title: String) -> TitleSignal {
        if let Some(path) = title.strip_prefix("__rustimal_pick__:") {
            return match msys_to_windows(path) {
                Some(dir) => TitleSignal::Pick(dir),
                None => TitleSignal::Pick(self.cwd.clone().unwrap_or_else(|| PathBuf::from("."))),
            };
        }
        if let Some(request) = title.strip_prefix("__rustimal_review__:") {
            return match review_request(request, &self.review_token) {
                Some((dir, args)) => match msys_to_windows(dir).or_else(|| self.cwd.clone()) {
                    Some(cwd) => TitleSignal::Review { cwd, args: args.to_string() },
                    None => TitleSignal::None,
                },
                None => TitleSignal::None,
            };
        }
        if let Some(request) = title.strip_prefix("__rustimal_do__:") {
            return match review_request(request, &self.review_token) {
                Some((dir, agent)) => match msys_to_windows(dir).or_else(|| self.cwd.clone()) {
                    Some(cwd) => TitleSignal::Do { cwd, agent: agent.to_string() },
                    None => TitleSignal::None,
                },
                None => TitleSignal::None,
            };
        }
        if let Some(request) = title.strip_prefix("__rustimal_t3__:") {
            return match review_request(request, &self.review_token) {
                Some((dir, args)) => match msys_to_windows(dir).or_else(|| self.cwd.clone()) {
                    Some(cwd) => TitleSignal::T3 { cwd, args: args.to_string() },
                    None => TitleSignal::None,
                },
                None => TitleSignal::None,
            };
        }
        if let Some(cmd) = title.strip_prefix("__rustimal_cmd__:") {
            self.cmd = Some((Instant::now(), cmd.trim().to_string()));
            return TitleSignal::None;
        }
        if title == "__rustimal_claude__" {
            self.claude = true;
            self.claude_title.clear();
            self.claude_status = None;
            self.status_mtime = None;
            if let Some(f) = self.status_file() {
                let _ = std::fs::remove_file(f);
            }
            return TitleSignal::None;
        }
        if let Some((prefix, path)) = title.split_once(':')
            && prefix.chars().all(|c| c.is_ascii_alphanumeric()) && path.starts_with('/') {
                if let Some(p) = msys_to_windows(path) {
                    self.cwd = Some(p);
                }
                // Back at a prompt: whatever was running has exited. Claude can
                // leave the view scrolled back a little on exit, so snap down.
                if self.claude {
                    self.term.lock().scroll_display(alacritty_terminal::grid::Scroll::Bottom);
                }
                self.claude = false;
                self.claude_busy = None;
                self.title = title;
                // The prompt is back: report the command that just finished. Claude has its
                // own signal (it finishes replying long before the session ends).
                return match self.cmd.take() {
                    Some((started, cmd)) if cmd.split_whitespace().next() != Some("claude") => {
                        TitleSignal::Done(Done { what: cmd, secs: started.elapsed().as_secs_f32() })
                    }
                    _ => TitleSignal::None,
                };
            }
        let mut signal = TitleSignal::None;
        if self.claude {
            self.claude_title = title.trim_start_matches(|c: char| !c.is_alphanumeric()).trim().to_string();
            // Claude Code shows a braille spinner in the title while it works, and a static
            // mark when it's waiting for you.
            if title.chars().next().is_some_and(|c| ('\u{2800}'..='\u{28ff}').contains(&c)) {
                self.claude_busy.get_or_insert_with(Instant::now);
            } else if let Some(since) = self.claude_busy.take() {
                signal = TitleSignal::Done(Done { what: "Claude".into(), secs: since.elapsed().as_secs_f32() });
            }
        }
        self.title = title;
        signal
    }

    /// The task `do` left for this pane. It comes in a file, since a window title would
    /// mangle long or unusual text. Empty if there is none.
    pub fn take_task(&self) -> String {
        let Some(file) = crate::config::state_dir().map(|d| d.join(format!("do-{}.txt", self.status_key))) else {
            return String::new();
        };
        let task = std::fs::read_to_string(&file).unwrap_or_default();
        let _ = std::fs::remove_file(file);
        task
    }

    fn status_file(&self) -> Option<PathBuf> {
        crate::config::state_dir().map(|d| d.join(format!("claude-{}.json", self.status_key)))
    }

    /// Re-read Claude's status file if it changed. Returns true on new data.
    pub fn poll_status(&mut self) -> bool {
        if !self.claude {
            return false;
        }
        let Some(file) = self.status_file() else { return false };
        let Ok(mtime) = std::fs::metadata(&file).and_then(|m| m.modified()) else { return false };
        if self.status_mtime == Some(mtime) {
            return false;
        }
        self.status_mtime = Some(mtime);
        let Some(status) = std::fs::read_to_string(&file).ok().and_then(|t| claude::parse_status(&t)) else {
            return false;
        };
        let changed = self.claude_status.as_ref() != Some(&status);
        self.claude_status = Some(status);
        changed
    }

    /// Short name for the header: the folder name, or "rustimal" at home.
    pub fn display_name(&self) -> String {
        let home = dirs::home_dir();
        match &self.cwd {
            Some(cwd) if Some(cwd) != home.as_ref() => cwd
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_else(|| cwd.to_string_lossy().into_owned()),
            _ => "rustimal".into(),
        }
    }

    pub fn shutdown(&self) {
        let _ = self.sender.send(Msg::Shutdown);
    }
}

/// The cursor sits right after rustimal's prompt (`... ❯ `) with nothing typed on the line, on
/// the normal screen.
pub fn cursor_at_prompt<T>(term: &Term<T>) -> bool {
    if term.mode().contains(TermMode::ALT_SCREEN) {
        return false;
    }
    let cursor = term.grid().cursor.point;
    let row = crate::search::row_chars(term, cursor.line);
    let before: String = row.iter().filter(|&&(col, ..)| col < cursor.column.0).map(|&(_, c, _)| c).collect();
    let after_is_empty = row.iter().all(|&(col, c, _)| col < cursor.column.0 || c == ' ');
    before.ends_with("\u{276f} ") && after_is_empty
}

/// Readline is showing a long list a page at a time and waiting for a key (`--More--`).
pub fn awaiting_more<T>(term: &Term<T>) -> bool {
    let cursor = term.grid().cursor.point;
    let row = crate::search::row_chars(term, cursor.line);
    let before: String = row.iter().filter(|&&(col, ..)| col < cursor.column.0).map(|&(_, c, _)| c).collect();
    !term.mode().contains(TermMode::ALT_SCREEN) && before.trim_end().ends_with("--More--")
}

/// The output of the last command: everything printed after its prompt line, up to the next
/// prompt (or the cursor, while it is still running). Found from the prompts on screen, so it
/// works with rustimal's prompt only, and as far back as the scrollback goes.
pub fn last_output<T>(term: &Term<T>) -> Option<String> {
    if term.mode().contains(TermMode::ALT_SCREEN) {
        return None;
    }
    let marker = "\u{276f} ";
    let text = |line: i32| -> String { crate::search::row_chars(term, Line(line)).iter().map(|&(_, c, _)| c).collect() };
    let top = term.topmost_line().0;
    // The prompt waiting at the cursor (maybe with text typed) is not output.
    let mut end = term.grid().cursor.point.line.0 - i32::from(typed_text(term).is_some());
    while end >= top && text(end).trim().is_empty() {
        end -= 1;
    }
    let cmd = (top..=end).rev().find(|&line| text(line).contains(marker))?;
    // A long command wraps onto more rows; the output starts after the last of them.
    let last_col = Column(term.columns().saturating_sub(1));
    let mut first = cmd;
    while first < end && term.grid()[Line(first)][last_col].flags.contains(Flags::WRAPLINE) {
        first += 1;
    }
    first += 1;
    if first > end {
        return None;
    }
    let out = term.bounds_to_string(Point::new(Line(first), Column(0)), Point::new(Line(end), last_col));
    let out = out.trim_matches('\n').trim_end().to_string();
    (!out.is_empty()).then_some(out)
}

/// The command being typed at the prompt: its characters with their screen columns, and where
/// the cursor is among them.
pub struct CmdLine {
    pub line: i32,
    pub cells: Vec<(usize, char, usize)>,
    pub cursor: usize,
}

impl CmdLine {
    pub fn chars(&self) -> Vec<char> {
        self.cells.iter().map(|c| c.1).collect()
    }

    pub fn text(&self) -> String {
        self.cells.iter().map(|c| c.1).collect()
    }

    /// Which gap between characters a click lands in: `col` is the screen column clicked, and
    /// `right` whether it was the right half of that cell. Left of the text is 0, right of it
    /// is the end.
    pub fn index_at(&self, col: usize, right: bool) -> usize {
        self.cells.iter().take_while(|&&(c, _, w)| c + w <= col || (c <= col && right)).count()
    }
}

/// The command line at the cursor, from rustimal's prompt to the last character on the row.
/// Not for a command that wraps onto several rows, or on the alternate screen.
pub fn command_line<T>(term: &Term<T>) -> Option<CmdLine> {
    if term.mode().contains(TermMode::ALT_SCREEN) {
        return None;
    }
    let cursor = term.grid().cursor.point;
    let last_col = Column(term.columns().saturating_sub(1));
    if term.grid()[cursor.line][last_col].flags.contains(Flags::WRAPLINE) {
        return None;
    }
    let row = crate::search::row_chars(term, cursor.line);
    let marker = row.windows(2).rposition(|w| w[0].1 == '\u{276f}' && w[1].1 == ' ')?;
    let after = &row[marker + 2..];
    let cursor_idx = after.iter().filter(|&&(col, ..)| col < cursor.column.0).count();
    let text_end = after.iter().rposition(|c| c.1 != ' ').map_or(0, |i| i + 1);
    let end = text_end.max(cursor_idx);
    Some(CmdLine { line: cursor.line.0, cells: after[..end].to_vec(), cursor: cursor_idx })
}

/// Highlight `lo..hi` of the command line as the terminal selection (or none if it is empty).
pub fn show_selection<T>(term: &mut Term<T>, cl: &CmdLine, lo: usize, hi: usize) {
    if lo >= hi || hi > cl.cells.len() {
        term.selection = None;
        return;
    }
    let cols = term.columns();
    let start = cl.cells[lo].0;
    let (end, side) = if hi < cl.cells.len() {
        (cl.cells[hi].0, Side::Left)
    } else {
        let (col, _, width) = cl.cells[hi - 1];
        if col + width >= cols { (cols - 1, Side::Right) } else { (col + width, Side::Left) }
    };
    let mut sel = Selection::new(SelectionType::Simple, Point::new(Line(cl.line), Column(start)), Side::Left);
    sel.update(Point::new(Line(cl.line), Column(end)), side);
    term.selection = Some(sel);
}

/// What is typed on the prompt line after rustimal's `❯ `, up to the cursor.
pub fn typed_text<T>(term: &Term<T>) -> Option<String> {
    if term.mode().contains(TermMode::ALT_SCREEN) {
        return None;
    }
    let cursor = term.grid().cursor.point;
    let row = crate::search::row_chars(term, cursor.line);
    let before: String = row.iter().filter(|&&(col, ..)| col < cursor.column.0).map(|&(_, c, _)| c).collect();
    let marker = "\u{276f} ";
    let at = before.rfind(marker)?;
    Some(before[at + marker.len()..].to_string())
}

fn window_size(grid: GridSize, cell: (f32, f32)) -> WindowSize {
    WindowSize {
        num_lines: grid.rows as u16,
        num_cols: grid.cols as u16,
        cell_width: cell.0 as u16,
        cell_height: cell.1 as u16,
    }
}

fn msys_to_windows(path: &str) -> Option<PathBuf> {
    let mut parts = path.trim_start_matches('/').splitn(2, '/');
    let drive = parts.next()?;
    if drive.len() != 1 || !drive.chars().all(|c| c.is_ascii_alphabetic()) {
        return None;
    }
    let rest = parts.next().unwrap_or("");
    let p = PathBuf::from(format!("{}:\\{}", drive.to_ascii_uppercase(), rest.replace('/', "\\")));
    p.is_dir().then_some(p)
}

impl Drop for Pane {
    fn drop(&mut self) {
        self.shutdown();
        if let Some(f) = self.status_file() {
            let _ = std::fs::remove_file(f);
        }
    }
}

/// A random value for a pane. `RandomState` is seeded by the operating system.
fn new_token() -> String {
    use std::hash::{BuildHasher, Hasher, RandomState};
    let part = || RandomState::new().build_hasher().finish();
    format!("{:016x}{:016x}", part(), part())
}

/// Any program can set the terminal's title, and so can a file that is merely printed. A
/// review opens a folder and runs git in it, so the request must carry the pane's own
/// token: `<token>:<folder>|<arguments>`.
fn review_request<'a>(request: &'a str, token: &str) -> Option<(&'a str, &'a str)> {
    let (given, rest) = request.split_once(':')?;
    if token.is_empty() || given != token {
        return None;
    }
    rest.split_once('|')
}

#[cfg(test)]
mod tests {

    #[test]
    fn a_click_lands_between_characters() {
        // "ab" at columns 0..2, a wide character at 2..4, "c" at 4.
        let cl = CmdLine { line: 0, cells: vec![(0, 'a', 1), (1, 'b', 1), (2, '世', 2), (4, 'c', 1)], cursor: 4 };
        assert_eq!(cl.index_at(0, false), 0, "left half of the first character");
        assert_eq!(cl.index_at(0, true), 1, "right half of it");
        assert_eq!(cl.index_at(1, false), 1);
        assert_eq!(cl.index_at(2, false), 2, "before the wide character");
        assert_eq!(cl.index_at(3, true), 3, "after the wide character");
        assert_eq!(cl.index_at(4, true), 4);
        assert_eq!(cl.index_at(30, false), 4, "past the end of the text is the end");
        let empty = CmdLine { line: 0, cells: vec![], cursor: 0 };
        assert_eq!(empty.index_at(5, true), 0);
    }
    use super::*;
    use alacritty_terminal::event::VoidListener;
    use alacritty_terminal::term::Config;
    use alacritty_terminal::vte::ansi::Processor;

    struct Size(usize, usize);

    impl Dimensions for Size {
        fn total_lines(&self) -> usize {
            self.0
        }
        fn screen_lines(&self) -> usize {
            self.0
        }
        fn columns(&self) -> usize {
            self.1
        }
    }

    fn screen(rows: usize, cols: usize, text: &str) -> Term<VoidListener> {
        let mut term = Term::new(Config::default(), &Size(rows, cols), VoidListener);
        let mut parser: Processor = Processor::new();
        parser.advance(&mut term, text.as_bytes());
        term
    }

    #[test]
    fn last_output_is_what_the_last_command_printed() {
        let term = screen(20, 60, "~ \u{276f} echo one\r\none\r\n\r\n~ \u{276f} ls\r\nfile a\r\nfile b\r\n\r\n~ \u{276f} ");
        assert_eq!(last_output(&term).as_deref(), Some("file a\nfile b"));
        // With something typed on the new prompt, the output is still the same.
        let term = screen(20, 60, "~ \u{276f} ls\r\nfile a\r\nfile b\r\n\r\n~ \u{276f} cd sr");
        assert_eq!(last_output(&term).as_deref(), Some("file a\nfile b"));
    }

    #[test]
    fn last_output_while_the_command_still_runs() {
        let term = screen(20, 60, "~ \u{276f} make\r\nbuilding a\r\nbuilding b");
        assert_eq!(last_output(&term).as_deref(), Some("building a\nbuilding b"));
    }

    #[test]
    fn last_output_survives_scrolling_and_wrapped_commands() {
        // Output taller than the screen scrolls the command line into scrollback.
        let mut text = String::from("~ \u{276f} seq 1 40\r\n");
        for i in 1..=40 {
            text += &format!("{i}\r\n");
        }
        text += "\r\n~ \u{276f} ";
        let term = screen(10, 40, &text);
        let out = last_output(&term).unwrap();
        assert!(out.starts_with("1\n2\n3\n") && out.ends_with("\n39\n40"), "{out:?}");
        assert_eq!(out.lines().count(), 40);
        // A command long enough to wrap: its second row is not output.
        let long = "x".repeat(50);
        let term = screen(10, 30, &format!("~ \u{276f} echo {long}\r\n{long}\r\n\r\n~ \u{276f} "));
        assert_eq!(last_output(&term).as_deref(), Some(long.as_str()));
    }

    #[test]
    fn the_command_line_is_found_with_the_cursor_in_it() {
        // "cd src" typed, then the cursor moved back two characters.
        let term = screen(10, 40, "~ \u{276f} cd src\x1b[2D");
        let cl = command_line(&term).unwrap();
        assert_eq!(cl.text(), "cd src");
        assert_eq!(cl.cursor, 4);
        // An empty prompt has an empty line.
        let term = screen(10, 40, "~ \u{276f} ");
        let cl = command_line(&term).unwrap();
        assert!(cl.cells.is_empty() && cl.cursor == 0);
        // Trailing spaces up to the cursor belong to the line.
        let term = screen(10, 40, "~ \u{276f} ls  ");
        let cl = command_line(&term).unwrap();
        assert_eq!((cl.text().as_str(), cl.cursor), ("ls  ", 4));
        // Output has no command line.
        assert!(command_line(&screen(10, 40, "just output")).is_none());
    }

    #[test]
    fn the_selection_covers_the_chosen_characters() {
        let mut term = screen(10, 40, "~ \u{276f} echo hello world");
        let cl = command_line(&term).unwrap();
        show_selection(&mut term, &cl, 5, 10);
        assert_eq!(term.selection_to_string().as_deref(), Some("hello"));
        show_selection(&mut term, &cl, 11, cl.cells.len());
        assert_eq!(term.selection_to_string().as_deref(), Some("world"), "up to the end of the line");
        show_selection(&mut term, &cl, 0, cl.cells.len());
        assert_eq!(term.selection_to_string().as_deref(), Some("echo hello world"));
        show_selection(&mut term, &cl, 3, 3);
        assert!(term.selection.is_none(), "an empty range is no selection");
    }

    #[test]
    fn no_output_for_a_command_that_printed_nothing() {
        let term = screen(10, 40, "~ \u{276f} true\r\n\r\n~ \u{276f} ");
        assert_eq!(last_output(&term), None);
        assert_eq!(last_output(&screen(10, 40, "")), None);
    }
}

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

    #[test]
    fn only_the_panes_own_shell_can_open_a_review() {
        let token = new_token();
        assert_ne!(token, new_token());
        let good = format!("{token}:/c/app|12 --base main");
        assert_eq!(review_request(&good, &token), Some(("/c/app", "12 --base main")));
        assert_eq!(review_request(&format!("{token}:/c/app|"), &token), Some(("/c/app", "")));
        assert_eq!(review_request("guess:/c/evil|12", &token), None);
        assert_eq!(review_request(":/c/evil|12", ""), None);
        assert_eq!(review_request("/c/evil|12", &token), None);
    }
}