mnml-rs 0.2.13

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
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
//! `Pane::Request` — a request fired from a `.http` / `.curl` / `.rest` editor
//! (the `http.send` command), with its response below: status line, headers,
//! pretty-printed body, and `@assert` / `@capture` results. The send runs on a
//! background thread; [`crate::app::App::tick`] polls the result channel and
//! flips the pane from [`RunState::Sending`] to `Done` / `Failed`.
//!
//! **Editable form fields.** A `Tab` keypress flips between
//! [`ViewMode::Response`] (the read-only view of the last send) and
//! [`ViewMode::Edit`], where the URL, method, and body are editable in place.
//! In Edit mode `Shift+Tab` / `Tab` cycle which field has the caret; typing /
//! backspace / arrows / Home / End edit the focused field; `Space` on Method
//! cycles through the standard verbs; `r` re-fires the request using the
//! current field values (so you can tweak a URL and re-send without flipping
//! back to the source file). Headers stay read-only in this first cut — the
//! list-of-pairs UI is heavier and lands in a follow-up.

use std::path::PathBuf;
use std::time::Duration;

use crate::http::Request;
use crate::http::script::{AssertionResult, Script};

pub struct RequestPane {
    /// The `.http`/`.curl`/`.rest` file the request was launched from (title only).
    pub source_path: Option<PathBuf>,
    /// Name of the source block this request came from, if the source file is
    /// multi-block (`### name` separator). `Some("")` for an unnamed block in a
    /// multi-block file (the `###` separator alone). `None` for single-block
    /// files (`.curl`, or `.http` with no `###` separators) — those overwrite
    /// the whole file on save. Used by `App::save_request_to_source` to do
    /// format-preserving writeback that only edits the matched block.
    pub source_block_name: Option<String>,
    /// The request being sent — templates already expanded, `@set-*` already
    /// applied. **Mutable from the Edit view**: the URL/method/body field
    /// editors mutate this directly so the next `r` re-fires with the edits.
    pub request: Request,
    /// Directives parsed from the same source (re-run on every send).
    pub script: Script,
    /// Set when this pane fires a send, matched against the worker's reply so a
    /// stale result (pane re-fired, or indices shifted) is ignored.
    pub job_id: u64,
    pub state: RunState,
    /// Top rendered row.
    pub scroll: usize,
    /// Which view is up — the Response (read-only) or the Edit form.
    pub view: ViewMode,
    /// Focused field in Edit mode.
    pub focus: EditField,
    /// Byte-offset caret for the URL field (always at a char boundary).
    pub url_cursor: usize,
    /// Byte-offset caret for the Body field. `request.body` is created on
    /// first body keystroke if it was `None`.
    pub body_cursor: usize,
    /// Editable text representation of the headers — `Key: Value` per line.
    /// Source of truth in Edit mode; parsed back into `request.headers` via
    /// [`Self::commit_headers`] before each send.
    pub headers_buffer: String,
    /// Byte-offset caret for the Headers field.
    pub headers_cursor: usize,
    /// Which tab the Edit view is showing. The tab strip (Body /
    /// Headers / Params / Vars / Source) sits above the per-tab
    /// content area; URL + Method always stay above the strip.
    /// Default = Body so the form mirrors rqst's startup tab.
    /// 2026-06-19 — added when the Edit view was restructured into
    /// a tabbed UI to match the rqst Postman-style layout.
    pub edit_tab: EditTab,
    /// Editable raw curl / `.http` source. Lives only as long as
    /// the pane (not persisted to disk). Typing on the Source tab
    /// appends here; `:http.paste_curl` with an empty clipboard
    /// falls back to parsing this buffer, populating the
    /// structured fields, then clearing.
    pub source_buffer: String,
    pub source_cursor: usize,
    /// Placeholder cursor used by `App::http_field_*` when the
    /// focused field is `Method` (which lacks a real cursor).
    /// Not persisted; recomputed each call.
    pub method_cursor_scratch: usize,
    /// The previous Done response (if any). Saved off when a new
    /// send completes — lets `:http.diff_last_two` compare the
    /// current Done against this snapshot. Cleared on a fresh
    /// :http.new or paste_curl that overwrites the request.
    pub prev_response: Option<Box<ResponseView>>,
    /// Case-insensitive substring filter applied to header rows
    /// (Edit-tab Headers list, request-summary headers, response
    /// headers). Empty ⇒ show all. Set by `/` in the pane; matches
    /// the sidebar-filter idiom used across Integrations / Agents /
    /// Settings. (#11)
    pub filter: String,
    /// `/` in the pane focuses the filter input; typing appends;
    /// Esc clears + unfocuses; Enter commits + unfocuses.
    pub filter_focused: bool,
    /// Wrap response body lines instead of clipping. Toggled by the
    /// `wrap` chip in the response section header (or `w` in Response
    /// view). Off by default so JSON keeps its raw line breaks. (#11)
    pub body_wrap: bool,
    /// Currently-hovered Params-row key. Set by the mouse-move
    /// handler; the row-row renderer paints it with the shared
    /// `row_highlight_menu` primitive so users see which row will
    /// react to their click. (#11 v13)
    pub hover_params_key: Option<String>,
    /// Currently-hovered Vars-row key (same shape as
    /// `hover_params_key`).
    pub hover_vars_key: Option<String>,
    /// Currently-hovered Auth-row id (same shape).
    pub hover_auth_id: Option<String>,
    /// Orientation of the Request/Response split within the pane.
    /// Vertical = stacked (Request top, Response bottom — default);
    /// Horizontal = side-by-side (Request left, Response right).
    /// Toggled by the `[ ▤ | ▥ ]` chip on the Request block's title
    /// bar or the `Ctrl+\` chord. AI zone stays pinned to the pane's
    /// bottom regardless.
    pub split_orientation: SplitOrientation,
    /// Currently-active Response sub-tab (Body / Headers / Timeline
    /// / Tests). Persists on the pane so a user's choice sticks
    /// across re-fires.
    pub response_tab: ResponseTab,
    /// Inline params-add editor. `None` when idle. `Some(...)` when
    /// the user clicked "+ Add new parameter" — renders as an
    /// editable row at the bottom of the Params list with Tab
    /// cycling between key and value. Enter commits (appends to
    /// URL); Esc cancels.
    pub params_add: Option<InlineKvDraft>,
    /// Inline headers-add editor. Same shape as `params_add` —
    /// Bruno-style key/value inline row. Enter commits (appends
    /// `Name: value\n` to `headers_buffer`); Esc cancels.
    pub headers_add: Option<InlineKvDraft>,
    /// In-place value-cell edit on an existing Params or Headers
    /// row. Populated when the user clicks a value cell.
    pub kv_edit: Option<KvValueEdit>,
    /// Manual override for how the Response body renders (Auto /
    /// JSON / XML / HTML / Text). Set by the `JSON ▼` chip on the
    /// response tab strip. Default = Auto (existing detect_body
    /// logic wins).
    pub response_body_format: ResponseBodyFormat,
    /// When Some, the Request edit area is split side-by-side: the
    /// primary `edit_tab` renders on the left, and this tab renders
    /// on the right. Both sides read and write the same underlying
    /// request state, so edits in one are immediately visible in the
    /// other (Body|Vars, Params|Headers, etc. — 2026-07-07).
    pub edit_tab_split: Option<EditTab>,
    /// Percent of the split area given to the LEFT side (clamped
    /// 10..=90). Only meaningful when `edit_tab_split` is Some.
    pub edit_split_ratio: u16,
    /// Optional short label for the tab — typically the swagger
    /// operation's `summary` field, extracted from the leading
    /// `# ...` comment when the request was loaded from a `.curl`
    /// / `.http` file. When set, `Pane::title()` shows
    /// `METHOD  <summary>` instead of `METHOD  <url>`. Reads much
    /// better in the bufferline for autogenerated stub files whose
    /// URLs contain long path segments and `{{VAR}}` templates.
    /// 2026-07-09 user request.
    pub summary: Option<String>,
    /// VS Code-style preview tab. Set to `true` when the pane was
    /// opened via arrow-nav or single-click in the HTTP panel —
    /// user is BROWSING, not committing to keep the tab. Any edit
    /// (typing URL, changing method, editing body/headers/params/
    /// vars) flips it to `false` and promotes the tab to permanent.
    /// Opening another preview Request pane REPLACES this one
    /// instead of adding a new bufferline tab.
    ///
    /// 2026-07-08 user report: "if im scrolling through requests
    /// with arrow key im getting a bunch of new tabs opened."
    pub is_preview: bool,
}

/// Draft state for an inline "add a new key/value pair" editor.
/// Shared by the Params and Headers tabs — Bruno-style: key field
/// on the left, value on the right, Tab cycles focus.
#[derive(Debug, Default, Clone)]
pub struct InlineKvDraft {
    pub key: String,
    pub value: String,
    pub key_cursor: usize,
    pub value_cursor: usize,
    /// `true` when the caret is on the value field; `false` on key.
    pub on_value: bool,
}

/// Backwards-compat alias — old code called this `ParamsAddDraft`.
pub type ParamsAddDraft = InlineKvDraft;

/// State for in-place edit of an existing Params or Headers row's
/// name OR value cell. Click a cell → set this; type / backspace
/// modifies `buffer`; Enter commits; Esc cancels.
#[derive(Debug, Clone)]
pub struct KvValueEdit {
    /// Which tab this edit belongs to. Guards the commit path so
    /// a Params edit doesn't accidentally rewrite a header.
    pub kind: KvEditKind,
    /// Original key of the row — used to locate the entry to
    /// update when the user commits. If the row was deleted or
    /// renamed under us, commit becomes a no-op.
    pub original_key: String,
    /// Current buffer contents. Renders as the edited cell text.
    pub buffer: String,
    pub cursor: usize,
    /// Which cell of the row is being edited. `false` = value cell
    /// (default when clicking the value column). `true` = name cell
    /// — commit renames the key, preserving the row's position and
    /// current value.
    pub editing_name: bool,
}

/// Which KV table an in-place edit targets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KvEditKind {
    Params,
    Headers,
    /// #23 v3 — env var cell edit. Commit path writes back to
    /// the active .env file via `App::write_env_var` (or the
    /// delete path when `buffer.is_empty()` for a name edit).
    Vars,
}

/// Manual override for how the Response body renders in the Body
/// sub-tab. `None` = auto-detect from content-type header + body
/// shape (existing behavior). `Some(...)` forces that format
/// regardless of what the server said. Set by the `JSON ▼` chip
/// on the response tab strip.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResponseBodyFormat {
    Auto,
    Json,
    Xml,
    Html,
    Text,
}

/// Two-way orientation for the Request/Response zones inside a
/// single Request pane. Kept on the pane so orientation persists
/// across renders + tab switches.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SplitOrientation {
    /// Auto — the renderer picks Vertical or Horizontal from the
    /// available width. Threshold: `>= AUTO_HORIZONTAL_THRESHOLD`
    /// cells → Horizontal (side-by-side); narrower → Vertical
    /// (stacked). Default for new panes. 2026-07-07.
    Auto,
    Vertical,
    Horizontal,
}

/// Pane-content width at or above which `SplitOrientation::Auto`
/// resolves to Horizontal (side-by-side). Below this, Auto stacks
/// Request over Response. Tuned so each half in horizontal mode still
/// has ~50 cells of comfortable width.
pub const AUTO_HORIZONTAL_THRESHOLD: u16 = 100;

impl SplitOrientation {
    /// Cycle Auto → Vertical → Horizontal → Auto. Was a 2-state
    /// Vertical ↔ Horizontal toggle before Auto shipped.
    pub fn toggle(self) -> Self {
        match self {
            SplitOrientation::Auto => SplitOrientation::Vertical,
            SplitOrientation::Vertical => SplitOrientation::Horizontal,
            SplitOrientation::Horizontal => SplitOrientation::Auto,
        }
    }

    /// Resolve `Auto` against the pane's available width; Vertical /
    /// Horizontal pass through unchanged. Callers use this at render
    /// time so the enum stays clean.
    pub fn resolve(self, pane_width: u16) -> Self {
        match self {
            SplitOrientation::Auto => {
                if pane_width >= AUTO_HORIZONTAL_THRESHOLD {
                    SplitOrientation::Horizontal
                } else {
                    SplitOrientation::Vertical
                }
            }
            other => other,
        }
    }
}

/// Sub-tabs inside the Response zone — mirrors Bruno's Response
/// pane (Body / Headers / Timeline / Tests). Kept on the
/// `RequestPane` so the user's choice persists across renders.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResponseTab {
    Body,
    Headers,
    Timeline,
    Tests,
}

impl ResponseTab {
    pub const ALL: &'static [ResponseTab] = &[
        ResponseTab::Body,
        ResponseTab::Headers,
        ResponseTab::Timeline,
        ResponseTab::Tests,
    ];
    pub fn label(self) -> &'static str {
        match self {
            ResponseTab::Body => "Body",
            ResponseTab::Headers => "Headers",
            ResponseTab::Timeline => "Timeline",
            ResponseTab::Tests => "Tests",
        }
    }
    pub fn next(self) -> Self {
        let i = Self::ALL.iter().position(|t| *t == self).unwrap_or(0);
        Self::ALL[(i + 1) % Self::ALL.len()]
    }
    pub fn prev(self) -> Self {
        let i = Self::ALL.iter().position(|t| *t == self).unwrap_or(0);
        Self::ALL[(i + Self::ALL.len() - 1) % Self::ALL.len()]
    }
}

/// The tabbed UI on the Edit view. `Tab` advances; `Shift+Tab`
/// retreats. Mouse-clickable. The URL + Method row always stays
/// visible above the strip; only the area below switches.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditTab {
    Body,
    Headers,
    Params,
    Auth,
    Vars,
    Source,
}

impl EditTab {
    // Bruno-style tab order — Params leads (what most REST-client
    // users tweak first), Body next, then structural fields.
    // Source is labeled "Script" to match Bruno's terminology (mnml
    // uses it for the raw .http source view; the naming just
    // parallels Bruno's Script tab).
    pub const ALL: &'static [EditTab] = &[
        EditTab::Params,
        EditTab::Body,
        EditTab::Headers,
        EditTab::Auth,
        EditTab::Vars,
        EditTab::Source,
    ];
    pub fn label(self) -> &'static str {
        match self {
            EditTab::Body => "Body",
            EditTab::Headers => "Headers",
            EditTab::Params => "Params",
            EditTab::Auth => "Auth",
            EditTab::Vars => "Vars",
            EditTab::Source => "Script",
        }
    }
    pub fn next(self) -> Self {
        let i = Self::ALL.iter().position(|t| *t == self).unwrap_or(0);
        Self::ALL[(i + 1) % Self::ALL.len()]
    }
    pub fn prev(self) -> Self {
        let i = Self::ALL.iter().position(|t| *t == self).unwrap_or(0);
        Self::ALL[(i + Self::ALL.len() - 1) % Self::ALL.len()]
    }
}

/// Which face of the request pane is shown.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ViewMode {
    /// The send's result — status / headers / body / asserts / captures.
    Response,
    /// The editable request form — URL, method, body.
    Edit,
}

/// The currently-edited field in [`ViewMode::Edit`]. Cycled by Tab / Shift-Tab.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditField {
    Url,
    Method,
    Headers,
    Body,
    /// 2026-06-19 v2 — Source-tab editable buffer. Typing populates
    /// `source_buffer`; Ctrl+Enter (or `:http.paste_curl` with
    /// empty clipboard fall-back) parses the buffer into the
    /// structured Method/URL/Headers/Body fields.
    Source,
}

impl EditField {
    pub fn next(self) -> Self {
        match self {
            EditField::Url => EditField::Method,
            EditField::Method => EditField::Headers,
            EditField::Headers => EditField::Body,
            EditField::Body => EditField::Url,
            // Source is reached only when the Source tab is active;
            // Tab from Source cycles back to URL (out of the Source
            // tab implicitly via re-render with the new focus).
            EditField::Source => EditField::Url,
        }
    }
    pub fn prev(self) -> Self {
        match self {
            EditField::Url => EditField::Body,
            EditField::Method => EditField::Url,
            EditField::Headers => EditField::Method,
            EditField::Body => EditField::Headers,
            EditField::Source => EditField::Body,
        }
    }
    pub fn label(self) -> &'static str {
        match self {
            EditField::Url => "URL",
            EditField::Method => "Method",
            EditField::Headers => "Headers",
            EditField::Body => "Body",
            EditField::Source => "Source",
        }
    }
}

/// Serialise headers as `Key: Value\n…` for the editable text buffer.
///
/// **Always emits a trailing `\n`** so callers that rebuild the buffer +
/// place the cursor at `headers_buffer.len()` (there are ~10 such call
/// sites across `src/app/http.rs`, see the r4 comment at
/// `http_next_block`) land on a fresh empty line rather than mid-value
/// in the last existing header. Without the trailer, any keystroke on
/// `focus == Headers` after a rebuild silently appends to the last
/// header's value — and in the common case where the last header is
/// `Authorization`, that value goes out on the wire as a corrupted
/// Bearer token with no error and no visual clue.
/// See R6 api-workflow SEV-1 (2026-08-09).
pub fn headers_to_text(headers: &[(String, String)]) -> String {
    if headers.is_empty() {
        return String::new();
    }
    let mut out = headers
        .iter()
        .map(|(k, v)| format!("{k}: {v}"))
        .collect::<Vec<_>>()
        .join("\n");
    out.push('\n');
    out
}

/// Parse the editable headers buffer back into `Vec<(name, value)>`. Lines
/// without a `:` are dropped; whitespace around the name and value is
/// trimmed. Blank lines are skipped. Header *names* are lower-cased? No —
/// preserved as typed, like the other parsers in `crate::http`.
pub fn parse_headers_text(text: &str) -> Vec<(String, String)> {
    text.lines()
        .filter_map(|l| {
            let l = l.trim();
            if l.is_empty() || l.starts_with('#') {
                return None;
            }
            let (k, v) = split_header_line(l)?;
            let k = k.trim();
            let v = v.trim();
            if k.is_empty() {
                None
            } else {
                Some((k.to_string(), v.to_string()))
            }
        })
        .collect()
}

/// Split a `Header-Name: value` line on the FIRST `:` only. Using
/// `split_once(':')` would truncate values that themselves contain a
/// colon (`X-Redirect-To: https://host/path`, RFC3339 timestamps,
/// etc.) — silently dropping everything past the first colon in the
/// value. Returns `None` when no `:` is present.
///
/// #polish 2026-07-06 — was `split_once(':')` at four sites (this
/// parser + the Headers KV table render + the kv-edit prefill +
/// the kv-edit commit rewrite).
pub fn split_header_line(l: &str) -> Option<(&str, &str)> {
    let i = l.find(':')?;
    Some((&l[..i], &l[i + 1..]))
}

/// The standard HTTP verbs the Method field cycles through. `Space` advances
/// to the next; if the field's current value isn't in this set (it came from
/// a `.http`/`.curl` file with something unusual), the first cycle lands on
/// the value after the closest match — practically the same as starting from
/// GET, which is fine.
pub const STANDARD_METHODS: &[&str] = &["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];

pub fn cycle_method(current: &str) -> String {
    let cur = current.trim().to_ascii_uppercase();
    let idx = STANDARD_METHODS
        .iter()
        .position(|m| **m == cur)
        .unwrap_or(0);
    let next = (idx + 1) % STANDARD_METHODS.len();
    STANDARD_METHODS[next].to_string()
}

pub enum RunState {
    Sending,
    /// 2026-06-20 — SSE progressive display. Stream is open and
    /// events have started arriving; mutating `partial.body` as
    /// each event lands. Flips to `Done` on stream close.
    Streaming(Box<ResponseView>),
    Done(Box<ResponseView>),
    Failed(String),
}

/// Progressive SSE stream messages. Worker thread sends Open
/// → Event* → Close. App.tick drains and mutates the matching
/// Request pane's Streaming state. job_id matches RequestPane.job_id.
pub enum SseStreamMsg {
    Open {
        job_id: u64,
        status: u16,
        status_text: String,
        headers: Vec<(String, String)>,
        started: std::time::Instant,
    },
    Event {
        job_id: u64,
        name: String,
        data: String,
    },
    Close {
        job_id: u64,
    },
    Error {
        job_id: u64,
        error: String,
    },
}

#[derive(Clone)]
pub struct ResponseView {
    pub status: u16,
    pub status_text: String,
    pub headers: Vec<(String, String)>,
    pub body: String,
    /// Raw response bytes — the round-trip-safe source of truth for
    /// disk writes (`http.save_response` on binary payloads).
    /// api-workflow SEV-1 2026-07-11.
    pub body_bytes: Vec<u8>,
    pub elapsed: Duration,
    /// Per-phase timing carried through from `http::Response`.
    /// Currently split into `wait` (send → headers received) and
    /// `receive` (body read).
    pub timing: crate::http::Timing,
    pub assertions: Vec<AssertionResult>,
    pub captures: Vec<(String, String)>,
    /// Result of validating the response body against a integration
    /// `*.schema.json` file (if one exists). `None` if validation
    /// wasn't attempted (e.g. response from the browser pane with
    /// no source file). The Response view renders a one-line
    /// "Schema: ✓ valid" / "Schema: ✗ N errors" footer when this
    /// is `Some`.
    pub schema_result: Option<crate::http::schema::SchemaResult>,
    /// 2026-06-21 api-workflow SEV-2 — proper SSE event counter
    /// for streaming responses. Was previously emulated by pushing
    /// empty `("", "")` tuples into `captures` and clearing on
    /// close — which silently dropped any real `@capture` results.
    pub sse_event_count: u32,
}

impl RequestPane {
    pub fn new(
        source_path: Option<PathBuf>,
        request: Request,
        script: Script,
        job_id: u64,
    ) -> Self {
        let url_cursor = request.url.len();
        let body_cursor = request.body.as_deref().map(str::len).unwrap_or(0);
        let headers_buffer = headers_to_text(&request.headers);
        let headers_cursor = headers_buffer.len();
        RequestPane {
            source_path,
            source_block_name: None,
            request,
            script,
            job_id,
            state: RunState::Sending,
            scroll: 0,
            view: ViewMode::Response,
            focus: EditField::Url,
            url_cursor,
            body_cursor,
            headers_buffer,
            headers_cursor,
            edit_tab: EditTab::Body,
            source_buffer: String::new(),
            source_cursor: 0,
            method_cursor_scratch: 0,
            prev_response: None,
            filter: String::new(),
            filter_focused: false,
            body_wrap: false,
            hover_params_key: None,
            hover_vars_key: None,
            hover_auth_id: None,
            split_orientation: SplitOrientation::Auto,
            response_tab: ResponseTab::Body,
            params_add: None,
            headers_add: None,
            kv_edit: None,
            response_body_format: ResponseBodyFormat::Auto,
            edit_tab_split: None,
            edit_split_ratio: 50,
            summary: None,
            is_preview: false,
        }
    }

    /// Toggle the side-by-side edit split. If already open, close it.
    /// If closed, open with a sensible secondary tab (Vars if the
    /// primary is anything else, Body when the primary is Vars).
    pub fn toggle_edit_split(&mut self) {
        if self.edit_tab_split.is_some() {
            self.edit_tab_split = None;
        } else {
            let default = if self.edit_tab == EditTab::Vars {
                EditTab::Body
            } else {
                EditTab::Vars
            };
            self.edit_tab_split = Some(default);
            self.edit_split_ratio = 50;
        }
    }

    /// Render this request as an `.http` block — what
    /// `App::save_request_to_source` writes back into multi-block source files.
    /// `name` (without leading `###`) controls the leading separator: `Some(s)`
    /// emits `### s` (or bare `###` when `s.is_empty()`); `None` skips the
    /// separator entirely (used when the matched block had no `###` prefix).
    pub fn as_http_block(&self, name: Option<&str>) -> String {
        let mut out = String::new();
        if let Some(n) = name {
            if n.is_empty() {
                out.push_str("###\n");
            } else {
                out.push_str("### ");
                out.push_str(n);
                out.push('\n');
            }
        }
        out.push_str(&self.request.method);
        out.push(' ');
        out.push_str(&self.request.url);
        out.push('\n');
        for (k, v) in &self.request.headers {
            out.push_str(k);
            out.push_str(": ");
            out.push_str(v);
            out.push('\n');
        }
        if let Some(body) = &self.request.body {
            out.push('\n');
            out.push_str(body);
            if !body.ends_with('\n') {
                out.push('\n');
            }
        }
        out
    }

    /// Parse the editable `headers_buffer` back into `request.headers`. Called
    /// before each send so the in-flight request reflects the user's edits.
    /// In Response mode (where `headers_buffer` is still tracking the original
    /// list) this is a no-op as long as the buffer matches.
    pub fn commit_headers(&mut self) {
        self.request.headers = parse_headers_text(&self.headers_buffer);
    }

    /// Flip between the read-only Response view and the editable form. Resets
    /// focus to the URL field every time you enter Edit (more predictable
    /// than remembering which field you were on last).
    pub fn toggle_view(&mut self) {
        self.view = match self.view {
            ViewMode::Response => ViewMode::Edit,
            ViewMode::Edit => ViewMode::Response,
        };
        if self.view == ViewMode::Edit {
            self.focus = EditField::Url;
        }
    }
    pub fn focus_next_field(&mut self) {
        self.focus = self.focus.next();
        self.sync_edit_tab_to_focus();
    }
    pub fn focus_prev_field(&mut self) {
        self.focus = self.focus.prev();
        self.sync_edit_tab_to_focus();
    }

    /// api-workflow-user r4 SEV-2 (2026-08-06) — Tab-cycling
    /// through EditField (URL → Method → Headers → Body → …) used
    /// to update `focus` but not `edit_tab`. If the visible tab was
    /// Body and the user Tab'd to Headers, keystrokes appended to
    /// the raw `headers_buffer` with zero visual feedback,
    /// corrupting the last header value. Switch the visible tab to
    /// match the new focus so what the user sees is what they type
    /// into.
    fn sync_edit_tab_to_focus(&mut self) {
        let target = match self.focus {
            EditField::Headers => Some(EditTab::Headers),
            EditField::Body => Some(EditTab::Body),
            EditField::Source => Some(EditTab::Source),
            // Url/Method live in the header row above the tab strip;
            // no tab flip needed for those.
            EditField::Url | EditField::Method => None,
        };
        if let Some(tab) = target {
            self.edit_tab = tab;
        }
    }

    /// Mutable handle to the focused field's `(text, cursor)`. Returns `None`
    /// for Method — that field is cycled via [`cycle_method`], not typed into.
    fn focused_text_mut(&mut self) -> Option<(&mut String, &mut usize)> {
        match self.focus {
            EditField::Url => Some((&mut self.request.url, &mut self.url_cursor)),
            EditField::Method => None,
            EditField::Headers => Some((&mut self.headers_buffer, &mut self.headers_cursor)),
            EditField::Body => {
                // Lazily create an empty body on first edit.
                let body = self.request.body.get_or_insert_with(String::new);
                Some((body, &mut self.body_cursor))
            }
            EditField::Source => Some((&mut self.source_buffer, &mut self.source_cursor)),
        }
    }

    /// Insert one character at the focused field's cursor. URL strips newlines
    /// (single-line field); Headers + Body accept them.
    pub fn type_char(&mut self, c: char) {
        if self.focus == EditField::Method {
            if c == ' ' {
                self.request.method = cycle_method(&self.request.method);
            }
            return;
        }
        let single_line = self.focus == EditField::Url;
        if single_line && c == '\n' {
            return;
        }
        let Some((s, cur)) = self.focused_text_mut() else {
            return;
        };
        let pos = (*cur).min(s.len());
        s.insert(pos, c);
        *cur = pos + c.len_utf8();
    }

    /// 2026-08-08 — insert a literal string at the caret. Used by
    /// Ctrl+V paste routing. URL is single-line so embedded
    /// newlines are collapsed to spaces; Headers / Body / Source
    /// keep newlines verbatim.
    pub fn insert_str(&mut self, s: &str) {
        if self.focus == EditField::Method {
            return;
        }
        let single_line = self.focus == EditField::Url;
        let cleaned: String = if single_line {
            s.chars()
                .filter(|c| *c != '\0')
                .map(|c| if c == '\n' || c == '\r' { ' ' } else { c })
                .collect()
        } else {
            s.chars().filter(|c| *c != '\0').collect()
        };
        let Some((buf, cur)) = self.focused_text_mut() else {
            return;
        };
        let pos = (*cur).min(buf.len());
        buf.insert_str(pos, &cleaned);
        *cur = pos + cleaned.len();
    }

    /// 2026-08-08 — Ctrl+W: kill the trailing whitespace-run + word
    /// on the current line of the focused field.
    pub fn delete_word_back(&mut self) {
        let Some((s, cur)) = self.focused_text_mut() else {
            return;
        };
        let pos = (*cur).min(s.len());
        if pos == 0 {
            return;
        }
        let line_start = s[..pos].rfind('\n').map(|i| i + 1).unwrap_or(0);
        let head = &s[line_start..pos];
        let trimmed = head.trim_end_matches(char::is_whitespace);
        let cut = trimmed
            .char_indices()
            .rev()
            .find(|&(_, c)| c.is_whitespace())
            .map(|(i, c)| line_start + i + c.len_utf8())
            .unwrap_or(line_start);
        s.replace_range(cut..pos, "");
        *cur = cut;
    }

    /// 2026-08-08 — Ctrl+U: kill to the current line's start.
    pub fn delete_to_line_start(&mut self) {
        let Some((s, cur)) = self.focused_text_mut() else {
            return;
        };
        let pos = (*cur).min(s.len());
        let line_start = s[..pos].rfind('\n').map(|i| i + 1).unwrap_or(0);
        if line_start == pos {
            return;
        }
        s.replace_range(line_start..pos, "");
        *cur = line_start;
    }

    /// 2026-08-08 — Ctrl+K: kill to the current line's end.
    pub fn delete_to_line_end(&mut self) {
        let Some((s, cur)) = self.focused_text_mut() else {
            return;
        };
        let pos = (*cur).min(s.len());
        let end = s[pos..].find('\n').map(|rel| pos + rel).unwrap_or(s.len());
        if end == pos {
            return;
        }
        s.replace_range(pos..end, "");
    }

    /// Backspace at the focused field's caret.
    pub fn backspace(&mut self) {
        let Some((s, cur)) = self.focused_text_mut() else {
            return;
        };
        if *cur == 0 || s.is_empty() {
            return;
        }
        let prev = s[..*cur]
            .char_indices()
            .next_back()
            .map(|(i, _)| i)
            .unwrap_or(0);
        s.replace_range(prev..*cur, "");
        *cur = prev;
    }

    /// Forward-delete — remove the char AT the caret. Mirrors
    /// `backspace` for the Delete key (macOS Fn+Delete etc.).
    pub fn delete_forward(&mut self) {
        let Some((s, cur)) = self.focused_text_mut() else {
            return;
        };
        if *cur >= s.len() {
            return;
        }
        let end = s[*cur..]
            .char_indices()
            .nth(1)
            .map(|(i, _)| *cur + i)
            .unwrap_or(s.len());
        s.replace_range(*cur..end, "");
    }

    /// Move the focused field's caret left one char (no-op for Method).
    pub fn move_left(&mut self) {
        let Some((s, cur)) = self.focused_text_mut() else {
            return;
        };
        if *cur == 0 {
            return;
        }
        *cur = s[..*cur]
            .char_indices()
            .next_back()
            .map(|(i, _)| i)
            .unwrap_or(0);
    }

    /// Move the focused field's caret right one char.
    pub fn move_right(&mut self) {
        let Some((s, cur)) = self.focused_text_mut() else {
            return;
        };
        if *cur >= s.len() {
            return;
        }
        let step = s[*cur..].chars().next().map(char::len_utf8).unwrap_or(0);
        *cur += step;
    }

    pub fn move_home(&mut self) {
        match self.focus {
            EditField::Url => self.url_cursor = 0,
            EditField::Headers => {
                let cur = self.headers_cursor.min(self.headers_buffer.len());
                self.headers_cursor = self.headers_buffer[..cur]
                    .rfind('\n')
                    .map(|i| i + 1)
                    .unwrap_or(0);
            }
            EditField::Body => {
                let s = self.request.body.as_deref().unwrap_or("");
                // Home goes to the start of the current line in Body.
                let cur = self.body_cursor.min(s.len());
                self.body_cursor = s[..cur].rfind('\n').map(|i| i + 1).unwrap_or(0);
            }
            EditField::Source => {
                let s = self.source_buffer.as_str();
                let cur = self.source_cursor.min(s.len());
                self.source_cursor = s[..cur].rfind('\n').map(|i| i + 1).unwrap_or(0);
            }
            EditField::Method => {}
        }
    }
    pub fn move_end(&mut self) {
        match self.focus {
            EditField::Url => self.url_cursor = self.request.url.len(),
            EditField::Headers => {
                let cur = self.headers_cursor.min(self.headers_buffer.len());
                let to_eol = self.headers_buffer[cur..]
                    .find('\n')
                    .unwrap_or(self.headers_buffer.len() - cur);
                self.headers_cursor = cur + to_eol;
            }
            EditField::Body => {
                let s = self.request.body.as_deref().unwrap_or("");
                let cur = self.body_cursor.min(s.len());
                let to_end_of_line = s[cur..].find('\n').unwrap_or(s.len() - cur);
                self.body_cursor = cur + to_end_of_line;
            }
            EditField::Source => {
                let s = self.source_buffer.as_str();
                let cur = self.source_cursor.min(s.len());
                let to_eol = s[cur..].find('\n').unwrap_or(s.len() - cur);
                self.source_cursor = cur + to_eol;
            }
            EditField::Method => {}
        }
    }

    pub fn title(&self) -> String {
        // Tab label priority (2026-07-09 user request):
        //   1. `METHOD  <summary>` when the request has a summary
        //      (extracted from the leading `# ...` comment in a
        //      loaded `.curl`/`.http` file). Reads much better for
        //      autogenerated stubs like
        //      `POST {{BASE_URL}}/v3/api/test-executions/playwright/builds`
        //      → `POST  Trigger a Playwright build`.
        //   2. Bruno-style `METHOD  short-url` when a URL is set
        //      (strip scheme + query/fragment).
        //   3. Source-file basename (or "new request") for empty
        //      panes.
        // Method comes first so the per-verb tab coloring
        // (bufferline picks the icon + fg color from `request.method`)
        // reads as a chip prefix.
        let method = self.request.method.to_uppercase();
        let base = if let Some(s) = self.summary.as_deref().filter(|s| !s.trim().is_empty()) {
            format!("{method}  {s}")
        } else if !self.request.url.is_empty() {
            let short = self
                .request
                .url
                .strip_prefix("https://")
                .or_else(|| self.request.url.strip_prefix("http://"))
                .unwrap_or(&self.request.url);
            let short = short.split(['?', '#']).next().unwrap_or(short);
            format!("{method}  {short}")
        } else {
            self.source_path
                .as_ref()
                .and_then(|p| p.file_name())
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_else(|| format!("{method}  new request"))
        };
        // Tab markers: only signal states the user needs to know
        // about at a glance. A clean 2xx Done state used to render
        // a `⚡` but the Response block already shows the status
        // chip — the tab marker was just visual noise. Now:
        //   Sending  → "…" (in flight)
        //   Streaming → "▶" (SSE open)
        //   Failed assertions on Done → "✗"
        //   Everything else → no marker.
        let marker = match &self.state {
            RunState::Sending => "",
            RunState::Streaming(_) => "",
            RunState::Done(r) if r.assertions.iter().any(|a| !a.passed) => "",
            _ => "",
        };
        if marker.is_empty() {
            base
        } else {
            format!("{base} {marker}")
        }
    }

    /// `METHOD url` as a one-liner.
    pub fn request_line(&self) -> String {
        format!("{} {}", self.request.method, self.request.url)
    }

    /// Render this request as a `curl` command line (for `http.copy_curl`).
    pub fn as_curl(&self) -> String {
        // Header and body sides already POSIX-escape single quotes
        // (`'\''` closes+injects+reopens the string). The URL side
        // was NOT escaped — a URL containing an apostrophe produced
        // shell-broken curl. api-workflow SEV-2 2026-07-11.
        let esc = |s: &str| s.replace('\'', "'\\''");
        let mut out = format!("curl '{}'", esc(&self.request.url));
        if self.request.method != "GET"
            && !(self.request.method == "POST" && self.request.body.is_some())
        {
            out.push_str(&format!(" -X {}", self.request.method));
        }
        for (k, v) in &self.request.headers {
            out.push_str(&format!(" \\\n  -H '{}: {}'", k, esc(v)));
        }
        if let Some(body) = &self.request.body {
            out.push_str(&format!(" \\\n  --data-raw '{}'", esc(body)));
        }
        out
    }

    /// Python (using the `requests` library).
    pub fn as_python(&self) -> String {
        let mut out = String::from("import requests\n\n");
        let mut headers_str = String::from("headers = {\n");
        for (k, v) in &self.request.headers {
            headers_str.push_str(&format!("    {:?}: {:?},\n", k, v));
        }
        headers_str.push_str("}\n\n");
        out.push_str(&headers_str);
        let m = self.request.method.to_lowercase();
        match &self.request.body {
            Some(body) if !body.is_empty() => {
                out.push_str(&format!("data = {body:?}\n\n"));
                out.push_str(&format!(
                    "response = requests.{m}({url:?}, headers=headers, data=data)\n",
                    url = self.request.url,
                ));
            }
            _ => {
                out.push_str(&format!(
                    "response = requests.{m}({url:?}, headers=headers)\n",
                    url = self.request.url,
                ));
            }
        }
        out.push_str("print(response.status_code)\nprint(response.text)\n");
        out
    }

    /// JavaScript (`fetch` API).
    pub fn as_js_fetch(&self) -> String {
        let mut out = format!(
            "const response = await fetch({url:?}, {{\n  method: {m:?},\n",
            url = self.request.url,
            m = self.request.method,
        );
        out.push_str("  headers: {\n");
        for (k, v) in &self.request.headers {
            out.push_str(&format!("    {k:?}: {v:?},\n"));
        }
        out.push_str("  },\n");
        if let Some(body) = &self.request.body
            && !body.is_empty()
        {
            out.push_str(&format!("  body: {body:?},\n"));
        }
        out.push_str(
            "});\nconst data = await response.text();\nconsole.log(response.status, data);\n",
        );
        out
    }

    /// Go (net/http).
    pub fn as_go(&self) -> String {
        // 2026-07-21 fix: `strings` was unconditionally imported
        // but only USED when the body was non-empty — Go compile
        // error ("imported and not used") on bodyless requests.
        // Also fixed a `push_str` block that had `{{ }}` in a raw
        // string (not a format!), leaking literal double-braces
        // into the snippet — was `if err != nil {{ panic(err) }}`
        // in the output.
        let has_body = self.request.body.is_some();
        let mut out =
            String::from("package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n");
        if has_body {
            out.push_str("\t\"strings\"\n");
        }
        out.push_str(")\n\nfunc main() {\n");
        let body_expr = if let Some(b) = &self.request.body {
            format!("strings.NewReader({b:?})")
        } else {
            "nil".to_string()
        };
        out.push_str(&format!(
            "\treq, err := http.NewRequest({m:?}, {url:?}, {body})\n\tif err != nil {{ panic(err) }}\n",
            m = self.request.method,
            url = self.request.url,
            body = body_expr,
        ));
        for (k, v) in &self.request.headers {
            out.push_str(&format!("\treq.Header.Set({k:?}, {v:?})\n"));
        }
        out.push_str(
            "\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil { panic(err) }\n\tdefer resp.Body.Close()\n\tbody, _ := io.ReadAll(resp.Body)\n\tfmt.Println(resp.Status)\n\tfmt.Println(string(body))\n}\n",
        );
        out
    }

    /// wget one-liner.
    pub fn as_wget(&self) -> String {
        let mut out = format!(
            "wget --method={} '{}'",
            self.request.method, self.request.url
        );
        for (k, v) in &self.request.headers {
            out.push_str(&format!(
                " \\\n  --header='{}: {}'",
                k,
                v.replace('\'', "'\\''"),
            ));
        }
        if let Some(body) = &self.request.body {
            out.push_str(&format!(
                " \\\n  --body-data='{}'",
                body.replace('\'', "'\\''"),
            ));
        }
        out
    }

    /// HTTPie one-liner.
    pub fn as_httpie(&self) -> String {
        let mut out = format!("http {} '{}'", self.request.method, self.request.url);
        for (k, v) in &self.request.headers {
            out.push_str(&format!(" '{}:{}'", k, v));
        }
        if let Some(body) = &self.request.body
            && !body.is_empty()
        {
            let escaped = body.replace('\'', "'\\''");
            out.push_str(&format!(" <<< '{escaped}'"));
        }
        out
    }
}

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

    fn pane() -> RequestPane {
        RequestPane::new(
            None,
            Request {
                method: "GET".into(),
                url: "https://x.com/a".into(),
                headers: Vec::new(),
                body: None,
                insecure: false,
            },
            Script::default(),
            1,
        )
    }

    #[test]
    fn split_header_line_preserves_colons_in_value() {
        // Regression for #polish 2026-07-06 — `split_once(':')` used
        // to truncate values at the first colon, silently dropping
        // URL schemes / timestamps.
        let (k, v) = split_header_line("X-Redirect-To: https://host/path").unwrap();
        assert_eq!(k, "X-Redirect-To");
        assert_eq!(v, " https://host/path");
        let (k, v) = split_header_line("Timestamp: 2024-01-01T12:00:00Z").unwrap();
        assert_eq!(k, "Timestamp");
        assert_eq!(v, " 2024-01-01T12:00:00Z");
    }

    #[test]
    fn headers_to_text_emits_trailing_newline() {
        // R6 api-workflow SEV-1 2026-08-09 — without the trailer, a
        // cursor placed at buffer.len() (which ~10 call sites do on
        // rebuild) lands inside the LAST header's value; any typed
        // key silently corrupts it and — for Authorization — sends
        // a mangled Bearer over the wire. Trailer makes cursor-at-end
        // start a fresh line instead.
        let headers = vec![
            ("Authorization".to_string(), "Bearer abc".to_string()),
            ("X-Trace".to_string(), "42".to_string()),
        ];
        let text = headers_to_text(&headers);
        assert!(
            text.ends_with('\n'),
            "headers_to_text output must end with \\n so cursor-at-end lands on a fresh line, got {text:?}"
        );
        // And the round-trip still works — the parser drops trailing
        // blank lines, so headers survive intact.
        assert_eq!(parse_headers_text(&text), headers);
    }

    #[test]
    fn headers_to_text_empty_returns_empty_string() {
        // Zero headers → empty string (no bare newline). A cursor
        // at .len() on an empty string is column 0 of an empty line —
        // typing starts a new header without corrupting anything.
        assert_eq!(headers_to_text(&[]), "");
    }

    #[test]
    fn typing_after_headers_rebuild_does_not_corrupt_last_value() {
        // End-to-end: rebuild the headers buffer + place cursor at
        // .len() (the shape every rebuild call site uses), then
        // append a keystroke and re-parse. The last header's value
        // must be unchanged; the appended text must land as its own
        // line (which the parser drops as unrecognised — no
        // colon — but crucially does NOT merge into the prior row).
        let mut buf = headers_to_text(&[
            ("Authorization".to_string(), "Bearer TOKEN".to_string()),
            ("X-Shared".to_string(), "shared-secret".to_string()),
        ]);
        buf.push_str("X-Trace: abc"); // simulate cursor-at-end keystroke
        let rows = parse_headers_text(&buf);
        // The two original headers survive intact.
        assert_eq!(rows[0], ("Authorization".into(), "Bearer TOKEN".into()));
        assert_eq!(rows[1], ("X-Shared".into(), "shared-secret".into()));
        // The typed row becomes its own new header, not appended to
        // X-Shared's value.
        assert_eq!(rows.len(), 3);
        assert_eq!(rows[2], ("X-Trace".into(), "abc".into()));
    }

    #[test]
    fn parse_headers_text_preserves_colons_in_value() {
        // End-to-end via the parser callers actually use.
        let rows = parse_headers_text(
            "Content-Type: application/json\nX-Redirect-To: https://host:443/path\n",
        );
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[1].0, "X-Redirect-To");
        assert_eq!(rows[1].1, "https://host:443/path");
    }

    #[test]
    fn toggle_view_lands_on_url_in_edit() {
        let mut p = pane();
        assert_eq!(p.view, ViewMode::Response);
        p.toggle_view();
        assert_eq!(p.view, ViewMode::Edit);
        assert_eq!(p.focus, EditField::Url);
        p.toggle_view();
        assert_eq!(p.view, ViewMode::Response);
    }

    #[test]
    fn focus_cycles_url_method_headers_body() {
        let mut p = pane();
        p.toggle_view();
        assert_eq!(p.focus, EditField::Url);
        p.focus_next_field();
        assert_eq!(p.focus, EditField::Method);
        p.focus_next_field();
        assert_eq!(p.focus, EditField::Headers);
        p.focus_next_field();
        assert_eq!(p.focus, EditField::Body);
        p.focus_next_field();
        assert_eq!(p.focus, EditField::Url);
        p.focus_prev_field();
        assert_eq!(p.focus, EditField::Body);
        p.focus_prev_field();
        assert_eq!(p.focus, EditField::Headers);
    }

    #[test]
    fn headers_round_trip_through_buffer() {
        // Build a request with two headers, drive the pane to edit them, then
        // commit + verify the parsed result.
        let req = Request {
            method: "GET".into(),
            url: "https://x/".into(),
            headers: vec![
                ("Accept".into(), "application/json".into()),
                ("Authorization".into(), "Bearer xyz".into()),
            ],
            body: None,
            insecure: false,
        };
        let mut p = RequestPane::new(None, req, Script::default(), 1);
        // Trailing `\n` is intentional as of R6 api-workflow SEV-1 —
        // see `headers_to_text` doc + the
        // `headers_to_text_emits_trailing_newline` test.
        assert_eq!(
            p.headers_buffer,
            "Accept: application/json\nAuthorization: Bearer xyz\n"
        );

        // Edit: focus Headers, append a new line `X-Trace: abc`.
        p.toggle_view();
        p.focus = EditField::Headers;
        p.move_end();
        p.type_char('\n');
        for c in "X-Trace: abc".chars() {
            p.type_char(c);
        }
        p.commit_headers();
        assert_eq!(p.request.headers.len(), 3);
        assert_eq!(p.request.headers[2], ("X-Trace".into(), "abc".into()));

        // Delete a line — empty the header line entirely; commit drops it.
        p.headers_buffer = "Accept: application/json\n\nAuthorization: Bearer xyz".into();
        p.commit_headers();
        assert_eq!(p.request.headers.len(), 2);

        // Lines without `:` are dropped.
        p.headers_buffer = "Accept: application/json\nthis-is-not-a-header".into();
        p.commit_headers();
        assert_eq!(p.request.headers.len(), 1);
    }

    #[test]
    fn url_field_typing_and_backspace() {
        let mut p = pane();
        p.toggle_view();
        p.move_end();
        p.type_char('?');
        p.type_char('q');
        p.type_char('=');
        p.type_char('1');
        assert_eq!(p.request.url, "https://x.com/a?q=1");
        p.backspace();
        p.backspace();
        assert_eq!(p.request.url, "https://x.com/a?q");
        // URL strips newlines (single-line field).
        p.type_char('\n');
        assert_eq!(p.request.url, "https://x.com/a?q");
    }

    #[test]
    fn body_field_creates_on_first_keystroke_and_accepts_newlines() {
        let mut p = pane();
        p.toggle_view();
        p.focus = EditField::Body;
        assert!(p.request.body.is_none());
        for c in "{\"a\":\n  1}".chars() {
            p.type_char(c);
        }
        assert_eq!(p.request.body.as_deref(), Some("{\"a\":\n  1}"));
        // Home moves to the start of the current line, not the whole body.
        p.move_home();
        assert_eq!(p.body_cursor, "{\"a\":\n".len());
    }

    #[test]
    fn method_cycles_via_space() {
        let mut p = pane();
        p.toggle_view();
        p.focus = EditField::Method;
        assert_eq!(p.request.method, "GET");
        p.type_char(' ');
        assert_eq!(p.request.method, "POST");
        p.type_char(' ');
        assert_eq!(p.request.method, "PUT");
        // Non-space typing on Method is ignored.
        p.type_char('x');
        assert_eq!(p.request.method, "PUT");
    }

    #[test]
    fn cycle_method_wraps() {
        assert_eq!(cycle_method("OPTIONS"), "GET");
        assert_eq!(cycle_method("get"), "POST");
        // Unknown method falls back to "GET" → "POST".
        assert_eq!(cycle_method("FROBNICATE"), "POST");
    }

    #[test]
    fn move_left_right_clamp() {
        let mut p = pane();
        p.toggle_view();
        let len = p.request.url.len();
        p.url_cursor = 0;
        p.move_left(); // no-op at 0
        assert_eq!(p.url_cursor, 0);
        p.url_cursor = len;
        p.move_right(); // no-op at end
        assert_eq!(p.url_cursor, len);
    }

    #[test]
    fn as_go_no_body_omits_strings_import_and_uses_single_braces() {
        // No body → don't import "strings" (unused-import compile
        // error in Go); the response-error block should use single
        // braces, not `{{ … }}`.
        let mut p = pane();
        p.request.method = "GET".into();
        p.request.url = "https://api.example.com/x".into();
        p.request.body = None;
        let go = p.as_go();
        assert!(!go.contains("\"strings\""), "no strings import:\n{go}");
        assert!(!go.contains("{{"), "no leaked double-braces:\n{go}");
        assert!(
            go.contains("if err != nil { panic(err) }"),
            "single-brace panic block:\n{go}"
        );
    }

    #[test]
    fn as_go_with_body_imports_strings() {
        let mut p = pane();
        p.request.method = "POST".into();
        p.request.url = "https://api.example.com/x".into();
        p.request.body = Some(r#"{"a":1}"#.into());
        let go = p.as_go();
        assert!(go.contains("\"strings\""), "strings imported:\n{go}");
        assert!(go.contains("strings.NewReader"), "strings used:\n{go}");
    }
}