coding-agent-search 0.5.1

Unified TUI search over local coding agent histories
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
//! Smart filename generation for HTML exports.
//!
//! Generates cross-platform safe filenames from session metadata,
//! ensuring compatibility with Windows, macOS, and Linux filesystems.
//!
//! # Features
//!
//! - **Cross-platform safety**: Handles Windows reserved names, invalid characters
//! - **Smart downloads detection**: Finds platform-specific downloads folder
//! - **Collision handling**: Automatic numeric suffixes for duplicate names
//! - **Agent normalization**: Canonical slugs for all supported agents
//! - **Topic support**: Robot mode can specify intelligent topic names

use std::path::{Path, PathBuf};

use tracing::{debug, trace};

/// Options for filename generation.
#[derive(Debug, Clone, Default)]
pub struct FilenameOptions {
    /// Include date in filename
    pub include_date: bool,

    /// Include agent name in filename
    pub include_agent: bool,

    /// Include project name in filename
    pub include_project: bool,

    /// Include topic in filename (if provided)
    pub include_topic: bool,

    /// Maximum filename length (excluding extension)
    pub max_length: Option<usize>,

    /// Custom prefix
    pub prefix: Option<String>,

    /// Custom suffix (before extension)
    pub suffix: Option<String>,
}

/// Metadata for filename generation.
#[derive(Debug, Clone, Default)]
pub struct FilenameMetadata {
    /// Session title or ID
    pub title: Option<String>,

    /// ISO date (YYYY-MM-DD)
    pub date: Option<String>,

    /// Agent name (claude, codex, etc.)
    pub agent: Option<String>,

    /// Project name
    pub project: Option<String>,

    /// Topic provided by calling agent (robot mode).
    /// Will be normalized to lowercase with underscores.
    pub topic: Option<String>,
}

/// Normalize a topic string to lowercase with underscores.
///
/// This is the canonical way to convert a user-provided topic
/// into the format expected by CASS filenames:
/// - Converts to lowercase
/// - Replaces spaces with underscores
/// - Removes invalid characters
/// - Collapses multiple underscores
///
/// # Examples
/// ```
/// use coding_agent_search::html_export::normalize_topic;
/// assert_eq!(normalize_topic("My Cool Topic"), "my_cool_topic");
/// assert_eq!(normalize_topic("HTML Export Feature"), "html_export_feature");
/// ```
pub fn normalize_topic(topic: &str) -> String {
    sanitize(topic)
}

/// Generate a safe, descriptive filename.
///
/// Returns a filename without extension (add .html manually).
pub fn generate_filename(metadata: &FilenameMetadata, options: &FilenameOptions) -> String {
    let mut parts = Vec::new();

    // Add prefix
    if let Some(prefix) = &options.prefix {
        push_part(&mut parts, prefix);
    }

    // Add date
    if options.include_date
        && let Some(date) = &metadata.date
    {
        push_part(&mut parts, date);
    }

    // Add agent
    if options.include_agent
        && let Some(agent) = &metadata.agent
    {
        push_part(&mut parts, agent);
    }

    // Add project
    if options.include_project
        && let Some(project) = &metadata.project
    {
        push_part(&mut parts, project);
    }

    // Add topic (robot mode can supply this for intelligent naming)
    if options.include_topic
        && let Some(topic) = &metadata.topic
    {
        let normalized = normalize_topic(topic);
        if !normalized.is_empty() {
            parts.push(normalized);
        }
    }

    // Add title (always included if present)
    if let Some(title) = &metadata.title {
        push_part(&mut parts, title);
    }

    // Add suffix
    if let Some(suffix) = &options.suffix {
        push_part(&mut parts, suffix);
    }

    // Combine parts
    let filename = if parts.is_empty() {
        "session".to_string()
    } else {
        parts.join("_")
    };

    let final_name = finalize_filename(filename, options.max_length);
    debug!(
        component = "file",
        operation = "generate_filename",
        parts = parts.len(),
        max_length = options.max_length.unwrap_or(0),
        result_len = final_name.len(),
        "Generated filename"
    );
    final_name
}

/// Generate a filename with path.
pub fn generate_filepath(
    base_dir: &std::path::Path,
    metadata: &FilenameMetadata,
    options: &FilenameOptions,
) -> PathBuf {
    let ext = ".html";
    let base_max = MAX_FILENAME_LEN.saturating_sub(ext.len());
    let mut adjusted = options.clone();
    adjusted.max_length = Some(match options.max_length {
        Some(user_max) => user_max.min(base_max).max(1),
        None => base_max,
    });
    let filename = generate_filename(metadata, &adjusted);
    let path = base_dir.join(format!("{filename}{ext}"));
    debug!(
        component = "file",
        operation = "generate_filepath",
        path = %path.display(),
        "Generated filepath"
    );
    path
}

/// Sanitize a string for use in filenames.
///
/// - Replaces invalid characters with underscores
/// - Removes leading/trailing whitespace
/// - Collapses multiple underscores
/// - Limits to ASCII alphanumeric plus safe punctuation
fn sanitize(s: &str) -> String {
    let mut result = String::new();
    let mut last_was_underscore = false;

    for c in s.chars() {
        if c.is_ascii_alphanumeric() || c == '-' {
            result.push(c.to_ascii_lowercase());
            last_was_underscore = false;
        } else if c == ' ' || c == '_' || c == '.' || c == '/' || c == '\\' {
            // Replace separators with underscore, avoiding duplicates
            if !last_was_underscore && !result.is_empty() {
                result.push('_');
                last_was_underscore = true;
            }
        }
        // Skip other characters
    }

    // Trim leading/trailing underscores
    result.trim_matches('_').to_string()
}

/// Push a sanitized part if it is non-empty.
fn push_part(parts: &mut Vec<String>, raw: &str) {
    let sanitized = sanitize(raw);
    if !sanitized.is_empty() {
        parts.push(sanitized);
    }
}

const MAX_FILENAME_LEN: usize = 255;

/// Finalize a filename by enforcing length limits and avoiding reserved names.
fn finalize_filename(mut name: String, max_len: Option<usize>) -> String {
    if name.is_empty() {
        name = "session".to_string();
    }

    name = trim_separators(&name);
    if name.is_empty() {
        name = "session".to_string();
    }

    name = enforce_max_len(name, max_len);
    name = avoid_reserved_name(name);
    name = enforce_max_len(name, max_len);

    name = trim_separators(&name);
    if name.is_empty() {
        "session".to_string()
    } else {
        name
    }
}

fn enforce_max_len(mut name: String, max_len: Option<usize>) -> String {
    let limit = max_len
        .unwrap_or(MAX_FILENAME_LEN)
        .clamp(1, MAX_FILENAME_LEN);
    if name.len() > limit {
        // Safe truncation at char boundary to avoid panic on multi-byte UTF-8
        let safe_limit = truncate_to_char_boundary(&name, limit);
        name.truncate(safe_limit);
        name = trim_separators(&name);
    }
    name
}

/// Find the largest byte index <= `max_bytes` that is on a UTF-8 char boundary.
fn truncate_to_char_boundary(s: &str, max_bytes: usize) -> usize {
    if max_bytes >= s.len() {
        return s.len();
    }
    // Walk backwards from max_bytes to find a char boundary
    let mut end = max_bytes;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    end
}

fn trim_separators(name: &str) -> String {
    name.trim_matches(|c| c == '_' || c == '-').to_string()
}

fn avoid_reserved_name(name: String) -> String {
    if is_reserved_basename(&name) {
        format!("session_{}", name)
    } else {
        name
    }
}

fn is_reserved_basename(name: &str) -> bool {
    let upper = name.to_ascii_uppercase();
    let base_name = upper.split('.').next().unwrap_or(&upper);
    RESERVED_NAMES.contains(&base_name)
}

/// Characters that are invalid in filenames across platforms.
const INVALID_CHARS: &[char] = &[
    '<', '>', ':', '"', '/', '\\', '|', '?', '*', '\0', '\n', '\r', '\t',
];

/// Reserved filenames on Windows.
const RESERVED_NAMES: &[&str] = &[
    "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8",
    "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
];

/// Check if a filename is valid across platforms.
pub fn is_valid_filename(name: &str) -> bool {
    if name.is_empty() {
        return false;
    }

    // Check for invalid characters
    if name.chars().any(|c| INVALID_CHARS.contains(&c)) {
        return false;
    }

    // Check for reserved names (Windows)
    let upper = name.to_ascii_uppercase();
    let base_name = upper.split('.').next().unwrap_or(&upper);
    if RESERVED_NAMES.contains(&base_name) {
        return false;
    }

    // Check for leading/trailing spaces or dots
    if name.starts_with(' ') || name.starts_with('.') || name.ends_with(' ') || name.ends_with('.')
    {
        return false;
    }

    // Check length (Windows MAX_PATH is 260, but NTFS supports 255 per component)
    if name.len() > 255 {
        return false;
    }

    true
}

// ============================================================================
// Platform-specific downloads folder detection
// ============================================================================

/// Get the default export directory.
///
/// Returns the current working directory as the default.
/// This is more intuitive for CLI usage where exports should go
/// where the user is working.
pub fn get_downloads_dir() -> PathBuf {
    // Primary: Current working directory (most intuitive for CLI usage)
    std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
}

/// Generate a unique filename that doesn't collide with existing files.
///
/// If the base filename exists, appends numeric suffixes: `file_1.html`, `file_2.html`, etc.
/// As an ultimate fallback, appends a timestamp.
pub fn unique_filename(dir: &Path, base_filename: &str) -> PathBuf {
    let base_filename = safe_unique_base_filename(base_filename);
    let path = dir.join(&base_filename);
    if !filename_path_is_occupied(&path) {
        return path;
    }

    // Extract stem and extension
    let (stem, ext) = if let Some(dot_pos) = base_filename.rfind('.') {
        (&base_filename[..dot_pos], &base_filename[dot_pos..])
    } else {
        (base_filename.as_str(), "")
    };

    // Try numeric suffixes
    for i in 1..1000 {
        let suffix = format!("_{i}");
        let new_name = unique_candidate_filename(stem, ext, &suffix);
        let new_path = dir.join(&new_name);
        if !filename_path_is_occupied(&new_path) {
            trace!(
                component = "file",
                operation = "collision_check",
                attempts = i,
                path = %new_path.display(),
                "Resolved filename collision"
            );
            return new_path;
        }
    }

    // Ultimate fallback: high-resolution timestamp with bounded collision probes.
    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    unique_timestamp_fallback_filename(dir, stem, ext, ts)
}

fn unique_timestamp_fallback_filename(dir: &Path, stem: &str, ext: &str, ts: u128) -> PathBuf {
    for attempt in 0..1000 {
        let suffix = if attempt == 0 {
            format!("_{ts}")
        } else {
            format!("_{ts}_{attempt}")
        };
        let fallback = dir.join(unique_candidate_filename(stem, ext, &suffix));
        if !filename_path_is_occupied(&fallback) {
            trace!(
                component = "file",
                operation = "collision_fallback",
                attempts = attempt,
                path = %fallback.display(),
                "Resolved filename via timestamp"
            );
            return fallback;
        }
    }

    let suffix = format!("_{}_{}", ts, std::process::id());
    dir.join(unique_candidate_filename(stem, ext, &suffix))
}

fn filename_path_is_occupied(path: &Path) -> bool {
    match std::fs::symlink_metadata(path) {
        Ok(_) => true,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => false,
        Err(_) => true,
    }
}

fn unique_candidate_filename(stem: &str, ext: &str, suffix: &str) -> String {
    let ext = bounded_extension_for_collision_candidate(ext, suffix.len());
    let reserved_len = suffix.len().saturating_add(ext.len());
    let max_stem_len = MAX_FILENAME_LEN.saturating_sub(reserved_len).max(1);
    let mut candidate_stem = if stem.len() > max_stem_len {
        let safe_end = truncate_to_char_boundary(stem, max_stem_len);
        trim_separators(&stem[..safe_end])
    } else {
        trim_separators(stem)
    };
    if candidate_stem.is_empty() {
        let safe_end = truncate_to_char_boundary("session", max_stem_len);
        candidate_stem = "session"[..safe_end].to_string();
    }
    format!("{candidate_stem}{suffix}{ext}")
}

fn bounded_extension_for_collision_candidate(ext: &str, suffix_len: usize) -> String {
    if ext.is_empty() {
        return String::new();
    }

    // Keep at least one byte for the stem. If the extension alone would crowd
    // out the collision suffix, truncate it rather than returning a filename
    // component longer than platform limits.
    let max_ext_len = MAX_FILENAME_LEN
        .saturating_sub(suffix_len)
        .saturating_sub(1);
    if max_ext_len < 2 {
        return String::new();
    }
    if ext.len() <= max_ext_len {
        return ext.to_string();
    }

    let safe_end = truncate_to_char_boundary(ext, max_ext_len);
    let truncated = &ext[..safe_end];
    if truncated.len() < 2 {
        String::new()
    } else {
        truncated.trim_end_matches('.').to_string()
    }
}

fn safe_unique_base_filename(base_filename: &str) -> String {
    let raw = Path::new(base_filename)
        .file_name()
        .and_then(|name| name.to_str())
        .map(str::trim)
        .filter(|name| !name.is_empty() && *name != "." && *name != "..")
        .unwrap_or("session.html");

    if is_valid_filename(raw) {
        return raw.to_string();
    }

    let (stem_raw, ext) = split_safe_extension(raw);
    let stem = sanitize(stem_raw);
    let stem = if stem.is_empty() {
        "session".to_string()
    } else {
        let max_stem_len = MAX_FILENAME_LEN.saturating_sub(ext.len()).max(1);
        finalize_filename(stem, Some(max_stem_len))
    };
    let candidate = format!("{stem}{ext}");

    if is_valid_filename(&candidate) {
        candidate
    } else if ext.is_empty() {
        "session".to_string()
    } else {
        format!("session{ext}")
    }
}

fn split_safe_extension(filename: &str) -> (&str, String) {
    let Some(dot_pos) = filename.rfind('.') else {
        return (filename, String::new());
    };
    if dot_pos == 0 {
        return ("", sanitize_extension(&filename[1..]));
    }

    let extension = sanitize_extension(&filename[dot_pos + 1..]);
    (&filename[..dot_pos], extension)
}

fn sanitize_extension(extension: &str) -> String {
    let ext: String = extension
        .chars()
        .filter(|c| c.is_ascii_alphanumeric())
        .take(16)
        .map(|c| c.to_ascii_lowercase())
        .collect();
    if ext.is_empty() {
        String::new()
    } else {
        format!(".{ext}")
    }
}

// ============================================================================
// Agent slug normalization
// ============================================================================

/// Normalize agent name to canonical slug.
///
/// Maps various agent name formats to a consistent short form.
pub fn agent_slug(agent: &str) -> String {
    match agent.to_lowercase().replace(['-', '_'], "").as_str() {
        "claudecode" | "claude" => "claude".to_string(),
        "cursor" | "cursorai" => "cursor".to_string(),
        "chatgpt" | "gpt" | "openai" => "chatgpt".to_string(),
        "gemini" | "geminicli" | "google" => "gemini".to_string(),
        "codex" | "codexcli" => "codex".to_string(),
        "aider" => "aider".to_string(),
        "piagent" | "pi" => "piagent".to_string(),
        "factory" | "droid" => "factory".to_string(),
        "opencode" => "opencode".to_string(),
        "cline" => "cline".to_string(),
        "amp" => "amp".to_string(),
        "copilot" | "githubcopilot" => "copilot".to_string(),
        "cody" | "sourcegraph" => "cody".to_string(),
        "windsurf" => "windsurf".to_string(),
        "grok" => "grok".to_string(),
        other => {
            // Slugify unknown agents
            let slug = sanitize(other);
            if slug.len() > 15 {
                // Safe truncation at char boundary to avoid panic
                let safe_end = truncate_to_char_boundary(&slug, 15);
                slug[..safe_end].trim_end_matches('_').to_string()
            } else {
                slug
            }
        }
    }
}

/// Extract workspace/project name from a path.
///
/// Returns the last path component as a slug, or "standalone" if no workspace.
pub fn workspace_slug(workspace: Option<&Path>) -> String {
    match workspace {
        Some(path) => {
            // Get last component (project name)
            let name = path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("unknown");
            let slug = sanitize(name);
            if slug.len() > 20 {
                // Safe truncation at char boundary to avoid panic
                let safe_end = truncate_to_char_boundary(&slug, 20);
                slug[..safe_end].trim_end_matches('_').to_string()
            } else if slug.is_empty() {
                "project".to_string()
            } else {
                slug
            }
        }
        None => "standalone".to_string(),
    }
}

/// Format a Unix timestamp as a filename-safe datetime string.
///
/// Output format: `YYYY_MM_DD_HHMM` (e.g., `2026_01_25_1430`)
pub fn datetime_slug(timestamp_ms: Option<i64>) -> String {
    use chrono::{TimeZone, Utc};

    let dt = timestamp_ms
        .and_then(|ts| Utc.timestamp_millis_opt(ts).single())
        .unwrap_or_else(Utc::now);

    dt.format("%Y_%m_%d_%H%M").to_string()
}

/// Extract a topic from conversation content.
///
/// Priority order:
/// 1. Explicit title (if provided)
/// 2. First user message (truncated, cleaned)
/// 3. Fallback to "session"
pub fn extract_topic(title: Option<&str>, first_user_message: Option<&str>) -> String {
    // Priority 1: Explicit title
    if let Some(t) = title {
        let topic = sanitize(t);
        if !topic.is_empty() {
            return truncate_topic(&topic, 30);
        }
    }

    // Priority 2: First user message
    if let Some(msg) = first_user_message {
        // Extract meaningful words, skip code/urls
        let words: Vec<&str> = msg
            .split_whitespace()
            .filter(|w| !w.starts_with("http"))
            .filter(|w| !w.contains('/'))
            .filter(|w| !w.starts_with('`'))
            .filter(|w| w.len() < 20)
            .take(5)
            .collect();

        if !words.is_empty() {
            let topic = sanitize(&words.join(" "));
            if !topic.is_empty() {
                return truncate_topic(&topic, 30);
            }
        }
    }

    // Fallback
    "session".to_string()
}

/// Truncate a topic to max length at word boundaries.
fn truncate_topic(topic: &str, max_len: usize) -> String {
    if topic.len() <= max_len {
        return topic.to_string();
    }

    // Safe truncation at char boundary to avoid panic on multi-byte UTF-8
    let safe_end = truncate_to_char_boundary(topic, max_len);
    let truncated = &topic[..safe_end];

    // Try to truncate at underscore boundary for cleaner result
    if let Some(last_underscore) = truncated.rfind('_')
        && last_underscore > safe_end / 2
    {
        return truncated[..last_underscore].to_string();
    }

    truncated.trim_end_matches('_').to_string()
}

/// Generate a complete filename with all components.
///
/// Format: `{agent}_{workspace}_{datetime}_{topic}.html`
pub fn generate_full_filename(
    agent: &str,
    workspace: Option<&Path>,
    timestamp_ms: Option<i64>,
    title: Option<&str>,
    first_user_message: Option<&str>,
) -> String {
    let agent_part = agent_slug(agent);
    let workspace_part = workspace_slug(workspace);
    let datetime_part = datetime_slug(timestamp_ms);
    let topic_part = extract_topic(title, first_user_message);

    let ext = ".html";
    let base_max = MAX_FILENAME_LEN.saturating_sub(ext.len());
    let base = format!(
        "{}_{}_{}_{}",
        agent_part, workspace_part, datetime_part, topic_part
    );
    let base = finalize_filename(base, Some(base_max));
    let filename = format!("{base}{ext}");
    debug!(
        component = "file",
        operation = "generate_full_filename",
        agent = agent,
        result_len = filename.len(),
        "Generated full filename"
    );
    filename
}

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

    #[test]
    fn test_sanitize_basic() {
        assert_eq!(sanitize("Hello World"), "hello_world");
        assert_eq!(sanitize("test.file"), "test_file");
        assert_eq!(sanitize("path/to/file"), "path_to_file");
    }

    #[test]
    fn test_sanitize_special_chars() {
        assert_eq!(sanitize("file<>:name"), "filename");
        assert_eq!(sanitize("test?*file"), "testfile");
    }

    #[test]
    fn test_sanitize_multiple_separators() {
        assert_eq!(sanitize("hello   world"), "hello_world");
        assert_eq!(sanitize("test___file"), "test_file");
    }

    #[test]
    fn test_generate_filename_basic() {
        let meta = FilenameMetadata {
            title: Some("My Session".to_string()),
            ..Default::default()
        };
        let opts = FilenameOptions::default();

        assert_eq!(generate_filename(&meta, &opts), "my_session");
    }

    #[test]
    fn test_generate_filename_with_date() {
        let meta = FilenameMetadata {
            title: Some("Session".to_string()),
            date: Some("2026-01-25".to_string()),
            ..Default::default()
        };
        let opts = FilenameOptions {
            include_date: true,
            ..Default::default()
        };

        let result = generate_filename(&meta, &opts);
        assert!(result.starts_with("2026-01-25"));
        assert!(result.contains("session"));
    }

    #[test]
    fn test_generate_filename_max_length() {
        let meta = FilenameMetadata {
            title: Some("A very long session title that exceeds limits".to_string()),
            ..Default::default()
        };
        let opts = FilenameOptions {
            max_length: Some(20),
            ..Default::default()
        };

        let result = generate_filename(&meta, &opts);
        assert!(result.len() <= 20);
    }

    #[test]
    fn test_generate_filename_zero_max_length() {
        let meta = FilenameMetadata {
            title: Some("Any Title".to_string()),
            ..Default::default()
        };
        let opts = FilenameOptions {
            max_length: Some(0),
            ..Default::default()
        };

        let result = generate_filename(&meta, &opts);
        assert!(!result.is_empty());
        assert!(result.len() <= 1);
    }

    #[test]
    fn test_generate_filename_caps_at_platform_limit() {
        let meta = FilenameMetadata {
            title: Some("a".repeat(400)),
            ..Default::default()
        };
        let opts = FilenameOptions {
            max_length: Some(400),
            ..Default::default()
        };

        let result = generate_filename(&meta, &opts);
        assert!(result.len() <= MAX_FILENAME_LEN);
    }

    #[test]
    fn test_generate_filename_empty() {
        let meta = FilenameMetadata::default();
        let opts = FilenameOptions::default();

        assert_eq!(generate_filename(&meta, &opts), "session");
    }

    #[test]
    fn test_generate_filename_skips_empty_parts() {
        let meta = FilenameMetadata {
            title: Some("Valid Session".to_string()),
            ..Default::default()
        };
        let opts = FilenameOptions {
            prefix: Some("###".to_string()),
            ..Default::default()
        };

        assert_eq!(generate_filename(&meta, &opts), "valid_session");
    }

    #[test]
    fn test_generate_filename_all_invalid() {
        let meta = FilenameMetadata {
            title: Some("###".to_string()),
            ..Default::default()
        };
        let opts = FilenameOptions::default();

        assert_eq!(generate_filename(&meta, &opts), "session");
    }

    #[test]
    fn test_generate_filename_reserved_name() {
        let meta = FilenameMetadata {
            title: Some("CON".to_string()),
            ..Default::default()
        };
        let opts = FilenameOptions::default();

        assert_eq!(generate_filename(&meta, &opts), "session_con");
    }

    #[test]
    fn test_is_valid_filename() {
        assert!(is_valid_filename("valid_file.txt"));
        assert!(is_valid_filename("test-123"));

        assert!(!is_valid_filename(""));
        assert!(!is_valid_filename("file<name"));
        assert!(!is_valid_filename("CON")); // Reserved on Windows
        assert!(!is_valid_filename(".hidden")); // Leading dot
    }

    #[test]
    fn test_generate_filepath() {
        let meta = FilenameMetadata {
            title: Some("test".to_string()),
            ..Default::default()
        };
        let opts = FilenameOptions::default();
        let path = generate_filepath(std::path::Path::new("/tmp"), &meta, &opts);

        assert_eq!(path, PathBuf::from("/tmp/test.html"));
    }

    #[test]
    fn test_generate_filepath_respects_extension_limit() {
        let meta = FilenameMetadata {
            title: Some("a".repeat(300)),
            ..Default::default()
        };
        let opts = FilenameOptions::default();
        let path = generate_filepath(std::path::Path::new("/tmp"), &meta, &opts);
        let filename = path.file_name().unwrap().to_string_lossy();
        assert!(filename.len() <= MAX_FILENAME_LEN);
        assert!(filename.ends_with(".html"));
    }

    #[test]
    fn test_normalize_topic_basic() {
        assert_eq!(normalize_topic("My Cool Topic"), "my_cool_topic");
        assert_eq!(
            normalize_topic("HTML Export Feature"),
            "html_export_feature"
        );
        assert_eq!(
            normalize_topic("debugging auth flow"),
            "debugging_auth_flow"
        );
    }

    #[test]
    fn test_normalize_topic_special_chars() {
        // Special characters should be removed
        assert_eq!(normalize_topic("API Design (v2)"), "api_design_v2");
        assert_eq!(normalize_topic("fix: login bug"), "fix_login_bug");
        assert_eq!(normalize_topic("add feature #123"), "add_feature_123");
    }

    #[test]
    fn test_normalize_topic_already_normalized() {
        // Already normalized topics should pass through
        assert_eq!(normalize_topic("already_normalized"), "already_normalized");
        assert_eq!(normalize_topic("lowercase_topic"), "lowercase_topic");
    }

    #[test]
    fn test_normalize_topic_multiple_spaces() {
        // Multiple spaces should collapse to single underscore
        assert_eq!(normalize_topic("too   many    spaces"), "too_many_spaces");
    }

    #[test]
    fn test_generate_filename_with_topic() {
        let meta = FilenameMetadata {
            date: Some("2026-01-25".to_string()),
            agent: Some("claude".to_string()),
            topic: Some("Debugging Auth Flow".to_string()),
            ..Default::default()
        };
        let opts = FilenameOptions {
            include_date: true,
            include_agent: true,
            include_topic: true,
            ..Default::default()
        };

        let result = generate_filename(&meta, &opts);
        assert!(result.contains("2026-01-25"));
        assert!(result.contains("claude"));
        assert!(result.contains("debugging_auth_flow"));
    }

    #[test]
    fn test_generate_filename_topic_without_flag() {
        // Topic should not appear if include_topic is false
        let meta = FilenameMetadata {
            topic: Some("My Topic".to_string()),
            title: Some("Session".to_string()),
            ..Default::default()
        };
        let opts = FilenameOptions {
            include_topic: false,
            ..Default::default()
        };

        let result = generate_filename(&meta, &opts);
        assert!(!result.contains("my_topic"));
        assert_eq!(result, "session");
    }

    #[test]
    fn test_generate_filename_full_robot_mode() {
        // Typical robot mode export with all metadata
        let meta = FilenameMetadata {
            date: Some("2026-01-25".to_string()),
            agent: Some("claude_code".to_string()),
            project: Some("my-project".to_string()),
            topic: Some("Fix Authentication Bug".to_string()),
            title: None, // Robot mode might not use title
        };
        let opts = FilenameOptions {
            include_date: true,
            include_agent: true,
            include_project: true,
            include_topic: true,
            ..Default::default()
        };

        let result = generate_filename(&meta, &opts);
        // Should produce something like: 2026-01-25_claude_code_my-project_fix_authentication_bug
        assert!(result.starts_with("2026-01-25"));
        assert!(result.contains("claude_code"));
        assert!(result.contains("my-project"));
        assert!(result.contains("fix_authentication_bug"));
    }

    // ========================================================================
    // Smart filename generation tests
    // ========================================================================

    #[test]
    fn test_agent_slug_canonical() {
        assert_eq!(agent_slug("claude_code"), "claude");
        assert_eq!(agent_slug("Claude-Code"), "claude");
        assert_eq!(agent_slug("cursor"), "cursor");
        assert_eq!(agent_slug("ChatGPT"), "chatgpt");
        assert_eq!(agent_slug("gemini-cli"), "gemini");
        assert_eq!(agent_slug("github_copilot"), "copilot");
    }

    #[test]
    fn test_agent_slug_unknown() {
        // Unknown agents get slugified
        assert_eq!(agent_slug("MyCustomAgent"), "mycustomagent");
        // Long names get truncated
        let long = agent_slug("VeryLongAgentNameThatExceedsLimit");
        assert!(long.len() <= 15);
    }

    #[test]
    fn test_workspace_slug_with_path() {
        let path = PathBuf::from("/home/user/projects/my-awesome-project");
        assert_eq!(workspace_slug(Some(&path)), "my-awesome-project");
    }

    #[test]
    fn test_workspace_slug_without_path() {
        assert_eq!(workspace_slug(None), "standalone");
    }

    #[test]
    fn test_workspace_slug_long_name() {
        let path = PathBuf::from("/path/to/very-long-project-name-that-exceeds-limit");
        let slug = workspace_slug(Some(&path));
        assert!(slug.len() <= 20);
    }

    #[test]
    fn test_datetime_slug_format() {
        // Test with a known timestamp (2026-01-25 14:30:00 UTC in milliseconds)
        let ts = 1769436600000i64;
        let slug = datetime_slug(Some(ts));
        // Should produce format like YYYY_MM_DD_HHMM
        assert!(slug.contains('_'));
        assert_eq!(slug.len(), 15); // YYYY_MM_DD_HHMM
    }

    #[test]
    fn test_datetime_slug_none() {
        // Should use current time when None
        let slug = datetime_slug(None);
        assert!(slug.starts_with("202")); // Reasonable year check
        assert_eq!(slug.len(), 15);
    }

    #[test]
    fn test_extract_topic_from_title() {
        let topic = extract_topic(Some("Fix Auth Bug"), None);
        assert_eq!(topic, "fix_auth_bug");
    }

    #[test]
    fn test_extract_topic_from_message() {
        let topic = extract_topic(None, Some("Help me debug this authentication issue"));
        // Topic gets truncated to 30 chars at word boundary
        assert_eq!(topic, "help_me_debug_this");
    }

    #[test]
    fn test_extract_topic_skips_urls() {
        let topic = extract_topic(None, Some("Check https://example.com for the issue"));
        assert!(!topic.contains("http"));
        assert!(topic.contains("check"));
    }

    #[test]
    fn test_extract_topic_fallback() {
        let topic = extract_topic(None, None);
        assert_eq!(topic, "session");
    }

    #[test]
    fn test_generate_full_filename() {
        let filename = generate_full_filename(
            "claude_code",
            Some(Path::new("/projects/myapp")),
            Some(1769436600000),
            Some("Fix Auth"),
            None,
        );

        assert!(filename.starts_with("claude_"));
        assert!(filename.contains("myapp"));
        assert!(filename.ends_with(".html"));
    }

    #[test]
    fn test_get_downloads_dir_returns_path() {
        let downloads = get_downloads_dir();
        // Should return some valid path
        assert!(!downloads.as_os_str().is_empty());
    }

    #[test]
    fn test_unique_filename_no_collision() {
        let dir = std::env::temp_dir();
        let unique_base = format!("test_unique_{}.html", std::process::id());
        let path = unique_filename(&dir, &unique_base);
        // Should return the original name if no collision
        assert!(
            path.to_string_lossy()
                .contains(&unique_base.replace(".html", ""))
        );
    }

    #[test]
    fn test_unique_filename_confines_path_components_to_dir() {
        let dir = Path::new("/exports");

        assert_eq!(
            unique_filename(dir, "../escape.html"),
            PathBuf::from("/exports/escape.html")
        );
        assert_eq!(
            unique_filename(dir, "/tmp/escape.html"),
            PathBuf::from("/exports/escape.html")
        );
    }

    #[test]
    fn test_unique_filename_sanitizes_invalid_basename_preserving_extension() {
        let dir = Path::new("/exports");

        assert_eq!(
            unique_filename(dir, "CON.html"),
            PathBuf::from("/exports/session_con.html")
        );
        assert_eq!(
            unique_filename(dir, "bad<name>.HTML"),
            PathBuf::from("/exports/badname.html")
        );
        assert_eq!(
            unique_filename(dir, "../../"),
            PathBuf::from("/exports/session.html")
        );
    }

    #[test]
    fn test_unique_filename_collision_keeps_platform_length_limit() {
        let temp = tempfile::tempdir().expect("tempdir");
        let base_filename = format!("{}.html", "a".repeat(MAX_FILENAME_LEN - ".html".len()));
        std::fs::write(temp.path().join(&base_filename), b"existing").expect("write existing");

        let path = unique_filename(temp.path(), &base_filename);
        let filename = path.file_name().unwrap().to_string_lossy();

        assert_ne!(filename.as_ref(), base_filename);
        assert!(filename.ends_with("_1.html"), "{filename}");
        assert!(filename.len() <= MAX_FILENAME_LEN, "{filename}");
    }

    #[test]
    fn test_unique_filename_collision_with_long_extension_keeps_platform_length_limit() {
        let temp = tempfile::tempdir().expect("tempdir");
        let base_filename = format!("a.{}", "b".repeat(MAX_FILENAME_LEN - "a.".len()));
        assert_eq!(base_filename.len(), MAX_FILENAME_LEN);
        assert!(is_valid_filename(&base_filename));
        std::fs::write(temp.path().join(&base_filename), b"existing").expect("write existing");

        let path = unique_filename(temp.path(), &base_filename);
        let filename = path.file_name().unwrap().to_string_lossy();

        assert_ne!(filename.as_ref(), base_filename);
        assert!(filename.starts_with("a_1."), "{filename}");
        assert!(filename.len() <= MAX_FILENAME_LEN, "{filename}");
        assert!(
            is_valid_filename(&filename),
            "collision candidate should remain platform-safe: {filename}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_unique_filename_treats_dangling_symlink_as_collision() {
        let temp = tempfile::tempdir().expect("tempdir");
        let occupied = temp.path().join("session.html");
        std::os::unix::fs::symlink(temp.path().join("missing-target.html"), &occupied)
            .expect("create dangling symlink");

        let path = unique_filename(temp.path(), "session.html");

        assert_eq!(
            path.file_name().and_then(|name| name.to_str()),
            Some("session_1.html")
        );
        assert!(
            std::fs::symlink_metadata(&occupied)
                .expect("dangling symlink metadata")
                .file_type()
                .is_symlink(),
            "unique_filename must not replace a dangling symlink placeholder"
        );
    }

    #[test]
    fn test_unique_timestamp_fallback_checks_occupied_candidate() {
        let temp = tempfile::tempdir().expect("tempdir");
        std::fs::write(temp.path().join("session_123.html"), b"existing")
            .expect("write occupied timestamp fallback");

        let path = unique_timestamp_fallback_filename(temp.path(), "session", ".html", 123);

        assert_eq!(
            path.file_name().and_then(|name| name.to_str()),
            Some("session_123_1.html")
        );
        assert!(
            !filename_path_is_occupied(&path),
            "fallback helper should return an unoccupied path"
        );
    }

    #[test]
    fn test_truncate_topic() {
        // Short topics unchanged
        assert_eq!(truncate_topic("short", 30), "short");

        // Long topics truncated at word boundary
        let long = "this_is_a_very_long_topic_name_that_needs_truncation";
        let truncated = truncate_topic(long, 30);
        assert!(truncated.len() <= 30);
        assert!(!truncated.ends_with('_'));
    }

    // ========================================================================
    // UTF-8 boundary safety tests
    // ========================================================================

    #[test]
    fn test_truncate_to_char_boundary() {
        // ASCII string
        assert_eq!(truncate_to_char_boundary("hello", 3), 3);
        assert_eq!(truncate_to_char_boundary("hello", 10), 5);

        // UTF-8 multi-byte characters
        // "日本語" = 3 chars, 9 bytes (each char is 3 bytes)
        let japanese = "日本語";
        assert_eq!(japanese.len(), 9);
        // Truncating at byte 4 should back up to byte 3 (end of first char)
        assert_eq!(truncate_to_char_boundary(japanese, 4), 3);
        // Truncating at byte 6 should stay at 6 (end of second char)
        assert_eq!(truncate_to_char_boundary(japanese, 6), 6);

        // "café" = 4 chars, 5 bytes (é is 2 bytes)
        let cafe = "café";
        assert_eq!(cafe.len(), 5);
        // Truncating at byte 4 should back up to byte 3 (before the é)
        assert_eq!(truncate_to_char_boundary(cafe, 4), 3);
    }

    #[test]
    fn test_enforce_max_len_utf8_safe() {
        // This test would panic before the fix if max_len cuts into a multi-byte char
        let long_with_emoji = "this_is_a_test_with_emoji_🎉_at_end";
        let result = enforce_max_len(long_with_emoji.to_string(), Some(30));
        // Should not panic, and result should be valid UTF-8
        assert!(result.len() <= 30);
        // The result should be valid UTF-8 (this wouldn't compile if not)
        let _ = result.chars().count();
    }

    #[test]
    fn test_agent_slug_utf8_safe() {
        // Long agent name with non-ASCII should not panic
        let result = agent_slug("müllerâgentnamëthätexceedslimit");
        // Should not panic, and result should be valid UTF-8
        assert!(result.len() <= 15);
        let _ = result.chars().count();
    }

    #[test]
    fn test_workspace_slug_utf8_safe() {
        // Project path with non-ASCII chars
        let path = PathBuf::from("/home/user/projéctswithöddnämesthätexceedlimits");
        let result = workspace_slug(Some(&path));
        // Should not panic, and result should be valid UTF-8
        assert!(result.len() <= 20);
        let _ = result.chars().count();
    }

    #[test]
    fn test_truncate_topic_utf8_safe() {
        // Topic with multi-byte characters that would panic if sliced incorrectly
        let topic = "日本語_programming_topic_that_is_very_long";
        let result = truncate_topic(topic, 20);
        // Should not panic, and result should be valid UTF-8
        assert!(result.len() <= 20);
        let _ = result.chars().count();
    }
}