mnml-rs 0.2.14

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
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
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
//! The AI track. Two backends, picked by `[ai] backend` (see [`AiBackend`]):
//! `Cli` shells out to one-shot `claude -p "<prompt>"` subprocesses (the Claude
//! Code CLI in print mode — full tool use, the user's auth); `Api` posts
//! directly to `api.anthropic.com/v1/messages` ([`api_client`]) with an agentic
//! loop of its own (read-only — and optionally write — workspace tools). A
//! [`Pane::Ai`](crate::pane::Pane::Ai) shows the answer (rendered as markdown);
//! on-selection actions (`ai.explain` / `ai.fix` / `ai.refactor` /
//! `ai.write_tests`) and a free-text `ai.ask` build the prompt and spawn the
//! run. The work happens on a thread; [`crate::app::App::tick`] polls the
//! result channel — same pattern as the HTTP request pane.
//!
//! Interactive agentic AI is the `Pane::Pty` `claude`/`codex` panes; the
//! `Pane::Ai` surface is the "ask / do one thing to this code" path.
//!
//! Each one-shot is given a session id, so a `Pane::Ai` can be *promoted* to a
//! full interactive Claude Code pane (`claude --resume <id>`) when you want to go
//! deeper — the quick answer isn't a dead end. A promoted (or any) session can
//! also be mirrored as a rendered transcript ([`transcript`], [`AiState::Live`]).
//!
//! An on-selection `fix`/`refactor` answer carries an [`ApplyTarget`] (the source
//! file + byte range it was asked about); the first `a` in the pane extracts the
//! answer's first fenced code block ([`first_code_block`]), diffs it against the
//! live range ([`line_diff`] → a [`PendingApply`] the pane previews), and a second
//! `a` writes it back over that range (left dirty for review).
//!
//! An in-flight `-p` run can be cancelled (`x` in the pane): the worker uses
//! [`stream_to_channel`] / [`one_shot_cancellable`], which poll an `AtomicBool`
//! and kill the child.
//!
//! Output is streamed: [`stream_to_channel`] forwards stdout chunks as
//! [`AiMsg::Delta`]s while the run is in flight (the pane shows them as they
//! arrive — [`AiState::Streaming`]), then a final [`AiMsg::Done`] with the clean
//! trimmed answer (or [`AiMsg::Failed`]).

pub mod api_client;
pub mod transcript;

/// Which backend an AI job hits. `Cli` shells out to `claude -p` (the
/// default — uses the user's Claude Code auth / subscription, full tool
/// use). `Api` posts directly to `https://api.anthropic.com/v1/messages`
/// with SSE streaming + its own agentic tool loop (read-only workspace
/// tools by default; see `[ai] api_tools`). Requires `$ANTHROPIC_API_KEY`
/// and bills API credits.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AiBackend {
    Cli,
    Api,
}

impl AiBackend {
    pub fn parse(s: &str) -> Self {
        match s.to_ascii_lowercase().as_str() {
            "api" | "http" | "direct" => AiBackend::Api,
            _ => AiBackend::Cli,
        }
    }
}

/// Which engine produces inline ghost-text completions. `Unset` means
/// the user hasn't picked yet — enabling inline suggestions opens the
/// setup picker.
///
/// - `ClaudeCode` uses the user's Claude Max/Pro subscription via
///   the OAuth token read from `~/.config/mnml/ai_token`. Users
///   populate that file by clicking the AI-usage overlay chip's
///   "Fetch from Keychain" (macOS) or by pasting the token by hand.
///   The wizard's auto-select uses `claude` binary + `~/.claude/`
///   presence as a proxy for "signed in", and the first ghost-text
///   call surfaces a targeted "run `claude` to sign in" toast if the
///   token isn't there yet. Anthropic's TOS
///   officially restricts OAuth-token use to Claude Code + claude.ai
///   — this path is grey-area but community-established (Zed, Continue,
///   avante.nvim, aider all ship it). Ghost-text is low-volume so
///   quota impact is minimal; if it stops working, users switch to
///   `ClaudeApi`.
/// - `ClaudeApi` uses `api_client::complete_code` with
///   `$ANTHROPIC_API_KEY` (billed to a pay-per-token console budget).
/// - `Local` is the `fim-engine` candle-embedded model (a managed
///   ~1 GB GGUF download, runs in-process — offline, no auth).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SuggestBackend {
    Unset,
    ClaudeCode,
    ClaudeApi,
    Local,
}

impl SuggestBackend {
    pub fn parse(s: &str) -> Self {
        match s.to_ascii_lowercase().as_str() {
            "claude-code" | "cc" | "sub" | "subscription" => SuggestBackend::ClaudeCode,
            "claude-api" | "claude" | "api" => SuggestBackend::ClaudeApi,
            "local" | "candle" => SuggestBackend::Local,
            _ => SuggestBackend::Unset,
        }
    }
    pub fn as_str(self) -> &'static str {
        match self {
            SuggestBackend::Unset => "unset",
            SuggestBackend::ClaudeCode => "claude-code",
            SuggestBackend::ClaudeApi => "claude-api",
            SuggestBackend::Local => "local",
        }
    }
}

/// A generic AI product mnml routes to. Currently Claude (Anthropic —
/// Claude Code CLI + Anthropic API) and Codex (OpenAI's `codex exec`).
/// The routing schema (`[ai.routing.<product>]`) lets each product be
/// pinned to a backend independently. Task #975 (2026-08-17).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AiProduct {
    Claude,
    Codex,
}

impl AiProduct {
    /// The TOML key under `[ai.routing]` for this product.
    pub fn key(self) -> &'static str {
        match self {
            AiProduct::Claude => "claude",
            AiProduct::Codex => "codex",
        }
    }
    /// The binary that would provide the "sub" backend for this product.
    pub fn sub_binary(self) -> &'static str {
        match self {
            AiProduct::Claude => "claude",
            AiProduct::Codex => "codex",
        }
    }
}

/// A user's declared routing choice for one AI product.
///
/// - `Sub`: force the subscription (CLI) path; error if the binary is
///   missing.
/// - `Api`: force the direct-API path; error if the vendor's API-key
///   env var is missing (`$ANTHROPIC_API_KEY` for Claude,
///   `$OPENAI_API_KEY` for Codex).
/// - `Auto`: detect the binary on PATH. Sub if found, else Api if the
///   env key is set, else Sub (the failure surfaces on first call with
///   the actionable "run `claude` to sign in" toast, which is the same
///   behaviour as an explicit `Sub` choice on a fresh machine).
/// - `Off`: user-declared intent to disable this AI product. v1 partial:
///   ghost-text short-circuits (`ai_inline_suggestions` returns false),
///   but ask/explain/fix/refactor/write-tests still fire `claude -p` —
///   the chip-hide + palette-command gate is deferred (documented as a
///   TODO on `ai_backend()`). Reviewer flag 2026-08-17 on 2a5a5b14 —
///   fix pending. For now: setting `Off` reliably disables ghost-text
///   only; other commands still bill / call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RoutingBackend {
    Sub,
    Api,
    Auto,
    Off,
}

impl RoutingBackend {
    pub fn parse(s: &str) -> Self {
        match s.to_ascii_lowercase().as_str() {
            "sub" | "subscription" | "cli" | "cc" | "claude-code" => RoutingBackend::Sub,
            "api" | "http" | "direct" | "claude-api" => RoutingBackend::Api,
            "off" | "disable" | "disabled" => RoutingBackend::Off,
            _ => RoutingBackend::Auto,
        }
    }
    pub fn as_str(self) -> &'static str {
        match self {
            RoutingBackend::Sub => "sub",
            RoutingBackend::Api => "api",
            RoutingBackend::Auto => "auto",
            RoutingBackend::Off => "off",
        }
    }
}

/// The `Auto` variant resolved against the current machine. Every code
/// path that fires an AI request switches on this — never on the raw
/// declared choice — so the auto detection stays in one place.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResolvedBackend {
    Sub,
    Api,
    Off,
}

/// Read the DECLARED routing choice for `product` from the `[ai]`
/// table. Pure — no PATH probes, no env reads. Testable off a synthetic
/// toml value. `resolve_backend` layers the auto-detection on top.
///
/// Precedence:
/// 1. `[ai.routing.<product>] backend = "..."` (the new key) wins.
/// 2. Fall back to the legacy `[ai] backend` key, Claude only:
///    `"cli"` → `Sub`, `"api"` → `Api`, anything else → `Auto`.
/// 3. Codex has no legacy key — its default is `Auto`.
pub fn configured_backend(ai: &toml::Value, product: AiProduct) -> RoutingBackend {
    if let Some(s) = ai
        .get("routing")
        .and_then(|r| r.get(product.key()))
        .and_then(|p| p.get("backend"))
        .and_then(|v| v.as_str())
    {
        return RoutingBackend::parse(s);
    }
    match product {
        AiProduct::Claude => match ai.get("backend").and_then(|v| v.as_str()) {
            Some(s) => {
                let low = s.to_ascii_lowercase();
                match low.as_str() {
                    "api" | "http" | "direct" => RoutingBackend::Api,
                    "cli" | "sub" | "subscription" | "cc" | "claude-code" => RoutingBackend::Sub,
                    "off" | "disable" | "disabled" => RoutingBackend::Off,
                    _ => RoutingBackend::Auto,
                }
            }
            None => RoutingBackend::Auto,
        },
        AiProduct::Codex => RoutingBackend::Auto,
    }
}

/// True when the user has BOTH the new `[ai.routing.claude] backend`
/// key AND the legacy `[ai] backend` key set. Startup uses this to
/// emit a one-line deprecation warning so users know the new key
/// silently wins. Only checked for Claude (Codex has no legacy key).
pub fn has_legacy_and_new_claude(ai: &toml::Value) -> bool {
    let new = ai
        .get("routing")
        .and_then(|r| r.get("claude"))
        .and_then(|p| p.get("backend"))
        .is_some();
    let legacy = ai.get("backend").is_some();
    new && legacy
}

/// Resolve `configured_backend(ai, product)` against the current
/// machine. Turns `Auto` into a concrete `Sub` or `Api` by probing
/// `PATH` for the sub binary and the vendor's API-key env var
/// (`$ANTHROPIC_API_KEY` for Claude, `$OPENAI_API_KEY` for Codex).
/// `Off` and explicit `Sub` / `Api` pass through untouched.
pub fn resolve_backend(ai: &toml::Value, product: AiProduct) -> ResolvedBackend {
    match configured_backend(ai, product) {
        RoutingBackend::Sub => ResolvedBackend::Sub,
        RoutingBackend::Api => ResolvedBackend::Api,
        RoutingBackend::Off => ResolvedBackend::Off,
        RoutingBackend::Auto => {
            let (bin, key_env) = match product {
                AiProduct::Claude => ("claude", "ANTHROPIC_API_KEY"),
                AiProduct::Codex => ("codex", "OPENAI_API_KEY"),
            };
            let has_bin = crate::integration_detect::is_binary_installed(bin);
            let has_key = std::env::var(key_env)
                .ok()
                .filter(|s| !s.trim().is_empty())
                .is_some();
            if has_bin {
                ResolvedBackend::Sub
            } else if has_key {
                ResolvedBackend::Api
            } else {
                // No detection wins; default to sub so the first
                // call surfaces the "run `<bin>` to sign in" toast
                // rather than silently failing under Api.
                ResolvedBackend::Sub
            }
        }
    }
}

use std::path::PathBuf;
use std::process::Command;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

/// Where an on-selection AI action's suggested code can be applied back: the
/// source file + the byte range that was sent (a selection, or the whole
/// buffer). Captured at ask-time; on `a` in the answer pane the first fenced
/// code block replaces this range (left dirty for review). Offsets are clamped
/// to the buffer's current length on apply, so a since-then edit can't corrupt.
#[derive(Debug, Clone)]
pub struct ApplyTarget {
    pub path: PathBuf,
    pub start: usize,
    pub end: usize,
}

/// The contents of the first fenced code block (```… or ~~~…) in markdown `md`,
/// with the trailing newline trimmed. `None` if there's no fence. An unterminated
/// block returns whatever followed the opening fence.
pub fn first_code_block(md: &str) -> Option<String> {
    let mut in_block = false;
    let mut out = String::new();
    for line in md.lines() {
        let is_fence = {
            let t = line.trim_start();
            t.starts_with("```") || t.starts_with("~~~")
        };
        if !in_block {
            if is_fence {
                in_block = true;
            }
            continue;
        }
        if is_fence {
            return Some(out.trim_end_matches('\n').to_string());
        }
        out.push_str(line);
        out.push('\n');
    }
    in_block.then(|| out.trim_end_matches('\n').to_string())
}

/// One line of a [`line_diff`] preview.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiffLine {
    /// Unchanged context (may be the synthetic `… N lines …` elision).
    Ctx(String),
    /// A removed line.
    Del(String),
    /// An added line.
    Add(String),
}

/// A minimal line diff `old` → `new`: trim the common prefix/suffix lines (keep
/// up to `CTX` of each, with an elision marker if more were dropped), then emit
/// the changed middle as `Del`s then `Add`s. Good enough for previewing an AI
/// suggestion over a selection (it's not a real LCS — two distant edit regions
/// collapse into one block, which is fine here).
pub fn line_diff(old: &str, new: &str) -> Vec<DiffLine> {
    const CTX: usize = 3;
    let o: Vec<&str> = old.split('\n').collect();
    let n: Vec<&str> = new.split('\n').collect();
    let mut pre = 0;
    while pre < o.len() && pre < n.len() && o[pre] == n[pre] {
        pre += 1;
    }
    let mut suf = 0;
    while suf < o.len() - pre && suf < n.len() - pre && o[o.len() - 1 - suf] == n[n.len() - 1 - suf]
    {
        suf += 1;
    }
    let mut out: Vec<DiffLine> = Vec::new();
    let push_ctx = |lines: &[&str], from_end: bool, out: &mut Vec<DiffLine>| {
        if lines.len() <= CTX {
            for l in lines {
                out.push(DiffLine::Ctx(l.to_string()));
            }
        } else if from_end {
            out.push(DiffLine::Ctx(format!(
                "{} unchanged lines …",
                lines.len() - CTX
            )));
            for l in &lines[lines.len() - CTX..] {
                out.push(DiffLine::Ctx(l.to_string()));
            }
        } else {
            for l in &lines[..CTX] {
                out.push(DiffLine::Ctx(l.to_string()));
            }
            out.push(DiffLine::Ctx(format!(
                "{} unchanged lines …",
                lines.len() - CTX
            )));
        }
    };
    if pre > 0 {
        // The leading context is the *suffix* of the common-prefix block.
        push_ctx(&o[..pre], true, &mut out);
    }
    for l in &o[pre..o.len() - suf] {
        out.push(DiffLine::Del(l.to_string()));
    }
    for l in &n[pre..n.len() - suf] {
        out.push(DiffLine::Add(l.to_string()));
    }
    if suf > 0 {
        push_ctx(&o[o.len() - suf..], false, &mut out);
    }
    out
}

/// A pending "apply this AI suggestion" awaiting confirmation: where it goes +
/// the new code + the preview diff (`a` again applies; `r` re-ask clears it).
#[derive(Debug, Clone)]
pub struct PendingApply {
    pub target: ApplyTarget,
    pub code: String,
    pub diff: Vec<DiffLine>,
}

/// The `Pane::Ai` payload — either a `claude -p` one-shot (+ its answer) or a
/// live mirror of a Claude Code session transcript.
pub struct AiPane {
    /// Short label for the bufferline / close prompt.
    pub title: String,
    /// For a one-shot: the prompt sent to `claude -p` (re-sent on `r`). For a
    /// live mirror: a short label (the session id prefix).
    pub prompt: String,
    /// The Claude Code session id — `c` resumes it as an interactive pty pane.
    pub session_id: String,
    /// Matched against the worker's reply (re-fire / shifted indices ⇒ stale).
    pub job_id: u64,
    pub state: AiState,
    /// Top rendered row.
    pub scroll: usize,
    /// For an on-selection `fix`/`refactor`: where the suggested code can be
    /// applied back (`a` in the pane). `None` for explain / free-text asks / etc.
    pub target: Option<ApplyTarget>,
    /// First `a` stages the suggestion here (with a diff preview); a second `a`
    /// applies it. Cleared on apply / re-ask.
    pub pending_apply: Option<PendingApply>,
    /// Set this to ask an in-flight `claude -p` worker to kill its child and
    /// bail (`x` in the pane while `Asking`). Replaced on each re-ask.
    pub cancel: Arc<AtomicBool>,
}

pub enum AiState {
    /// A `claude -p` run is in flight; no output yet.
    Asking,
    /// A `claude -p` run is in flight and streaming — the text so far.
    Streaming(String),
    /// `claude -p` finished — its (markdown) answer.
    Done(String),
    /// `claude -p` failed — the error.
    Failed(String),
    /// A live mirror of a session transcript: `path` is the `.jsonl`, `last_len`
    /// the size we last parsed at, `turns` the parsed conversation.
    Live {
        path: PathBuf,
        last_len: u64,
        turns: Vec<transcript::Turn>,
    },
}

impl AiPane {
    pub fn new(
        title: impl Into<String>,
        prompt: String,
        session_id: String,
        job_id: u64,
        cancel: Arc<AtomicBool>,
    ) -> Self {
        AiPane {
            title: title.into(),
            prompt,
            session_id,
            job_id,
            state: AiState::Asking,
            scroll: 0,
            target: None,
            pending_apply: None,
            cancel,
        }
    }

    /// A live transcript mirror of `session_id` at `path` (read once now).
    pub fn live(session_id: String, path: PathBuf) -> Self {
        let turns = transcript::read(&path);
        let last_len = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
        let short: String = session_id.chars().take(8).collect();
        AiPane {
            title: format!("claude session {short}"),
            prompt: format!("session {short}"),
            session_id,
            job_id: 0,
            state: AiState::Live {
                path,
                last_len,
                turns,
            },
            scroll: usize::MAX, // start at the bottom (newest)
            target: None,
            pending_apply: None,
            cancel: Arc::new(AtomicBool::new(false)),
        }
    }

    pub fn is_live(&self) -> bool {
        matches!(self.state, AiState::Live { .. })
    }

    /// The text the user sees in the answer body, suitable for copying.
    /// `None` while no answer is rendered yet (Asking with no deltas) or
    /// for `Live` mirrors (those are scroll-back transcripts, not a
    /// single answer body — copy via the buffer instead).
    pub fn answer_text(&self) -> Option<&str> {
        match &self.state {
            AiState::Streaming(s) | AiState::Done(s) => Some(s.as_str()),
            AiState::Failed(s) => Some(s.as_str()),
            AiState::Asking | AiState::Live { .. } => None,
        }
    }

    pub fn tab_title(&self) -> String {
        let marker = match self.state {
            AiState::Asking | AiState::Streaming(_) => "",
            AiState::Failed(_) => "",
            AiState::Done(_) => "",
            AiState::Live { .. } => "",
        };
        format!("{} {marker}", self.title)
    }
}

/// The binary used for one-shot prompts. (`codex exec` could be wired similarly.)
const CLI: &str = "claude";

/// A message a streaming `claude -p` worker sends back over `App.ai_chan`.
#[derive(Debug, Clone)]
pub enum AiMsg {
    /// More stdout text (append it to the pane's running buffer).
    Delta(String),
    /// The run finished — the full, trimmed answer (replaces the buffer).
    Done(String),
    /// The run failed (or was cancelled) — the reason.
    Failed(String),
    /// Token usage for the just-finished API request — sent just before
    /// `Done` by the direct-API workers (the CLI backend doesn't report
    /// it). Drives the session token/cost tally.
    Usage {
        input_tokens: u64,
        output_tokens: u64,
    },
    /// The agent loop wants to run a risky tool (a `write_file`) and is
    /// **blocked** waiting for the user to approve. The main thread opens
    /// a confirm prompt and replies through the job's confirm channel.
    /// `summary` describes the pending action.
    ConfirmTool { summary: String },
}

/// Run `claude -p --session-id <session_id> <prompt>`, forwarding stdout chunks
/// to `sink` as [`AiMsg::Delta`]s as they arrive, then a final [`AiMsg::Done`]
/// (trimmed stdout) or [`AiMsg::Failed`]. Checks `cancel` while the child runs
/// (kills it + reports `"cancelled"` if it goes true). Blocking — call from a
/// worker thread; every message is tagged with `job_id`.
pub fn stream_to_channel(
    prompt: &str,
    session_id: &str,
    cancel: &AtomicBool,
    sink: std::sync::mpsc::Sender<(u64, AiMsg)>,
    job_id: u64,
) {
    stream_cli_to_channel(
        CLI,
        &["-p", "--session-id", session_id, prompt],
        cancel,
        sink,
        job_id,
        "Claude Code",
    );
}

/// `codex exec <prompt>` variant. Mirrors [`stream_to_channel`] for the
/// OpenAI Codex CLI — used by `git.codex_commit` to get an AI-written
/// commit message from `codex` instead of `claude`. (No session id —
/// codex's invocation is stateless per call.)
pub fn stream_codex_to_channel(
    prompt: &str,
    cancel: &AtomicBool,
    sink: std::sync::mpsc::Sender<(u64, AiMsg)>,
    job_id: u64,
) {
    stream_cli_to_channel(
        "codex",
        &["exec", prompt],
        cancel,
        sink,
        job_id,
        "Codex CLI",
    );
}

/// Shared spawn-and-pump core. Splits out the bin / args from the
/// streaming machinery so `claude -p` and `codex exec` can both flow
/// through it without duplicating the reader-thread + cancel-loop logic.
fn stream_cli_to_channel(
    bin: &str,
    args: &[&str],
    cancel: &AtomicBool,
    sink: std::sync::mpsc::Sender<(u64, AiMsg)>,
    job_id: u64,
    friendly_name: &str,
) {
    use std::io::Read;
    use std::process::Stdio;
    let mut child = match Command::new(bin)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
    {
        Ok(c) => c,
        Err(e) => {
            let _ = sink.send((
                job_id,
                AiMsg::Failed(format!(
                    "running `{bin}`: {e} — is the {friendly_name} on PATH?"
                )),
            ));
            return;
        }
    };
    let mut so = child.stdout.take().expect("piped stdout");
    let mut se = child.stderr.take().expect("piped stderr");
    // Reader thread: pump stdout chunks straight to `sink` (lossy UTF-8 per
    // chunk — a split multibyte char is transient; the final `Done` is clean),
    // accumulating the raw bytes to return on join.
    let chunk_sink = sink.clone();
    let so_h = std::thread::spawn(move || {
        let mut acc = Vec::new();
        let mut buf = [0u8; 4096];
        loop {
            match so.read(&mut buf) {
                Ok(0) | Err(_) => break,
                Ok(n) => {
                    acc.extend_from_slice(&buf[..n]);
                    let _ = chunk_sink.send((
                        job_id,
                        AiMsg::Delta(String::from_utf8_lossy(&buf[..n]).into_owned()),
                    ));
                }
            }
        }
        acc
    });
    let se_h = std::thread::spawn(move || {
        let mut v = Vec::new();
        let _ = se.read_to_end(&mut v);
        v
    });
    let mut killed = false;
    loop {
        if !killed && cancel.load(Ordering::Relaxed) {
            let _ = child.kill();
            killed = true;
        }
        match child.try_wait() {
            Ok(Some(status)) => {
                let out = so_h.join().unwrap_or_default();
                let err = se_h.join().unwrap_or_default();
                let _ = sink.send((job_id, settle(killed, status.success(), &out, &err)));
                return;
            }
            Ok(None) => std::thread::sleep(std::time::Duration::from_millis(40)),
            Err(e) => {
                let _ = sink.send((job_id, AiMsg::Failed(format!("waiting on `{bin}`: {e}"))));
                return;
            }
        }
    }
}

/// Decide the final [`AiMsg`] for a finished `claude -p` from `(was it killed,
/// exited 0, stdout, stderr)`.
fn settle(killed: bool, success: bool, stdout: &[u8], stderr: &[u8]) -> AiMsg {
    if killed {
        return AiMsg::Failed("cancelled".to_string());
    }
    let out = String::from_utf8_lossy(stdout);
    if success {
        let s = out.trim();
        return if s.is_empty() {
            AiMsg::Failed("(empty response)".to_string())
        } else {
            AiMsg::Done(s.to_string())
        };
    }
    let err = String::from_utf8_lossy(stderr);
    let m = [err.trim(), out.trim()]
        .into_iter()
        .find(|s| !s.is_empty())
        .unwrap_or("`claude -p` failed");
    AiMsg::Failed(m.lines().next().unwrap_or(m).to_string())
}

/// Run `claude -p --session-id <session_id> <prompt>` to completion and return
/// its stdout (trimmed), or a one-line error. Blocking — call from a worker
/// thread. The session id lets the answer be resumed interactively later.
pub fn one_shot(prompt: &str, session_id: &str) -> Result<String, String> {
    one_shot_cancellable(prompt, session_id, &AtomicBool::new(false))
}

/// Like [`one_shot`], but checks `cancel` while the child runs: if it goes true,
/// the child is killed and `Err("cancelled")` returned. (Polls every ~40 ms;
/// stdout/stderr are drained on threads so a large answer can't deadlock the
/// pipes.) Blocking — call from a worker thread.
pub fn one_shot_cancellable(
    prompt: &str,
    session_id: &str,
    cancel: &AtomicBool,
) -> Result<String, String> {
    use std::io::Read;
    use std::process::Stdio;
    let mut child = Command::new(CLI)
        .args(["-p", "--session-id", session_id])
        .arg(prompt)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| format!("running `{CLI} -p`: {e} — is the Claude Code CLI on PATH?"))?;
    let mut so = child.stdout.take().expect("piped stdout");
    let mut se = child.stderr.take().expect("piped stderr");
    let so_h = std::thread::spawn(move || {
        let mut v = Vec::new();
        let _ = so.read_to_end(&mut v);
        v
    });
    let se_h = std::thread::spawn(move || {
        let mut v = Vec::new();
        let _ = se.read_to_end(&mut v);
        v
    });
    let mut killed = false;
    loop {
        if !killed && cancel.load(Ordering::Relaxed) {
            let _ = child.kill();
            killed = true;
        }
        match child.try_wait() {
            Ok(Some(status)) => {
                let out = so_h.join().unwrap_or_default();
                let err = se_h.join().unwrap_or_default();
                if killed {
                    return Err("cancelled".to_string());
                }
                let stdout = String::from_utf8_lossy(&out);
                if status.success() {
                    let s = stdout.trim();
                    return if s.is_empty() {
                        Err("(empty response)".to_string())
                    } else {
                        Ok(s.to_string())
                    };
                }
                let stderr = String::from_utf8_lossy(&err);
                let msg = [stderr.trim(), stdout.trim()]
                    .into_iter()
                    .find(|s| !s.is_empty())
                    .unwrap_or("`claude -p` failed");
                return Err(msg.lines().next().unwrap_or(msg).to_string());
            }
            Ok(None) => std::thread::sleep(std::time::Duration::from_millis(40)),
            Err(e) => return Err(format!("waiting on `{CLI} -p`: {e}")),
        }
    }
}

/// A fresh UUID-v4-shaped session id (from `/dev/urandom`, with a time+pid
/// fallback). Not crypto — just needs to be unique per `claude -p` run.
pub fn gen_session_id() -> String {
    let mut b = [0u8; 16];
    let filled = {
        use std::io::Read;
        std::fs::File::open("/dev/urandom")
            .and_then(|mut f| f.read_exact(&mut b))
            .is_ok()
    };
    if !filled {
        let seed = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)
            ^ ((std::process::id() as u128) << 64);
        let mut z = seed;
        for chunk in b.chunks_mut(8) {
            z = z.wrapping_add(0x9e37_79b9_7f4a_7c15);
            let mut x = z as u64;
            x = (x ^ (x >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
            x = (x ^ (x >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
            x ^= x >> 31;
            for (i, by) in chunk.iter_mut().enumerate() {
                *by = x.to_le_bytes()[i];
            }
        }
    }
    b[6] = (b[6] & 0x0f) | 0x40;
    b[8] = (b[8] & 0x3f) | 0x80;
    let mut s = String::with_capacity(36);
    for (i, by) in b.iter().enumerate() {
        if matches!(i, 4 | 6 | 8 | 10) {
            s.push('-');
        }
        s.push_str(&format!("{by:02x}"));
    }
    s
}

// ── prompts for the on-selection actions ────────────────────────────

/// Wrap `code` in a fenced block tagged with `lang` (empty → untagged).
fn fenced(code: &str, lang: &str) -> String {
    format!("```{lang}\n{}\n```", code.trim_end_matches('\n'))
}

/// Build the prompt for an on-selection action. `what` is the kind id
/// (`explain`/`fix`/`refactor`/`write_tests`); `code` is the selection (or whole
/// buffer); `lang` is the buffer's language hint.
pub fn action_prompt(what: &str, code: &str, lang: &str) -> String {
    let block = fenced(code, lang);
    match what {
        "explain" => format!(
            "Explain what this {lang} code does, concisely. Cover its purpose, the \
             non-obvious bits, and anything that looks wrong.\n\n{block}"
        ),
        "fix" => format!(
            "Find and fix any bugs in this {lang} code. Reply with the corrected code \
             in a single fenced block, then a short bullet list of what you changed.\n\n{block}"
        ),
        "refactor" => format!(
            "Refactor this {lang} code for clarity without changing behaviour. Reply \
             with the refactored code in a single fenced block, then a short note on \
             what you did.\n\n{block}"
        ),
        "write_tests" => format!(
            "Write thorough unit tests for this {lang} code (idiomatic for the language; \
             cover the edge cases). Reply with the test code in a single fenced block.\n\n{block}"
        ),
        _ => format!("Look at this {lang} code:\n\n{block}"),
    }
}

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

    #[test]
    fn first_code_block_extracts_the_fence() {
        let md = "Here's the fix:\n\n```rust\nfn x() -> i32 { 1 }\n```\n\n- changed the return\n";
        assert_eq!(first_code_block(md).as_deref(), Some("fn x() -> i32 { 1 }"));
        assert_eq!(first_code_block("no code here").as_deref(), None);
        // unterminated → whatever followed the opener
        assert_eq!(first_code_block("```\na\nb\n").as_deref(), Some("a\nb"));
        // only the *first* block
        assert_eq!(
            first_code_block("```\nfirst\n```\n```\nsecond\n```").as_deref(),
            Some("first")
        );
    }

    #[test]
    fn settle_picks_the_right_outcome() {
        assert!(matches!(settle(true, false, b"x", b""), AiMsg::Failed(m) if m == "cancelled"));
        assert!(matches!(settle(false, true, b"  hello  \n", b""), AiMsg::Done(m) if m == "hello"));
        assert!(
            matches!(settle(false, true, b"   \n  ", b""), AiMsg::Failed(m) if m == "(empty response)")
        );
        // failure → first non-empty of stderr / stdout, first line only.
        assert!(
            matches!(settle(false, false, b"", b"boom: bad\nmore"), AiMsg::Failed(m) if m == "boom: bad")
        );
        assert!(
            matches!(settle(false, false, b"stdout err", b""), AiMsg::Failed(m) if m == "stdout err")
        );
        assert!(
            matches!(settle(false, false, b"", b""), AiMsg::Failed(m) if m == "`claude -p` failed")
        );
    }

    #[test]
    fn line_diff_trims_common_prefix_and_suffix() {
        use DiffLine::*;
        // A change in the middle, short context kept verbatim.
        let d = line_diff("a\nb\nOLD\nc\nd", "a\nb\nNEW1\nNEW2\nc\nd");
        assert_eq!(
            d,
            vec![
                Ctx("a".into()),
                Ctx("b".into()),
                Del("OLD".into()),
                Add("NEW1".into()),
                Add("NEW2".into()),
                Ctx("c".into()),
                Ctx("d".into()),
            ]
        );
        // Pure append: no Del, just the new tail.
        assert_eq!(
            line_diff("a\nb", "a\nb\nc"),
            vec![Ctx("a".into()), Ctx("b".into()), Add("c".into())]
        );
        // Long leading context is elided down to 3 lines (+ a marker).
        let d = line_diff("1\n2\n3\n4\n5\nX", "1\n2\n3\n4\n5\nY");
        assert_eq!(d[0], Ctx("… 2 unchanged lines …".into()));
        assert_eq!(
            &d[1..],
            &[
                Ctx("3".into()),
                Ctx("4".into()),
                Ctx("5".into()),
                Del("X".into()),
                Add("Y".into())
            ]
        );
        // Identical input ⇒ nothing changed (all context, no Del/Add).
        let d = line_diff("same\ntext", "same\ntext");
        assert!(d.iter().all(|l| matches!(l, Ctx(_))));
    }

    #[test]
    fn action_prompt_includes_code_and_lang() {
        let p = action_prompt("explain", "fn x() {}", "rust");
        assert!(p.contains("```rust\nfn x() {}\n```"));
        assert!(p.to_lowercase().contains("explain"));
        let p = action_prompt("write_tests", "def f(): pass", "python");
        assert!(p.contains("```python"));
        assert!(p.to_lowercase().contains("test"));
    }

    // ── Per-product routing (task #975) ─────────────────────────────

    fn ai_from(s: &str) -> toml::Value {
        toml::from_str::<toml::Value>(s).unwrap()
    }

    #[test]
    fn configured_backend_defaults_to_auto_when_empty() {
        let ai = ai_from("");
        assert_eq!(
            configured_backend(&ai, AiProduct::Claude),
            RoutingBackend::Auto
        );
        assert_eq!(
            configured_backend(&ai, AiProduct::Codex),
            RoutingBackend::Auto
        );
    }

    #[test]
    fn configured_backend_reads_new_key_per_product() {
        let ai = ai_from(
            r#"
            [routing.claude]
            backend = "sub"
            [routing.codex]
            backend = "off"
            "#,
        );
        assert_eq!(
            configured_backend(&ai, AiProduct::Claude),
            RoutingBackend::Sub
        );
        assert_eq!(
            configured_backend(&ai, AiProduct::Codex),
            RoutingBackend::Off
        );
    }

    #[test]
    fn configured_backend_migrates_legacy_backend_key_for_claude() {
        // Legacy `[ai] backend = "cli"` → Sub for Claude.
        let ai = ai_from(r#"backend = "cli""#);
        assert_eq!(
            configured_backend(&ai, AiProduct::Claude),
            RoutingBackend::Sub
        );
        // Codex isn't governed by the legacy key — stays Auto.
        assert_eq!(
            configured_backend(&ai, AiProduct::Codex),
            RoutingBackend::Auto
        );
        // Legacy `[ai] backend = "api"` → Api for Claude.
        let ai = ai_from(r#"backend = "api""#);
        assert_eq!(
            configured_backend(&ai, AiProduct::Claude),
            RoutingBackend::Api
        );
    }

    #[test]
    fn configured_backend_new_key_wins_over_legacy() {
        // New key set → legacy is ignored, new value wins.
        let ai = ai_from(
            r#"
            backend = "api"
            [routing.claude]
            backend = "sub"
            "#,
        );
        assert_eq!(
            configured_backend(&ai, AiProduct::Claude),
            RoutingBackend::Sub
        );
        assert!(has_legacy_and_new_claude(&ai));
    }

    #[test]
    fn has_legacy_and_new_flags_dual_config_only() {
        // Only legacy — no flag.
        let ai = ai_from(r#"backend = "cli""#);
        assert!(!has_legacy_and_new_claude(&ai));
        // Only new — no flag.
        let ai = ai_from(
            r#"[routing.claude]
backend = "sub""#,
        );
        assert!(!has_legacy_and_new_claude(&ai));
        // Both — flag.
        let ai = ai_from(
            r#"
            backend = "cli"
            [routing.claude]
            backend = "api"
            "#,
        );
        assert!(has_legacy_and_new_claude(&ai));
    }

    #[test]
    fn routing_backend_parse_covers_synonyms() {
        assert_eq!(RoutingBackend::parse("sub"), RoutingBackend::Sub);
        assert_eq!(RoutingBackend::parse("subscription"), RoutingBackend::Sub);
        assert_eq!(RoutingBackend::parse("cli"), RoutingBackend::Sub);
        assert_eq!(RoutingBackend::parse("cc"), RoutingBackend::Sub);
        assert_eq!(RoutingBackend::parse("claude-code"), RoutingBackend::Sub);
        assert_eq!(RoutingBackend::parse("api"), RoutingBackend::Api);
        assert_eq!(RoutingBackend::parse("claude-api"), RoutingBackend::Api);
        assert_eq!(RoutingBackend::parse("http"), RoutingBackend::Api);
        assert_eq!(RoutingBackend::parse("off"), RoutingBackend::Off);
        assert_eq!(RoutingBackend::parse("disabled"), RoutingBackend::Off);
        assert_eq!(RoutingBackend::parse(""), RoutingBackend::Auto);
        assert_eq!(RoutingBackend::parse("nonsense"), RoutingBackend::Auto);
        assert_eq!(RoutingBackend::parse("auto"), RoutingBackend::Auto);
    }

    #[test]
    fn resolve_backend_passes_explicit_choices_through() {
        // Explicit off / sub / api never touch the auto detector, so
        // this test is deterministic regardless of the host machine.
        let ai = ai_from(
            r#"[routing.claude]
backend = "off""#,
        );
        assert_eq!(
            resolve_backend(&ai, AiProduct::Claude),
            ResolvedBackend::Off
        );
        let ai = ai_from(
            r#"[routing.claude]
backend = "sub""#,
        );
        assert_eq!(
            resolve_backend(&ai, AiProduct::Claude),
            ResolvedBackend::Sub
        );
        let ai = ai_from(
            r#"[routing.claude]
backend = "api""#,
        );
        assert_eq!(
            resolve_backend(&ai, AiProduct::Claude),
            ResolvedBackend::Api
        );
        let ai = ai_from(
            r#"[routing.codex]
backend = "off""#,
        );
        assert_eq!(resolve_backend(&ai, AiProduct::Codex), ResolvedBackend::Off);
        // Codex explicit sub / api pass through symmetrically with
        // Claude — regression guard for the Codex-Api support added
        // 2026-08-17 (was previously Sub-only + hardcoded Auto = Sub).
        let ai = ai_from(
            r#"[routing.codex]
backend = "sub""#,
        );
        assert_eq!(resolve_backend(&ai, AiProduct::Codex), ResolvedBackend::Sub);
        let ai = ai_from(
            r#"[routing.codex]
backend = "api""#,
        );
        assert_eq!(resolve_backend(&ai, AiProduct::Codex), ResolvedBackend::Api);
    }

    #[test]
    fn resolve_backend_migrates_legacy_cli_to_sub() {
        // No auto detection involved — legacy `cli` maps directly to Sub.
        let ai = ai_from(r#"backend = "cli""#);
        assert_eq!(
            resolve_backend(&ai, AiProduct::Claude),
            ResolvedBackend::Sub
        );
    }
}