tmai 1.6.0

Tactful Multi Agent Interface - Monitor and control multiple AI coding agents
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
//! `tmai init` command — sets up Claude Code hooks integration.
//!
//! Generates a hook authentication token and configures Claude Code's
//! `~/.claude/settings.json` to send HTTP hook events to tmai's web server.

use std::fs;
use std::path::PathBuf;

use anyhow::{Context, Result};
use serde_json::{json, Value};

/// Marker used to identify tmai-generated hook entries
const TMAI_STATUS_PREFIX: &str = "tmai: ";

/// Get the hooks token file path
fn hooks_token_path() -> Result<PathBuf> {
    let config_dir = dirs::config_dir()
        .or_else(|| dirs::home_dir().map(|h| h.join(".config")))
        .context("Cannot determine config directory")?
        .join("tmai");
    Ok(config_dir.join("hooks_token"))
}

/// Get or generate a hook token
fn ensure_hook_token(force: bool) -> Result<String> {
    let path = hooks_token_path()?;

    if !force {
        if let Ok(existing) = fs::read_to_string(&path) {
            let token = existing.trim().to_string();
            if !token.is_empty() {
                return Ok(token);
            }
        }
    }

    let token = uuid::Uuid::new_v4().to_string();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }

    // Write token file with restricted permissions from the start (no race window)
    #[cfg(unix)]
    {
        use std::fs::OpenOptions;
        use std::io::Write;
        use std::os::unix::fs::OpenOptionsExt;
        let mut file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(&path)
            .with_context(|| format!("Failed to write hooks token to {}", path.display()))?;
        file.write_all(token.as_bytes())
            .with_context(|| format!("Failed to write hooks token to {}", path.display()))?;
    }
    #[cfg(not(unix))]
    {
        fs::write(&path, &token)
            .with_context(|| format!("Failed to write hooks token to {}", path.display()))?;
    }

    println!("Generated hook token: {}", path.display());
    Ok(token)
}

/// Load the existing hook token (if any) from the config directory
pub fn load_hook_token() -> Option<String> {
    let path = hooks_token_path().ok()?;
    fs::read_to_string(&path)
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

/// Generate the statusline.sh script that forwards JSON to tmai
///
/// The script reads stdin (statusline JSON from Claude Code), forwards it to
/// tmai's HTTP endpoint, then outputs a minimal status line for the terminal.
fn generate_statusline_script(
    token: &str,
    port: u16,
    include_tmux_pane: bool,
    existing_command: Option<&str>,
) -> Result<PathBuf> {
    let home = dirs::home_dir().context("Cannot determine home directory")?;
    let script_path = home.join(".claude").join("statusline.sh");

    // Build pane_id header: use $TMUX_PANE when tmux is available
    let pane_header = if include_tmux_pane {
        "-H \"X-Tmai-Pane-Id: $TMUX_PANE\" ".to_string()
    } else {
        String::new()
    };

    // Display section: delegate to existing tool if available, otherwise use built-in
    let display_section = if let Some(cmd) = existing_command {
        format!(
            r#"# Delegate display to existing statusline tool
echo "$INPUT" | {cmd}"#
        )
    } else {
        r#"# Display a minimal status line (no existing tool detected)
MODEL=$(echo "$INPUT" | jq -r '.model.display_name // empty')
COST=$(echo "$INPUT" | jq -r '.cost.total_cost_usd // empty')
CTX=$(echo "$INPUT" | jq -r '.context_window.used_percentage // empty')

STATUS=""
[ -n "$MODEL" ] && STATUS="$MODEL"
[ -n "$COST" ] && STATUS="$STATUS \$$COST"
[ -n "$CTX" ] && STATUS="$STATUS ctx:$CTX%"

echo "$STATUS""#
            .to_string()
    };

    let script = format!(
        r#"#!/usr/bin/env bash
# tmai statusline hook — forwards statusline JSON to tmai, then delegates display
# Generated by `tmai init`. Re-run `tmai init` to regenerate.

INPUT=$(cat)

# Forward to tmai (fire-and-forget, don't block Claude Code)
curl -s -o /dev/null -m 1 \
  -X POST "http://localhost:{port}/hooks/statusline" \
  -H "Authorization: Bearer {token}" \
  {pane_header}-H "Content-Type: application/json" \
  -d "$INPUT" &

{display_section}
"#
    );

    if let Some(parent) = script_path.parent() {
        fs::create_dir_all(parent)?;
    }

    // Write with executable permissions
    #[cfg(unix)]
    {
        use std::fs::OpenOptions;
        use std::io::Write;
        use std::os::unix::fs::OpenOptionsExt;
        let mut file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o755)
            .open(&script_path)
            .with_context(|| {
                format!(
                    "Failed to write statusline script to {}",
                    script_path.display()
                )
            })?;
        file.write_all(script.as_bytes())?;
    }
    #[cfg(not(unix))]
    {
        fs::write(&script_path, &script).with_context(|| {
            format!(
                "Failed to write statusline script to {}",
                script_path.display()
            )
        })?;
    }

    Ok(script_path)
}

/// Extract existing statusLine command from settings, if it's not tmai-managed.
///
/// Returns the command string if a user-defined statusLine exists.
fn detect_existing_statusline(settings: &Value) -> Option<String> {
    let cmd = settings.get("statusLine")?.get("command")?.as_str()?;

    // If it's already our generated script, there's no "existing" tool to preserve
    if cmd.contains("statusline.sh") {
        // Check if the script itself delegates to another tool (parse existing script)
        if let Ok(content) = std::fs::read_to_string(cmd) {
            // Look for "Delegate display to existing statusline tool" + the piped command
            for line in content.lines() {
                if let Some(rest) = line.strip_prefix("echo \"$INPUT\" | ") {
                    let rest = rest.trim();
                    if !rest.is_empty() {
                        return Some(rest.to_string());
                    }
                }
            }
        }
        return None;
    }

    Some(cmd.to_string())
}

/// Set statusLine config to point to tmai's generated script.
fn set_statusline_config(settings: &mut Value, script_path: &std::path::Path) {
    let obj = match settings.as_object_mut() {
        Some(o) => o,
        None => return,
    };

    obj.insert(
        "statusLine".to_string(),
        json!({
            "type": "command",
            "command": script_path.to_string_lossy()
        }),
    );
}

/// Get the Claude Code settings.json path
fn claude_settings_path() -> Result<PathBuf> {
    let home = dirs::home_dir().context("Cannot determine home directory")?;
    Ok(home.join(".claude").join("settings.json"))
}

/// Connection timeout for HTTP hooks in seconds.
/// Short timeout prevents Claude Code from stalling when tmai is not running.
/// 2 seconds is more than enough for localhost connections.
const HOOK_TIMEOUT_SECS: u64 = 2;

/// Build a tmai hook entry for a given event (new wrapper format)
///
/// When `include_tmux_pane` is true, includes `X-Tmai-Pane-Id: $TMUX_PANE` header
/// and `allowedEnvVars`. When false (webui/standalone), omits it to avoid
/// hook errors from undefined environment variable.
fn build_hook_entry(event: &str, token: &str, port: u16, include_tmux_pane: bool) -> Value {
    let mut headers = serde_json::Map::new();
    headers.insert(
        "Authorization".to_string(),
        json!(format!("Bearer {}", token)),
    );
    if include_tmux_pane {
        headers.insert("X-Tmai-Pane-Id".to_string(), json!("$TMUX_PANE"));
    }

    let mut hook = serde_json::Map::new();
    hook.insert("type".to_string(), json!("http"));
    hook.insert(
        "url".to_string(),
        json!(format!("http://localhost:{}/hooks/event", port)),
    );
    hook.insert("headers".to_string(), json!(headers));
    hook.insert("timeout".to_string(), json!(HOOK_TIMEOUT_SECS));
    if include_tmux_pane {
        hook.insert("allowedEnvVars".to_string(), json!(["TMUX_PANE"]));
    }
    hook.insert(
        "statusMessage".to_string(),
        json!(format!("{}{}", TMAI_STATUS_PREFIX, event)),
    );

    json!({ "hooks": [hook] })
}

/// Check if a hook entry belongs to tmai (supports both old and new format)
fn is_tmai_entry(entry: &Value) -> bool {
    // Old format: entry.statusMessage
    if let Some(s) = entry.get("statusMessage").and_then(|v| v.as_str()) {
        if s.starts_with(TMAI_STATUS_PREFIX) {
            return true;
        }
    }
    // New format: entry.hooks[*].statusMessage
    if let Some(hooks) = entry.get("hooks").and_then(|v| v.as_array()) {
        for h in hooks {
            if let Some(s) = h.get("statusMessage").and_then(|v| v.as_str()) {
                if s.starts_with(TMAI_STATUS_PREFIX) {
                    return true;
                }
            }
        }
    }
    false
}

/// Hook events that tmai subscribes to
fn target_events() -> &'static [&'static str] {
    &[
        "SessionStart",
        "UserPromptSubmit",
        "PreToolUse",
        "PostToolUse",
        "Notification",
        "PermissionRequest",
        "Stop",
        "SubagentStart",
        "SubagentStop",
        "TeammateIdle",
        "TaskCreated",
        "TaskCompleted",
        "SessionEnd",
        "ConfigChange",
        "WorktreeCreate",
        "WorktreeRemove",
        "PreCompact",
        "PostToolUseFailure",
        "InstructionsLoaded",
    ]
}

/// Merge tmai hooks into existing settings
///
/// For each target event, adds a tmai hook entry to the event's array.
/// Existing non-tmai entries are preserved. Existing tmai entries are
/// replaced (identified by statusMessage prefix).
fn merge_hooks(settings: &mut Value, token: &str, port: u16, include_tmux_pane: bool) -> usize {
    // Ensure settings is an object
    if !settings.is_object() {
        *settings = json!({});
    }

    let hooks_entry = settings
        .as_object_mut()
        .unwrap()
        .entry("hooks")
        .or_insert_with(|| json!({}));

    // If hooks is not an object, replace it
    if !hooks_entry.is_object() {
        *hooks_entry = json!({});
    }
    let hooks = hooks_entry.as_object_mut().unwrap();

    let mut count = 0;

    for event in target_events() {
        let event_entry = hooks.entry(event.to_string()).or_insert_with(|| json!([]));

        // If event entry is not an array, replace it
        if !event_entry.is_array() {
            *event_entry = json!([]);
        }
        let event_hooks = event_entry.as_array_mut().unwrap();

        // Remove existing tmai entries (old and new format)
        event_hooks.retain(|entry| !is_tmai_entry(entry));

        // Add new tmai entry
        event_hooks.push(build_hook_entry(event, token, port, include_tmux_pane));
        count += 1;
    }

    count
}

/// Remove tmai hooks from settings
/// MCP server name in Claude Code settings
const MCP_SERVER_NAME: &str = "tmai";

/// Get the path to ~/.claude.json (Claude Code user-scope config for MCP servers)
fn claude_json_path() -> Result<PathBuf> {
    let home = dirs::home_dir().context("Cannot determine home directory")?;
    Ok(home.join(".claude.json"))
}

/// Add tmai MCP server to ~/.claude.json (user-scope MCP config).
///
/// Claude Code reads MCP servers from ~/.claude.json, NOT ~/.claude/settings.json.
fn add_mcp_server_to_claude_json() -> Result<bool> {
    let path = claude_json_path()?;

    let mut config: Value = if path.exists() {
        let content = fs::read_to_string(&path)
            .with_context(|| format!("Failed to read {}", path.display()))?;
        serde_json::from_str(&content)
            .with_context(|| format!("Failed to parse {}", path.display()))?
    } else {
        json!({})
    };

    if !config.is_object() {
        config = json!({});
    }

    let mcp_servers = config
        .as_object_mut()
        .unwrap()
        .entry("mcpServers")
        .or_insert_with(|| json!({}));

    if !mcp_servers.is_object() {
        *mcp_servers = json!({});
    }

    let servers = mcp_servers.as_object_mut().unwrap();

    // If a "tmai" entry exists that is NOT tmai-managed, don't overwrite it
    if let Some(existing) = servers.get(MCP_SERVER_NAME) {
        let is_managed = existing
            .get("_tmai_managed")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        if !is_managed {
            return Ok(false);
        }
    }

    // Resolve tmai binary path (use current executable path)
    let tmai_command = std::env::current_exe()
        .ok()
        .and_then(|p| p.to_str().map(|s| s.to_string()))
        .unwrap_or_else(|| "tmai".to_string());

    let entry = json!({
        "type": "stdio",
        "command": tmai_command,
        "args": ["mcp"],
        "_tmai_managed": true
    });

    servers.insert(MCP_SERVER_NAME.to_string(), entry);

    // Write back
    let formatted = serde_json::to_string_pretty(&config)?;
    fs::write(&path, formatted).with_context(|| format!("Failed to write {}", path.display()))?;

    Ok(true)
}

/// Remove tmai MCP server from ~/.claude.json.
fn remove_mcp_server_from_claude_json() -> Result<bool> {
    let path = claude_json_path()?;
    if !path.exists() {
        return Ok(false);
    }

    let content =
        fs::read_to_string(&path).with_context(|| format!("Failed to read {}", path.display()))?;
    let mut config: Value = serde_json::from_str(&content)
        .with_context(|| format!("Failed to parse {}", path.display()))?;

    let Some(mcp_servers) = config.get_mut("mcpServers").and_then(|s| s.as_object_mut()) else {
        return Ok(false);
    };

    let should_remove = mcp_servers
        .get(MCP_SERVER_NAME)
        .and_then(|e| e.get("_tmai_managed"))
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

    if !should_remove {
        return Ok(false);
    }

    mcp_servers.remove(MCP_SERVER_NAME);

    let formatted = serde_json::to_string_pretty(&config)?;
    fs::write(&path, formatted).with_context(|| format!("Failed to write {}", path.display()))?;

    Ok(true)
}

/// Helper for tests: merge MCP server into a Value (does not touch filesystem)
#[cfg(test)]
fn merge_mcp_server(settings: &mut Value) -> bool {
    if !settings.is_object() {
        *settings = json!({});
    }
    let mcp_servers = settings
        .as_object_mut()
        .unwrap()
        .entry("mcpServers")
        .or_insert_with(|| json!({}));
    if !mcp_servers.is_object() {
        *mcp_servers = json!({});
    }
    let servers = mcp_servers.as_object_mut().unwrap();
    if let Some(existing) = servers.get(MCP_SERVER_NAME) {
        if !existing
            .get("_tmai_managed")
            .and_then(|v| v.as_bool())
            .unwrap_or(false)
        {
            return false;
        }
    }
    servers.insert(
        MCP_SERVER_NAME.to_string(),
        json!({"type": "stdio", "command": "tmai", "args": ["mcp"], "_tmai_managed": true}),
    );
    true
}

/// Helper for tests: remove MCP server from a Value (does not touch filesystem)
#[cfg(test)]
fn remove_mcp_server(settings: &mut Value) -> bool {
    let Some(mcp_servers) = settings
        .get_mut("mcpServers")
        .and_then(|s| s.as_object_mut())
    else {
        return false;
    };
    if !mcp_servers
        .get(MCP_SERVER_NAME)
        .and_then(|e| e.get("_tmai_managed"))
        .and_then(|v| v.as_bool())
        .unwrap_or(false)
    {
        return false;
    }
    mcp_servers.remove(MCP_SERVER_NAME);
    true
}

fn remove_tmai_hooks(settings: &mut Value) -> usize {
    let Some(hooks) = settings.get_mut("hooks").and_then(|h| h.as_object_mut()) else {
        return 0;
    };

    let mut removed = 0;

    for (_event, entries) in hooks.iter_mut() {
        if let Some(arr) = entries.as_array_mut() {
            let before = arr.len();
            arr.retain(|entry| !is_tmai_entry(entry));
            removed += before - arr.len();
        }
    }

    removed
}

/// Run the `tmai uninit` command — remove tmai hooks from Claude Code settings
pub fn run_uninit() -> Result<()> {
    println!("tmai uninit — Removing Claude Code hooks integration\n");

    // Read existing Claude Code settings
    let settings_path = claude_settings_path()?;
    if !settings_path.exists() {
        println!("No settings file found at {}", settings_path.display());
        println!("Nothing to remove.");
        return Ok(());
    }

    let content = fs::read_to_string(&settings_path)
        .with_context(|| format!("Failed to read {}", settings_path.display()))?;
    let mut settings: Value = serde_json::from_str(&content)
        .with_context(|| format!("Failed to parse {}", settings_path.display()))?;

    // Remove tmai hooks
    let removed = remove_tmai_hooks(&mut settings);

    // Remove tmai MCP server from ~/.claude.json
    let mcp_removed = remove_mcp_server_from_claude_json().unwrap_or(false);

    // Remove statusLine config if it points to our script
    let mut statusline_removed = false;
    if let Some(obj) = settings.as_object_mut() {
        if let Some(sl) = obj.get("statusLine") {
            if sl
                .get("command")
                .and_then(|v| v.as_str())
                .is_some_and(|cmd| cmd.contains("statusline.sh"))
            {
                obj.remove("statusLine");
                statusline_removed = true;
            }
        }
    }

    if removed > 0 || statusline_removed || mcp_removed {
        // Write back settings if anything was removed
        let formatted = serde_json::to_string_pretty(&settings)?;
        fs::write(&settings_path, formatted)
            .with_context(|| format!("Failed to write {}", settings_path.display()))?;

        if removed > 0 {
            println!(
                "Removed {} tmai hook entries from {}",
                removed,
                settings_path.display()
            );
        }
        if mcp_removed {
            println!("Removed tmai MCP server from mcpServers");
        }
        if statusline_removed {
            println!("Removed statusLine config from {}", settings_path.display());
        }
    } else {
        println!("No tmai entries found in {}", settings_path.display());
    }

    // Remove statusline.sh script
    if let Some(home) = dirs::home_dir() {
        let script_path = home.join(".claude").join("statusline.sh");
        if script_path.exists() {
            fs::remove_file(&script_path)
                .with_context(|| format!("Failed to remove {}", script_path.display()))?;
            println!("Removed statusline script: {}", script_path.display());
        }
    }

    // Always attempt to remove the token file, even if no hook entries were found
    if let Ok(token_path) = hooks_token_path() {
        if token_path.exists() {
            fs::remove_file(&token_path)
                .with_context(|| format!("Failed to remove {}", token_path.display()))?;
            println!("Removed hook token: {}", token_path.display());
        }
    }

    println!("\nDone! tmai hooks have been removed from Claude Code settings.");
    Ok(())
}

/// Run the `tmai init` command
pub fn run(force: bool) -> Result<()> {
    println!("tmai init — Setting up Claude Code hooks integration\n");

    // Load tmai settings to get the configured web port
    let tmai_settings = tmai_core::config::Settings::load(None::<&std::path::PathBuf>)
        .context("Failed to load tmai settings for hook setup")?;
    let port = tmai_settings.web.port;

    // Step 1: Ensure hook token
    let token = ensure_hook_token(force)?;

    // Step 2: Read existing Claude Code settings
    let settings_path = claude_settings_path()?;
    let mut settings: Value = if settings_path.exists() {
        let content = fs::read_to_string(&settings_path)
            .with_context(|| format!("Failed to read {}", settings_path.display()))?;
        serde_json::from_str(&content)
            .with_context(|| format!("Failed to parse {}", settings_path.display()))?
    } else {
        json!({})
    };

    // Step 3: Merge tmai hooks
    // Include $TMUX_PANE header only when tmux is available;
    // in webui mode, pane_id is resolved via session_id/cwd fallback
    let include_tmux_pane = std::env::var("TMUX").is_ok();
    if !include_tmux_pane {
        println!("Note: tmux not detected — hooks will use session_id for agent matching");
    }
    let count = merge_hooks(&mut settings, &token, port, include_tmux_pane);

    // Step 3b: Generate statusline.sh (preserving existing statusline tool if present)
    let existing_cmd = detect_existing_statusline(&settings);
    if let Some(ref cmd) = existing_cmd {
        println!("Detected existing statusLine command: {cmd}");
        println!("  → tmai will forward data to tmai AND delegate display to this command");
    }
    let statusline_path =
        generate_statusline_script(&token, port, include_tmux_pane, existing_cmd.as_deref())?;
    set_statusline_config(&mut settings, &statusline_path);
    println!("Generated statusline script: {}", statusline_path.display());

    // Step 3c: Add MCP server to ~/.claude.json (separate from hooks settings)
    let mcp_added = add_mcp_server_to_claude_json().unwrap_or(false);

    // Step 4: Write back settings (hooks + statusline to ~/.claude/settings.json)
    if let Some(parent) = settings_path.parent() {
        fs::create_dir_all(parent)?;
    }
    let formatted = serde_json::to_string_pretty(&settings)?;
    fs::write(&settings_path, formatted)
        .with_context(|| format!("Failed to write {}", settings_path.display()))?;

    println!(
        "Added {} hook entries to {}",
        count,
        settings_path.display()
    );
    if mcp_added {
        println!("Added tmai MCP server to ~/.claude.json");
    }

    // Clean up legacy MCP entry from ~/.claude/settings.json (was incorrectly placed there before)
    if let Some(obj) = settings.as_object_mut() {
        if let Some(mcp) = obj.get_mut("mcpServers").and_then(|m| m.as_object_mut()) {
            if mcp
                .get("tmai")
                .and_then(|e| e.get("_tmai_managed"))
                .and_then(|v| v.as_bool())
                .unwrap_or(false)
            {
                mcp.remove("tmai");
                // Re-write settings to remove the legacy entry
                let formatted = serde_json::to_string_pretty(&settings)?;
                fs::write(&settings_path, formatted)
                    .with_context(|| format!("Failed to write {}", settings_path.display()))?;
                println!(
                    "Cleaned up legacy MCP entry from {}",
                    settings_path.display()
                );
            }
        }
    }
    println!("\nSetup complete! tmai will now receive hook events from Claude Code.");
    println!(
        "Make sure to start tmai with web server enabled (port {}).",
        port
    );

    Ok(())
}

/// Get the Codex CLI config.toml path
fn codex_config_path() -> Result<PathBuf> {
    let home = dirs::home_dir().context("Cannot determine home directory")?;
    Ok(home.join(".codex").join("config.toml"))
}

/// Codex hook events that tmai subscribes to
fn codex_target_events() -> &'static [&'static str] {
    &["SessionStart", "Stop", "AfterAgent", "AfterToolUse"]
}

/// Marker comment used to identify tmai-generated hook entries in Codex config
const TMAI_CODEX_MARKER: &str = "# tmai-managed";

/// Check if an existing Codex hook entry was created by tmai.
///
/// Uses two heuristics (either is sufficient):
/// 1. TOML comment suffix contains the marker `# tmai-managed`
/// 2. Command string ends with `codex-hook` (survives comment stripping by formatters)
fn is_tmai_codex_entry(item: &toml_edit::Item) -> bool {
    // Check marker comment in TOML suffix
    let has_marker = item
        .as_value()
        .and_then(|val| val.decor().suffix())
        .and_then(|s| s.as_str())
        .is_some_and(|s| s.contains(TMAI_CODEX_MARKER));
    if has_marker {
        return true;
    }

    // Fallback: check if the command string itself points to tmai codex-hook
    item.as_str()
        .is_some_and(|s| s.trim_end().ends_with("codex-hook"))
}

/// Run the `tmai init --codex` command — configure Codex CLI hooks
pub fn run_codex_init(force: bool) -> Result<()> {
    println!("\nConfiguring Codex CLI hooks integration...\n");

    let config_path = codex_config_path()?;

    // Read existing config or start fresh
    let existing = if config_path.exists() {
        fs::read_to_string(&config_path)
            .with_context(|| format!("Failed to read {}", config_path.display()))?
    } else {
        String::new()
    };

    // Parse as TOML document (preserving formatting)
    // Bail on parse error to avoid silently wiping user's config
    let mut doc = existing
        .parse::<toml_edit::DocumentMut>()
        .with_context(|| {
            format!(
                "Failed to parse {} — fix the TOML syntax and retry",
                config_path.display()
            )
        })?;

    // Find the tmai binary path
    let tmai_bin = std::env::current_exe()
        .context("Cannot determine tmai binary path")?
        .to_string_lossy()
        .to_string();

    // Build hook entries for each target event
    // Codex hooks format in config.toml:
    //   [hooks]
    //   SessionStart = "tmai codex-hook"
    //   Stop = "tmai codex-hook"
    //   AfterAgent = "tmai codex-hook"
    //   AfterToolUse = "tmai codex-hook"
    if !doc.contains_table("hooks") {
        doc["hooks"] = toml_edit::Item::Table(toml_edit::Table::new());
    }

    let hooks = doc["hooks"].as_table_mut().unwrap();
    // Quote the binary path for shell safety (Codex spawns hooks via shell)
    let hook_command = if tmai_bin.contains(' ') || tmai_bin.contains('\'') {
        // Use double quotes; escape any existing double quotes in the path
        format!("\"{}\" codex-hook", tmai_bin.replace('"', "\\\""))
    } else {
        format!("{} codex-hook", tmai_bin)
    };
    let mut count = 0;

    for event in codex_target_events() {
        // Skip existing non-tmai entries unless --force is passed
        if let Some(existing_item) = hooks.get(event) {
            if !is_tmai_codex_entry(existing_item) && !force {
                println!(
                    "  Skipping {} — existing user-managed hook (use --force to overwrite)",
                    event
                );
                continue;
            }
        }

        // Set the hook command with a tmai marker comment
        let mut value = toml_edit::value(hook_command.clone());
        value
            .as_value_mut()
            .unwrap()
            .decor_mut()
            .set_suffix(format!(" {}", TMAI_CODEX_MARKER));
        hooks[event] = value;
        count += 1;
    }

    // Write back
    if let Some(parent) = config_path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&config_path, doc.to_string())
        .with_context(|| format!("Failed to write {}", config_path.display()))?;

    println!("Added {} hook entries to {}", count, config_path.display());
    println!("Codex CLI will now forward hook events to tmai via `tmai codex-hook`.");

    Ok(())
}

/// Run the `tmai uninit --codex` command — remove tmai hooks from Codex config
pub fn run_codex_uninit() -> Result<()> {
    let config_path = codex_config_path()?;
    if !config_path.exists() {
        println!("No Codex config found at {}", config_path.display());
        return Ok(());
    }

    let content = fs::read_to_string(&config_path)
        .with_context(|| format!("Failed to read {}", config_path.display()))?;

    let mut doc: toml_edit::DocumentMut = content.parse().with_context(|| {
        format!(
            "Failed to parse {} — fix the TOML syntax and retry",
            config_path.display()
        )
    })?;

    if let Some(hooks) = doc.get_mut("hooks").and_then(|h| h.as_table_mut()) {
        let mut removed = 0;
        for event in codex_target_events() {
            if hooks.get(event).is_some_and(is_tmai_codex_entry) {
                hooks.remove(event);
                removed += 1;
            }
        }

        if removed > 0 {
            fs::write(&config_path, doc.to_string())
                .with_context(|| format!("Failed to write {}", config_path.display()))?;
            println!(
                "Removed {} tmai hook entries from {}",
                removed,
                config_path.display()
            );
        } else {
            println!("No tmai hook entries found in {}", config_path.display());
        }
    }

    Ok(())
}

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

    #[test]
    fn test_build_hook_entry() {
        let entry = build_hook_entry("PreToolUse", "test-token", 9876, true);
        // New format: wrapper with hooks array
        let hooks = entry["hooks"].as_array().unwrap();
        assert_eq!(hooks.len(), 1);
        assert_eq!(hooks[0]["type"], "http");
        assert_eq!(hooks[0]["url"], "http://localhost:9876/hooks/event");
        assert_eq!(hooks[0]["headers"]["Authorization"], "Bearer test-token");
        assert_eq!(hooks[0]["headers"]["X-Tmai-Pane-Id"], "$TMUX_PANE");
        assert_eq!(hooks[0]["statusMessage"], "tmai: PreToolUse");
        assert_eq!(hooks[0]["timeout"], HOOK_TIMEOUT_SECS);
    }

    #[test]
    fn test_build_hook_entry_without_tmux_pane() {
        let entry = build_hook_entry("PostToolUse", "test-token", 9876, false);
        let hooks = entry["hooks"].as_array().unwrap();
        assert_eq!(hooks[0]["headers"]["Authorization"], "Bearer test-token");
        // No TMUX_PANE header or allowedEnvVars
        assert!(hooks[0]["headers"].get("X-Tmai-Pane-Id").is_none());
        assert!(hooks[0].get("allowedEnvVars").is_none());
    }

    #[test]
    fn test_merge_hooks_empty_settings() {
        let mut settings = json!({});
        let count = merge_hooks(&mut settings, "token-123", 9876, true);
        assert_eq!(count, target_events().len());

        // Verify hooks structure (new wrapper format)
        let hooks = settings["hooks"].as_object().unwrap();
        for event in target_events() {
            let entries = hooks[*event].as_array().unwrap();
            assert_eq!(entries.len(), 1);
            assert_eq!(
                entries[0]["hooks"][0]["statusMessage"],
                format!("tmai: {}", event)
            );
        }
    }

    #[test]
    fn test_merge_hooks_preserves_existing() {
        let mut settings = json!({
            "hooks": {
                "PreToolUse": [
                    {
                        "type": "command",
                        "command": "echo pre-tool",
                        "statusMessage": "user: pre-tool"
                    }
                ]
            }
        });

        merge_hooks(&mut settings, "token-123", 9876, true);

        // Existing entry should be preserved
        let pre_tool = settings["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(pre_tool.len(), 2);
        assert_eq!(pre_tool[0]["statusMessage"], "user: pre-tool");
        // New tmai entry is in wrapper format
        assert!(pre_tool[1]["hooks"][0]["statusMessage"]
            .as_str()
            .unwrap()
            .starts_with("tmai: "));
    }

    #[test]
    fn test_merge_hooks_replaces_existing_tmai_old_format() {
        // Old format tmai entry (statusMessage at top level)
        let mut settings = json!({
            "hooks": {
                "PreToolUse": [
                    {
                        "type": "http",
                        "url": "http://localhost:9876/hooks/event",
                        "statusMessage": "tmai: PreToolUse"
                    },
                    {
                        "type": "command",
                        "command": "echo other",
                        "statusMessage": "other: test"
                    }
                ]
            }
        });

        merge_hooks(&mut settings, "new-token", 9876, true);

        let pre_tool = settings["hooks"]["PreToolUse"].as_array().unwrap();
        // Should have 2: the "other" one + the new tmai one (old tmai replaced)
        assert_eq!(pre_tool.len(), 2);
        assert_eq!(pre_tool[0]["statusMessage"], "other: test");
        // New entry uses wrapper format
        assert_eq!(
            pre_tool[1]["hooks"][0]["headers"]["Authorization"],
            "Bearer new-token"
        );
    }

    #[test]
    fn test_merge_hooks_replaces_existing_tmai_new_format() {
        // New format tmai entry (statusMessage inside hooks array)
        let mut settings = json!({
            "hooks": {
                "PreToolUse": [
                    {
                        "hooks": [{
                            "type": "http",
                            "url": "http://localhost:9876/hooks/event",
                            "statusMessage": "tmai: PreToolUse"
                        }]
                    },
                    {
                        "hooks": [{
                            "type": "command",
                            "command": "echo other",
                            "statusMessage": "other: test"
                        }]
                    }
                ]
            }
        });

        merge_hooks(&mut settings, "new-token", 9876, true);

        let pre_tool = settings["hooks"]["PreToolUse"].as_array().unwrap();
        // Should have 2: the non-tmai wrapper + the new tmai wrapper
        assert_eq!(pre_tool.len(), 2);
        assert_eq!(pre_tool[0]["hooks"][0]["statusMessage"], "other: test");
        assert_eq!(
            pre_tool[1]["hooks"][0]["headers"]["Authorization"],
            "Bearer new-token"
        );
    }

    #[test]
    fn test_remove_tmai_hooks_old_format() {
        let mut settings = json!({
            "hooks": {
                "PreToolUse": [
                    {"statusMessage": "tmai: PreToolUse"},
                    {"statusMessage": "other: test"}
                ],
                "Stop": [
                    {"statusMessage": "tmai: Stop"}
                ]
            }
        });

        let removed = remove_tmai_hooks(&mut settings);
        assert_eq!(removed, 2);

        let pre_tool = settings["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(pre_tool.len(), 1);
        assert_eq!(pre_tool[0]["statusMessage"], "other: test");

        let stop = settings["hooks"]["Stop"].as_array().unwrap();
        assert_eq!(stop.len(), 0);
    }

    #[test]
    fn test_remove_tmai_hooks_new_format() {
        let mut settings = json!({
            "hooks": {
                "PreToolUse": [
                    {"hooks": [{"statusMessage": "tmai: PreToolUse"}]},
                    {"hooks": [{"statusMessage": "other: test"}]}
                ],
                "Stop": [
                    {"hooks": [{"statusMessage": "tmai: Stop"}]}
                ]
            }
        });

        let removed = remove_tmai_hooks(&mut settings);
        assert_eq!(removed, 2);

        let pre_tool = settings["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(pre_tool.len(), 1);
        assert_eq!(pre_tool[0]["hooks"][0]["statusMessage"], "other: test");

        let stop = settings["hooks"]["Stop"].as_array().unwrap();
        assert_eq!(stop.len(), 0);
    }

    #[test]
    fn test_remove_tmai_hooks_mixed_formats() {
        // Settings with both old and new format tmai entries
        let mut settings = json!({
            "hooks": {
                "PreToolUse": [
                    {"statusMessage": "tmai: PreToolUse"},
                    {"hooks": [{"statusMessage": "tmai: PreToolUse"}]},
                    {"statusMessage": "other: test"}
                ]
            }
        });

        let removed = remove_tmai_hooks(&mut settings);
        assert_eq!(removed, 2);

        let pre_tool = settings["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(pre_tool.len(), 1);
        assert_eq!(pre_tool[0]["statusMessage"], "other: test");
    }

    #[test]
    fn test_target_events_count() {
        // Should have 19 target events
        assert_eq!(target_events().len(), 19);
    }

    #[test]
    fn test_remove_tmai_hooks_no_hooks_section() {
        let mut settings = json!({ "other": "value" });
        let removed = remove_tmai_hooks(&mut settings);
        assert_eq!(removed, 0);
    }

    #[test]
    fn test_remove_tmai_hooks_empty_hooks() {
        let mut settings = json!({ "hooks": {} });
        let removed = remove_tmai_hooks(&mut settings);
        assert_eq!(removed, 0);
    }

    #[test]
    fn test_is_tmai_entry_old_format() {
        let entry = json!({"type": "http", "statusMessage": "tmai: PreToolUse"});
        assert!(is_tmai_entry(&entry));
    }

    #[test]
    fn test_is_tmai_entry_new_format() {
        let entry = json!({"hooks": [{"type": "http", "statusMessage": "tmai: PreToolUse"}]});
        assert!(is_tmai_entry(&entry));
    }

    #[test]
    fn test_is_tmai_entry_non_tmai() {
        let entry = json!({"type": "command", "statusMessage": "other: test"});
        assert!(!is_tmai_entry(&entry));

        let entry = json!({"hooks": [{"statusMessage": "other: test"}]});
        assert!(!is_tmai_entry(&entry));

        let entry = json!({"hooks": []});
        assert!(!is_tmai_entry(&entry));
    }

    #[test]
    fn test_migration_old_to_new_format() {
        // Simulate settings with old-format tmai entries
        let mut settings = json!({
            "hooks": {
                "PreToolUse": [
                    {
                        "type": "http",
                        "url": "http://localhost:9876/hooks/event",
                        "headers": {"Authorization": "Bearer old-token"},
                        "statusMessage": "tmai: PreToolUse"
                    }
                ],
                "Stop": [
                    {
                        "type": "http",
                        "url": "http://localhost:9876/hooks/event",
                        "headers": {"Authorization": "Bearer old-token"},
                        "statusMessage": "tmai: Stop"
                    },
                    {
                        "type": "command",
                        "command": "echo user-hook",
                        "statusMessage": "user: stop-hook"
                    }
                ]
            }
        });

        // Merge with new token — should replace old-format entries with new-format
        merge_hooks(&mut settings, "new-token", 9876, true);

        // PreToolUse: old entry removed, new wrapper entry added
        let pre_tool = settings["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(pre_tool.len(), 1);
        assert_eq!(
            pre_tool[0]["hooks"][0]["headers"]["Authorization"],
            "Bearer new-token"
        );
        // No top-level statusMessage (that was old format)
        assert!(pre_tool[0].get("statusMessage").is_none());

        // Stop: user entry preserved, old tmai replaced with new format
        let stop = settings["hooks"]["Stop"].as_array().unwrap();
        assert_eq!(stop.len(), 2);
        assert_eq!(stop[0]["statusMessage"], "user: stop-hook");
        assert_eq!(
            stop[1]["hooks"][0]["headers"]["Authorization"],
            "Bearer new-token"
        );
    }

    #[test]
    fn test_merge_mcp_server_empty_settings() {
        let mut settings = json!({});
        let added = merge_mcp_server(&mut settings);
        assert!(added);

        let mcp = settings["mcpServers"]["tmai"].as_object().unwrap();
        assert!(mcp.contains_key("command"));
        assert_eq!(mcp["args"], json!(["mcp"]));
        assert_eq!(mcp["_tmai_managed"], json!(true));
    }

    #[test]
    fn test_merge_mcp_server_preserves_others() {
        let mut settings = json!({
            "mcpServers": {
                "other-server": {"command": "other", "args": []}
            }
        });
        merge_mcp_server(&mut settings);

        assert!(settings["mcpServers"]["other-server"].is_object());
        assert!(settings["mcpServers"]["tmai"].is_object());
    }

    #[test]
    fn test_remove_mcp_server() {
        let mut settings = json!({
            "mcpServers": {
                "tmai": {"command": "tmai", "args": ["mcp"], "_tmai_managed": true},
                "other": {"command": "other"}
            }
        });
        let removed = remove_mcp_server(&mut settings);
        assert!(removed);
        assert!(!settings["mcpServers"]
            .as_object()
            .unwrap()
            .contains_key("tmai"));
        assert!(settings["mcpServers"]
            .as_object()
            .unwrap()
            .contains_key("other"));
    }

    #[test]
    fn test_remove_mcp_server_not_managed() {
        let mut settings = json!({
            "mcpServers": {
                "tmai": {"command": "custom-tmai", "args": ["custom"]}
            }
        });
        let removed = remove_mcp_server(&mut settings);
        assert!(!removed);
        // Should NOT remove user-defined tmai entry
        assert!(settings["mcpServers"]
            .as_object()
            .unwrap()
            .contains_key("tmai"));
    }

    #[test]
    fn test_merge_mcp_server_skips_user_defined() {
        let mut settings = json!({
            "mcpServers": {
                "tmai": {"command": "custom-tmai", "args": ["custom-arg"]}
            }
        });
        let added = merge_mcp_server(&mut settings);
        assert!(!added);
        // Should NOT overwrite user-defined entry
        assert_eq!(settings["mcpServers"]["tmai"]["command"], "custom-tmai");
        assert_eq!(
            settings["mcpServers"]["tmai"]["args"],
            json!(["custom-arg"])
        );
    }

    #[test]
    fn test_merge_mcp_server_updates_managed() {
        let mut settings = json!({
            "mcpServers": {
                "tmai": {"command": "old-path", "args": ["mcp"], "_tmai_managed": true}
            }
        });
        let added = merge_mcp_server(&mut settings);
        assert!(added);
        // Should update the managed entry (new binary path)
        assert_ne!(settings["mcpServers"]["tmai"]["command"], "old-path");
        assert_eq!(settings["mcpServers"]["tmai"]["_tmai_managed"], true);
    }
}