smart-tree 8.0.0

Smart Tree - An intelligent, AI-friendly directory visualization tool
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
//! REST API endpoints for file browser and system state

use super::{FileTreeNode, SharedState};
use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    response::IntoResponse,
    Json,
};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;

#[derive(Debug, Deserialize)]
pub struct PathQuery {
    path: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct TreeQuery {
    path: Option<String>,
    depth: Option<usize>,
}

#[derive(Debug, Serialize)]
pub struct HealthResponse {
    status: String,
    version: String,
    connections: usize,
    git_branch: Option<String>,
    cwd: String,
}

#[derive(Debug, Serialize)]
pub struct FileContent {
    path: String,
    content: String,
    is_binary: bool,
    size: u64,
    mime_type: String,
}

#[derive(Debug, Deserialize)]
pub struct WriteFileRequest {
    path: String,
    content: String,
}

/// Health check endpoint
pub async fn health(State(state): State<SharedState>) -> Json<HealthResponse> {
    let state_guard = state.read().await;
    let connections = state_guard.connections;
    let cwd = state_guard.cwd.clone();
    drop(state_guard);

    // Try to get git branch
    let git_branch = get_git_branch(&cwd);

    Json(HealthResponse {
        status: "ok".to_string(),
        version: env!("CARGO_PKG_VERSION").to_string(),
        connections,
        git_branch,
        cwd: cwd.to_string_lossy().to_string(),
    })
}

/// Get current git branch by reading .git/HEAD
fn get_git_branch(cwd: &std::path::Path) -> Option<String> {
    // Walk up to find .git directory
    let mut current = cwd.to_path_buf();
    loop {
        let git_dir = current.join(".git");
        if git_dir.exists() {
            let head_path = git_dir.join("HEAD");
            if let Ok(content) = fs::read_to_string(&head_path) {
                let content = content.trim();
                // ref: refs/heads/branch-name
                if let Some(branch) = content.strip_prefix("ref: refs/heads/") {
                    return Some(branch.to_string());
                }
                // Detached HEAD - return short hash
                if content.len() >= 7 {
                    return Some(format!("({})", &content[..7]));
                }
            }
            break;
        }
        if !current.pop() {
            break;
        }
    }
    None
}

/// List files in a directory
pub async fn list_files(
    State(state): State<SharedState>,
    Query(query): Query<PathQuery>,
) -> Result<Json<Vec<FileTreeNode>>, (StatusCode, String)> {
    let base_path = {
        let s = state.read().await;
        s.cwd.clone()
    };

    let path = match &query.path {
        Some(p) => {
            let requested = PathBuf::from(p);
            if requested.is_absolute() {
                requested
            } else {
                base_path.join(requested)
            }
        }
        None => base_path,
    };

    let path = path
        .canonicalize()
        .map_err(|e| (StatusCode::NOT_FOUND, format!("Path not found: {}", e)))?;

    let mut entries = Vec::new();

    let read_dir = fs::read_dir(&path).map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to read directory: {}", e),
        )
    })?;

    for entry in read_dir.flatten() {
        let metadata = entry.metadata().ok();
        let is_dir = metadata.as_ref().map(|m| m.is_dir()).unwrap_or(false);
        let size = metadata.as_ref().map(|m| m.len()).unwrap_or(0);
        let modified = metadata
            .as_ref()
            .and_then(|m| m.modified().ok())
            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0);

        let name = entry.file_name().to_string_lossy().to_string();
        let file_type = if is_dir {
            "directory".to_string()
        } else {
            get_file_type(&name)
        };

        entries.push(FileTreeNode {
            name,
            path: entry.path().to_string_lossy().to_string(),
            is_dir,
            size,
            modified,
            file_type,
        });
    }

    // Sort: directories first, then alphabetically
    entries.sort_by(|a, b| match (a.is_dir, b.is_dir) {
        (true, false) => std::cmp::Ordering::Less,
        (false, true) => std::cmp::Ordering::Greater,
        _ => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
    });

    Ok(Json(entries))
}

/// Read file content
pub async fn read_file(
    Query(query): Query<PathQuery>,
) -> Result<Json<FileContent>, (StatusCode, String)> {
    let path = query.path.ok_or_else(|| {
        (
            StatusCode::BAD_REQUEST,
            "Missing path parameter".to_string(),
        )
    })?;

    let path = PathBuf::from(&path);

    let metadata = fs::metadata(&path)
        .map_err(|e| (StatusCode::NOT_FOUND, format!("File not found: {}", e)))?;

    if metadata.is_dir() {
        return Err((StatusCode::BAD_REQUEST, "Path is a directory".to_string()));
    }

    let size = metadata.len();

    // Check if binary
    let is_binary = is_binary_file(&path);

    let content = if is_binary {
        "[Binary file]".to_string()
    } else if size > 1_000_000 {
        "[File too large to display]".to_string()
    } else {
        fs::read_to_string(&path).map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Failed to read file: {}", e),
            )
        })?
    };

    let mime_type = get_mime_type(&path);

    Ok(Json(FileContent {
        path: path.to_string_lossy().to_string(),
        content,
        is_binary,
        size,
        mime_type,
    }))
}

/// Write file content
pub async fn write_file(
    Json(request): Json<WriteFileRequest>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    let path = PathBuf::from(&request.path);

    fs::write(&path, &request.content).map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to write file: {}", e),
        )
    })?;

    Ok((StatusCode::OK, "File saved"))
}

/// Get directory tree
pub async fn get_tree(
    State(state): State<SharedState>,
    Query(query): Query<TreeQuery>,
) -> Result<Json<Vec<FileTreeNode>>, (StatusCode, String)> {
    let base_path = {
        let s = state.read().await;
        s.cwd.clone()
    };

    let path = match &query.path {
        Some(p) => PathBuf::from(p),
        None => base_path,
    };

    let depth = query.depth.unwrap_or(3);

    let nodes = collect_tree(&path, depth, 0)?;

    Ok(Json(nodes))
}

fn collect_tree(
    path: &PathBuf,
    max_depth: usize,
    current_depth: usize,
) -> Result<Vec<FileTreeNode>, (StatusCode, String)> {
    if current_depth >= max_depth {
        return Ok(Vec::new());
    }

    let mut entries = Vec::new();

    let read_dir = fs::read_dir(path).map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to read directory: {}", e),
        )
    })?;

    for entry in read_dir.flatten() {
        let name = entry.file_name().to_string_lossy().to_string();

        // Skip hidden files and common ignored directories
        if name.starts_with('.')
            || name == "node_modules"
            || name == "target"
            || name == "__pycache__"
        {
            continue;
        }

        let metadata = entry.metadata().ok();
        let is_dir = metadata.as_ref().map(|m| m.is_dir()).unwrap_or(false);
        let size = metadata.as_ref().map(|m| m.len()).unwrap_or(0);
        let modified = metadata
            .as_ref()
            .and_then(|m| m.modified().ok())
            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0);

        let file_type = if is_dir {
            "directory".to_string()
        } else {
            get_file_type(&name)
        };

        entries.push(FileTreeNode {
            name,
            path: entry.path().to_string_lossy().to_string(),
            is_dir,
            size,
            modified,
            file_type,
        });
    }

    entries.sort_by(|a, b| match (a.is_dir, b.is_dir) {
        (true, false) => std::cmp::Ordering::Less,
        (false, true) => std::cmp::Ordering::Greater,
        _ => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
    });

    Ok(entries)
}

/// Render markdown to HTML
pub async fn render_markdown(
    Query(query): Query<PathQuery>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    let path = query.path.ok_or_else(|| {
        (
            StatusCode::BAD_REQUEST,
            "Missing path parameter".to_string(),
        )
    })?;

    let content = fs::read_to_string(&path)
        .map_err(|e| (StatusCode::NOT_FOUND, format!("File not found: {}", e)))?;

    // Return raw markdown - client will render with marked.js
    Ok(content)
}

fn get_file_type(name: &str) -> String {
    let ext = name.rsplit('.').next().unwrap_or("").to_lowercase();
    match ext.as_str() {
        "rs" => "rust",
        "py" => "python",
        "js" => "javascript",
        "ts" => "typescript",
        "tsx" | "jsx" => "react",
        "html" | "htm" => "html",
        "css" | "scss" | "sass" => "css",
        "json" => "json",
        "yaml" | "yml" => "yaml",
        "toml" => "toml",
        "md" | "markdown" => "markdown",
        "sh" | "bash" | "zsh" => "shell",
        "go" => "go",
        "c" | "h" => "c",
        "cpp" | "hpp" | "cc" => "cpp",
        "java" => "java",
        "rb" => "ruby",
        "php" => "php",
        "sql" => "sql",
        "txt" => "text",
        "lock" => "lock",
        "gitignore" | "dockerignore" => "ignore",
        _ => "file",
    }
    .to_string()
}

fn get_mime_type(path: &std::path::Path) -> String {
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_lowercase();

    match ext.as_str() {
        "rs" | "py" | "js" | "ts" | "go" | "c" | "cpp" | "java" | "rb" | "php" => "text/plain",
        "html" | "htm" => "text/html",
        "css" => "text/css",
        "json" => "application/json",
        "md" => "text/markdown",
        "txt" => "text/plain",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "svg" => "image/svg+xml",
        "pdf" => "application/pdf",
        _ => "application/octet-stream",
    }
    .to_string()
}

fn is_binary_file(path: &std::path::Path) -> bool {
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_lowercase();

    matches!(
        ext.as_str(),
        "png"
            | "jpg"
            | "jpeg"
            | "gif"
            | "ico"
            | "webp"
            | "mp3"
            | "mp4"
            | "wav"
            | "avi"
            | "mkv"
            | "zip"
            | "tar"
            | "gz"
            | "bz2"
            | "xz"
            | "7z"
            | "exe"
            | "dll"
            | "so"
            | "dylib"
            | "pdf"
            | "doc"
            | "docx"
            | "xls"
            | "xlsx"
            | "ttf"
            | "woff"
            | "woff2"
            | "eot"
            | "sqlite"
            | "db"
    )
}

// ----- Config Handling -----

#[derive(Serialize, Deserialize, Debug)]
pub struct LayoutConfig {
    sidebar_width: f64,
    terminal_height: f64,
    preview_width: f64,
    layout_mode: String,
}

#[derive(Serialize, Deserialize, Debug, Default)]
pub struct ThemeConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    bg_primary: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    bg_secondary: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    accent_primary: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    accent_secondary: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    fg_primary: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    fg_secondary: Option<String>,
}

async fn get_project_st_dir(state: &SharedState) -> Result<PathBuf, String> {
    let cwd = state.read().await.cwd.clone();
    Ok(cwd.join(".st"))
}

async fn ensure_project_st_dir_exists(state: &SharedState) -> Result<PathBuf, String> {
    let config_dir = get_project_st_dir(state).await?;
    if !config_dir.exists() {
        fs::create_dir_all(&config_dir)
            .map_err(|e| format!("Failed to create project .st directory: {}", e))?;
    }
    Ok(config_dir)
}

async fn get_layout_config_path(state: &SharedState) -> Result<PathBuf, String> {
    get_project_st_dir(state).await.map(|dir| dir.join("layout.json"))
}

impl Default for LayoutConfig {
    fn default() -> Self {
        Self {
            sidebar_width: 25.0,
            terminal_height: 33.3,
            preview_width: 33.3,
            layout_mode: "default".to_string(),
        }
    }
}

pub async fn get_layout_config(
    State(state): State<SharedState>,
) -> Result<Json<LayoutConfig>, (StatusCode, String)> {
    let path =
        get_layout_config_path(&state).await.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;
    if !path.exists() {
        return Ok(Json(LayoutConfig::default()));
    }
    let content = fs::read_to_string(&path).map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to read layout config: {}", e),
        )
    })?;
    let config: LayoutConfig = serde_json::from_str(&content).map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to parse layout config: {}", e),
        )
    })?;
    Ok(Json(config))
}

pub async fn save_layout_config(
    State(state): State<SharedState>,
    Json(payload): Json<LayoutConfig>,
) -> Result<StatusCode, (StatusCode, String)> {
    ensure_project_st_dir_exists(&state).await.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;
    let path =
        get_layout_config_path(&state).await.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;
    let content = serde_json::to_string_pretty(&payload).map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to serialize layout config: {}", e),
        )
    })?;
    fs::write(&path, content).map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to write layout config: {}", e),
        )
    })?;
    Ok(StatusCode::OK)
}

// --- Theme Config ---

fn get_user_st_dir() -> Result<PathBuf, String> {
    dirs::home_dir()
        .map(|home| home.join(".st"))
        .ok_or_else(|| "Could not find home directory".to_string())
}

fn ensure_user_st_dir_exists() -> Result<PathBuf, String> {
    let config_dir = get_user_st_dir()?;
    if !config_dir.exists() {
        fs::create_dir_all(&config_dir)
            .map_err(|e| format!("Failed to create user .st directory: {}", e))?;
    }
    Ok(config_dir)
}

fn get_theme_config_path() -> Result<PathBuf, String> {
    get_user_st_dir().map(|dir| dir.join("theme.json"))
}

pub async fn get_theme_config() -> Result<Json<ThemeConfig>, (StatusCode, String)> {
    let path = get_theme_config_path().map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;
    if !path.exists() {
        return Ok(Json(ThemeConfig::default()));
    }

    let content = fs::read_to_string(&path).map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to read theme config: {}", e),
        )
    })?;

    if content.is_empty() {
        return Ok(Json(ThemeConfig::default()));
    }

    let config: ThemeConfig = serde_json::from_str(&content).map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to parse theme config: {}", e),
        )
    })?;

    Ok(Json(config))
}

pub async fn save_theme_config(
    Json(payload): Json<ThemeConfig>,
) -> Result<StatusCode, (StatusCode, String)> {
    ensure_user_st_dir_exists().map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;
    let path = get_theme_config_path().map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;

    // Merge with existing config
    let mut current_config = if path.exists() {
        let content = fs::read_to_string(&path).unwrap_or_default();
        if content.is_empty() {
            ThemeConfig::default()
        } else {
            serde_json::from_str(&content).unwrap_or_default()
        }
    } else {
        ThemeConfig::default()
    };

    if let Some(val) = payload.bg_primary {
        current_config.bg_primary = Some(val);
    }
    if let Some(val) = payload.bg_secondary {
        current_config.bg_secondary = Some(val);
    }
    if let Some(val) = payload.accent_primary {
        current_config.accent_primary = Some(val);
    }
    if let Some(val) = payload.accent_secondary {
        current_config.accent_secondary = Some(val);
    }
    if let Some(val) = payload.fg_primary {
        current_config.fg_primary = Some(val);
    }
    if let Some(val) = payload.fg_secondary {
        current_config.fg_secondary = Some(val);
    }

    let content = serde_json::to_string_pretty(&current_config).map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to serialize theme config: {}", e),
        )
    })?;

    fs::write(&path, content).map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to write theme config: {}", e),
        )
    })?;

    Ok(StatusCode::OK)
}

// ----- Log Handling -----

#[derive(Debug, Deserialize)]
pub struct LogQuery {
    level: Option<String>,
}

/// Get recent logs from the in-memory store
pub async fn get_logs(
    State(state): State<SharedState>,
    Query(query): Query<LogQuery>,
) -> Result<Json<Vec<crate::in_memory_logger::LogEntry>>, StatusCode> {
    let state_guard = state.read().await;
    let entries = state_guard.log_store.entries.lock().unwrap();

    let filtered_logs: Vec<crate::in_memory_logger::LogEntry> =
        if let Some(min_level_str) = query.level {
            let min_level = match min_level_str.to_uppercase().as_str() {
                "ERROR" => Some(tracing::Level::ERROR),
                "WARN" => Some(tracing::Level::WARN),
                "INFO" => Some(tracing::Level::INFO),
                "DEBUG" => Some(tracing::Level::DEBUG),
                "TRACE" => Some(tracing::Level::TRACE),
                _ => None,
            };

            if let Some(min_level) = min_level {
                entries
                    .iter()
                    .filter(|entry| {
                        entry
                            .level
                            .parse::<tracing::Level>()
                            .unwrap_or(tracing::Level::TRACE)
                            <= min_level
                    })
                    .cloned()
                    .collect()
            } else {
                entries.iter().cloned().collect()
            }
        } else {
            entries.iter().cloned().collect()
        };

    Ok(Json(filtered_logs))
}

// ----- Prompt Handling -----

#[derive(Debug, Deserialize)]
pub struct PromptRequest {
    pub question: String,
}

#[derive(Debug, Serialize)]
pub struct PromptResponse {
    pub answer: String,
}

#[derive(Debug, Deserialize)]
pub struct PromptAnswer {
    pub answer: String,
}

#[derive(Debug, Serialize)]
pub struct PromptListResponse {
    pub id: String,
    pub question: String,
}

/// AI requests a prompt to be answered by the user
pub async fn ask_prompt(
    State(state): State<SharedState>,
    Json(request): Json<PromptRequest>,
) -> Result<Json<PromptResponse>, (StatusCode, String)> {
    let (tx, rx) = tokio::sync::oneshot::channel();
    let prompt_id = {
        let dashboard = state.read().await;
        let id = dashboard
            .prompt_manager
            .next_id
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
            .to_string();
        
        dashboard.prompt_manager.pending.write().await.insert(id.clone(), tx);
        dashboard.prompt_manager.active_prompts.write().await.insert(id.clone(), request.question.clone());
        dashboard.collab_hub.read().await.announce_prompt(id.clone(), request.question.clone());
        id
    };

    // Wait for the answer
    match rx.await {
        Ok(answer) => {
            // Clean up active prompt
            let dashboard = state.read().await;
            dashboard.prompt_manager.active_prompts.write().await.remove(&prompt_id);
            
            Ok(Json(PromptResponse { answer }))
        }
        Err(_) => Err((
            StatusCode::INTERNAL_SERVER_ERROR,
            "Prompt cancelled or server shutting down".to_string(),
        )),
    }
}

/// User provides an answer to a prompt
pub async fn answer_prompt(
    State(state): State<SharedState>,
    Path(prompt_id): Path<String>,
    Json(answer): Json<PromptAnswer>,
) -> Result<StatusCode, (StatusCode, String)> {
    let dashboard = state.read().await;
    let mut pending = dashboard.prompt_manager.pending.write().await;
    
    if let Some(tx) = pending.remove(&prompt_id) {
        let _ = tx.send(answer.answer);
        
        // Also cleanup active prompts
        dashboard.prompt_manager.active_prompts.write().await.remove(&prompt_id);
        
        Ok(StatusCode::OK)
    } else {
        Err((StatusCode::NOT_FOUND, "Prompt ID not found".to_string()))
    }
}

/// Get all active prompts (fallback in case UI wants to fetch)
pub async fn get_active_prompts(
    State(state): State<SharedState>,
) -> Json<Vec<PromptListResponse>> {
    let dashboard = state.read().await;
    let prompts = dashboard.prompt_manager.active_prompts.read().await;
    
    let list: Vec<PromptListResponse> = prompts
        .iter()
        .map(|(id, q)| PromptListResponse {
            id: id.clone(),
            question: q.clone(),
        })
        .collect();
        
    Json(list)
}