cordy 0.2.0

A cross-platform TUI coding agent in Rust — workspace tabs, PTY terminals, direct-key panels, hot-swap any model/provider mid-conversation, MCP, skills, sub-agents and background jobs.
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
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
//! Terminal UI — Elm/MVU.
//!
//! [`Model`] holds all state; [`update`] is a pure `(Model, Msg) -> Effect` transition tested in
//! isolation; [`view`] renders the model; [`run`] is the runtime that owns the terminal, spawns
//! the agent driver, and pumps input/agent/permission events through `update`. The input line is
//! a cursor-aware editor with OpenCode-style keybinds; Tab cycles the active mode.

mod chrome;
mod goal_display;
mod input;
mod markdown;
mod picker;
mod runtime;
mod term;
mod theme;

pub use runtime::{dump_frame, run};

use crate::core::agent::AgentEvent;

/// One rendered line of conversation history.
#[derive(Debug, Clone, PartialEq)]
pub enum Entry {
    User(String),
    Assistant(String),
    Tool {
        /// Tool-call id, so a live "running" entry can be updated in place when it finishes.
        id: String,
        name: String,
        text: String,
        saved: u64,
        /// True while the tool is executing (shown before its output arrives).
        running: bool,
        /// The tool reported a failure — drives the ✗ marker in the transcript.
        error: bool,
    },
    System(String),
    /// Completion footer under an assistant reply: mode chip + model + elapsed seconds.
    Turn {
        mode: String,
        model: String,
        secs: f64,
    },
}

/// What selecting a command-palette row does.
#[derive(Clone)]
pub enum PaletteAction {
    /// Run a slash command (or prefill it if it needs an argument).
    Command(String),
    /// Hot-swap to this model on the current provider.
    SwitchModel(String),
    /// Switch the active mode/agent by index.
    SwitchMode(usize),
    /// Connect to a saved provider by its config name (resolves base URL + key).
    SwitchProvider(String),
    /// Apply the theme at this index in `THEME_NAMES`.
    SwitchTheme(usize),
}

/// A row in the ctrl+p command palette.
#[derive(Clone)]
pub struct PaletteItem {
    pub label: String,
    pub hint: String,
    pub action: PaletteAction,
}

/// A small action menu opened by clicking a transcript message (copy / rewind / delete).
#[derive(Debug, Clone)]
pub struct MsgMenu {
    /// Index into `transcript` of the clicked entry.
    pub entry: usize,
    /// Highlighted action row.
    pub sel: usize,
    /// Anchor position (mouse column/row) the popup is drawn at.
    pub col: u16,
    pub row: u16,
}

/// Which step of the `/connect` provider wizard is showing.
#[derive(Debug, Clone, PartialEq)]
pub enum ConnectStep {
    /// Choosing a provider preset.
    Pick,
    /// Typing a custom base URL (for the "Custom…" preset).
    Url,
    /// Typing a display name (required — the id is derived from it).
    Name,
    /// Typing the API key.
    Key,
}

/// Transient state for the in-TUI `/connect` provider wizard (OpenCode-style).
#[derive(Debug, Clone)]
pub struct Connect {
    pub step: ConnectStep,
    /// Highlighted preset while picking.
    pub sel: usize,
    /// Chosen preset index (valid once past [`ConnectStep::Pick`]).
    pub preset: usize,
    /// Resolved base URL (from the preset or typed for a custom endpoint).
    pub base: String,
    /// The chosen display name (id is derived from it).
    pub name: String,
    /// Current text field (URL → name → key).
    pub input: String,
}

impl Default for Connect {
    fn default() -> Self {
        Connect {
            step: ConnectStep::Pick,
            sel: 0,
            preset: 0,
            base: String::new(),
            name: String::new(),
            input: String::new(),
        }
    }
}

/// All UI state.
#[derive(Default)]
pub struct Model {
    pub transcript: Vec<Entry>,
    /// Current input line.
    pub input: String,
    /// Cursor byte offset within `input`.
    pub cursor: usize,
    /// Selection anchor (byte offset); `Some` while a shift-selection is active. The selected
    /// range is `[min(anchor,cursor), max(anchor,cursor))`.
    pub anchor: Option<usize>,
    /// Assistant text streaming in for the current (not-yet-finalized) message.
    pub streaming: String,
    pub status: String,
    pub busy: bool,
    /// When set, a permission modal is showing this summary and awaiting y/n.
    pub pending: Option<String>,
    pub should_quit: bool,
    /// Input mode line (provider · model), set once at startup.
    pub subtitle: String,
    /// Bottom-bar left segment (cwd), set once at startup.
    pub footer: String,
    /// Whether to draw the animated mascot.
    pub show_mascot: bool,
    /// Available modes/agents cycled with Tab.
    pub modes: Vec<String>,
    pub mode_idx: usize,
    /// Ticks remaining for the mode-switch flash animation.
    pub mode_flash: u8,
    /// Leader key (ctrl+x) is pending its second keystroke.
    pub leader: bool,
    /// Command palette (ctrl+p) open state, filter query, selected row, and item source.
    pub palette_open: bool,
    pub palette_query: String,
    pub palette_sel: usize,
    pub palette: Vec<PaletteItem>,
    /// Session picker overlay: open state, rows `(id, label)`, and selection.
    pub sessions_open: bool,
    pub sessions: Vec<(String, String)>,
    pub sessions_sel: usize,
    /// The `/connect` provider wizard, when open.
    pub connect: Option<Connect>,
    /// Provider manager overlay (`/providers`): open state, rows `(id, kind, base)`, selection.
    pub providers_open: bool,
    pub providers: Vec<(String, String, String)>,
    pub providers_sel: usize,
    /// Status view overlay (<leader>s).
    pub status_open: bool,
    /// Theme picker overlay (<leader>t): open state, selection, and the active theme name.
    pub theme_open: bool,
    pub theme_sel: usize,
    pub theme_name: String,
    /// Every selectable theme name in picker order (builtins + custom JSON themes). Kept on the
    /// model so key handling and the picker agree without reaching for the registry.
    pub theme_names: Vec<String>,
    /// Generic info modal (skills / mcp listings): title + body lines. `None` when closed.
    pub info: Option<(String, Vec<String>)>,
    /// Live counts for the status bar: running background jobs and active sub-agents.
    pub bg_count: usize,
    pub subagent_count: usize,
    /// Recently-used models (newest first) for F2 cycling, and favorited models (ctrl+f).
    pub recents: Vec<String>,
    pub favorites: Vec<String>,
    /// View toggles (OpenCode `none`-key features, exposed as commands).
    pub show_thinking: bool,
    pub show_tool_output: bool,
    pub animations: bool,
    /// Live reasoning/thinking buffer for the current turn (shown when `show_thinking`).
    pub thinking: String,
    /// Stashed prompt drafts (`/stash` push · `/unstash` pop).
    pub stash: Vec<String>,
    /// Loaded skills as `(name, description)`, and MCP servers as `(name, status)`.
    pub skills: Vec<(String, String)>,
    pub mcp_names: Vec<(String, String)>,
    /// Inline input autocomplete candidates (slash commands / `@` file paths).
    pub suggestions: Vec<String>,
    /// Highlighted row within `suggestions` (navigated with ↑/↓ while the popup is open).
    pub suggestion_sel: usize,
    /// Messages typed while the agent was busy, sent in order once the turn completes.
    pub queue: Vec<String>,
    /// Draft stashed when browsing history with ↑, restored when stepping back past the newest.
    pub history_draft: Option<(String, usize)>,
    /// Large pastes collapsed to `[pasted N chars]` placeholders; expanded on submit. Indexed by
    /// the id embedded in the placeholder token.
    pub pastes: std::collections::HashMap<u32, String>,
    /// Monotonic id source for `pastes`.
    pub paste_seq: u32,
    /// Text columns available for one input row (excludes the prompt gutter); set during render
    /// so cursor navigation can follow wrapped visual lines.
    pub input_width: u16,
    /// Transcript hit-testing (set during render): the viewport rect, the absolute index of the
    /// first visible rendered line, and per-`transcript`-entry `(start_line, line_count)` ranges.
    /// Used to map a mouse click back to the entry under it (click-to-rewind).
    pub transcript_rect: Option<(u16, u16, u16, u16)>,
    pub transcript_start: usize,
    pub entry_spans: Vec<(usize, usize)>,
    /// Open message-action menu (click a message), if any.
    pub msg_menu: Option<MsgMenu>,
    /// The menu popup's resolved rect `(x, y, w, h)`, stashed during render for click hit-testing.
    pub msg_menu_rect: Option<(u16, u16, u16, u16)>,
    /// Submitted-prompt history (newest last) and the browse cursor while pressing ↑/↓.
    pub history: Vec<String>,
    pub history_idx: Option<usize>,
    /// Input-editor undo/redo snapshots `(text, cursor)`.
    pub undo_stack: Vec<(String, usize)>,
    pub redo_stack: Vec<(String, usize)>,
    /// Removed message groups, for messages_redo (<leader>r).
    pub msg_redo: Vec<Vec<Entry>>,
    /// Transcript scroll offset from the bottom (0 = follow latest).
    pub scroll: u16,
    /// Largest useful `scroll` for the content currently rendered, and the transcript viewport's
    /// height. Both are stashed during render so key handling can page and clamp correctly.
    pub max_scroll: u16,
    pub viewport_h: u16,
    /// Animation frame counter (advanced on each tick).
    pub tick: u64,
    // Live cost/token HUD accumulators.
    pub total_in: u64,
    pub total_out: u64,
    pub total_saved: u64,
    /// Prompt tokens sent on the most recent turn — i.e. how much context is currently in use
    /// (each turn resends the full history), for the context gauge.
    pub last_in: u64,
    /// Active model's context window (from config/models.dev), for the context gauge.
    pub context_window: Option<u64>,
    /// Per-million-token pricing for the active model, if known.
    pub price_in: Option<f64>,
    pub price_out: Option<f64>,
    /// Active model + provider, for the status-line placeholders.
    pub model_name: String,
    pub provider_kind: String,
    /// User-customizable status-line template (placeholders like `{model}`, `{ctx}`, `{cost}`).
    /// `None` uses the built-in default layout.
    pub statusline: Option<String>,
    /// A newer published Cordy version, if the startup update check found one.
    pub latest_version: Option<String>,
    /// Status-bar chip for the session goal (`goal: active · 12.5K/50K · 3m`), when one is set.
    pub goal_line: Option<String>,
    /// Working-tree git state for the header, refreshed on a background tick.
    pub git: Option<chrome::GitStatus>,
    /// Tab strip: one entry per open workspace, and the focused index.
    pub tabs: Vec<chrome::TabMeta>,
    pub tab: usize,
    /// Number of live PTY terminals, for the status bar.
    pub term_count: usize,
    /// The open direct-key overlay (models, modes, skills, git, context, tabs), if any.
    pub picker: Option<picker::Picker>,
    /// Clickable regions, rebuilt every frame: `(x, y, w, h, target)`. Later entries win, so
    /// overlays drawn on top of the chrome naturally take the click.
    pub hits: Vec<(u16, u16, u16, u16, Hit)>,
    /// The region the pointer is currently over, for hover highlighting.
    pub hover: Option<Hit>,
    /// Whether Cordy currently owns the mouse (clicks, hover, wheel) or the terminal does
    /// (drag-to-select). Mirrors the real capture state so the indicator can't lie.
    pub mouse_on: bool,
    /// Tool entries whose full output the user unfolded by clicking them.
    pub expanded: std::collections::HashSet<String>,
    /// Provider calls made on this tab, newest last, for the model-events panel.
    pub events: Vec<ModelEvent>,
}

/// The slice of [`Model`] that belongs to one tab.
///
/// Focusing a tab swaps this whole block in and out of the model, so a background tab keeps its
/// transcript, draft, scroll position, model and cost counters while another one is on screen.
/// Everything *not* listed here (themes, the palette, favorites, overlay state) is deliberately
/// shared across tabs — those are app preferences, not workspace state.
#[derive(Default)]
pub struct TabState {
    pub transcript: Vec<Entry>,
    pub input: String,
    pub cursor: usize,
    pub anchor: Option<usize>,
    pub streaming: String,
    pub status: String,
    pub busy: bool,
    pub subtitle: String,
    pub mode_idx: usize,
    pub thinking: String,
    pub queue: Vec<String>,
    pub history_draft: Option<(String, usize)>,
    pub pastes: std::collections::HashMap<u32, String>,
    pub paste_seq: u32,
    pub transcript_start: usize,
    pub entry_spans: Vec<(usize, usize)>,
    pub history: Vec<String>,
    pub history_idx: Option<usize>,
    pub undo_stack: Vec<(String, usize)>,
    pub redo_stack: Vec<(String, usize)>,
    pub msg_redo: Vec<Vec<Entry>>,
    pub scroll: u16,
    pub total_in: u64,
    pub total_out: u64,
    pub total_saved: u64,
    pub last_in: u64,
    pub context_window: Option<u64>,
    pub price_in: Option<f64>,
    pub price_out: Option<f64>,
    pub model_name: String,
    pub provider_kind: String,
    pub goal_line: Option<String>,
    pub events: Vec<ModelEvent>,
}

/// Something on screen you can click. Everything Cordy shows in its chrome is a shortcut to a
/// panel, so the chrome doubles as a menu bar for people who reach for the mouse.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Hit {
    /// Focus this tab.
    Tab(usize),
    /// The mode chip → mode picker.
    Mode,
    /// The model chip → model picker.
    ModelChip,
    /// The git segment → git menu.
    Git,
    /// The context meter → context inspector.
    Context,
    /// The cost readout → model events.
    Cost,
    /// The `^X keys` pointer → which-key overlay.
    Keys,
    /// A row in the open picker, by row index.
    Row(usize),
    /// Anywhere inside the open picker that is not a row (clicks there must not close it).
    Panel,
    /// Hint-bar buttons.
    Palette,
    Skills,
    Editor,
    Term,
    Tabs,
    Stop,
    /// The mouse-ownership indicator — click to hand the mouse back to the terminal.
    Mouse,
    /// A transcript entry: click to open its action menu, or to fold/unfold a tool's output.
    Entry(usize),
}

impl Model {
    /// Register a clickable region for this frame.
    pub fn push_hit(&mut self, x: u16, y: u16, w: u16, h: u16, target: Hit) {
        if w > 0 && h > 0 {
            self.hits.push((x, y, w, h, target));
        }
    }

    /// The topmost region under `(col, row)`, if any.
    pub fn hit_at(&self, col: u16, row: u16) -> Option<Hit> {
        self.hits
            .iter()
            .rev()
            .find(|(x, y, w, h, _)| col >= *x && col < x + w && row >= *y && row < y + h)
            .map(|(_, _, _, _, t)| *t)
    }

    /// Whether any overlay is open. Mouse capture follows this: while something is open the app
    /// takes the mouse so its rows are clickable, and hands it straight back when it closes so the
    /// terminal's own selection keeps working the rest of the time.
    pub fn overlay_open(&self) -> bool {
        self.picker.is_some()
            || self.palette_open
            || self.sessions_open
            || self.providers_open
            || self.theme_open
            || self.status_open
            || self.leader
            || self.connect.is_some()
            || self.info.is_some()
            || self.msg_menu.is_some()
            || self.pending.is_some()
    }
}

/// One provider call, recorded for the model-events panel.
#[derive(Debug, Clone, PartialEq)]
pub struct ModelEvent {
    pub model: String,
    pub mode: String,
    /// Wall-clock duration of the turn in seconds.
    pub secs: f64,
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub cost: f64,
    /// `Some` when the turn ended in an error.
    pub error: Option<String>,
}

impl Model {
    /// Swap this tab's slice of state with `t`. Used both to park the focused tab and to reach
    /// into a background tab to apply an event to it.
    pub fn swap_tab(&mut self, t: &mut TabState) {
        use std::mem::swap;
        swap(&mut self.transcript, &mut t.transcript);
        swap(&mut self.input, &mut t.input);
        swap(&mut self.cursor, &mut t.cursor);
        swap(&mut self.anchor, &mut t.anchor);
        swap(&mut self.streaming, &mut t.streaming);
        swap(&mut self.status, &mut t.status);
        swap(&mut self.busy, &mut t.busy);
        swap(&mut self.subtitle, &mut t.subtitle);
        swap(&mut self.mode_idx, &mut t.mode_idx);
        swap(&mut self.thinking, &mut t.thinking);
        swap(&mut self.queue, &mut t.queue);
        swap(&mut self.history_draft, &mut t.history_draft);
        swap(&mut self.pastes, &mut t.pastes);
        swap(&mut self.paste_seq, &mut t.paste_seq);
        swap(&mut self.transcript_start, &mut t.transcript_start);
        swap(&mut self.entry_spans, &mut t.entry_spans);
        swap(&mut self.history, &mut t.history);
        swap(&mut self.history_idx, &mut t.history_idx);
        swap(&mut self.undo_stack, &mut t.undo_stack);
        swap(&mut self.redo_stack, &mut t.redo_stack);
        swap(&mut self.msg_redo, &mut t.msg_redo);
        swap(&mut self.scroll, &mut t.scroll);
        swap(&mut self.total_in, &mut t.total_in);
        swap(&mut self.total_out, &mut t.total_out);
        swap(&mut self.total_saved, &mut t.total_saved);
        swap(&mut self.last_in, &mut t.last_in);
        swap(&mut self.context_window, &mut t.context_window);
        swap(&mut self.price_in, &mut t.price_in);
        swap(&mut self.price_out, &mut t.price_out);
        swap(&mut self.model_name, &mut t.model_name);
        swap(&mut self.provider_kind, &mut t.provider_kind);
        swap(&mut self.goal_line, &mut t.goal_line);
        swap(&mut self.events, &mut t.events);
    }

    /// Refresh the tab strip's cached metadata from the focused tab (title, model, mode, busy).
    pub fn sync_tab_meta(&mut self) {
        let (model_name, mode, busy) =
            (self.model_name.clone(), self.mode().to_string(), self.busy);
        let idx = self.tab;
        if let Some(meta) = self.tabs.get_mut(idx) {
            meta.model = model_name;
            meta.mode = mode;
            meta.busy = busy;
            meta.unread = 0;
        }
    }

    /// The HUD line: cumulative tokens, optimizer savings, and estimated cost.
    pub fn hud_line(&self) -> String {
        let mut s = format!("{} in / {} out", self.total_in, self.total_out);
        if self.total_saved > 0 {
            s.push_str(&format!(" · saved ~{}", self.total_saved));
        }
        if let (Some(pi), Some(po)) = (self.price_in, self.price_out) {
            let cost = (self.total_in as f64) / 1e6 * pi + (self.total_out as f64) / 1e6 * po;
            s.push_str(&format!(" · ${cost:.4}"));
        }
        s
    }

    /// Estimated cost so far as `$x.xxxx`, or empty when pricing is unknown.
    pub fn cost_str(&self) -> String {
        match (self.price_in, self.price_out) {
            (Some(pi), Some(po)) => {
                let cost = (self.total_in as f64) / 1e6 * pi + (self.total_out as f64) / 1e6 * po;
                format!("${cost:.4}")
            }
            _ => String::new(),
        }
    }

    /// Context-window gauge: `ctx 12k/128k 9%` when the window is known, `ctx 12k` when only the
    /// last prompt size is known, empty before anything has been sent.
    pub fn ctx_line(&self) -> String {
        if self.last_in == 0 {
            return String::new();
        }
        let used = crate::core::models_dev::fmt_context(self.last_in);
        match self.context_window {
            Some(w) if w > 0 => {
                let pct = ((self.last_in as f64 / w as f64) * 100.0).round() as u64;
                format!(
                    "ctx {used}/{} {pct}%",
                    crate::core::models_dev::fmt_context(w)
                )
            }
            _ => format!("ctx {used}"),
        }
    }

    /// Percentage of the active model's context window occupied by the last prompt (0 when the
    /// window size is unknown or nothing has been sent).
    pub fn ctx_pct(&self) -> u64 {
        match self.context_window {
            Some(w) if w > 0 && self.last_in > 0 => (self.last_in * 100 / w).min(100),
            _ => 0,
        }
    }

    /// The active mode/agent name.
    pub fn mode(&self) -> &str {
        self.modes
            .get(self.mode_idx)
            .map(String::as_str)
            .unwrap_or("build")
    }

    /// Indices of palette items matching the current query (case-insensitive substring).
    pub fn palette_filtered(&self) -> Vec<usize> {
        let q = self.palette_query.to_lowercase();
        self.palette
            .iter()
            .enumerate()
            .filter(|(_, it)| {
                q.is_empty()
                    || it.label.to_lowercase().contains(&q)
                    || it.hint.to_lowercase().contains(&q)
            })
            .map(|(i, _)| i)
            .collect()
    }
}

/// Messages that drive the model.
pub enum Msg {
    // Input editing (OpenCode keybinds map onto these).
    Insert(char),
    Backspace,
    Delete,
    Left,
    Right,
    /// Buffer start/end (Home/End keys).
    Home,
    End,
    /// Current-line start/end (ctrl+a / ctrl+e).
    LineHome,
    LineEnd,
    /// Insert a newline (multiline input).
    Newline,
    /// Move the cursor to the same column on the previous/next logical line.
    CursorUp,
    CursorDown,
    /// Word-wise cursor motion.
    WordForward,
    WordBackward,
    KillWordBack,
    /// Delete the word after the cursor.
    KillWordForward,
    KillToStart,
    KillToEnd,
    /// Delete the current logical line.
    KillLine,
    ClearInput,
    /// Input-editor undo / redo.
    Undo,
    Redo,
    /// Browse submitted-prompt history.
    HistoryPrev,
    HistoryNext,
    /// Cycle the active mode (+1 forward / -1 back).
    CycleMode(i8),
    Submit,
    Quit,
    Agent(AgentEvent),
    /// A permission request arrived with this human-readable summary.
    Permission(String),
    /// The pending permission was answered; clear the modal.
    PermissionResolved,
    Tick,
}

/// Side effect the runtime must perform after an update.
#[derive(Debug, PartialEq)]
pub enum Effect {
    None,
    Submit(String),
    Quit,
}

/// Pure state transition. All side effects are returned as [`Effect`] for the runtime to run.
pub fn update(model: &mut Model, msg: Msg) -> Effect {
    // While a permission modal is open, ignore text editing.
    let editing_blocked = model.pending.is_some();
    match msg {
        Msg::Insert(c) if !editing_blocked => {
            push_undo(model);
            delete_selection(model); // typing replaces an active selection
            model.input.insert(model.cursor, c);
            model.cursor += c.len_utf8();
            Effect::None
        }
        Msg::Insert(_) => Effect::None,
        Msg::Newline => {
            if !editing_blocked {
                push_undo(model);
                delete_selection(model);
                model.input.insert(model.cursor, '\n');
                model.cursor += 1;
            }
            Effect::None
        }
        Msg::Backspace => {
            if !editing_blocked {
                if selection_nonempty(model) {
                    push_undo(model);
                    delete_selection(model);
                } else if model.cursor > 0 {
                    push_undo(model);
                    let p = prev_boundary(&model.input, model.cursor);
                    model.input.replace_range(p..model.cursor, "");
                    model.cursor = p;
                }
            }
            Effect::None
        }
        Msg::Delete => {
            if !editing_blocked {
                if selection_nonempty(model) {
                    push_undo(model);
                    delete_selection(model);
                } else if model.cursor < model.input.len() {
                    push_undo(model);
                    let n = next_boundary(&model.input, model.cursor);
                    model.input.replace_range(model.cursor..n, "");
                }
            }
            Effect::None
        }
        Msg::Left => {
            model.cursor = prev_boundary(&model.input, model.cursor);
            Effect::None
        }
        Msg::Right => {
            model.cursor = next_boundary(&model.input, model.cursor);
            Effect::None
        }
        Msg::Home => {
            model.cursor = 0;
            Effect::None
        }
        Msg::End => {
            model.cursor = model.input.len();
            Effect::None
        }
        Msg::LineHome => {
            model.cursor = line_home(&model.input, model.cursor);
            Effect::None
        }
        Msg::LineEnd => {
            model.cursor = line_end(&model.input, model.cursor);
            Effect::None
        }
        Msg::CursorUp => {
            if let Some(c) =
                move_vertical(&model.input, model.cursor, -1, model.input_width as usize)
            {
                model.cursor = c;
            }
            Effect::None
        }
        Msg::CursorDown => {
            if let Some(c) =
                move_vertical(&model.input, model.cursor, 1, model.input_width as usize)
            {
                model.cursor = c;
            }
            Effect::None
        }
        Msg::WordForward => {
            model.cursor = word_forward(&model.input, model.cursor);
            Effect::None
        }
        Msg::WordBackward => {
            model.cursor = word_start(&model.input, model.cursor);
            Effect::None
        }
        Msg::KillWordBack => {
            if !editing_blocked && model.cursor > 0 {
                push_undo(model);
                let w = word_start(&model.input, model.cursor);
                model.input.replace_range(w..model.cursor, "");
                model.cursor = w;
            }
            Effect::None
        }
        Msg::KillWordForward => {
            if !editing_blocked && model.cursor < model.input.len() {
                push_undo(model);
                let w = word_forward(&model.input, model.cursor);
                model.input.replace_range(model.cursor..w, "");
            }
            Effect::None
        }
        Msg::KillToStart => {
            if !editing_blocked {
                push_undo(model);
                let h = line_home(&model.input, model.cursor);
                model.input.replace_range(h..model.cursor, "");
                model.cursor = h;
            }
            Effect::None
        }
        Msg::KillToEnd => {
            if !editing_blocked {
                push_undo(model);
                let e = line_end(&model.input, model.cursor);
                model.input.replace_range(model.cursor..e, "");
            }
            Effect::None
        }
        Msg::KillLine => {
            if !editing_blocked {
                push_undo(model);
                let (a, b) = current_line_range(&model.input, model.cursor);
                // Remove the line's text plus its trailing newline (or the leading one at EOF).
                let mut end = b;
                if model.input[end..].starts_with('\n') {
                    end += 1;
                } else if a > 0 {
                    // last line: also drop the preceding newline
                    return kill_last_line(model, a, b);
                }
                model.input.replace_range(a..end, "");
                model.cursor = a.min(model.input.len());
            }
            Effect::None
        }
        Msg::ClearInput => {
            if !model.input.is_empty() {
                push_undo(model);
            }
            model.input.clear();
            model.cursor = 0;
            model.anchor = None;
            model.history_idx = None;
            Effect::None
        }
        Msg::Undo => {
            if let Some((text, cur)) = model.undo_stack.pop() {
                model.redo_stack.push((model.input.clone(), model.cursor));
                model.input = text;
                model.cursor = cur.min(model.input.len());
            }
            Effect::None
        }
        Msg::Redo => {
            if let Some((text, cur)) = model.redo_stack.pop() {
                model.undo_stack.push((model.input.clone(), model.cursor));
                model.input = text;
                model.cursor = cur.min(model.input.len());
            }
            Effect::None
        }
        Msg::HistoryPrev => {
            history_prev(model);
            Effect::None
        }
        Msg::HistoryNext => {
            history_next(model);
            Effect::None
        }
        Msg::CycleMode(dir) => {
            if !model.modes.is_empty() {
                let n = model.modes.len() as isize;
                let i = (model.mode_idx as isize + dir as isize).rem_euclid(n);
                model.mode_idx = i as usize;
                model.mode_flash = 6;
            }
            Effect::None
        }
        Msg::Submit => {
            if model.input.trim().is_empty() {
                return Effect::None;
            }
            let text = std::mem::take(&mut model.input);
            model.cursor = 0;
            model.anchor = None;
            model.history_draft = None;
            // Busy: hold the message in the queue; it is dispatched when the turn completes. The
            // queue is shown above the prompt (see the input view) rather than the transcript, so
            // the message appears in-line only once it actually starts processing.
            if model.busy {
                model.queue.push(text);
                model.history_idx = None;
                return Effect::None;
            }
            if model.history.last().map(String::as_str) != Some(text.as_str()) {
                model.history.push(text.clone());
            }
            model.history_idx = None;
            model.undo_stack.clear();
            model.redo_stack.clear();
            model.transcript.push(Entry::User(text.clone()));
            model.busy = true;
            model.status = "thinking…".into();
            model.thinking.clear();
            model.scroll = 0; // snap back to the latest on a new turn
            Effect::Submit(text)
        }
        Msg::Quit => {
            model.should_quit = true;
            Effect::Quit
        }
        Msg::Agent(ev) => {
            apply_agent(model, ev);
            Effect::None
        }
        Msg::Permission(summary) => {
            model.pending = Some(summary);
            Effect::None
        }
        Msg::PermissionResolved => {
            model.pending = None;
            Effect::None
        }
        Msg::Tick => {
            if model.animations {
                model.tick = model.tick.wrapping_add(1);
            }
            model.mode_flash = model.mode_flash.saturating_sub(1);
            Effect::None
        }
    }
}

/// Whether an active selection spans at least one character.
fn selection_nonempty(model: &Model) -> bool {
    model.anchor.is_some_and(|a| a != model.cursor)
}

/// Delete the active selection (if any), moving the cursor to its start. Clears the anchor.
/// Returns whether anything was removed.
fn delete_selection(model: &mut Model) -> bool {
    if let Some(a) = model.anchor.take() {
        let (s, e) = (a.min(model.cursor), a.max(model.cursor));
        if s != e {
            model.input.replace_range(s..e, "");
            model.cursor = s;
            return true;
        }
    }
    false
}

/// Snapshot the input for undo before a mutation, dropping the oldest when the stack is large.
/// A new edit invalidates the redo stack.
fn push_undo(model: &mut Model) {
    model.undo_stack.push((model.input.clone(), model.cursor));
    if model.undo_stack.len() > 200 {
        model.undo_stack.remove(0);
    }
    model.redo_stack.clear();
    model.history_idx = None;
}

/// Replace the input with the previous history entry. The live draft is stashed on the first
/// step into history so stepping back past the newest entry restores it verbatim.
fn history_prev(model: &mut Model) {
    if model.history.is_empty() {
        return;
    }
    let idx = match model.history_idx {
        None => {
            // Entering history from a live draft — remember it (text + cursor) to restore later.
            model.history_draft = Some((model.input.clone(), model.cursor));
            model.history.len() - 1
        }
        Some(0) => 0,
        Some(i) => i - 1,
    };
    model.history_idx = Some(idx);
    model.input = model.history[idx].clone();
    model.cursor = model.input.len();
}

/// Move forward through history; stepping past the newest entry restores the stashed draft.
fn history_next(model: &mut Model) {
    match model.history_idx {
        Some(i) if i + 1 < model.history.len() => {
            model.history_idx = Some(i + 1);
            model.input = model.history[i + 1].clone();
            model.cursor = model.input.len();
        }
        Some(_) => {
            model.history_idx = None;
            let (text, cur) = model.history_draft.take().unwrap_or_default();
            model.cursor = cur.min(text.len());
            model.input = text;
        }
        None => {}
    }
}

/// Byte ranges (start, end-exclusive-of-newline) of each logical line in `s`.
fn line_ranges(s: &str) -> Vec<(usize, usize)> {
    let mut v = Vec::new();
    let mut start = 0;
    for (i, c) in s.char_indices() {
        if c == '\n' {
            v.push((start, i));
            start = i + c.len_utf8();
        }
    }
    v.push((start, s.len()));
    v
}

/// The byte range of the logical line containing `cursor`.
fn current_line_range(s: &str, cursor: usize) -> (usize, usize) {
    let ranges = line_ranges(s);
    for &(a, b) in &ranges {
        if cursor <= b {
            return (a, b);
        }
    }
    (0, s.len())
}

/// Start of the current logical line (for Home).
fn line_home(s: &str, cursor: usize) -> usize {
    current_line_range(s, cursor).0
}

/// End of the current logical line (for End).
fn line_end(s: &str, cursor: usize) -> usize {
    current_line_range(s, cursor).1
}

/// Visual rows of `s` hard-wrapped at `width` characters, as byte ranges `(start, end)`. Each
/// logical line yields at least one row; an over-long line splits every `width` chars. `width == 0`
/// disables wrapping (one row per logical line).
fn visual_rows(s: &str, width: usize) -> Vec<(usize, usize)> {
    let width = if width == 0 { usize::MAX } else { width };
    let mut rows = Vec::new();
    for (a, b) in line_ranges(s) {
        let mut chunk_start = a;
        let mut count = 0usize;
        let mut pos = a;
        for ch in s[a..b].chars() {
            if count == width {
                rows.push((chunk_start, pos));
                chunk_start = pos;
                count = 0;
            }
            pos += ch.len_utf8();
            count += 1;
        }
        rows.push((chunk_start, pos)); // trailing (possibly empty) remainder
    }
    rows
}

/// The (visual row, column-in-chars) of `cursor` within the wrapped rows of `s`.
fn visual_row_col(rows: &[(usize, usize)], s: &str, cursor: usize) -> (usize, usize) {
    for (r, &(a, b)) in rows.iter().enumerate() {
        if cursor <= b {
            return (r, s[a..cursor].chars().count());
        }
    }
    (rows.len().saturating_sub(1), 0)
}

/// Move the cursor vertically by `dir` (−1 up / +1 down) across wrapped visual rows, preserving the
/// column. Returns `None` at the top/bottom visual row (caller may fall back to history).
fn move_vertical(s: &str, cursor: usize, dir: i32, width: usize) -> Option<usize> {
    let rows = visual_rows(s, width);
    let (row, col) = visual_row_col(&rows, s, cursor);
    let target = row as i32 + dir;
    if target < 0 || target as usize >= rows.len() {
        return None;
    }
    let (a, b) = rows[target as usize];
    let mut pos = a;
    for (n, ch) in s[a..b].chars().enumerate() {
        if n == col {
            return Some(pos);
        }
        pos += ch.len_utf8();
    }
    Some(b) // column past the row end → clamp to end
}

/// Next word boundary after byte index `i` (skip whitespace, then the word).
fn word_forward(s: &str, i: usize) -> usize {
    let mut j = i;
    while j < s.len() {
        let c = s[j..].chars().next().unwrap();
        if c.is_whitespace() {
            j += c.len_utf8();
        } else {
            break;
        }
    }
    while j < s.len() {
        let c = s[j..].chars().next().unwrap();
        if c.is_whitespace() {
            break;
        }
        j += c.len_utf8();
    }
    j
}

/// Delete the last logical line together with the newline that precedes it.
fn kill_last_line(model: &mut Model, a: usize, b: usize) -> Effect {
    let start = prev_boundary(&model.input, a); // the '\n' before this line
    model.input.replace_range(start..b, "");
    model.cursor = start.min(model.input.len());
    Effect::None
}

/// Spinner frame for the current tick (used while busy).
pub fn spinner_frame(tick: u64) -> char {
    const FRAMES: [char; 10] = ['', '', '', '', '', '', '', '', '', ''];
    FRAMES[(tick as usize) % FRAMES.len()]
}

/// Short human token count: `1.2k`, `3.4M`.
pub fn fmt_tokens(n: u64) -> String {
    if n >= 1_000_000 {
        format!("{:.1}M", n as f64 / 1e6)
    } else if n >= 1_000 {
        format!("{:.1}k", n as f64 / 1e3)
    } else {
        n.to_string()
    }
}

/// Previous char boundary before byte index `i`.
fn prev_boundary(s: &str, i: usize) -> usize {
    s[..i]
        .char_indices()
        .next_back()
        .map(|(idx, _)| idx)
        .unwrap_or(0)
}

/// Next char boundary after byte index `i`.
fn next_boundary(s: &str, i: usize) -> usize {
    s[i..]
        .char_indices()
        .nth(1)
        .map(|(idx, _)| i + idx)
        .unwrap_or_else(|| s.len())
}

/// Start of the word before byte index `i` (skips trailing spaces then the word).
fn word_start(s: &str, i: usize) -> usize {
    let mut j = i;
    while j > 0 {
        let p = prev_boundary(s, j);
        if s[p..j].chars().next().is_some_and(char::is_whitespace) {
            j = p;
        } else {
            break;
        }
    }
    while j > 0 {
        let p = prev_boundary(s, j);
        if s[p..j].chars().next().is_some_and(|c| !c.is_whitespace()) {
            j = p;
        } else {
            break;
        }
    }
    j
}

/// A compact one-line preview of a tool's arguments for the live "running" row.
fn tool_arg_preview(input: &serde_json::Value) -> String {
    use serde_json::Value;
    let raw = match input {
        Value::Object(map) => {
            let mut pick = None;
            for k in [
                "command",
                "cmd",
                "path",
                "file_path",
                "pattern",
                "query",
                "url",
                "id",
            ] {
                if let Some(Value::String(v)) = map.get(k) {
                    pick = Some(v.clone());
                    break;
                }
            }
            pick.unwrap_or_else(|| input.to_string())
        }
        Value::String(s) => s.clone(),
        Value::Null => return String::new(),
        other => other.to_string(),
    };
    let one = raw.lines().next().unwrap_or("").trim();
    if one.chars().count() > 100 {
        format!("{}", one.chars().take(100).collect::<String>())
    } else {
        one.to_string()
    }
}

/// Fold an agent event into the transcript / streaming buffer.
fn apply_agent(model: &mut Model, ev: AgentEvent) {
    match ev {
        AgentEvent::TextDelta(s) => model.streaming.push_str(&s),
        AgentEvent::ThinkingDelta(s) => model.thinking.push_str(&s),
        AgentEvent::ToolStarted { id, name, input } => {
            flush_streaming(model);
            model.status = format!("running {name}");
            // Show the tool live (with a one-line arg preview) the moment it starts.
            model.transcript.push(Entry::Tool {
                id,
                name,
                text: tool_arg_preview(&input),
                saved: 0,
                running: true,
                error: false,
            });
        }
        AgentEvent::ToolFinished { id, name, output } => {
            model.total_saved += output.saved;
            // Resolve the matching live entry in place; fall back to appending if none is found.
            if let Some(Entry::Tool {
                text,
                saved,
                running,
                error,
                ..
            }) = model
                .transcript
                .iter_mut()
                .rev()
                .find(|e| matches!(e, Entry::Tool { id: eid, running: true, .. } if *eid == id))
            {
                *text = output.text;
                *saved = output.saved;
                *running = false;
                *error = output.is_error;
            } else {
                model.transcript.push(Entry::Tool {
                    id,
                    name,
                    text: output.text,
                    saved: output.saved,
                    running: false,
                    error: output.is_error,
                });
            }
        }
        AgentEvent::TurnComplete { usage } => {
            flush_streaming(model);
            model.thinking.clear();
            model.busy = false;
            model.scroll = 0; // follow to the latest so the reply is visible
            model.total_in += usage.input_tokens;
            model.total_out += usage.output_tokens;
            if usage.input_tokens > 0 {
                model.last_in = usage.input_tokens; // current context occupancy
            }
            model.status = "ready".into();
        }
        AgentEvent::Steered(text) => {
            flush_streaming(model);
            model.transcript.push(Entry::System(format!(
                "↦ steering: {}",
                truncate_objective(&text)
            )));
        }
        AgentEvent::SubAgent { agent, note } => {
            model
                .transcript
                .push(Entry::System(format!("  ↳ [{agent}] {note}")));
        }
        AgentEvent::GoalContinued { objective, turn } => {
            flush_streaming(model);
            model.transcript.push(Entry::System(format!(
                "↻ goal turn {turn}{}",
                truncate_objective(&objective)
            )));
            model.busy = true;
            model.status = "goal: working…".into();
        }
        AgentEvent::Error(e) => {
            flush_streaming(model);
            model.transcript.push(Entry::System(format!("error: {e}")));
            model.busy = false;
            model.status = "error".into();
        }
    }
}

/// One line of an objective, for a transcript note.
fn truncate_objective(objective: &str) -> String {
    let line = objective.lines().next().unwrap_or("").trim();
    if line.chars().count() <= 72 {
        return line.to_string();
    }
    let head: String = line.chars().take(69).collect();
    format!("{head}")
}

fn flush_streaming(model: &mut Model) {
    if !model.streaming.is_empty() {
        let text = std::mem::take(&mut model.streaming);
        model.transcript.push(Entry::Assistant(text));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::types::{ToolOutput, Usage};

    fn typed(s: &str) -> Model {
        let mut m = Model::default();
        for c in s.chars() {
            update(&mut m, Msg::Insert(c));
        }
        m
    }

    #[test]
    fn typing_places_cursor_at_end() {
        let m = typed("hello");
        assert_eq!(m.input, "hello");
        assert_eq!(m.cursor, 5);
    }

    #[test]
    fn cursor_move_and_insert_in_middle() {
        let mut m = typed("helo");
        update(&mut m, Msg::Left); // after 'hel', before 'o'
        update(&mut m, Msg::Insert('l'));
        assert_eq!(m.input, "hello");
    }

    #[test]
    fn backspace_and_delete_at_cursor() {
        let mut m = typed("abc");
        update(&mut m, Msg::Home);
        update(&mut m, Msg::Delete); // remove 'a'
        assert_eq!(m.input, "bc");
        update(&mut m, Msg::End);
        update(&mut m, Msg::Backspace); // remove 'c'
        assert_eq!(m.input, "b");
    }

    #[test]
    fn kill_word_and_line() {
        let mut m = typed("foo bar baz");
        update(&mut m, Msg::KillWordBack); // removes "baz"
        assert_eq!(m.input, "foo bar ");
        update(&mut m, Msg::KillToStart);
        assert_eq!(m.input, "");
    }

    #[test]
    fn submit_takes_input_and_resets_cursor() {
        let mut m = typed("hi");
        let eff = update(&mut m, Msg::Submit);
        assert_eq!(eff, Effect::Submit("hi".into()));
        assert_eq!(m.input, "");
        assert_eq!(m.cursor, 0);
        assert!(m.busy);
    }

    #[test]
    fn tab_cycles_mode_and_flashes() {
        let mut m = Model {
            modes: vec!["build".into(), "plan".into()],
            ..Default::default()
        };
        assert_eq!(m.mode(), "build");
        update(&mut m, Msg::CycleMode(1));
        assert_eq!(m.mode(), "plan");
        assert!(m.mode_flash > 0);
        update(&mut m, Msg::CycleMode(1));
        assert_eq!(m.mode(), "build"); // wraps
        update(&mut m, Msg::CycleMode(-1));
        assert_eq!(m.mode(), "plan"); // reverse wraps
    }

    #[test]
    fn tick_decays_flash() {
        let mut m = Model {
            mode_flash: 2,
            ..Default::default()
        };
        update(&mut m, Msg::Tick);
        assert_eq!(m.mode_flash, 1);
    }

    #[test]
    fn streaming_then_complete_flushes_assistant() {
        let mut m = Model {
            busy: true,
            ..Default::default()
        };
        update(&mut m, Msg::Agent(AgentEvent::TextDelta("hel".into())));
        update(&mut m, Msg::Agent(AgentEvent::TextDelta("lo".into())));
        assert_eq!(m.streaming, "hello");
        update(
            &mut m,
            Msg::Agent(AgentEvent::TurnComplete {
                usage: Usage::default(),
            }),
        );
        assert_eq!(m.transcript, vec![Entry::Assistant("hello".into())]);
        assert!(!m.busy);
    }

    #[test]
    fn hud_accumulates_tokens_savings_and_cost() {
        let mut m = Model {
            price_in: Some(1.0),
            price_out: Some(2.0),
            ..Default::default()
        };
        update(
            &mut m,
            Msg::Agent(AgentEvent::ToolFinished {
                id: "1".into(),
                name: "bash".into(),
                output: ToolOutput {
                    text: "x".into(),
                    is_error: false,
                    saved: 30,
                },
            }),
        );
        update(
            &mut m,
            Msg::Agent(AgentEvent::TurnComplete {
                usage: Usage {
                    input_tokens: 1_000_000,
                    output_tokens: 500_000,
                    ..Default::default()
                },
            }),
        );
        let hud = m.hud_line();
        assert!(hud.contains("1000000 in / 500000 out"), "{hud}");
        assert!(hud.contains("saved ~30"), "{hud}");
        assert!(hud.contains("$2.0000"), "{hud}");
    }

    #[test]
    fn ctx_gauge_reports_usage_percent() {
        let mut m = Model {
            context_window: Some(128_000),
            ..Default::default()
        };
        assert_eq!(m.ctx_line(), ""); // nothing sent yet
        update(
            &mut m,
            Msg::Agent(AgentEvent::TurnComplete {
                usage: Usage {
                    input_tokens: 12_800,
                    output_tokens: 50,
                    ..Default::default()
                },
            }),
        );
        assert_eq!(m.last_in, 12_800);
        let line = m.ctx_line();
        assert!(line.contains("128k"), "{line}");
        assert!(line.contains("10%"), "{line}");
    }

    #[test]
    fn submit_snaps_scroll_to_latest() {
        let mut m = typed("hi");
        m.scroll = 20;
        update(&mut m, Msg::Submit);
        assert_eq!(m.scroll, 0);
    }

    #[test]
    fn multiline_newline_and_vertical_move() {
        let mut m = typed("abc");
        update(&mut m, Msg::Newline);
        for c in "de".chars() {
            update(&mut m, Msg::Insert(c));
        }
        assert_eq!(m.input, "abc\nde");
        // cursor after "de" (row 1, col 2). Up → row 0 col 2 (after "ab").
        update(&mut m, Msg::CursorUp);
        assert_eq!(m.cursor, 2);
        update(&mut m, Msg::CursorDown);
        assert_eq!(m.cursor, 6); // clamped to end of "de"
        // no line above the first → cursor unchanged, caller falls back to history
        update(&mut m, Msg::Home);
        assert!(move_vertical(&m.input, m.cursor, -1, 0).is_none());
    }

    #[test]
    fn vertical_move_follows_wrapped_visual_rows() {
        // A single logical line longer than the width wraps into visual rows; Up must move to the
        // row above (not fall through to history) until the top visual row.
        let m = typed("abcdefghij"); // 10 chars, width 4 → rows "abcd" "efgh" "ij"
        // cursor at 9 (before 'j'), visual row 2 col 1. Up → row 1 col 1 = byte 5.
        assert_eq!(move_vertical(&m.input, 9, -1, 4), Some(5));
        // row 1 → row 0 col 1 = byte 1.
        assert_eq!(move_vertical(&m.input, 5, -1, 4), Some(1));
        // top visual row → None (caller falls back to history).
        assert_eq!(move_vertical(&m.input, 1, -1, 4), None);
        // Down from the top row returns to row 1.
        assert_eq!(move_vertical(&m.input, 1, 1, 4), Some(5));
    }

    #[test]
    fn history_down_restores_draft() {
        let mut m = typed("my draft");
        m.history.push("older msg".into());
        // Up enters history, stashing the draft.
        update(&mut m, Msg::HistoryPrev);
        assert_eq!(m.input, "older msg");
        // Down past the newest restores the draft verbatim (with cursor).
        update(&mut m, Msg::HistoryNext);
        assert_eq!(m.input, "my draft");
        assert_eq!(m.cursor, "my draft".len());
    }

    #[test]
    fn busy_submit_queues_message() {
        let mut m = typed("second");
        m.busy = true;
        let eff = update(&mut m, Msg::Submit);
        assert_eq!(eff, Effect::None);
        assert_eq!(m.queue, vec!["second".to_string()]);
        assert!(m.input.is_empty());
    }

    #[test]
    fn line_home_end_vs_buffer() {
        let mut m = typed("ab\ncd");
        // cursor at end (row1 col2). LineHome → start of "cd".
        update(&mut m, Msg::LineHome);
        assert_eq!(m.cursor, 3);
        update(&mut m, Msg::Home); // buffer start
        assert_eq!(m.cursor, 0);
        update(&mut m, Msg::LineEnd);
        assert_eq!(m.cursor, 2); // end of "ab"
        update(&mut m, Msg::End);
        assert_eq!(m.cursor, 5);
    }

    #[test]
    fn word_motions_and_forward_delete() {
        let mut m = typed("foo bar baz");
        update(&mut m, Msg::Home);
        update(&mut m, Msg::WordForward); // to end of "foo"
        assert_eq!(m.cursor, 3);
        update(&mut m, Msg::WordForward); // to end of "bar"
        assert_eq!(m.cursor, 7);
        update(&mut m, Msg::Home);
        update(&mut m, Msg::KillWordForward); // deletes "foo"
        assert_eq!(m.input, " bar baz");
    }

    #[test]
    fn kill_line_removes_current_line() {
        let mut m = typed("one\ntwo\nthree");
        // cursor on "three" (last line)
        update(&mut m, Msg::KillLine);
        assert_eq!(m.input, "one\ntwo");
        // now on "two" (last line) again
        update(&mut m, Msg::KillLine);
        assert_eq!(m.input, "one");
    }

    #[test]
    fn history_browse_up_down() {
        let mut m = Model::default();
        for prompt in ["first", "second"] {
            for c in prompt.chars() {
                update(&mut m, Msg::Insert(c));
            }
            update(&mut m, Msg::Submit);
            m.busy = false; // simulate turn completion
        }
        assert_eq!(m.history, vec!["first".to_string(), "second".to_string()]);
        update(&mut m, Msg::HistoryPrev);
        assert_eq!(m.input, "second");
        update(&mut m, Msg::HistoryPrev);
        assert_eq!(m.input, "first");
        update(&mut m, Msg::HistoryNext);
        assert_eq!(m.input, "second");
        update(&mut m, Msg::HistoryNext); // past newest → empty draft
        assert_eq!(m.input, "");
    }

    #[test]
    fn selection_delete_and_replace() {
        let mut m = typed("hello");
        m.anchor = Some(0); // select the whole "hello"
        update(&mut m, Msg::Backspace);
        assert_eq!(m.input, "");
        assert!(m.anchor.is_none());

        let mut m = typed("hello");
        m.cursor = 0;
        m.anchor = Some(5); // select all, cursor at start
        update(&mut m, Msg::Insert('X')); // typing replaces the selection
        assert_eq!(m.input, "X");
    }

    #[test]
    fn undo_redo_restores_edits() {
        let mut m = typed("hello");
        update(&mut m, Msg::KillWordBack); // ""
        assert_eq!(m.input, "");
        update(&mut m, Msg::Undo);
        assert_eq!(m.input, "hello");
        update(&mut m, Msg::Redo);
        assert_eq!(m.input, "");
    }

    #[test]
    fn swapping_tabs_moves_workspace_state_but_not_preferences() {
        let mut m = Model {
            transcript: vec![Entry::User("tab one".into())],
            input: "draft".into(),
            cursor: 5,
            scroll: 7,
            total_in: 100,
            model_name: "gpt-4o".into(),
            // shared across tabs — must NOT move
            theme_name: "nord".into(),
            favorites: vec!["claude-opus-5".into()],
            ..Default::default()
        };
        let mut parked = TabState {
            transcript: vec![Entry::User("tab two".into())],
            input: "other".into(),
            cursor: 2,
            model_name: "claude-opus-5".into(),
            ..Default::default()
        };

        m.swap_tab(&mut parked);
        assert_eq!(m.transcript, vec![Entry::User("tab two".into())]);
        assert_eq!(m.input, "other");
        assert_eq!(m.cursor, 2);
        assert_eq!(m.model_name, "claude-opus-5");
        assert_eq!(m.scroll, 0); // the parked tab's own scroll
        // Preferences stayed with the app, not the tab.
        assert_eq!(m.theme_name, "nord");
        assert_eq!(m.favorites, vec!["claude-opus-5".to_string()]);
        // The first tab's state is intact in the parking slot.
        assert_eq!(parked.transcript, vec![Entry::User("tab one".into())]);
        assert_eq!(parked.total_in, 100);

        // Swapping back is an exact round trip.
        m.swap_tab(&mut parked);
        assert_eq!(m.transcript, vec![Entry::User("tab one".into())]);
        assert_eq!(m.input, "draft");
        assert_eq!(m.scroll, 7);
        assert_eq!(m.total_in, 100);
    }

    #[test]
    fn tab_meta_follows_the_focused_tab() {
        let mut m = Model {
            modes: vec!["build".into(), "plan".into()],
            mode_idx: 1,
            model_name: "gpt-4o".into(),
            busy: true,
            tabs: vec![
                chrome::TabMeta::default(),
                chrome::TabMeta {
                    unread: 3,
                    ..Default::default()
                },
            ],
            tab: 1,
            ..Default::default()
        };
        m.sync_tab_meta();
        assert_eq!(m.tabs[1].mode, "plan");
        assert_eq!(m.tabs[1].model, "gpt-4o");
        assert!(m.tabs[1].busy);
        assert_eq!(m.tabs[1].unread, 0, "focusing a tab clears its badge");
        assert_eq!(m.tabs[0].mode, "", "other tabs are untouched");
    }

    #[test]
    fn permission_modal_blocks_input_editing() {
        let mut m = Model::default();
        update(&mut m, Msg::Permission("edit foo.rs".into()));
        assert_eq!(m.pending.as_deref(), Some("edit foo.rs"));
        update(&mut m, Msg::Insert('x')); // ignored while modal open
        assert_eq!(m.input, "");
        update(&mut m, Msg::PermissionResolved);
        assert!(m.pending.is_none());
    }
}