nexus-chat 0.1.16

A local-first terminal chat app for deep research and multi-agent work
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
use anyhow::Result;
use crossterm::event::{
    Event, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent,
    MouseEventKind,
};
use futures_util::StreamExt;
use ratatui::DefaultTerminal;
use ratatui::layout::{Position, Rect};

use tui_textarea::CursorMove;

use crate::app_view::AppView;
use crate::ui;
use nexus_core::app::{AppEvent, ModelPanel, MouseTarget, Popup};

/// Ctrl+E/Ctrl+K in the space picker edit that space's instructions/memory
/// file. Returns the path to open, if the key matches and one resolves.
fn edit_file_target(app: &AppView, key: &KeyEvent) -> Option<std::path::PathBuf> {
    if !(app.popup == Popup::Space
        && app.space_mode == nexus_core::app::SpaceMode::Browse
        && key.modifiers.contains(KeyModifiers::CONTROL))
    {
        return None;
    }
    let (instructions, memory) = app.space_edit_target();
    match key.code {
        KeyCode::Char('e') => instructions,
        KeyCode::Char('k') => memory,
        _ => None,
    }
}

/// Ctrl+E in the skills popup opens the highlighted skill's SKILL.md.
fn skill_edit_target(app: &AppView, key: &KeyEvent) -> Option<std::path::PathBuf> {
    if !(app.popup == Popup::Skills
        && app.skills_mode == nexus_core::app::SkillsMode::Browse
        && key.modifiers.contains(KeyModifiers::CONTROL)
        && key.code == KeyCode::Char('e'))
    {
        return None;
    }
    app.skill_edit_path_for_selected()
}

/// Ctrl+E in the settings popup opens the app's base system prompt.
fn system_prompt_edit_target(app: &AppView, key: &KeyEvent) -> Option<std::path::PathBuf> {
    if !(app.popup == Popup::Settings
        && key.modifiers.contains(KeyModifiers::CONTROL)
        && key.code == KeyCode::Char('e'))
    {
        return None;
    }
    nexus_core::config::system_prompt_path().ok()
}

pub async fn run(mut app: AppView, terminal: &mut DefaultTerminal) -> Result<()> {
    let result = run_loop(&mut app, terminal).await;
    app.cancel_chat_tasks();
    result
}

// Long by design (event loop).
#[allow(clippy::too_many_lines)]
async fn run_loop(app: &mut AppView, terminal: &mut DefaultTerminal) -> Result<()> {
    let mut reader = EventStream::new();
    // Cheap poll for an omarchy theme switch (symlink target change) so a
    // `omarchy theme set` while nexus-chat is running takes effect live.
    let mut theme_poll = tokio::time::interval(std::time::Duration::from_secs(2));
    loop {
        // Locally-queued UI feedback (status lines, composer restore,
        // viewport resets) applies before the draw so it lands on the same
        // frame as the action that caused it.
        while let Some(ev) = app.pop_pending_event() {
            app.apply_event(&ev);
        }
        terminal.draw(|f| ui::render(f, app))?;
        if app.should_quit {
            break;
        }

        // Animate the thinking spinner only while a response streams.
        let streaming = app.is_streaming();
        let long_deadline = app.sel.deadline();
        let welcome = app.is_welcome();
        tokio::select! {
            maybe = reader.next() => match maybe {
                Some(Ok(Event::Key(k))) if k.kind == KeyEventKind::Press => {
                    if let Some(path) = edit_file_target(app, &k) {
                        edit_in_external_editor(terminal, &path)?;
                    } else if let Some(path) = skill_edit_target(app, &k) {
                        edit_in_external_editor(terminal, &path)?;
                        app.reload_skills();
                    } else if let Some(path) = system_prompt_edit_target(app, &k) {
                        edit_in_external_editor(terminal, &path)?;
                        app.reload_base_system_prompt();
                    } else if app.popup == Popup::Context && k.code == KeyCode::Char('v') {
                        match app.compact_summary_path() {
                            Some(path) => {
                                edit_in_external_editor(terminal, &path)?;
                                app.reload_compact_summary(&path)?;
                            }
                            None => app.push_status("session hasn't been compacted yet".to_string()),
                        }
                    } else {
                        handle_key(app, k)?;
                        // /edit queued an app file — open it now (this loop
                        // owns the terminal, run_command doesn't).
                        if let Some(edit) = app.pending_editor.take() {
                            match edit {
                                nexus_core::app::PendingEditor::AppFile(path) => {
                                    if let Err(e) = edit_in_external_editor(terminal, &path) {
                                        app.push_status(format!("editor failed: {e}"));
                                    }
                                }
                                nexus_core::app::PendingEditor::Persona(path) => {
                                    match edit_in_external_editor(terminal, &path) {
                                        Ok(()) => app.apply_swarm_persona_editor(&path)?,
                                        Err(e) => app.push_status(format!("editor failed: {e}")),
                                    }
                                }
                                nexus_core::app::PendingEditor::ScriptFile(path) => {
                                    if let Err(e) = edit_in_external_editor(terminal, &path) {
                                        app.push_status(format!("editor failed: {e}"));
                                    }
                                    app.refresh_scripts();
                                }
                            }
                        }
                    }
                }
                Some(Ok(Event::Mouse(m))) => {
                    let size = terminal.size()?;
                    handle_mouse(app, m, Rect::new(0, 0, size.width, size.height))?;
                }
                // Terminal-native paste (bracketed paste) — goes to whatever's
                // focused: the composer, or a popup's text field.
                Some(Ok(Event::Paste(text))) => {
                    app.paste(&text);
                }
                Some(Ok(_)) => {}
                Some(Err(e)) => return Err(e.into()),
                None => break,
            },
            event = app.next_event() => {
                // View-side events (status line, composer restore, viewport
                // reset) apply to the view layer; domain events go to their
                // handlers, which may push more pending events in turn.
                app.apply_event(&event);
                match event {
                    AppEvent::Status(_)
                    | AppEvent::Gate(_)
                    | AppEvent::Stream(None)
                    | AppEvent::ComposerSet(_)
                    | AppEvent::ComposerClear
                    | AppEvent::ViewportReset
                    | AppEvent::HistoryInvalidated
                    | AppEvent::OpenLoginPopup => {}
                    AppEvent::Stream(Some((task_id, e))) => app.on_chat_event(task_id, e)?,
                    AppEvent::Models(r) => {
                        app.on_models_result(r);
                        // First key just landed and nothing picked yet → jump
                        // into the picker (the domain can't open popups).
                        if !app.core.models.is_empty()
                            && app.core.current_model.is_none()
                            && app.popup == Popup::None
                        {
                            app.open_model_picker();
                        }
                    }
                    AppEvent::Title(t) => app.on_title_result(t),
                    AppEvent::Memory(m) => app.on_memory_result(m),
                    AppEvent::Compact(c) => app.on_compact_result(c),
                    AppEvent::SkillInstall(r) => app.on_skill_install_result(r),
                    AppEvent::Ocr(r) => app.on_ocr_done(r),
                    AppEvent::Embed(r) => app.on_embed_done(r),
                    AppEvent::OcrPull(r) => app.on_ocr_pull(r),
                    AppEvent::Research(r) => {
                        app.on_research_done(r);
                        // The job's channel closed: close the live view and
                        // clear its steer input (view state the domain no
                        // longer owns).
                        if app.core.research_rx.is_none() {
                            app.core.research_live_input.clear();
                            if app.popup == Popup::ResearchLive {
                                app.popup = Popup::None;
                            }
                        }
                    }
                    AppEvent::ResearchTopic(r) => app.on_research_topic_derived(r),
                    AppEvent::Login(r) => app.on_login_result(r),
                    AppEvent::UpdateCheck(r) => app.on_update_check(r),
                    AppEvent::Swarm(r) => app.on_swarm_update(r),
                }
            }
            () = async {
                if streaming {
                    tokio::time::sleep(std::time::Duration::from_millis(120)).await;
                } else {
                    std::future::pending::<()>().await;
                }
            } => app.tick_spinner(),
            // Long-press (held, unmoved) selects the whole conversation.
            () = async {
                match long_deadline {
                    Some(d) => tokio::time::sleep(d.saturating_duration_since(std::time::Instant::now())).await,
                    None => std::future::pending::<()>().await,
                }
            } => {
                match app.sel.check_long_press() {
                    Some(crate::selection::LongPress::Code(text)) => app.copy_text(&text),
                    Some(crate::selection::LongPress::Message(idx)) => app.copy_message(idx),
                    Some(crate::selection::LongPress::Url(url)) => app.copy_text(&url),
                    None => {}
                }
            }
            // Tick once a second on the start screen so the clock stays live.
            () = async {
                if welcome {
                    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
                } else {
                    std::future::pending::<()>().await;
                }
            } => {}
            _ = theme_poll.tick() => {
                let target = crate::theme::current_link_target();
                if target != app.theme_link {
                    let mode = app.background_mode;
                    app.theme = crate::theme::load();
                    app.theme.set_background_mode(mode);
                    app.theme_link = target;
                    app.theme_gen = app.theme_gen.wrapping_add(1);
                }
            }
        }
    }
    Ok(())
}

fn handle_key(app: &mut AppView, key: KeyEvent) -> Result<()> {
    // Ctrl+C always quits. Selecting text (mouse drag, in the composer or
    // history) copies it on release, so Ctrl+C doesn't need to double as copy.
    if key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::SHIFT)
        && key.code == KeyCode::Char('c')
    {
        app.should_quit = true;
        return Ok(());
    }
    // Ctrl+V pastes into whatever's focused (composer or a popup's text
    // field) — a fallback for terminals that don't send bracketed paste for
    // every popup, or don't send it at all.
    if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('v') {
        app.paste_from_clipboard();
        return Ok(());
    }

    match app.popup {
        Popup::Model => ui::popups::model::handle_key(app, key)?,
        Popup::Session => crate::ui::popups::session::handle_key(app, key)?,
        Popup::Key => crate::ui::popups::key::handle_key(app, key),
        Popup::Settings => ui::popups::settings::handle_key(app, key)?,
        Popup::Copy => crate::ui::popups::copy::handle_key(app, key),
        Popup::Space => crate::ui::popups::space::handle_key(app, key)?,
        Popup::Context => crate::ui::popups::context::handle_key(app, key),
        Popup::Skills => crate::ui::popups::skills::handle_key(app, key),
        Popup::Files => ui::popups::files::handle_key(app, key)?,
        Popup::Apps => ui::popups::apps::handle_key(app, key)?,
        Popup::Watch => ui::popups::watches::handle_key(app, key)?,
        Popup::ResearchLive => {
            ui::popups::research_live::handle_key(app, key);
        }
        Popup::Swarm => ui::popups::swarm::handle_key(app, key)?,
        Popup::Usage => {
            ui::popups::usage::handle_key(app, key);
        }
        Popup::Login => {
            ui::popups::login::handle_key(app, key);
        }

        Popup::None => handle_normal(app, key)?,
    }
    Ok(())
}

/// Suspend the TUI, open `path` in `$EDITOR` (falling back to `vi`), then
/// restore the terminal and force a full redraw (its contents are gone after
/// the editor exits).
fn edit_in_external_editor(terminal: &mut DefaultTerminal, path: &std::path::Path) -> Result<()> {
    let _ = crossterm::execute!(
        std::io::stdout(),
        crossterm::event::DisableMouseCapture,
        crossterm::event::DisableBracketedPaste
    );
    ratatui::restore();
    let editor_raw = std::env::var("EDITOR").unwrap_or_else(|_| "vi".to_string());
    let mut parts = editor_raw.split_whitespace();
    let editor = parts.next().unwrap_or("vi");
    let status = std::process::Command::new(editor)
        .args(parts)
        .arg(path)
        .status();
    *terminal = ratatui::init();
    let _ = crossterm::execute!(
        std::io::stdout(),
        crossterm::event::EnableMouseCapture,
        crossterm::event::EnableBracketedPaste
    );
    terminal.clear()?;
    match status {
        Ok(code) if code.success() => Ok(()),
        Ok(code) => {
            // Non-zero exit (vim `:cq`, user abort, etc.) — the terminal is
            // restored but the caller should not consume the edited file.
            Err(anyhow::anyhow!(
                "editor exited with code {}",
                code.code().unwrap_or(-1)
            ))
        }
        Err(e) => Err(anyhow::anyhow!("could not launch editor: {e}")),
    }
}

// Long by design (key dispatch).
#[allow(clippy::too_many_lines)]
fn handle_normal(app: &mut AppView, key: KeyEvent) -> Result<()> {
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
    let shift = key.modifiers.contains(KeyModifiers::SHIFT);

    // Slash-command autocomplete captures navigation while it's showing. Typing
    // (chars/backspace) still falls through so the list keeps filtering.
    if !app.command_matches().is_empty() {
        match key.code {
            KeyCode::Up => {
                app.move_command_selection(-1);
                return Ok(());
            }
            KeyCode::Down => {
                app.move_command_selection(1);
                return Ok(());
            }
            KeyCode::Tab => {
                app.accept_command(false)?;
                return Ok(());
            }
            KeyCode::Enter => {
                app.accept_command(true)?;
                return Ok(());
            }
            KeyCode::Esc => {
                app.set_input("");
                return Ok(());
            }
            _ => {}
        }
    }

    // @-file autocomplete — only when no slash command is showing.
    if app.at_state.is_some() {
        match key.code {
            KeyCode::Up => {
                app.move_at_selection(-1);
                return Ok(());
            }
            KeyCode::Down => {
                app.move_at_selection(1);
                return Ok(());
            }
            KeyCode::Tab | KeyCode::Enter => {
                app.accept_at_match();
                return Ok(());
            }
            KeyCode::Esc => {
                app.at_state = None;
                return Ok(());
            }
            _ => {}
        }
    }

    match key.code {
        // Shift+Enter and Ctrl+Enter insert a newline; plain Enter sends.
        KeyCode::Enter if shift || ctrl => app.input.insert_newline(),
        // A parked survey gate (survey answer or plan approval) intercepts
        // Enter — but only while the *viewed* session is the gated one, so a
        // gate in another session can never swallow typing. The reply routes
        // to the pipeline; an empty input means "approve" (plan) / "skip
        // ahead" (survey). Normal typing is untouched.
        KeyCode::Enter if app.survey_gate_targets_current_session() => {
            let text = app.input_text();
            app.set_input("");
            app.reply_to_survey_gate(&text);
        }
        KeyCode::Enter => app.submit()?,
        // Paste is handled by the terminal's bracketed paste (Event::Paste).
        // Ctrl+Shift+C copies the composer's selection to the OS clipboard for
        // terminals that forward it; otherwise the terminal's own copy works on
        // a mouse selection. Ctrl+X cuts.
        KeyCode::Char('a') if ctrl => app.input.select_all(),
        KeyCode::Char('c' | 'C') if ctrl && shift => app.copy_selection(),
        KeyCode::Char('x') if ctrl => app.cut_selection(),
        // Ctrl+R expands/collapses stored reasoning traces (editor's redo is
        // shadowed here — the composer rarely needs it).
        KeyCode::Char('r') if ctrl => app.toggle_reasoning_view()?,
        // Ctrl+T expands/collapses tool-call detail blocks in the transcript.
        KeyCode::Char('t') if ctrl => {
            app.show_tool_detail = !app.show_tool_detail;
            app.pin_viewport_top = true;
        }
        // Ctrl+N toggles incognito mode (no persistence, no apps).
        KeyCode::Char('n') if ctrl => app.toggle_incognito()?,
        // Ctrl+O navigates a session link message under the current selection.
        KeyCode::Char('o') if ctrl && app.sel.selected_text().is_some() => {
            app.open_session_link();
        }
        // 'p' pins, 'x' discards the [n] source under the current selection.
        // Both are plain letters guarded by an active mouse selection, so
        // composer typing is untouched (the guard fires only while a
        // selection exists).
        KeyCode::Char('p') if !ctrl && !shift && app.sel.selected_text().is_some() => {
            let selected = app.sel.selected_text();
            let owner = app.sel.owner_at_selection_start();
            app.core
                .flag_source_under_selection(Some("pinned"), selected, owner);
        }
        KeyCode::Char('x') if !ctrl && !shift && app.sel.selected_text().is_some() => {
            let selected = app.sel.selected_text();
            let owner = app.sel.owner_at_selection_start();
            app.core
                .flag_source_under_selection(Some("discarded"), selected, owner);
        }
        // Ctrl+↑ opens the live research-activity view (per-searcher
        // reasoning/tool calls) — only while a research job is running.
        KeyCode::Up if ctrl && app.research_rx.is_some() => app.open_research_live(),
        // Ctrl+G opens the context breakdown (system/memory/conversation/skills).
        // (Not Ctrl+I: that's the same byte as Tab on terminals without the
        // Kitty keyboard protocol, so it'd be unreachable on many of them.)
        KeyCode::Char('g') if ctrl => app.popup = Popup::Context,
        // Ctrl+Backspace deletes the previous word. (Alt+Backspace and Ctrl+W
        // also do this via the editor's default keymap.)
        KeyCode::Backspace if ctrl => {
            app.input.delete_word();
            app.refresh_at_matches();
            return Ok(());
        }
        // Up/Down move the composer cursor within a multi-row message first;
        // only once it's already at the top/bottom row do they scroll history.
        // Shift+Up/Down falls through to the default keymap instead, so it
        // extends the selection rather than being swallowed by this.
        KeyCode::Up if !shift => {
            let before = app.input.cursor();
            app.input.move_cursor(CursorMove::Up);
            if app.input.cursor() == before {
                app.scroll = app.scroll.saturating_add(1).min(app.max_scroll);
            }
            app.refresh_at_matches();
            return Ok(());
        }
        KeyCode::Down if !shift => {
            let before = app.input.cursor();
            app.input.move_cursor(CursorMove::Down);
            if app.input.cursor() == before {
                app.scroll = app.scroll.saturating_sub(1);
            }
            app.refresh_at_matches();
            return Ok(());
        }
        KeyCode::PageUp => app.scroll = app.scroll.saturating_add(10).min(app.max_scroll),
        KeyCode::PageDown => app.scroll = app.scroll.saturating_sub(10),
        // Esc stops the streaming response or clears the composer. (The old
        // Esc-stops-a-parked-plan-gate intercept is gone — approval is a chat
        // reply now; stopping a parked job is Ctrl+↑ then Ctrl+X in the live
        // view.)
        KeyCode::Esc if app.viewing_stream() => app.stop_stream()?,
        KeyCode::Esc => {
            app.set_input("");
        }
        // Everything else (chars, word-jump, selection, cut/copy/paste, undo)
        // goes to the editor via its default keymap. A keyboard (Shift+arrow)
        // selection has no "release" event like a mouse drag does, so keep
        // the clipboard synced to it live instead of requiring Ctrl+Shift+C.
        _ => {
            app.input.input(key);
            if app.input.is_selecting() {
                app.copy_selection_live();
            }
        }
    }
    app.refresh_at_matches();
    Ok(())
}

/// Mouse in the main view (no popup): composer click/drag places the cursor and
/// selects; history click/drag/double/triple selects text; wheel scrolls.
fn handle_input_mouse(app: &mut AppView, m: MouseEvent) {
    let over_input = app.input_inner.contains(Position::new(m.column, m.row));
    match m.kind {
        MouseEventKind::Down(MouseButton::Left) => {
            if over_input {
                app.mouse_target = MouseTarget::Input;
                app.sel.clear();
                let count = app.composer_click_down((m.column, m.row));
                composer_jump(app, m);
                match count {
                    2 => app.select_composer_word(),
                    n if n >= 3 => app.select_composer_line(),
                    _ => {
                        app.input.cancel_selection();
                        app.composer_word_anchor = None;
                    }
                }
            } else if let Some(p) = app.sel.pos_at(m.column, m.row) {
                app.mouse_target = MouseTarget::History;
                app.sel.on_down(p);
            } else {
                app.mouse_target = MouseTarget::None;
            }
        }
        MouseEventKind::Drag(MouseButton::Left) => match app.mouse_target {
            MouseTarget::Input => match app.composer_click_count {
                2 => {
                    composer_jump(app, m);
                    app.extend_composer_word_selection();
                }
                n if n >= 3 => {
                    composer_jump(app, m);
                    app.extend_composer_line_selection();
                }
                _ => {
                    if !app.input.is_selecting() {
                        app.input.start_selection();
                    }
                    composer_jump(app, m);
                }
            },
            MouseTarget::History => {
                if let Some(p) = app.sel.pos_at(m.column, m.row) {
                    app.sel.on_drag(p);
                }
            }
            MouseTarget::None => {}
        },
        MouseEventKind::Up(MouseButton::Left) => {
            match app.mouse_target {
                MouseTarget::History => {
                    let p = app.sel.pos_at(m.column, m.row);
                    // The timer normally handles a long press while the
                    // button is held.  Also check on release: some terminal
                    // event streams do not wake the timer reliably while a
                    // mouse button is down, and may only deliver the next
                    // event when the button is released.
                    let long_press = app.sel.check_long_press();
                    let long_press_handled = long_press.is_some() || app.sel.is_long_pressed();
                    if let Some(long_press) = long_press {
                        match long_press {
                            crate::selection::LongPress::Code(text)
                            | crate::selection::LongPress::Url(text) => app.copy_text(&text),
                            crate::selection::LongPress::Message(idx) => app.copy_message(idx),
                        }
                    }
                    match app.sel.on_up(p) {
                        Some(crate::selection::Action::Copy(text)) => app.copy_text(&text),
                        Some(crate::selection::Action::OpenUrl(url)) => {
                            let _ = open::that_detached(&url);
                            app.push_status(format!("opened {url}"));
                        }
                        None if !long_press_handled
                            && p.is_some_and(|p| app.open_image_at_line(p.0)) => {}
                        None if !long_press_handled && p.is_some() => {
                            // Click without drag on a non-image line: open URLs or start selection.
                        }
                        None => {}
                    }
                }
                // A drag in the composer selects text; releasing copies it
                // immediately, same as releasing a history-pane selection.
                // A plain click (no drag) never starts a selection, so this
                // doesn't fire just from placing the cursor.
                MouseTarget::Input if app.input.is_selecting() => app.copy_selection(),
                MouseTarget::Input | MouseTarget::None => {}
            }
            app.mouse_target = MouseTarget::None;
        }
        // Wheel scrolls the conversation history.
        MouseEventKind::ScrollUp => {
            app.scroll = app.scroll.saturating_add(3).min(app.max_scroll);
        }
        MouseEventKind::ScrollDown => app.scroll = app.scroll.saturating_sub(3),
        _ => {}
    }
}

/// Move the composer cursor to the clicked cell. ponytail: screen row/col mapped
/// straight to data line/char — exact when the composer isn't wrapped/scrolled
/// (tui-textarea keeps its screen<->data map private).
fn composer_jump(app: &mut AppView, m: MouseEvent) {
    let row = m.row.saturating_sub(app.input_inner.y);
    let col = m.column.saturating_sub(app.input_inner.x);
    app.input.move_cursor(CursorMove::Jump(row, col));
}

/// Route mouse events: composer click/drag when no popup is open, else the
/// model picker (the only interactive popup).
fn handle_mouse(app: &mut AppView, m: MouseEvent, screen: Rect) -> Result<()> {
    if app.popup == Popup::None {
        if m.kind == MouseEventKind::Down(MouseButton::Left) {
            let pos = Position::new(m.column, m.row);
            if let Some((_, index)) = app
                .notification_areas
                .iter()
                .find(|(area, _)| area.contains(pos))
                .copied()
            {
                app.activate_notification(index)?;
                return Ok(());
            }
        }
        handle_input_mouse(app, m);
        return Ok(());
    }
    if app.popup != Popup::Model {
        return Ok(());
    }
    let (fav_outer, avail_outer) = ui::popups::model::model_popup_areas(screen);
    let fav_inner = ui::popups::model::list_inner(fav_outer);
    let avail_inner = ui::popups::model::list_inner(avail_outer);
    let pos = Position::new(m.column, m.row);

    // Which panel is the cursor over?
    let panel = if fav_inner.contains(pos) {
        Some((ModelPanel::Favorites, fav_inner, app.fav_offset))
    } else if avail_inner.contains(pos) {
        Some((ModelPanel::Available, avail_inner, app.avail_offset))
    } else {
        None
    };

    match m.kind {
        MouseEventKind::Down(MouseButton::Left) => {
            if let Some((p, inner, offset)) = panel {
                let index = offset + (m.row - inner.y) as usize;
                app.pick_model_at(p, index)?; // no-op if index is past the list
            }
        }
        MouseEventKind::ScrollDown => {
            if let Some((p, ..)) = panel {
                app.model_focus = p;
                app.move_model_selection(1);
            }
        }
        MouseEventKind::ScrollUp => {
            if let Some((p, ..)) = panel {
                app.model_focus = p;
                app.move_model_selection(-1);
            }
        }
        _ => {}
    }
    Ok(())
}