winx-code-agent 0.2.352

Remote-first Rust MCP runtime with Streamable HTTP, durable PTYs, and guarded agent tools
Documentation
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
//! Turn detection for interactive TUIs piloted through the PTY.
//!
//! "Has the program finished this turn and is it ready for the next input?" is
//! the core question when driving a full-screen TUI (the `claude` CLI, `codex`,
//! a REPL, ...) like a human operator. We answer it with a hybrid signal:
//!
//!   * a generic **quiescence** check (the rendered screen stopped changing),
//!     handled by the caller, plus
//!   * pluggable per-app **recognizers** here that read the rendered screen and
//!     classify it as [`TurnState::Busy`], [`TurnState::AwaitingInput`] or
//!     [`TurnState::AwaitingApproval`].
//!
//! Recognizers operate on already-rendered, ANSI-stripped screen lines, so they
//! never deal with escape codes — only with the visible text a human sees.

use regex::Regex;
use serde::{Deserialize, Serialize};

/// What an interactive program is doing right now, inferred from the screen.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TurnState {
    /// Actively producing output (spinner / "esc to interrupt" / streaming).
    Busy,
    /// Idle at an input prompt, ready for the next message.
    AwaitingInput,
    /// Blocked on a confirmation/permission dialog needing an operator choice.
    AwaitingApproval,
    /// The recognizer can't tell from the screen alone (defer to quiescence).
    Unknown,
}

impl TurnState {
    /// A short, stable label for status footers.
    pub fn as_str(self) -> &'static str {
        match self {
            TurnState::Busy => "busy",
            TurnState::AwaitingInput => "awaiting_input",
            TurnState::AwaitingApproval => "awaiting_approval",
            TurnState::Unknown => "unknown",
        }
    }

    /// Whether this state means the turn is over and the operator may act
    /// (send the next prompt, or answer a prompt).
    pub fn is_ready(self) -> bool {
        matches!(self, TurnState::AwaitingInput | TurnState::AwaitingApproval)
    }
}

/// Everything a recognizer may read: the rendered, ANSI-stripped screen lines
/// plus the latest OSC 0/2 title and OSC 9 progress payload captured from the
/// raw PTY stream. OSC strings are empty when the tap has seen none — the
/// manifest engine then behaves exactly like a screen-only detector.
#[derive(Debug, Clone, Copy)]
pub struct TurnInput<'a> {
    pub screen: &'a [String],
    pub osc_title: &'a str,
    pub osc_progress: &'a str,
}

impl<'a> TurnInput<'a> {
    /// A screen-only input (no OSC evidence).
    pub fn screen_only(screen: &'a [String]) -> Self {
        Self { screen, osc_title: "", osc_progress: "" }
    }
}

/// Reads a rendered screen (ANSI already stripped, one `String` per line) and
/// classifies the current turn state for a specific kind of TUI.
pub trait TurnRecognizer: Send + Sync {
    /// Stable identifier, surfaced in the status footer.
    fn name(&self) -> &'static str;
    /// Classify the current screen.
    fn detect(&self, screen: &[String]) -> TurnState;
    /// Classify with the full input (screen + OSC evidence). Screen-only
    /// recognizers get this for free; the manifest recognizer overrides it to
    /// use OSC title/progress rules.
    fn detect_input(&self, input: &TurnInput<'_>) -> TurnState {
        self.detect(input.screen)
    }
}

/// Build the recognizer for a hint string. Hints resolve in this order:
///   * `generic`/`none`/`off` and `configurable` keep their dedicated
///     recognizers;
///   * `auto` (and unknown hints) combine the claude + codex manifests with
///     the legacy hand-written recognizers as fallback;
///   * anything matching a bundled agent-manifest id or alias (`claude`,
///     `codex`, `gemini`, `agy`, `cursor`, `opencode`, `grok`, `copilot`, ...)
///     gets that manifest, with the legacy recognizer (where one exists)
///     backing it up when no manifest rule fires.
pub fn recognizer_for(hint: &str) -> Box<dyn TurnRecognizer> {
    let hint = hint.trim().to_ascii_lowercase();
    match hint.as_str() {
        "generic" | "none" | "off" => return Box::new(GenericRecognizer),
        "configurable" => return configurable_from_env(),
        "auto" => return auto_recognizer(),
        _ => {}
    }
    let legacy: Option<Box<dyn TurnRecognizer>> = match hint.as_str() {
        "claude" => Some(Box::new(ClaudeRecognizer)),
        "codex" => Some(Box::new(CodexRecognizer)),
        // `gemini` was historically an alias for the antigravity recognizer;
        // it now resolves to the gemini manifest but keeps those markers as
        // the fallback layer.
        "antigravity" | "agy" | "gemini" => Some(Box::new(AntigravityRecognizer)),
        _ => None,
    };
    match crate::state::turn_manifest::manifest_for(&hint) {
        Some(manifest) => Box::new(ManifestRecognizer { manifest, fallback: legacy }),
        None => legacy.unwrap_or_else(auto_recognizer),
    }
}

/// The `auto` recognizer: claude + codex manifests (each backed by its legacy
/// recognizer), combined by priority. Falls back to the purely hand-written
/// [`AutoRecognizer`] only if a bundled manifest failed to load.
fn auto_recognizer() -> Box<dyn TurnRecognizer> {
    use crate::state::turn_manifest::manifest_for;
    let (Some(claude), Some(codex)) = (manifest_for("claude"), manifest_for("codex")) else {
        return Box::new(AutoRecognizer);
    };
    Box::new(ManifestAutoRecognizer {
        members: [
            ManifestRecognizer { manifest: claude, fallback: Some(Box::new(ClaudeRecognizer)) },
            ManifestRecognizer { manifest: codex, fallback: Some(Box::new(CodexRecognizer)) },
        ],
    })
}

/// Build a [`GenericConfigurable`] from the `WINX_TURN_RECOGNIZER_CONFIG` env var
/// (JSON markers), or fall back to the generic quiescence recognizer when it is
/// unset, empty, or invalid.
fn configurable_from_env() -> Box<dyn TurnRecognizer> {
    if let Ok(json) = std::env::var("WINX_TURN_RECOGNIZER_CONFIG") {
        if let Ok(markers) = serde_json::from_str::<crate::types::TurnRecognizerMarkers>(&json) {
            if !markers.is_empty() {
                return Box::new(GenericConfigurable::new(&markers));
            }
        }
    }
    Box::new(GenericRecognizer)
}

// --- shared helpers ---------------------------------------------------------

/// Whether any line on the screen contains `needle` (case-insensitive).
///
/// Busy markers are scanned across the WHOLE screen, not just the tail: a long
/// response can push the footer's "esc to interrupt" out of the last lines, and
/// missing it would flip a still-generating turn to "ready" mid-stream and
/// corrupt the next input. A rare false-busy (the model literally printing the
/// phrase) only delays the turn — strictly the safer error.
fn any_line_contains(screen: &[String], needle: &str) -> bool {
    screen.iter().any(|l| l.to_lowercase().contains(needle))
}

/// Last `n` non-blank lines, lowercased and joined — used for the dialog
/// phrase scan ("do you want", "trust this folder", ...) which is naturally
/// localized to the bottom of the screen.
fn tail_lower(screen: &[String], n: usize) -> String {
    let mut lines: Vec<String> = screen
        .iter()
        .rev()
        .filter(|l| !l.trim().is_empty())
        .take(n)
        .map(|l| l.to_lowercase())
        .collect();
    lines.reverse();
    lines.join("\n")
}

// --- Claude TUI -------------------------------------------------------------

/// Recognizer for the `claude` CLI (Ink/React TUI). Markers verified against a
/// real claude v2.1.x session captured through winx:
///   * **Busy**: the footer shows `esc to interrupt` while generating. We rely
///     on this and NOT on spinner glyphs — claude renders inline, so spent
///     spinner lines ("✽ Gusting… (3s)") linger in the scrollback after the
///     turn ends and would otherwise read as a false "busy".
///   * **`AwaitingApproval`**: a confirmation/permission dialog, recognized by its
///     prompt phrasing ("do you want", "trust this folder", "Esc to cancel", …).
///   * **`AwaitingInput`**: the `❯` input box is present and neither of the above.
pub struct ClaudeRecognizer;

impl ClaudeRecognizer {
    fn is_approval(screen: &[String]) -> bool {
        // Phrase-based: these are the actual prompts claude shows for the
        // trust-folder check and tool-permission dialogs. We deliberately do
        // NOT key off a bare "1./2." numbered menu — ordinary numbered prose in
        // a normal answer ("1. Agile…", "2. Waterfall…") would false-positive.
        let joined = tail_lower(screen, 30);
        joined.contains("do you want")
            || joined.contains("would you like")
            || joined.contains("trust this folder")
            || joined.contains("enter to confirm")
            || joined.contains("esc to cancel")
    }

    fn has_input_box(screen: &[String]) -> bool {
        // The Ink prompt char. Only consulted once we've ruled out Busy/approval,
        // so a lingering `❯` from earlier prompts can't mask an active turn.
        screen.iter().any(|l| l.contains('❯'))
    }
}

impl TurnRecognizer for ClaudeRecognizer {
    fn name(&self) -> &'static str {
        "claude"
    }

    fn detect(&self, screen: &[String]) -> TurnState {
        // Order matters: Busy and approval are checked before the input box so a
        // stale `❯` never shadows an active or blocked turn.
        if any_line_contains(screen, "esc to interrupt") {
            return TurnState::Busy;
        }
        if Self::is_approval(screen) {
            return TurnState::AwaitingApproval;
        }
        if Self::has_input_box(screen) {
            return TurnState::AwaitingInput;
        }
        TurnState::Unknown
    }
}

// --- Codex CLI --------------------------------------------------------------

/// Recognizer for the `codex` CLI (Ink TUI). Markers verified against a real
/// codex-cli 0.139.0 (gpt-5.5) session captured through winx:
///   * **Busy**: the footer shows `• Working (Ns • esc to interrupt)` while
///     generating — the same `esc to interrupt` anchor claude uses.
///   * **`AwaitingApproval`**: the command-confirmation dialog ("Would you like
///     to run the following command?", "Press enter to confirm or esc to
///     cancel") shown when codex must escalate (e.g. `-a untrusted`).
///   * **`AwaitingInput`**: the input box, whose prompt glyph is `›` (U+203A) —
///     distinct from claude's `❯` and from a bare `>`.
pub struct CodexRecognizer;

impl CodexRecognizer {
    fn is_approval(screen: &[String]) -> bool {
        // Phrase-based and localized to the bottom of the screen. The `›`
        // selection glyph also appears in this dialog, so it MUST be classified
        // as approval (checked before the input box), not as plain input.
        let joined = tail_lower(screen, 30);
        joined.contains("would you like to run")
            || joined.contains("press enter to confirm")
            || joined.contains("yes, proceed")
    }

    fn has_input_box(screen: &[String]) -> bool {
        // Codex's Ink prompt char is `›` (U+203A). Only consulted once Busy and
        // approval are ruled out, so a lingering `›` can't mask an active turn.
        screen.iter().any(|l| l.trim_start().starts_with('›'))
    }
}

impl TurnRecognizer for CodexRecognizer {
    fn name(&self) -> &'static str {
        "codex"
    }

    fn detect(&self, screen: &[String]) -> TurnState {
        // Order matters: Busy and approval before the input box so a stale `›`
        // never shadows an active or blocked turn.
        //
        // `preparing to execute` covers the transient where codex is running a
        // tool call: it briefly drops the `esc to interrupt` footer while the
        // submitted prompt's `›` still lingers in the history — without this it
        // would read as a false AwaitingInput mid-execution.
        if any_line_contains(screen, "esc to interrupt")
            || any_line_contains(screen, "preparing to execute")
        {
            return TurnState::Busy;
        }
        if Self::is_approval(screen) {
            return TurnState::AwaitingApproval;
        }
        if Self::has_input_box(screen) {
            return TurnState::AwaitingInput;
        }
        TurnState::Unknown
    }
}

// --- Antigravity CLI --------------------------------------------------------

/// Recognizer for the `agy` (Antigravity CLI, Gemini) TUI. **Best-effort.**
/// Unlike claude/codex (Ink, alt-screen + in-place redraw), agy renders in
/// append mode inside winx's PTY: spent `Generating…` / `esc to cancel` frames
/// ghost into later screens and are never cleared. We therefore lead with the
/// idle hint `? for shortcuts`, which only sits at the *bottom* of the screen
/// when input is actually ready — a busy turn pushes it out of the tail — and
/// only then fall back to the busy markers. Markers verified against a real
/// agy 1.0.8 (Gemini 3.5 Flash) session captured through winx.
///
/// Deliberately NOT part of [`AutoRecognizer`]: its markers (`esc to cancel`,
/// `generating`) are generic enough to pollute claude/codex detection, so it is
/// opt-in only via the `agy`/`antigravity` hint — mirroring [`GenericRecognizer`].
pub struct AntigravityRecognizer;

impl TurnRecognizer for AntigravityRecognizer {
    fn name(&self) -> &'static str {
        "antigravity"
    }

    fn detect(&self, screen: &[String]) -> TurnState {
        // Idle hint first: `? for shortcuts` only sits at the bottom when the
        // input box is ready. A busy turn pushes it out of the tail, and under
        // append-mode rendering spent busy markers ghost into the idle screen —
        // so leading with the idle hint (scoped to the tail) is what survives
        // the ghosting. Only then fall back to the busy markers.
        if tail_lower(screen, 4).contains("? for shortcuts") {
            return TurnState::AwaitingInput;
        }
        if any_line_contains(screen, "generating") || any_line_contains(screen, "esc to cancel") {
            return TurnState::Busy;
        }
        TurnState::Unknown
    }
}

// --- Generic ----------------------------------------------------------------

/// No app knowledge: always [`TurnState::Unknown`] so the caller decides purely
/// by quiescence. Correct (if conservative) for any TUI.
pub struct GenericRecognizer;

impl TurnRecognizer for GenericRecognizer {
    fn name(&self) -> &'static str {
        "generic"
    }

    fn detect(&self, _screen: &[String]) -> TurnState {
        TurnState::Unknown
    }
}

// --- Configurable from markers ----------------------------------------------

/// A recognizer built from marker strings/regexes in config
/// ([`crate::types::TurnRecognizerMarkers`]), so `wait_for_turn` can pilot an
/// arbitrary TUI without bespoke code. Same scan discipline as the built-ins:
/// busy across the whole screen (a long response can push its footer out of the
/// tail), approval/input tail-scoped so a stale scrollback prompt can't fire.
pub struct GenericConfigurable {
    busy: Vec<Regex>,
    approval: Vec<Regex>,
    input: Vec<Regex>,
}

impl GenericConfigurable {
    pub fn new(markers: &crate::types::TurnRecognizerMarkers) -> Self {
        Self {
            busy: compile_markers(&markers.busy),
            approval: compile_markers(&markers.awaiting_approval),
            input: compile_markers(&markers.awaiting_input),
        }
    }
}

/// Compile each marker as a case-insensitive regex, falling back to a literal
/// substring when the pattern doesn't compile; unusable markers are dropped.
fn compile_markers(patterns: &[String]) -> Vec<Regex> {
    patterns
        .iter()
        .filter_map(|pattern| {
            Regex::new(&format!("(?i){pattern}"))
                .or_else(|_| Regex::new(&format!("(?i){}", regex::escape(pattern))))
                .ok()
        })
        .collect()
}

impl TurnRecognizer for GenericConfigurable {
    fn name(&self) -> &'static str {
        "configurable"
    }

    fn detect(&self, screen: &[String]) -> TurnState {
        let whole = screen.join("\n");
        if self.busy.iter().any(|re| re.is_match(&whole)) {
            return TurnState::Busy;
        }
        let tail = tail_lower(screen, 30);
        if self.approval.iter().any(|re| re.is_match(&tail)) {
            return TurnState::AwaitingApproval;
        }
        if self.input.iter().any(|re| re.is_match(&tail)) {
            return TurnState::AwaitingInput;
        }
        TurnState::Unknown
    }
}

// --- Manifest-driven ---------------------------------------------------------

/// A recognizer backed by a data-driven agent manifest (see
/// [`crate::state::turn_manifest`]) with an optional legacy recognizer behind
/// it. A matched manifest rule is authoritative — including an explicit
/// `unknown` match (e.g. a transcript-viewer screen), which must NOT fall
/// through to the legacy recognizer: those screens show stale content that
/// legacy markers would misread. Only a complete manifest miss delegates.
pub struct ManifestRecognizer {
    manifest: &'static crate::state::turn_manifest::CompiledManifest,
    fallback: Option<Box<dyn TurnRecognizer>>,
}

impl TurnRecognizer for ManifestRecognizer {
    fn name(&self) -> &'static str {
        let manifest: &'static crate::state::turn_manifest::CompiledManifest = self.manifest;
        manifest.id()
    }

    fn detect(&self, screen: &[String]) -> TurnState {
        self.detect_input(&TurnInput::screen_only(screen))
    }

    fn detect_input(&self, input: &TurnInput<'_>) -> TurnState {
        let joined = input.screen.join("\n");
        let verdict = self.manifest.detect(crate::state::turn_manifest::DetectionInput {
            screen: &joined,
            osc_title: input.osc_title,
            osc_progress: input.osc_progress,
        });
        if let Some((rule_id, priority)) = verdict.rule {
            tracing::trace!(
                manifest = self.name(),
                rule = rule_id,
                priority,
                state = verdict.state.as_str(),
                "turn manifest rule matched"
            );
            return verdict.state;
        }
        match &self.fallback {
            Some(fallback) => fallback.detect_input(input),
            None => TurnState::Unknown,
        }
    }
}

/// Manifest-driven `auto`: claude + codex manifests evaluated side by side,
/// verdicts combined by priority (`Busy` > `AwaitingApproval` >
/// `AwaitingInput` > `Unknown`) — same arbitration as the legacy
/// [`AutoRecognizer`], so a busy app always wins over a stale prompt glyph.
struct ManifestAutoRecognizer {
    members: [ManifestRecognizer; 2],
}

impl TurnRecognizer for ManifestAutoRecognizer {
    fn name(&self) -> &'static str {
        "auto"
    }

    fn detect(&self, screen: &[String]) -> TurnState {
        self.detect_input(&TurnInput::screen_only(screen))
    }

    fn detect_input(&self, input: &TurnInput<'_>) -> TurnState {
        let states = self.members.each_ref().map(|member| member.detect_input(input));
        for want in [TurnState::Busy, TurnState::AwaitingApproval, TurnState::AwaitingInput] {
            if states.contains(&want) {
                return want;
            }
        }
        TurnState::Unknown
    }
}

// --- Auto -------------------------------------------------------------------

/// Runs every app-specific recognizer and combines their verdicts by priority:
/// `Busy` > `AwaitingApproval` > `AwaitingInput` > `Unknown`. A recognizer that
/// sees the app working therefore always wins over one that only sees a
/// (possibly stale) prompt glyph — so `auto` never reports a busy app as ready,
/// while still falling back to `Unknown` (quiescence) for an unknown TUI.
pub struct AutoRecognizer;

impl TurnRecognizer for AutoRecognizer {
    fn name(&self) -> &'static str {
        "auto"
    }

    fn detect(&self, screen: &[String]) -> TurnState {
        let states = [ClaudeRecognizer.detect(screen), CodexRecognizer.detect(screen)];
        for want in [TurnState::Busy, TurnState::AwaitingApproval, TurnState::AwaitingInput] {
            if states.contains(&want) {
                return want;
            }
        }
        TurnState::Unknown
    }
}

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

    fn lines(s: &[&str]) -> Vec<String> {
        s.iter().map(|x| (*x).to_string()).collect()
    }

    #[test]
    fn configurable_classifies_by_marker_case_insensitively() {
        let markers = crate::types::TurnRecognizerMarkers {
            busy: vec!["working".to_string()],
            awaiting_input: vec![r"\$".to_string()],
            awaiting_approval: vec!["confirm".to_string()],
        };
        let recognizer = GenericConfigurable::new(&markers);
        assert_eq!(recognizer.detect(&lines(&["WORKING on it"])), TurnState::Busy);
        assert_eq!(recognizer.detect(&lines(&["user@host:~$ "])), TurnState::AwaitingInput);
        assert_eq!(
            recognizer.detect(&lines(&["Please Confirm (y/n)"])),
            TurnState::AwaitingApproval
        );
        assert_eq!(recognizer.detect(&lines(&["just some text"])), TurnState::Unknown);
    }

    #[test]
    fn configurable_busy_beats_a_stale_prompt() {
        let markers = crate::types::TurnRecognizerMarkers {
            busy: vec!["esc to interrupt".to_string()],
            awaiting_input: vec![">".to_string()],
            awaiting_approval: vec![],
        };
        let recognizer = GenericConfigurable::new(&markers);
        // Both a prompt glyph and a busy marker on screen → Busy must win.
        assert_eq!(recognizer.detect(&lines(&["> ", "esc to interrupt"])), TurnState::Busy);
    }

    // Fixtures below are taken from a real `claude` v2.1.159 session captured
    // through winx's PTY.

    #[test]
    fn claude_busy_via_esc_to_interrupt() {
        let screen = lines(&[
            "❯ responda exatamente uma palavra: PONG",
            "",
            "* Hatching…",
            "⏵⏵ bypass permissions on (shift+tab to cycle) · esc to interrupt",
        ]);
        assert_eq!(ClaudeRecognizer.detect(&screen), TurnState::Busy);
        assert_eq!(AutoRecognizer.detect(&screen), TurnState::Busy);
    }

    #[test]
    fn claude_long_response_busy_even_with_stale_prompt() {
        // Regression for the review finding: on a long response the footer can
        // be far from the bottom and an old `❯` lingers in the scrollback.
        // Scanning the whole screen for "esc to interrupt" keeps it Busy, so we
        // never send input mid-stream.
        let mut screen = vec![
            "❯ old prompt from a previous turn".to_string(),
            String::new(),
            "●─here is a long answer".to_string(),
        ];
        screen.push("⏵⏵ bypass permissions on (shift+tab to cycle) · esc to interrupt".to_string());
        for i in 0..40 {
            screen.push(format!("streamed answer line {i}"));
        }
        assert_eq!(ClaudeRecognizer.detect(&screen), TurnState::Busy);
        assert_eq!(AutoRecognizer.detect(&screen), TurnState::Busy);
    }

    #[test]
    fn claude_idle_after_answer_is_input_not_busy() {
        // claude renders inline, so spent spinner lines linger in the scrollback
        // after the turn finishes. Once the footer drops "esc to interrupt" and
        // the `❯` box is back, the turn IS over. (Real post-answer screen.)
        let screen = lines(&[
            "❯ Responda com exatamente uma palavra, em maiúsculas: PONG",
            "· Gusting…",
            "●─PONG",
            "✽ Gusting… (3s · ↓ 1 tokens)",
            "✻ Baked for 4s",
            "❯",
            "⏵⏵ bypass permissions on (shift+tab to cycle) · ← for agents",
        ]);
        assert_eq!(ClaudeRecognizer.detect(&screen), TurnState::AwaitingInput);
    }

    #[test]
    fn claude_numbered_prose_is_not_approval() {
        // Regression: a normal answer containing a numbered list whose text
        // happens to contain "allows"/"known" must NOT read as an approval.
        let screen = lines(&[
            "❯ compare the methodologies",
            "1. Agile - allows iterative delivery",
            "2. Waterfall - assumes requirements are known up front",
            "❯",
            "⏵⏵ bypass permissions on (shift+tab to cycle) · ← for agents",
        ]);
        assert_eq!(ClaudeRecognizer.detect(&screen), TurnState::AwaitingInput);
    }

    #[test]
    fn claude_awaiting_approval_trust_prompt() {
        // The real "trust this folder?" approval shown on a fresh directory.
        let screen = lines(&[
            "Quick safety check: Is this a project you created or one you trust?",
            "❯ 1. Yes, I trust this folder",
            "  2. No, exit",
            "Enter to confirm · Esc to cancel",
        ]);
        assert_eq!(ClaudeRecognizer.detect(&screen), TurnState::AwaitingApproval);
    }

    #[test]
    fn claude_awaiting_approval_tool_menu() {
        let screen = lines(&[
            "⏺ Bash(rm -rf /tmp/x)",
            "Do you want to proceed?",
            "❯ 1. Yes",
            "  2. No, and tell Claude what to do differently",
        ]);
        assert_eq!(ClaudeRecognizer.detect(&screen), TurnState::AwaitingApproval);
    }

    #[test]
    fn auto_surfaces_codex_input_when_claude_is_blind() {
        // A real codex idle screen: claude's recognizer doesn't know the `›`
        // glyph and returns Unknown, but auto must still surface codex's
        // AwaitingInput rather than collapsing to Unknown.
        let screen = lines(&["• PONG", "› Run /review on my current changes"]);
        assert_eq!(ClaudeRecognizer.detect(&screen), TurnState::Unknown);
        assert_eq!(CodexRecognizer.detect(&screen), TurnState::AwaitingInput);
        assert_eq!(AutoRecognizer.detect(&screen), TurnState::AwaitingInput);
    }

    #[test]
    fn auto_stays_busy_with_stale_prompt_glyphs() {
        // Both a stale claude `❯` and a codex `›` can linger while a turn
        // streams; the `esc to interrupt` footer must keep auto Busy, never
        // letting a leftover prompt glyph flip it to ready.
        let screen = lines(&["❯ old", "› old", "• Working (2s • esc to interrupt)"]);
        assert_eq!(AutoRecognizer.detect(&screen), TurnState::Busy);
    }

    // Codex fixtures below are from a real `codex` (codex-cli 0.139.0, gpt-5.5)
    // session captured through winx's PTY.

    #[test]
    fn codex_busy_via_working_footer() {
        let screen = lines(&[
            "› escreva um poema longo sobre o oceano",
            "",
            "• Working (1s • esc to interrupt)",
            "",
            "  gpt-5.5 high · ~/Documents/projects/winx-code-agent",
        ]);
        assert_eq!(CodexRecognizer.detect(&screen), TurnState::Busy);
        assert_eq!(AutoRecognizer.detect(&screen), TurnState::Busy);
    }

    #[test]
    fn codex_idle_input_box_uses_angle_prompt() {
        // Regression: codex's Ink prompt glyph is `›` (U+203A), not claude's `❯`
        // nor a bare `>`. The old recognizer missed it and fell back to Unknown,
        // forcing pure quiescence. Now it reports AwaitingInput explicitly.
        let screen = lines(&[
            "• PONG",
            "",
            "› Run /review on my current changes",
            "",
            "  gpt-5.5 high · ~/Documents/projects/winx-code-agent",
        ]);
        assert_eq!(CodexRecognizer.detect(&screen), TurnState::AwaitingInput);
    }

    #[test]
    fn codex_awaiting_approval_command_dialog() {
        // The real approval dialog codex shows under `-a untrusted`. Note the
        // `›` selection glyph also appears here, so approval MUST be checked
        // before the input box or it would read as AwaitingInput.
        let screen = lines(&[
            "  Would you like to run the following command?",
            "",
            "  $ touch /tmp/x.txt",
            "",
            "› 1. Yes, proceed (y)",
            "  2. Yes, and don't ask again (p)",
            "  3. No, and tell Codex what to do differently (esc)",
            "",
            "  Press enter to confirm or esc to cancel",
        ]);
        assert_eq!(CodexRecognizer.detect(&screen), TurnState::AwaitingApproval);
        assert_eq!(AutoRecognizer.detect(&screen), TurnState::AwaitingApproval);
    }

    #[test]
    fn codex_preparing_to_execute_is_busy_not_input() {
        // Regression from a live session: while codex prepares/runs a tool call
        // it briefly shows no `esc to interrupt` footer, and the just-submitted
        // prompt's `›` lingers in the history above. That transient must read as
        // Busy, not a false AwaitingInput, or a pilot would inject mid-execution.
        let screen = lines(&[
            "› execute o comando de shell 'touch /tmp/x.txt'",
            "• Vou executar exatamente esse comando",
            "• Preparing to execute shell command  9",
        ]);
        assert_eq!(CodexRecognizer.detect(&screen), TurnState::Busy);
    }

    #[test]
    fn codex_busy_wins_over_stale_angle_prompt() {
        // A busy codex still shows the `›` input box; "esc to interrupt" must
        // keep it Busy so we never send input mid-stream.
        let screen = lines(&["› an earlier prompt", "• Working (3s • esc to interrupt)"]);
        assert_eq!(CodexRecognizer.detect(&screen), TurnState::Busy);
    }

    // Antigravity (`agy` 1.0.8, Gemini 3.5 Flash) fixtures captured through
    // winx. agy renders in append mode, so these intentionally include the ghost
    // `Generating…` / `esc to cancel` frames that linger after the turn — the
    // recognizer must see through them.

    #[test]
    fn antigravity_busy_via_generating_and_esc_to_cancel() {
        let screen = lines(&[
            "> responda com uma palavra: PONG    Gemini 3.5 Flash (Medium)",
            "⣾  Generating...",
            "  PONG",
            "esc to cancel    Gemini 3.5 Flash (Medium)",
        ]);
        assert_eq!(AntigravityRecognizer.detect(&screen), TurnState::Busy);
    }

    #[test]
    fn antigravity_idle_via_shortcuts_hint_despite_ghost_frames() {
        // The real idle screen still carries ghost `Generating…`/`esc to cancel`
        // lines from the finished turn, but `? for shortcuts` sits at the bottom
        // only when input is ready — so it must win over the ghosts.
        let screen = lines(&[
            "  PONG",
            "⣯  Generating..",
            "esc to cancel    Gemini 3.5 Flash (Medium)",
            "? for shortcuts",
        ]);
        assert_eq!(AntigravityRecognizer.detect(&screen), TurnState::AwaitingInput);
    }

    #[test]
    fn antigravity_is_opt_in_not_part_of_auto() {
        // agy's best-effort markers would pollute claude/codex, so it is opt-in
        // only and auto must stay blind to its idle hint.
        let screen = lines(&["? for shortcuts"]);
        assert_eq!(AntigravityRecognizer.detect(&screen), TurnState::AwaitingInput);
        assert_eq!(AutoRecognizer.detect(&screen), TurnState::Unknown);
    }

    #[test]
    fn generic_is_always_unknown() {
        let screen = lines(&["$ ls", "file.txt", "$"]);
        assert_eq!(GenericRecognizer.detect(&screen), TurnState::Unknown);
    }

    #[test]
    fn auto_falls_back_to_unknown_for_plain_shell() {
        let screen = lines(&["building...", "done", "user@host:~$"]);
        assert_eq!(AutoRecognizer.detect(&screen), TurnState::Unknown);
    }

    #[test]
    fn turn_state_ready_semantics() {
        assert!(TurnState::AwaitingInput.is_ready());
        assert!(TurnState::AwaitingApproval.is_ready());
        assert!(!TurnState::Busy.is_ready());
        assert!(!TurnState::Unknown.is_ready());
    }

    // --- manifest-driven recognizer_for wiring ------------------------------

    #[test]
    fn recognizer_for_resolves_manifest_hints() {
        // Core hints resolve to their manifests (name = manifest id)...
        assert_eq!(recognizer_for("claude").name(), "claude");
        assert_eq!(recognizer_for("codex").name(), "codex");
        assert_eq!(recognizer_for("gemini").name(), "gemini");
        assert_eq!(recognizer_for("agy").name(), "agy");
        // ...as do agents winx never had hand-written recognizers for.
        assert_eq!(recognizer_for("cursor").name(), "cursor");
        assert_eq!(recognizer_for("opencode").name(), "opencode");
        assert_eq!(recognizer_for("ghcs").name(), "copilot");
        // Non-manifest hints keep their historical routing.
        assert_eq!(recognizer_for("auto").name(), "auto");
        assert_eq!(recognizer_for("generic").name(), "generic");
        assert_eq!(recognizer_for("something-else").name(), "auto");
    }

    #[test]
    fn manifest_claude_falls_back_to_legacy_markers_on_a_miss() {
        // No manifest rule fires on this minimal screen (no prompt box rules,
        // no dialogs), so the legacy `❯` marker must still surface input.
        let screen = lines(&["● answered", "❯"]);
        let recognizer = recognizer_for("claude");
        assert_eq!(recognizer.detect(&screen), TurnState::AwaitingInput);
    }

    #[test]
    fn manifest_rules_beat_legacy_on_current_claude_screens() {
        // The 2.x claude prompt box sits between two horizontal rules — a
        // shape only the manifest knows. The legacy recognizer also says
        // AwaitingInput here (via `❯`), but the manifest's approval/working
        // coverage beyond this is what the fixture tests below rely on.
        let screen = lines(&["●─PONG", "──────────", "❯ ", "──────────", "  ⏵⏵ accept edits on"]);
        assert_eq!(recognizer_for("claude").detect(&screen), TurnState::AwaitingInput);

        // A permission dialog the legacy phrase list misses ("Do you want to
        // proceed?" + numbered menu after a horizontal rule).
        let screen = lines(&[
            "⏺ Bash(cargo test)",
            "──────────",
            "Do you want to proceed?",
            "❯ 1. Yes",
            "  2. No, and tell Claude what to do differently",
            "Esc to cancel",
        ]);
        assert_eq!(recognizer_for("claude").detect(&screen), TurnState::AwaitingApproval);
    }

    #[test]
    fn manifest_explicit_unknown_does_not_fall_through_to_legacy() {
        // A transcript viewer shows STALE content — the legacy recognizer
        // would read the old "esc to interrupt" as Busy, but the manifest's
        // transcript_viewer rule (state=unknown) is authoritative: defer to
        // quiescence instead.
        let screen = lines(&[
            "⏺ old tool output esc to interrupt",
            "Showing detailed transcript",
            "ctrl+o to toggle",
        ]);
        assert_eq!(ClaudeRecognizer.detect(&screen), TurnState::Busy);
        assert_eq!(recognizer_for("claude").detect(&screen), TurnState::Unknown);
    }

    #[test]
    fn osc_title_spinner_keeps_claude_busy_over_an_idle_looking_screen() {
        // Screen alone looks idle (stale ❯), but the OSC title still carries
        // the braille spinner claude renders while generating.
        let screen = lines(&["❯ old prompt"]);
        let recognizer = recognizer_for("claude");
        let input = TurnInput { screen: &screen, osc_title: "⠋ claude", osc_progress: "" };
        assert_eq!(recognizer.detect_input(&input), TurnState::Busy);
        // Same screen without the title falls to the legacy `❯` marker.
        assert_eq!(
            recognizer.detect_input(&TurnInput::screen_only(&screen)),
            TurnState::AwaitingInput
        );
    }

    #[test]
    fn auto_combines_manifest_and_legacy_verdicts() {
        // Codex working footer → Busy through the manifest members.
        let screen = lines(&["❯ old", "› old", "• Working (2s • esc to interrupt)"]);
        assert_eq!(recognizer_for("auto").detect(&screen), TurnState::Busy);
        // Codex idle prompt only the legacy fallback knows → AwaitingInput.
        let screen = lines(&["• PONG", "› Run /review on my current changes"]);
        assert_eq!(recognizer_for("auto").detect(&screen), TurnState::AwaitingInput);
        // Plain shell → Unknown (quiescence decides).
        let screen = lines(&["building...", "done", "user@host:~$"]);
        assert_eq!(recognizer_for("auto").detect(&screen), TurnState::Unknown);
    }
}