tmai-core 1.5.0

Core library for tmai - agent detection, state management, and monitoring
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
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
//! Action methods on [`TmaiCore`].
//!
//! These methods perform side-effects (send keys, focus panes, etc.) and
//! centralise logic that was previously duplicated across TUI and Web.

use crate::agents::{AgentStatus, ApprovalType};
use crate::detectors::get_detector;

use super::core::TmaiCore;
use super::types::{ApiError, SendPromptResult};

/// Maximum text length for send_text
const MAX_TEXT_LENGTH: usize = 1024;

/// Maximum number of queued prompts per agent
const MAX_PROMPT_QUEUE_SIZE: usize = 5;

/// Allowed special key names for send_key
const ALLOWED_KEYS: &[&str] = &[
    "Enter", "Escape", "Space", "Up", "Down", "Left", "Right", "Tab", "BTab", "BSpace",
];

/// Check if choices use checkbox format ([ ], [x], [X], [×], [✔])
pub fn has_checkbox_format(choices: &[String]) -> bool {
    choices.iter().any(|c| {
        let t = c.trim();
        t.starts_with("[ ]")
            || t.starts_with("[x]")
            || t.starts_with("[X]")
            || t.starts_with("[×]")
            || t.starts_with("[✔]")
    })
}

impl TmaiCore {
    // =========================================================
    // Helper: get command sender or error
    // =========================================================

    /// Return the command sender, or `ApiError::NoCommandSender`
    fn require_command_sender(
        &self,
    ) -> Result<&std::sync::Arc<crate::command_sender::CommandSender>, ApiError> {
        self.command_sender_ref().ok_or(ApiError::NoCommandSender)
    }

    // =========================================================
    // Agent actions
    // =========================================================

    /// Approve an agent action (send approval keys based on agent type).
    ///
    /// Returns `Ok(())` if approval was sent or the agent was already not awaiting.
    pub fn approve(&self, id: &str) -> Result<(), ApiError> {
        let target = self.resolve_agent_key(id)?;
        let (is_awaiting, agent_type, is_virtual) = {
            let state = self.state().read();
            let a = state.agents.get(&target).unwrap();
            (
                matches!(&a.status, AgentStatus::AwaitingApproval { .. }),
                a.agent_type.clone(),
                a.is_virtual,
            )
        };

        if is_virtual {
            return Err(ApiError::VirtualAgent { target });
        }

        if !is_awaiting {
            return Ok(());
        }

        let cmd = self.require_command_sender()?;
        let detector = get_detector(&agent_type);
        cmd.send_keys(&target, detector.approval_keys())?;
        Ok(())
    }

    /// Select a choice for a UserQuestion prompt.
    ///
    /// `choice` is 1-indexed (1 = first option, N+1 = "Other").
    pub fn select_choice(&self, id: &str, choice: usize) -> Result<(), ApiError> {
        let target = self.resolve_agent_key(id)?;
        // Virtual agents cannot receive key input
        {
            let state = self.state().read();
            let a = state.agents.get(&target).unwrap();
            if a.is_virtual {
                return Err(ApiError::VirtualAgent { target });
            }
        }

        let question_info = {
            let state = self.state().read();
            state.agents.get(&target).and_then(|agent| {
                if let AgentStatus::AwaitingApproval {
                    approval_type:
                        ApprovalType::UserQuestion {
                            choices,
                            multi_select,
                            cursor_position,
                        },
                    ..
                } = &agent.status
                {
                    Some((choices.clone(), *multi_select, *cursor_position))
                } else {
                    None
                }
            })
        };

        match question_info {
            Some((choices, multi_select, cursor_pos))
                if choice >= 1 && choice <= choices.len() + 1 =>
            {
                let cmd = self.require_command_sender()?;
                let cursor = if cursor_pos == 0 { 1 } else { cursor_pos };
                let steps = choice as i32 - cursor as i32;
                let key = if steps > 0 { "Down" } else { "Up" };
                for _ in 0..steps.unsigned_abs() {
                    cmd.send_keys(&target, key)?;
                }

                // Confirm: single-select always, multi-select only for checkbox toggle
                if !multi_select || has_checkbox_format(&choices) {
                    cmd.send_keys(&target, "Enter")?;
                }

                Ok(())
            }
            Some(_) => Err(ApiError::InvalidInput {
                message: "Invalid choice number".to_string(),
            }),
            // Agent exists but not in UserQuestion state — idempotent Ok
            None => Ok(()),
        }
    }

    /// Submit multi-select choices (checkbox or legacy format).
    ///
    /// `selected_choices` is a list of 1-indexed choice numbers.
    pub fn submit_selection(&self, id: &str, selected_choices: &[usize]) -> Result<(), ApiError> {
        let target = self.resolve_agent_key(id)?;
        // Virtual agents cannot receive key input
        {
            let state = self.state().read();
            let a = state.agents.get(&target).unwrap();
            if a.is_virtual {
                return Err(ApiError::VirtualAgent { target });
            }
        }

        let multi_info = {
            let state = self.state().read();
            state.agents.get(&target).and_then(|agent| {
                if let AgentStatus::AwaitingApproval {
                    approval_type:
                        ApprovalType::UserQuestion {
                            choices,
                            multi_select: true,
                            cursor_position,
                        },
                    ..
                } = &agent.status
                {
                    Some((choices.clone(), *cursor_position))
                } else {
                    None
                }
            })
        };

        match multi_info {
            Some((choices, cursor_pos)) => {
                let cmd = self.require_command_sender()?;
                let is_checkbox = has_checkbox_format(&choices);

                if is_checkbox && !selected_choices.is_empty() {
                    // Checkbox format: navigate to each selected choice and toggle
                    let mut sorted: Vec<usize> = selected_choices
                        .iter()
                        .copied()
                        .filter(|&c| c >= 1 && c <= choices.len())
                        .collect();
                    if sorted.is_empty() {
                        return Err(ApiError::InvalidInput {
                            message: "No valid choices".to_string(),
                        });
                    }
                    sorted.sort();
                    let mut current_pos = if cursor_pos == 0 { 1 } else { cursor_pos };

                    for &choice in &sorted {
                        let steps = choice as i32 - current_pos as i32;
                        let key = if steps > 0 { "Down" } else { "Up" };
                        for _ in 0..steps.unsigned_abs() {
                            cmd.send_keys(&target, key)?;
                        }
                        // Enter to toggle checkbox
                        cmd.send_keys(&target, "Enter")?;
                        current_pos = choice;
                    }
                    // Right + Enter to submit
                    cmd.send_keys(&target, "Right")?;
                    cmd.send_keys(&target, "Enter")?;
                } else {
                    // Legacy format: navigate past all choices then Enter
                    let downs_needed = choices.len().saturating_sub(cursor_pos.saturating_sub(1));
                    for _ in 0..downs_needed {
                        cmd.send_keys(&target, "Down")?;
                    }
                    cmd.send_keys(&target, "Enter")?;
                }
                Ok(())
            }
            // Agent exists but not in multi-select UserQuestion state — idempotent Ok
            None => Ok(()),
        }
    }

    /// Send text input to an agent followed by Enter.
    ///
    /// Includes a 50ms delay between text and Enter to prevent paste-burst issues.
    pub async fn send_text(&self, id: &str, text: &str) -> Result<(), ApiError> {
        if text.chars().count() > MAX_TEXT_LENGTH {
            return Err(ApiError::InvalidInput {
                message: format!(
                    "Text exceeds maximum length of {} characters",
                    MAX_TEXT_LENGTH
                ),
            });
        }

        let target = self.resolve_agent_key(id)?;
        let is_virtual = {
            let state = self.state().read();
            state.agents.get(&target).unwrap().is_virtual
        };

        if is_virtual {
            return Err(ApiError::VirtualAgent { target });
        }

        let cmd = self.require_command_sender()?;
        cmd.send_keys_literal(&target, text)?;
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        cmd.send_keys(&target, "Enter")?;

        self.audit_helper()
            .maybe_emit_input(&target, "input_text", "api_input", None);

        Ok(())
    }

    /// Send a prompt to an agent with status-aware behavior.
    ///
    /// - **Idle**: sends the prompt immediately (text + Enter).
    /// - **Offline** (stopped): sends the prompt to restart the agent.
    /// - **Processing**: queues the prompt (max 5); delivered when agent becomes Idle.
    /// - **Other** (AwaitingApproval, Error, Unknown): queues like Processing.
    ///
    /// Returns a JSON-serializable status indicating the action taken.
    pub async fn send_prompt(&self, id: &str, prompt: &str) -> Result<SendPromptResult, ApiError> {
        if prompt.chars().count() > MAX_TEXT_LENGTH {
            return Err(ApiError::InvalidInput {
                message: format!(
                    "Prompt exceeds maximum length of {} characters",
                    MAX_TEXT_LENGTH
                ),
            });
        }

        let target = self.resolve_agent_key(id)?;
        let (status, is_virtual) = {
            let state = self.state().read();
            let a = state.agents.get(&target).unwrap();
            (a.status.clone(), a.is_virtual)
        };

        if is_virtual {
            return Err(ApiError::VirtualAgent { target });
        }

        match status {
            AgentStatus::Idle | AgentStatus::Offline => {
                self.send_text(&target, prompt).await?;
                let action = if status.is_idle() {
                    "sent"
                } else {
                    "sent_restart"
                };
                Ok(SendPromptResult {
                    action: action.to_string(),
                    queue_size: 0,
                })
            }
            _ => {
                let queue_size = {
                    let mut state = self.state().write();
                    let queue = state.prompt_queue.entry(target.to_string()).or_default();
                    if queue.len() >= MAX_PROMPT_QUEUE_SIZE {
                        return Err(ApiError::InvalidInput {
                            message: format!(
                                "Prompt queue full (max {} per agent)",
                                MAX_PROMPT_QUEUE_SIZE
                            ),
                        });
                    }
                    queue.push_back(prompt.to_string());
                    queue.len()
                };
                Ok(SendPromptResult {
                    action: "queued".to_string(),
                    queue_size,
                })
            }
        }
    }

    /// Send a special key to an agent (whitelist-validated).
    pub fn send_key(&self, id: &str, key: &str) -> Result<(), ApiError> {
        if !ALLOWED_KEYS.contains(&key) {
            return Err(ApiError::InvalidInput {
                message: "Invalid key name".to_string(),
            });
        }

        let target = self.resolve_agent_key(id)?;
        let (is_virtual, has_pty) = {
            let state = self.state().read();
            let a = state.agents.get(&target).unwrap();
            (a.is_virtual, a.pty_session_id.is_some())
        };

        if is_virtual {
            return Err(ApiError::VirtualAgent { target });
        }

        if has_pty {
            if let Some(session) = self.pty_registry().get(&target) {
                let data = crate::utils::keys::tmux_key_to_bytes(key);
                session.write_input(&data).map_err(ApiError::CommandError)?;
            } else {
                return Err(ApiError::CommandError(anyhow::anyhow!(
                    "PTY session not found for agent"
                )));
            }
        } else {
            let cmd = self.require_command_sender()?;
            cmd.send_keys(&target, key)?;
        }

        self.audit_helper()
            .maybe_emit_input(&target, "special_key", "api_input", None);

        Ok(())
    }

    /// Toggle per-agent auto-approve override.
    ///
    /// - `None` → follow global setting (default)
    /// - `Some(true)` → force enabled for this agent
    /// - `Some(false)` → force disabled for this agent
    pub fn set_auto_approve_override(
        &self,
        id: &str,
        enabled: Option<bool>,
    ) -> Result<(), ApiError> {
        let target = self.resolve_agent_key(id)?;
        let mut state = self.state().write();
        state.agents.get_mut(&target).unwrap().auto_approve_override = enabled;
        Ok(())
    }

    /// Focus on a specific pane in tmux
    pub fn focus_pane(&self, id: &str) -> Result<(), ApiError> {
        let target = self.resolve_agent_key(id)?;
        {
            let state = self.state().read();
            let a = state.agents.get(&target).unwrap();
            if a.is_virtual {
                return Err(ApiError::VirtualAgent { target });
            }
        }

        let cmd = self.require_command_sender()?;
        cmd.runtime().focus_pane(&target)?;
        Ok(())
    }

    /// Request a fresh-session code review for a specific agent.
    ///
    /// Directly launches a review session in a new tmux window (blocking I/O
    /// is offloaded to `spawn_blocking`). Works regardless of `review.enabled`.
    pub fn request_review(&self, id: &str) -> Result<(), ApiError> {
        let target = self.resolve_agent_key(id)?;
        let (cwd, branch) = {
            let state = self.state().read();
            let a = state.agents.get(&target).unwrap();
            (a.cwd.clone(), a.git_branch.clone())
        };

        let request = crate::review::ReviewRequest {
            target: target.to_string(),
            cwd,
            branch,
            base_branch: self.settings().review.base_branch.clone(),
            last_message: None,
        };

        let settings = self.settings().review.clone();
        let event_tx = self.event_sender();
        let req_target = request.target.clone();

        tokio::task::spawn_blocking(move || {
            match crate::review::service::launch_review(&request, &settings, None) {
                Ok((review_target, output_file)) => {
                    tracing::info!(
                        source_target = %req_target,
                        review_target = %review_target,
                        output = %output_file.display(),
                        "Review session launched"
                    );
                    let _ = event_tx.send(super::events::CoreEvent::ReviewLaunched {
                        source_target: req_target,
                        review_target,
                    });
                }
                Err(e) => {
                    tracing::warn!(target = %req_target, %e, "Failed to launch review");
                }
            }
        });

        Ok(())
    }

    // =========================================================
    // Worktree actions
    // =========================================================

    /// List all worktrees from state as owned snapshots
    pub fn list_worktrees(&self) -> Vec<super::types::WorktreeSnapshot> {
        let state = self.state().read();
        let mut snapshots = Vec::new();
        for repo in &state.worktree_info {
            for wt in &repo.worktrees {
                snapshots.push(super::types::WorktreeSnapshot::from_detail(
                    &repo.repo_name,
                    &repo.repo_path,
                    wt,
                ));
            }
        }
        snapshots
    }

    /// Create a new git worktree, then optionally run setup commands
    pub async fn create_worktree(
        &self,
        req: &crate::worktree::WorktreeCreateRequest,
    ) -> Result<crate::worktree::types::WorktreeCreateResult, ApiError> {
        let result = crate::worktree::create_worktree(req).await?;

        // Emit event
        let _ = self
            .event_sender()
            .send(super::events::CoreEvent::WorktreeCreated {
                target: result.path.clone(),
                worktree: Some(crate::hooks::types::WorktreeInfo {
                    name: Some(result.branch.clone()),
                    path: Some(result.path.clone()),
                    branch: Some(result.branch.clone()),
                    original_repo: Some(req.repo_path.clone()),
                }),
            });

        // Spawn setup commands in background if configured
        let setup_commands = self.settings().worktree.setup_commands.clone();
        if !setup_commands.is_empty() {
            let timeout = self.settings().worktree.setup_timeout_secs;
            let wt_path = result.path.clone();
            let branch = result.branch.clone();
            let event_tx = self.event_sender();
            tokio::spawn(async move {
                match crate::worktree::run_setup_commands(&wt_path, &setup_commands, timeout).await
                {
                    Ok(()) => {
                        tracing::info!(
                            worktree = wt_path,
                            branch = branch,
                            "Worktree setup completed"
                        );
                        let _ = event_tx.send(super::events::CoreEvent::WorktreeSetupCompleted {
                            worktree_path: wt_path,
                            branch,
                        });
                    }
                    Err(e) => {
                        tracing::warn!(
                            worktree = wt_path,
                            branch = branch,
                            error = %e,
                            "Worktree setup failed"
                        );
                        let _ = event_tx.send(super::events::CoreEvent::WorktreeSetupFailed {
                            worktree_path: wt_path,
                            branch,
                            error: e,
                        });
                    }
                }
            });
        }

        Ok(result)
    }

    /// Fetch full diff for a worktree (on-demand, for diff viewer)
    pub async fn get_worktree_diff(
        &self,
        worktree_path: &str,
        base_branch: &str,
    ) -> Result<(Option<String>, Option<crate::git::DiffSummary>), ApiError> {
        let diff = crate::git::fetch_full_diff(worktree_path, base_branch).await;
        let summary = crate::git::fetch_diff_stat(worktree_path, base_branch).await;
        Ok((diff, summary))
    }

    /// Delete a git worktree
    ///
    /// Checks for running agents and uncommitted changes before removal.
    /// When force is true, kills the associated agent pane before deletion.
    pub async fn delete_worktree(
        &self,
        req: &crate::worktree::WorktreeDeleteRequest,
    ) -> Result<(), ApiError> {
        let worktree_path = std::path::Path::new(&req.repo_path)
            .join(".claude")
            .join("worktrees")
            .join(&req.worktree_name);
        let wt_path_str = worktree_path.to_string_lossy().to_string();

        // Find agent target associated with this worktree
        let agent_target = {
            let state = self.state().read();
            state
                .worktree_info
                .iter()
                .flat_map(|repo| &repo.worktrees)
                .find(|wt| wt.path == wt_path_str)
                .and_then(|wt| wt.agent_target.clone())
        };

        if let Some(ref target) = agent_target {
            if req.force {
                // Force mode: kill the agent pane before deletion
                tracing::info!(
                    target = %target,
                    worktree = %req.worktree_name,
                    "Killing agent pane before worktree deletion"
                );
                if let Err(e) = self.kill_pane(target) {
                    tracing::warn!(
                        target = %target,
                        error = %e,
                        "Failed to kill agent pane during worktree deletion"
                    );
                }
            } else {
                // Non-force mode: block deletion if agent is running
                return Err(ApiError::WorktreeError(
                    crate::worktree::WorktreeOpsError::AgentStillRunning(req.worktree_name.clone()),
                ));
            }
        }

        // Check for pending agent detection (spawned but not yet detected)
        {
            const PENDING_AGENT_GRACE_SECS: u64 = 60;
            let state = self.state().read();
            if let Some(spawned_at) = state.pending_agent_worktrees.get(&wt_path_str) {
                if spawned_at.elapsed().as_secs() < PENDING_AGENT_GRACE_SECS {
                    return Err(ApiError::WorktreeError(
                        crate::worktree::WorktreeOpsError::AgentPendingDetection(
                            req.worktree_name.clone(),
                        ),
                    ));
                }
            }
        }

        crate::worktree::delete_worktree(req).await?;

        // Emit event
        let _ = self
            .event_sender()
            .send(super::events::CoreEvent::WorktreeRemoved {
                target: wt_path_str,
                worktree: Some(crate::hooks::types::WorktreeInfo {
                    name: Some(req.worktree_name.clone()),
                    path: None,
                    branch: None,
                    original_repo: Some(req.repo_path.clone()),
                }),
            });

        Ok(())
    }

    /// Move an existing branch into a worktree.
    ///
    /// Auto-commits WIP changes if dirty, creates the worktree, and checks out the default branch.
    pub async fn move_to_worktree(
        &self,
        req: &crate::worktree::WorktreeMoveRequest,
    ) -> Result<crate::worktree::types::WorktreeCreateResult, ApiError> {
        let result = crate::worktree::move_to_worktree(req).await?;

        // Emit worktree created event
        let _ = self
            .event_sender()
            .send(super::events::CoreEvent::WorktreeCreated {
                target: result.path.clone(),
                worktree: Some(crate::hooks::types::WorktreeInfo {
                    name: Some(result.branch.clone()),
                    path: Some(result.path.clone()),
                    branch: Some(result.branch.clone()),
                    original_repo: Some(req.repo_path.clone()),
                }),
            });

        // Run setup commands in background if configured
        let setup_commands = self.settings().worktree.setup_commands.clone();
        if !setup_commands.is_empty() {
            let timeout = self.settings().worktree.setup_timeout_secs;
            let wt_path = result.path.clone();
            let branch = result.branch.clone();
            let event_tx = self.event_sender();
            tokio::spawn(async move {
                match crate::worktree::run_setup_commands(&wt_path, &setup_commands, timeout).await
                {
                    Ok(()) => {
                        tracing::info!(
                            worktree = wt_path,
                            branch = branch,
                            "Worktree setup completed"
                        );
                        let _ = event_tx.send(super::events::CoreEvent::WorktreeSetupCompleted {
                            worktree_path: wt_path,
                            branch,
                        });
                    }
                    Err(e) => {
                        tracing::warn!(
                            worktree = wt_path,
                            branch = branch,
                            error = %e,
                            "Worktree setup failed"
                        );
                        let _ = event_tx.send(super::events::CoreEvent::WorktreeSetupFailed {
                            worktree_path: wt_path,
                            branch,
                            error: e,
                        });
                    }
                }
            });
        }

        Ok(result)
    }

    /// Launch an agent in a worktree via tmux
    ///
    /// Creates a new tmux window in the worktree directory and starts the agent.
    /// Returns the new pane target identifier.
    pub fn launch_agent_in_worktree(
        &self,
        worktree_path: &str,
        agent_type: &crate::agents::AgentType,
        session: Option<&str>,
    ) -> Result<String, ApiError> {
        let cmd = self.require_command_sender()?;
        let rt = cmd.runtime();

        // Determine session to use (prefer first agent in display order for determinism)
        let session_name = session
            .map(|s| s.to_string())
            .or_else(|| {
                let state = self.state().read();
                state
                    .agent_order
                    .first()
                    .and_then(|key| state.agents.get(key))
                    .map(|a| a.session.clone())
            })
            .unwrap_or_else(|| "main".to_string());

        // Create a new window in the worktree directory
        let window_name = agent_type.short_name();
        let target = rt.new_window(&session_name, worktree_path, Some(window_name))?;

        // Build the launch command based on agent type
        let launch_cmd = match agent_type {
            crate::agents::AgentType::ClaudeCode => {
                // Extract worktree name from path for --worktree flag
                let wt_name = crate::git::extract_claude_worktree_name(worktree_path);
                match wt_name {
                    Some(name) if crate::git::is_valid_worktree_name(&name) => {
                        format!("claude --worktree {}", name)
                    }
                    _ => "claude".to_string(),
                }
            }
            crate::agents::AgentType::CodexCli => "codex".to_string(),
            crate::agents::AgentType::GeminiCli => "gemini".to_string(),
            crate::agents::AgentType::OpenCode => "opencode".to_string(),
            crate::agents::AgentType::Custom(name) => name.clone(),
        };

        // Run via tmai wrap for PTY monitoring
        rt.run_command_wrapped(&target, &launch_cmd)?;

        // Record pending agent state to prevent premature worktree deletion
        {
            let state = self.state();
            let mut s = state.write();
            s.pending_agent_worktrees
                .insert(worktree_path.to_string(), std::time::Instant::now());
        }

        tracing::info!(
            worktree = worktree_path,
            agent = %agent_type.short_name(),
            target = %target,
            "Launched agent in worktree"
        );

        Ok(target)
    }

    // =========================================================
    // Usage actions
    // =========================================================

    /// Get the cached usage snapshot from state.
    pub fn get_usage(&self) -> crate::usage::UsageSnapshot {
        self.state().read().usage.clone()
    }

    /// Start a background usage fetch.
    ///
    /// If a fetch is already in progress, this is a no-op.
    /// On completion, updates state and emits `CoreEvent::UsageUpdated`.
    pub fn fetch_usage(&self) {
        // Check and set fetching flag atomically
        {
            let mut state = self.state().write();
            if state.usage.fetching {
                return;
            }
            state.usage.fetching = true;
        }

        let state = self.state().clone();
        let event_tx = self.event_sender();

        // Determine if tmux is available by checking runtime
        let tmux_session = self.runtime().and_then(|_rt| {
            // If runtime supports tmux, try to get a session name from agents
            let s = self.state().read();
            s.agent_order
                .first()
                .and_then(|key| s.agents.get(key))
                .map(|a| a.session.clone())
        });

        tokio::spawn(async move {
            let result = crate::usage::fetch_usage_auto(tmux_session.as_deref()).await;

            let mut s = state.write();
            match result {
                Ok(snapshot) => {
                    s.usage = snapshot;
                    s.usage.fetching = false;
                    s.usage.error = None;
                }
                Err(e) => {
                    tracing::warn!("Usage fetch failed: {e}");
                    s.usage.fetching = false;
                    s.usage.error = Some(e.to_string());
                }
            }
            drop(s);
            let _ = event_tx.send(super::events::CoreEvent::UsageUpdated);
        });
    }

    /// Auto-fetch usage on startup if enabled in settings.
    pub fn start_initial_usage_fetch(&self) {
        let settings = self.settings();
        if settings.usage.enabled {
            tracing::info!("Usage monitoring enabled — starting initial fetch");
            self.fetch_usage();
        }
    }

    /// Kill a specific agent (PTY session or tmux pane)
    pub fn kill_pane(&self, id: &str) -> Result<(), ApiError> {
        let target = self.resolve_agent_key(id)?;
        let has_pty = {
            let state = self.state().read();
            let a = state.agents.get(&target).unwrap();
            if a.is_virtual {
                return Err(ApiError::VirtualAgent {
                    target: target.clone(),
                });
            }
            a.pty_session_id.is_some()
        };

        if has_pty {
            if let Some(session) = self.pty_registry().get(&target) {
                session.kill();
            }
            {
                let mut state = self.state().write();
                state.agents.remove(&target);
                state.agent_order.retain(|k| k != &target);
            }
            self.notify_agents_updated();
            Ok(())
        } else {
            let cmd = self.require_command_sender()?;
            cmd.runtime().kill_pane(&target)?;
            Ok(())
        }
    }

    /// Sync PTY-spawned agent statuses with actual PTY session liveness
    /// and hook registry state.
    ///
    /// - Hook status available: apply hook-derived status (highest fidelity)
    /// - Running sessions without hooks: set to `Processing`
    /// - Dead sessions: set to `Offline` and clean up from registry
    ///
    /// Returns true if any agent status was changed.
    pub fn sync_pty_sessions(&self) -> bool {
        let dead_ids = self.pty_registry().cleanup_dead();
        let mut changed = false;

        // Read hook states for PTY agents
        let hook_reg = self.hook_registry().read();

        let mut state = self.state().write();
        for (id, agent) in state.agents.iter_mut() {
            if agent.pty_session_id.is_none() {
                continue;
            }

            if dead_ids.contains(id) {
                // Process exited — set Offline and clean up mappings
                agent.status = crate::agents::AgentStatus::Offline;
                changed = true;
                // Remove from session_pane_map to prevent stale routing
                if let Some(sid) = &agent.pty_session_id {
                    let mut spm = self.session_pane_map().write();
                    spm.remove(sid);
                }
                continue;
            }

            // Try to apply hook-derived status.
            // PTY agent's ID is a session_id (UUID), but HookRegistry keys are
            // pane_ids from resolve_pane_id(). Try: direct match, then
            // session_pane_map lookup, then scan by session_id.
            let hook_state_ref = hook_reg
                .get(id)
                .or_else(|| {
                    // Lookup via session_pane_map (session_id → pane_id)
                    let spm = self.session_pane_map().read();
                    let sid = agent.pty_session_id.as_deref().unwrap_or(id);
                    spm.get(sid).and_then(|pane_id| hook_reg.get(pane_id))
                })
                .or_else(|| {
                    // Scan HookRegistry for matching session_id
                    let sid = agent.pty_session_id.as_deref().unwrap_or(id);
                    hook_reg.values().find(|hs| hs.session_id == sid)
                });
            if let Some(hook_state) = hook_state_ref {
                let new_status = crate::hooks::handler::hook_status_to_agent_status(hook_state);
                if agent.status != new_status {
                    agent.status = new_status;
                    agent.detection_source = crate::agents::DetectionSource::HttpHook;
                    changed = true;
                }
                // Update last_content from activity log
                let activity = crate::hooks::handler::format_activity_log(&hook_state.activity_log);
                if !activity.is_empty() && agent.last_content != activity {
                    agent.last_content = activity;
                    changed = true;
                }
                continue;
            }

            // No hook state — detect status from PTY scrollback (capture-pane equivalent)
            if let Some(session) = self.pty_registry().get(id) {
                let snapshot = session.scrollback_snapshot();
                let raw_text = String::from_utf8_lossy(&snapshot);
                // Take last ~4KB for detection (equivalent to capture-pane last N lines)
                let tail = if raw_text.len() > 4096 {
                    let start = raw_text.floor_char_boundary(raw_text.len() - 4096);
                    &raw_text[start..]
                } else {
                    &raw_text
                };
                let content = crate::utils::strip_ansi(tail);
                let detector = crate::detectors::get_detector(&agent.agent_type);
                let new_status = detector.detect_status("", &content);
                if agent.status != new_status {
                    agent.status = new_status;
                    agent.detection_source = crate::agents::DetectionSource::CapturePane;
                    changed = true;
                }
                // Update last_content for preview
                if agent.last_content != content {
                    agent.last_content = content;
                    changed = true;
                }
            }
        }

        changed
    }

    // =========================================================
    // Orchestrator
    // =========================================================

    /// Compose a system prompt from orchestrator settings.
    ///
    /// The prompt includes the role description, any non-empty workflow rules,
    /// and an instruction to use tmai MCP tools.
    /// When `project_path` is provided, uses per-project orchestrator override if set.
    pub fn compose_orchestrator_prompt(&self, project_path: Option<&str>) -> String {
        let settings = self.settings();
        let orch = settings.resolve_orchestrator(project_path);
        let mut parts: Vec<String> = Vec::new();

        // Role
        parts.push(orch.role.clone());

        // Rules (only include non-empty ones)
        let mut rule_lines: Vec<String> = Vec::new();
        if !orch.rules.branch.is_empty() {
            rule_lines.push(format!("- Branch: {}", orch.rules.branch));
        }
        if !orch.rules.merge.is_empty() {
            rule_lines.push(format!("- Merge: {}", orch.rules.merge));
        }
        if !orch.rules.review.is_empty() {
            rule_lines.push(format!("- Review: {}", orch.rules.review));
        }
        if !orch.rules.custom.is_empty() {
            rule_lines.push(format!("- {}", orch.rules.custom));
        }
        if !rule_lines.is_empty() {
            parts.push(format!("\nWorkflow rules:\n{}", rule_lines.join("\n")));
        }

        // MCP instruction
        parts.push(
            "\nUse tmai MCP tools to manage agents: list_agents, spawn_worktree, \
             dispatch_issue, get_agent_output, send_prompt, approve, etc."
                .to_string(),
        );

        parts.join("\n")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agents::{AgentType, MonitoredAgent};
    use crate::api::builder::TmaiCoreBuilder;
    use crate::config::Settings;
    use crate::state::AppState;

    fn make_core_with_agents(agents: Vec<MonitoredAgent>) -> TmaiCore {
        let state = AppState::shared();
        {
            let mut s = state.write();
            s.update_agents(agents);
        }
        TmaiCoreBuilder::new(Settings::default())
            .with_state(state)
            .build()
    }

    fn test_agent(id: &str, status: AgentStatus) -> MonitoredAgent {
        let mut agent = MonitoredAgent::new(
            id.to_string(),
            AgentType::ClaudeCode,
            "Title".to_string(),
            "/home/user".to_string(),
            100,
            "main".to_string(),
            "win".to_string(),
            0,
            0,
        );
        agent.status = status;
        agent
    }

    #[test]
    fn test_has_checkbox_format() {
        assert!(has_checkbox_format(&[
            "[ ] Option A".to_string(),
            "[ ] Option B".to_string(),
        ]));
        assert!(has_checkbox_format(&[
            "[x] Option A".to_string(),
            "[ ] Option B".to_string(),
        ]));
        assert!(has_checkbox_format(&[
            "[✔] Done".to_string(),
            "[ ] Not done".to_string(),
        ]));
        assert!(!has_checkbox_format(&[
            "Option A".to_string(),
            "Option B".to_string(),
        ]));
        assert!(!has_checkbox_format(&[]));
    }

    #[test]
    fn test_approve_not_found() {
        let core = TmaiCoreBuilder::new(Settings::default()).build();
        let result = core.approve("nonexistent");
        assert!(matches!(result, Err(ApiError::AgentNotFound { .. })));
    }

    #[test]
    fn test_approve_virtual_agent() {
        let mut agent = test_agent(
            "main:0.0",
            AgentStatus::AwaitingApproval {
                approval_type: ApprovalType::FileEdit,
                details: "edit foo.rs".to_string(),
            },
        );
        agent.is_virtual = true;
        let core = make_core_with_agents(vec![agent]);
        let result = core.approve("main:0.0");
        assert!(matches!(result, Err(ApiError::VirtualAgent { .. })));
    }

    #[test]
    fn test_approve_not_awaiting_is_ok() {
        let agent = test_agent("main:0.0", AgentStatus::Idle);
        let core = make_core_with_agents(vec![agent]);
        // No command sender, but should return Ok since not awaiting
        let result = core.approve("main:0.0");
        assert!(result.is_ok());
    }

    #[test]
    fn test_approve_awaiting_no_command_sender() {
        let agent = test_agent(
            "main:0.0",
            AgentStatus::AwaitingApproval {
                approval_type: ApprovalType::ShellCommand,
                details: "rm -rf".to_string(),
            },
        );
        let core = make_core_with_agents(vec![agent]);
        let result = core.approve("main:0.0");
        assert!(matches!(result, Err(ApiError::NoCommandSender)));
    }

    #[test]
    fn test_send_key_invalid() {
        let agent = test_agent("main:0.0", AgentStatus::Idle);
        let core = make_core_with_agents(vec![agent]);
        let result = core.send_key("main:0.0", "Delete");
        assert!(matches!(result, Err(ApiError::InvalidInput { .. })));
    }

    #[test]
    fn test_send_key_not_found() {
        let core = TmaiCoreBuilder::new(Settings::default()).build();
        let result = core.send_key("nonexistent", "Enter");
        assert!(matches!(result, Err(ApiError::AgentNotFound { .. })));
    }

    #[test]
    fn test_send_key_virtual_agent() {
        let mut agent = test_agent("main:0.0", AgentStatus::Idle);
        agent.is_virtual = true;
        let core = make_core_with_agents(vec![agent]);
        let result = core.send_key("main:0.0", "Enter");
        assert!(matches!(result, Err(ApiError::VirtualAgent { .. })));
    }

    #[test]
    fn test_select_choice_not_in_question() {
        let agent = test_agent("main:0.0", AgentStatus::Idle);
        let core = make_core_with_agents(vec![agent]);
        // Agent exists but not in UserQuestion state — idempotent Ok
        let result = core.select_choice("main:0.0", 1);
        assert!(result.is_ok());
    }

    #[test]
    fn test_select_choice_not_found() {
        let core = TmaiCoreBuilder::new(Settings::default()).build();
        let result = core.select_choice("nonexistent", 1);
        assert!(matches!(result, Err(ApiError::AgentNotFound { .. })));
    }

    #[test]
    fn test_select_choice_virtual_agent() {
        let mut agent = test_agent("main:0.0", AgentStatus::Idle);
        agent.is_virtual = true;
        let core = make_core_with_agents(vec![agent]);
        let result = core.select_choice("main:0.0", 1);
        assert!(matches!(result, Err(ApiError::VirtualAgent { .. })));
    }

    #[test]
    fn test_select_choice_invalid_number() {
        let agent = test_agent(
            "main:0.0",
            AgentStatus::AwaitingApproval {
                approval_type: ApprovalType::UserQuestion {
                    choices: vec!["A".to_string(), "B".to_string()],
                    multi_select: false,
                    cursor_position: 1,
                },
                details: "Pick one".to_string(),
            },
        );
        let core = make_core_with_agents(vec![agent]);
        // choice 0 is invalid (1-indexed)
        let result = core.select_choice("main:0.0", 0);
        assert!(matches!(result, Err(ApiError::InvalidInput { .. })));
        // choice 4 is invalid (only 2 choices + 1 Other = max 3)
        let result = core.select_choice("main:0.0", 4);
        assert!(matches!(result, Err(ApiError::InvalidInput { .. })));
    }

    #[tokio::test]
    async fn test_send_text_too_long() {
        let agent = test_agent("main:0.0", AgentStatus::Idle);
        let core = make_core_with_agents(vec![agent]);
        let long_text = "x".repeat(1025);
        let result = core.send_text("main:0.0", &long_text).await;
        assert!(matches!(result, Err(ApiError::InvalidInput { .. })));
    }

    #[tokio::test]
    async fn test_send_text_not_found() {
        let core = TmaiCoreBuilder::new(Settings::default()).build();
        let result = core.send_text("nonexistent", "hello").await;
        assert!(matches!(result, Err(ApiError::AgentNotFound { .. })));
    }

    #[tokio::test]
    async fn test_send_text_virtual_agent() {
        let mut agent = test_agent("main:0.0", AgentStatus::Idle);
        agent.is_virtual = true;
        let core = make_core_with_agents(vec![agent]);
        let result = core.send_text("main:0.0", "hello").await;
        assert!(matches!(result, Err(ApiError::VirtualAgent { .. })));
    }

    #[tokio::test]
    async fn test_send_text_at_max_length() {
        let agent = test_agent("main:0.0", AgentStatus::Idle);
        let core = make_core_with_agents(vec![agent]);
        // MAX_TEXT_LENGTH chars exactly should pass validation (fail at NoCommandSender)
        let text = "x".repeat(MAX_TEXT_LENGTH);
        let result = core.send_text("main:0.0", &text).await;
        assert!(!matches!(result, Err(ApiError::InvalidInput { .. })));
    }

    #[test]
    fn test_focus_pane_not_found() {
        let core = TmaiCoreBuilder::new(Settings::default()).build();
        let result = core.focus_pane("nonexistent");
        assert!(matches!(result, Err(ApiError::AgentNotFound { .. })));
    }

    #[test]
    fn test_focus_pane_virtual_agent() {
        let mut agent = test_agent("main:0.0", AgentStatus::Idle);
        agent.is_virtual = true;
        let core = make_core_with_agents(vec![agent]);
        let result = core.focus_pane("main:0.0");
        assert!(matches!(result, Err(ApiError::VirtualAgent { .. })));
    }

    #[test]
    fn test_kill_pane_not_found() {
        let core = TmaiCoreBuilder::new(Settings::default()).build();
        let result = core.kill_pane("nonexistent");
        assert!(matches!(result, Err(ApiError::AgentNotFound { .. })));
    }

    #[test]
    fn test_kill_pane_virtual_agent() {
        let mut agent = test_agent("main:0.0", AgentStatus::Idle);
        agent.is_virtual = true;
        let core = make_core_with_agents(vec![agent]);
        let result = core.kill_pane("main:0.0");
        assert!(matches!(result, Err(ApiError::VirtualAgent { .. })));
    }

    #[test]
    fn test_submit_selection_not_found() {
        let core = TmaiCoreBuilder::new(Settings::default()).build();
        let result = core.submit_selection("nonexistent", &[1]);
        assert!(matches!(result, Err(ApiError::AgentNotFound { .. })));
    }

    #[test]
    fn test_submit_selection_virtual_agent() {
        let mut agent = test_agent("main:0.0", AgentStatus::Idle);
        agent.is_virtual = true;
        let core = make_core_with_agents(vec![agent]);
        let result = core.submit_selection("main:0.0", &[1]);
        assert!(matches!(result, Err(ApiError::VirtualAgent { .. })));
    }

    #[test]
    fn test_submit_selection_not_in_multiselect() {
        let agent = test_agent("main:0.0", AgentStatus::Idle);
        let core = make_core_with_agents(vec![agent]);
        // Agent exists but not in multi-select state — idempotent Ok
        let result = core.submit_selection("main:0.0", &[1]);
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_initial_usage_fetch_sets_fetching_when_enabled() {
        let mut settings = Settings::default();
        settings.usage.enabled = true;
        let state = AppState::shared();
        let core = TmaiCoreBuilder::new(settings)
            .with_state(state.clone())
            .build();
        // Should set fetching=true since usage is enabled
        core.start_initial_usage_fetch();
        assert!(state.read().usage.fetching);
    }

    #[test]
    fn test_initial_usage_fetch_noop_when_disabled() {
        let mut settings = Settings::default();
        settings.usage.enabled = false;
        let state = AppState::shared();
        let core = TmaiCoreBuilder::new(settings)
            .with_state(state.clone())
            .build();
        core.start_initial_usage_fetch();
        // Should not set fetching since usage is disabled
        assert!(!state.read().usage.fetching);
    }

    /// Helper to set up worktree_info with an agent running in the given worktree path
    fn setup_worktree_info(
        state: &crate::state::SharedState,
        repo_path: &str,
        worktree_name: &str,
        agent_target: Option<String>,
    ) {
        use crate::state::{RepoWorktreeInfo, WorktreeDetail};
        let wt_path = std::path::Path::new(repo_path)
            .join(".claude")
            .join("worktrees")
            .join(worktree_name)
            .to_string_lossy()
            .to_string();
        let mut s = state.write();
        s.worktree_info = vec![RepoWorktreeInfo {
            repo_name: "test-repo".to_string(),
            repo_path: repo_path.to_string(),
            worktrees: vec![WorktreeDetail {
                name: worktree_name.to_string(),
                path: wt_path,
                branch: Some("feat/test".to_string()),
                is_main: false,
                agent_target,
                agent_status: Some(AgentStatus::Processing {
                    activity: String::new(),
                }),
                is_dirty: Some(false),
                diff_summary: None,
                agent_pending: false,
            }],
        }];
    }

    #[tokio::test]
    async fn test_delete_worktree_blocks_when_agent_running() {
        let state = AppState::shared();
        setup_worktree_info(&state, "/tmp/repo", "my-wt", Some("main:0.1".to_string()));
        let core = TmaiCoreBuilder::new(Settings::default())
            .with_state(state)
            .build();

        let req = crate::worktree::WorktreeDeleteRequest {
            repo_path: "/tmp/repo".to_string(),
            worktree_name: "my-wt".to_string(),
            force: false,
        };
        let result = core.delete_worktree(&req).await;
        assert!(
            matches!(
                result,
                Err(ApiError::WorktreeError(
                    crate::worktree::WorktreeOpsError::AgentStillRunning(_)
                ))
            ),
            "Should block deletion when agent is running and force=false"
        );
    }

    #[tokio::test]
    async fn test_delete_worktree_no_block_without_agent() {
        let state = AppState::shared();
        // No agent_target set for the worktree
        setup_worktree_info(&state, "/tmp/repo", "my-wt", None);
        let core = TmaiCoreBuilder::new(Settings::default())
            .with_state(state)
            .build();

        let req = crate::worktree::WorktreeDeleteRequest {
            repo_path: "/tmp/repo".to_string(),
            worktree_name: "my-wt".to_string(),
            force: false,
        };
        // Will fail at the git worktree level (path doesn't exist), but should NOT
        // fail with AgentStillRunning
        let result = core.delete_worktree(&req).await;
        assert!(
            !matches!(
                result,
                Err(ApiError::WorktreeError(
                    crate::worktree::WorktreeOpsError::AgentStillRunning(_)
                ))
            ),
            "Should not block deletion when no agent is running"
        );
    }

    // =========================================================
    // send_prompt tests
    // =========================================================

    #[tokio::test]
    async fn test_send_prompt_queues_when_processing() {
        let agent = test_agent(
            "test:0.0",
            AgentStatus::Processing {
                activity: "thinking".to_string(),
            },
        );
        let core = make_core_with_agents(vec![agent]);

        // send_prompt should queue (no command sender, but queue is written before send)
        let result = core.send_prompt("test:0.0", "do something").await;
        assert!(result.is_ok());
        let r = result.unwrap();
        assert_eq!(r.action, "queued");
        assert_eq!(r.queue_size, 1);

        // Verify queue state
        let state = core.state().read();
        let q = state.prompt_queue.get("test:0.0").unwrap();
        assert_eq!(q.len(), 1);
        assert_eq!(q[0], "do something");
    }

    #[tokio::test]
    async fn test_send_prompt_queue_overflow() {
        let agent = test_agent(
            "test:0.0",
            AgentStatus::Processing {
                activity: "thinking".to_string(),
            },
        );
        let core = make_core_with_agents(vec![agent]);

        // Fill up the queue (MAX_PROMPT_QUEUE_SIZE = 5)
        for i in 0..5 {
            let result = core.send_prompt("test:0.0", &format!("prompt {}", i)).await;
            assert!(result.is_ok());
            assert_eq!(result.unwrap().queue_size, i + 1);
        }

        // 6th prompt should fail
        let result = core.send_prompt("test:0.0", "overflow").await;
        assert!(result.is_err());
        match result {
            Err(ApiError::InvalidInput { message }) => {
                assert!(message.contains("queue full"));
            }
            other => panic!("Expected InvalidInput, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_send_prompt_idle_sends_immediately() {
        let agent = test_agent("test:0.0", AgentStatus::Idle);
        let core = make_core_with_agents(vec![agent]);

        // Idle agent — send_prompt tries to send immediately.
        // Without a CommandSender, it will fail at the send_text level, not the queue level.
        let result = core.send_prompt("test:0.0", "hello").await;
        // Should fail because no CommandSender, not because of queueing
        assert!(result.is_err());
        match result {
            Err(ApiError::NoCommandSender) => {} // expected
            other => panic!("Expected NoCommandSender, got {:?}", other),
        }

        // Queue should remain empty (not queued)
        let state = core.state().read();
        assert!(state.prompt_queue.get("test:0.0").is_none());
    }

    #[tokio::test]
    async fn test_send_prompt_offline_sends_immediately() {
        let agent = test_agent("test:0.0", AgentStatus::Offline);
        let core = make_core_with_agents(vec![agent]);

        // Offline agent — should try to send immediately (restart)
        let result = core.send_prompt("test:0.0", "restart prompt").await;
        assert!(result.is_err());
        match result {
            Err(ApiError::NoCommandSender) => {} // expected without tmux
            other => panic!("Expected NoCommandSender, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_send_prompt_not_found() {
        let core = make_core_with_agents(vec![]);

        let result = core.send_prompt("nonexistent", "hello").await;
        assert!(result.is_err());
        match result {
            Err(ApiError::AgentNotFound { target }) => {
                assert_eq!(target, "nonexistent");
            }
            other => panic!("Expected AgentNotFound, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_send_prompt_virtual_agent() {
        let mut agent = test_agent("test:0.0", AgentStatus::Idle);
        agent.is_virtual = true;
        let core = make_core_with_agents(vec![agent]);

        let result = core.send_prompt("test:0.0", "hello").await;
        assert!(result.is_err());
        match result {
            Err(ApiError::VirtualAgent { .. }) => {} // expected
            other => panic!("Expected VirtualAgent, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_send_prompt_too_long() {
        let agent = test_agent("test:0.0", AgentStatus::Idle);
        let core = make_core_with_agents(vec![agent]);

        let long_text = "a".repeat(MAX_TEXT_LENGTH + 1);
        let result = core.send_prompt("test:0.0", &long_text).await;
        assert!(result.is_err());
        match result {
            Err(ApiError::InvalidInput { message }) => {
                assert!(message.contains("maximum length"));
            }
            other => panic!("Expected InvalidInput, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_send_prompt_queues_when_awaiting_approval() {
        let agent = test_agent(
            "test:0.0",
            AgentStatus::AwaitingApproval {
                approval_type: ApprovalType::McpTool,
                details: "read file".to_string(),
            },
        );
        let core = make_core_with_agents(vec![agent]);

        let result = core.send_prompt("test:0.0", "after approval").await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().action, "queued");
    }

    #[test]
    fn test_prompt_queue_drain() {
        // Test the drain behavior by directly manipulating AppState
        let state = AppState::shared();
        {
            let mut s = state.write();
            let mut q = std::collections::VecDeque::new();
            q.push_back("first".to_string());
            q.push_back("second".to_string());
            s.prompt_queue.insert("agent1".to_string(), q);
        }

        // Pop front (simulating what the poller does)
        let prompt = {
            let mut s = state.write();
            s.prompt_queue.get_mut("agent1").and_then(|q| q.pop_front())
        };
        assert_eq!(prompt, Some("first".to_string()));

        // Verify second is still there
        let remaining = {
            let s = state.read();
            s.prompt_queue.get("agent1").unwrap().len()
        };
        assert_eq!(remaining, 1);
    }

    #[test]
    fn test_compose_orchestrator_prompt_default() {
        let core = TmaiCoreBuilder::new(Settings::default()).build();
        let prompt = core.compose_orchestrator_prompt(None);
        // Should contain default role
        assert!(prompt.contains("orchestrator agent"));
        // Should contain MCP tools instruction
        assert!(prompt.contains("tmai MCP tools"));
        // No rules section with empty rules
        assert!(!prompt.contains("Workflow rules:"));
    }

    #[test]
    fn test_compose_orchestrator_prompt_with_rules() {
        let mut settings = Settings::default();
        settings.orchestrator.role = "You are the boss.".to_string();
        settings.orchestrator.rules.branch = "feat/{issue}-{slug}".to_string();
        settings.orchestrator.rules.review = "Run CI first".to_string();

        let core = TmaiCoreBuilder::new(settings).build();
        let prompt = core.compose_orchestrator_prompt(None);
        assert!(prompt.contains("You are the boss."));
        assert!(prompt.contains("Workflow rules:"));
        assert!(prompt.contains("- Branch: feat/{issue}-{slug}"));
        assert!(prompt.contains("- Review: Run CI first"));
        // Merge rule is empty, should not appear
        assert!(!prompt.contains("- Merge:"));
    }
}