omniterm 0.1.4

Web-based tmux terminal manager with AI agent monitoring
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
use axum::{
    body::Body,
    extract::{Multipart, Query, State},
    http::{header, StatusCode},
    response::{IntoResponse, Response},
    routing::{get, post},
    Json, Router,
};
use anyhow::anyhow;
use serde::Deserialize;
use serde_json::json;
use tracing::error;

use crate::fs;
use crate::tmux;
use crate::AppState;

pub fn routes() -> Router<AppState> {
    Router::new()
        .route("/files", get(list_files).post(upload_file).delete(delete_file))
        .route("/files/download", get(download_file))
        .route("/files/read", get(read_file))
        .route("/files/write", post(write_file))
        .route("/files/mkdir", post(mkdir))
        .route("/files/rename", post(rename))
        .route("/files/move", post(move_files))
        .route("/files/copy", post(copy_files))
        .route("/files/search", get(search_files))
}

#[derive(Deserialize)]
struct FileQuery {
    path: Option<String>,
    workspace: Option<String>,      // project_id (existing, misnamed)
    session: Option<String>,
    workspace_id: Option<String>,   // NEW: actual workspace id
    sort: Option<String>,
    order: Option<String>,
}

#[derive(Deserialize)]
struct SearchQuery {
    q: String,
    path: Option<String>,
    workspace: Option<String>,
    session: Option<String>,
    workspace_id: Option<String>,
}

#[derive(Deserialize)]
struct RenameRequest {
    path: String,
    #[serde(rename = "newName")]
    new_name: String,
    workspace: Option<String>,
    session: Option<String>,
    workspace_id: Option<String>,
}

#[derive(Deserialize)]
struct MoveRequest {
    paths: Vec<String>,
    destination: String,
    workspace: Option<String>,
    session: Option<String>,
    workspace_id: Option<String>,
}

#[derive(Deserialize)]
struct CopyRequest {
    paths: Vec<String>,
    destination: String,
    workspace: Option<String>,
    session: Option<String>,
    workspace_id: Option<String>,
}

#[derive(Deserialize)]
struct WriteRequest {
    content: String,
}

/// Resolve project root path from project ID.
pub async fn resolve_project_root(state: &AppState, project_id: &str) -> Option<String> {
    sqlx::query_as::<_, (String,)>("SELECT path FROM projects WHERE id = ?")
        .bind(project_id)
        .fetch_optional(&state.db)
        .await
        .ok()
        .flatten()
        .map(|(p,)| p)
}

fn parse_sort(sort: Option<&str>, order: Option<&str>) -> (fs::SortKey, bool) {
    let key = match sort.as_deref() {
        Some("mtime") => fs::SortKey::Mtime,
        Some("size") => fs::SortKey::Size,
        _ => fs::SortKey::Name,
    };
    let desc = order.as_deref() == Some("desc");
    (key, desc)
}

/// Resolve base path from session ID (via tmux pane CWD).
/// Returns (base_path, tmux_session_name).
/// If the tmux session is missing (e.g. tmux server restarted), re-creates it
/// using the workspace_path as fallback CWD.
pub async fn resolve_session_base(state: &AppState, session_id: &str) -> Option<(String, String)> {
    let tmux_name: (String,) =
        sqlx::query_as("SELECT tmux_session_name FROM sessions WHERE id = ?")
            .bind(session_id)
            .fetch_optional(&state.db)
            .await
            .ok()
            .flatten()?;

    let tmux_name = tmux_name.0;

    // Try to get pane CWD; if it fails, the tmux session may have been lost
    match tmux::pane_cwd(&tmux_name).await {
        Ok(cwd) => Some((cwd, tmux_name)),
        Err(e) => {
            tracing::warn!(
                "tmux session '{}' unavailable ({}), attempting re-create",
                tmux_name, e
            );
            // Resolve workspace root as fallback CWD
            let root = resolve_session_workspace_root(state, session_id)
                .await
                .unwrap_or_else(|| {
                    std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string())
                });
            tmux::new_session(&tmux_name, &root, None).await.ok()?;
            let cwd = tmux::pane_cwd(&tmux_name).await.ok()?;
            tracing::info!("re-created tmux session '{}' at {}", tmux_name, cwd);
            Some((cwd, tmux_name))
        }
    }
}

/// Get workspace_path for a session (used for is_outside_workspace check).
async fn resolve_session_workspace_root(state: &AppState, session_id: &str) -> Option<String> {
    sqlx::query_as::<_, (String,)>(
        "SELECT workspace_path FROM sessions WHERE id = ?",
    )
    .bind(session_id)
    .fetch_optional(&state.db)
    .await
    .ok()
    .flatten()
    .map(|(p,)| p)
}

/// Resolve base path from query: session > workspace_id > project.
/// Returns (base_path, is_session_mode).
pub async fn resolve_base_from_query(
    state: &AppState,
    session: Option<&str>,
    workspace_id: Option<&str>,
    project: Option<&str>,
) -> Option<(std::path::PathBuf, bool)> {
    if let Some(sid) = session {
        let (cwd, _) = resolve_session_base(state, sid).await?;
        Some((std::path::PathBuf::from(cwd), true))
    } else if let Some(wid) = workspace_id {
        let pid = project.unwrap_or("default");
        let root = resolve_workspace_root(state, wid, pid).await?;
        Some((std::path::PathBuf::from(root), false))
    } else {
        let pid = project.unwrap_or("default");
        let root = resolve_project_root(state, pid).await?;
        Some((std::path::PathBuf::from(root), false))
    }
}

/// Resolve workspace root path from workspace_id + project_id.
/// Workspaces are discovered dynamically from git worktrees.
async fn resolve_workspace_root(
    state: &AppState,
    workspace_id: &str,
    project_id: &str,
) -> Option<String> {
    use crate::workspaces;
    let Some(project_root) = resolve_project_root(state, project_id).await else {
        return None;
    };
    let project = crate::models::project::Project {
        id: project_id.to_string(),
        name: String::new(),
        path: project_root,
        target_id: None,
        created_at: String::new(),
    };
    let wts = workspaces::list_workspaces(&project).await;
    wts.into_iter()
        .find(|w| w.id == workspace_id)
        .map(|w| w.path)
}

async fn list_files(
    State(state): State<AppState>,
    Query(q): Query<FileQuery>,
) -> impl IntoResponse {
    let (sort, desc) = parse_sort(q.sort.as_deref(), q.order.as_deref());

    // Session-based mode: resolve CWD from tmux
    if let Some(session_id) = q.session.as_deref() {
        let Some((cwd, _tmux_name)) = resolve_session_base(&state, session_id).await else {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({ "error": "session not found or tmux unavailable" })),
            );
        };

        let rel_path = q.path.as_deref().unwrap_or("");
        let base = std::path::Path::new(&cwd);

        if !base.exists() {
            return (StatusCode::OK, Json(json!({ "files": [], "cwd": cwd, "is_outside_workspace": true })));
        }

        // Determine if CWD is outside workspace
        let is_outside = if let Some(ws_root) = resolve_session_workspace_root(&state, session_id).await {
            !cwd.starts_with(&ws_root)
        } else {
            false
        };

        // Resolve the actual directory to list
        let list_base = if rel_path.is_empty() || rel_path == "." {
            base.to_path_buf()
        } else if std::path::Path::new(rel_path).is_absolute() {
            std::path::Path::new(rel_path).to_path_buf()
        } else {
            base.join(rel_path)
        };

        // Basic security: ensure path doesn't escape /
        let Ok(canonical) = list_base.canonicalize() else {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({ "error": "path not found" })),
            );
        };

        match fs::list_dir(&canonical, "", sort, desc).await {
            Ok(entries) => (
                StatusCode::OK,
                Json(json!({ "files": entries, "cwd": canonical.to_string_lossy(), "is_outside_workspace": is_outside })),
            ),
            Err(e) => {
                error!("list_files (session) failed: {}", e);
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(json!({ "error": e.to_string() })),
                )
            }
        }
    } else if let Some(workspace_id) = q.workspace_id.as_deref() {
        // Workspace-based mode: resolve workspace path from workspace_id
        let project_id = q.workspace.as_deref().unwrap_or("default");

        let Some(root) = resolve_workspace_root(&state, workspace_id, project_id).await else {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({ "error": "workspace not found" })),
            );
        };

        let base = std::path::Path::new(&root);
        if !base.exists() {
            return (StatusCode::OK, Json(json!({ "files": [], "cwd": root, "is_outside_workspace": false })));
        }

        let rel_path = q.path.as_deref().unwrap_or("");
        let list_base = if rel_path.is_empty() || rel_path == "." {
            base.to_path_buf()
        } else if std::path::Path::new(rel_path).is_absolute() {
            std::path::Path::new(rel_path).to_path_buf()
        } else {
            base.join(rel_path)
        };

        let Ok(canonical) = list_base.canonicalize() else {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({ "error": "path not found" })),
            );
        };

        // Detect if browsing outside workspace root (same as session mode behavior)
        let is_outside = match base.canonicalize() {
            Ok(canonical_root) => !canonical.starts_with(&canonical_root),
            Err(_) => false,
        };

        match fs::list_dir(&canonical, "", sort, desc).await {
            Ok(entries) => (
                StatusCode::OK,
                Json(json!({ "files": entries, "cwd": canonical.to_string_lossy(), "is_outside_workspace": is_outside })),
            ),
            Err(e) => {
                error!("list_files (workspace) failed: {}", e);
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(json!({ "error": e.to_string() })),
                )
            }
        }
    } else if let Some(project_id) = q.workspace.as_deref() {
        // Project-based mode (existing fallback, unchanged)
        let rel_path = q.path.as_deref().unwrap_or("");

        let Some(root) = resolve_project_root(&state, project_id).await else {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({ "error": "project not found" })),
            );
        };

        let base = std::path::Path::new(&root);

        if !base.exists() {
            return (StatusCode::OK, Json(json!([])));
        }

        match fs::list_dir(base, rel_path, sort, desc).await {
            Ok(entries) => (StatusCode::OK, Json(json!(entries))),
            Err(e) => {
                error!("list_files failed: {}", e);
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(json!({ "error": e.to_string() })),
                )
            }
        }
    } else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "session, workspace_id, or workspace parameter required" })),
        );
    }
}

async fn upload_file(
    State(state): State<AppState>,
    Query(q): Query<FileQuery>,
    mut multipart: Multipart,
) -> impl IntoResponse {
    let rel_path = q.path.as_deref().unwrap_or("");

    let Some((base, _)) = resolve_base_from_query(&state, q.session.as_deref(), q.workspace_id.as_deref(), q.workspace.as_deref()).await else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "workspace or session not found" })),
        );
    };

    let mut uploaded = Vec::new();

    while let Some(field) = multipart.next_field().await.unwrap_or(None) {
        let file_name = field.file_name().unwrap_or("upload").to_string();

        let data = match field.bytes().await {
            Ok(d) => d,
            Err(e) => {
                error!("failed to read upload data: {}", e);
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({ "error": "read failed" })),
                );
            }
        };

        // For session mode with absolute rel_path, use it as-is
        let target_path = if rel_path.is_empty() || rel_path == "." {
            file_name.clone()
        } else if std::path::Path::new(rel_path).is_absolute() {
            format!("{}/{}", rel_path.trim_end_matches('/'), file_name)
        } else {
            format!("{}/{}", rel_path.trim_end_matches('/'), file_name)
        };

        if let Err(e) = fs::write_file(&base, &target_path, &data).await {
            error!("upload write failed: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": e.to_string() })),
            );
        }

        uploaded.push(json!({
            "name": file_name,
            "path": target_path,
            "size": data.len(),
        }));
    }

    (StatusCode::OK, Json(json!(uploaded)))
}

async fn delete_file(
    State(state): State<AppState>,
    Query(q): Query<FileQuery>,
) -> impl IntoResponse {
    let Some(path_str) = q.path.as_deref() else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "path required" })),
        );
    };

    let Some((base, _)) = resolve_base_from_query(&state, q.session.as_deref(), q.workspace_id.as_deref(), q.workspace.as_deref()).await else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "workspace or session not found" })),
        );
    };

    match fs::delete_path(&base, path_str).await {
        Ok(()) => (StatusCode::OK, Json(json!({ "ok": true }))),
        Err(e) => {
            error!("delete failed: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": e.to_string() })),
            )
        }
    }
}

async fn download_file(State(state): State<AppState>, Query(q): Query<FileQuery>) -> Response {
    let Some(path_str) = q.path.as_deref() else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "path required" })),
        )
            .into_response();
    };

    let Some((base, _)) = resolve_base_from_query(&state, q.session.as_deref(), q.workspace_id.as_deref(), q.workspace.as_deref()).await else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "workspace or session not found" })),
        )
            .into_response();
    };

    // For session mode, paths may be absolute
    let full_path = if std::path::Path::new(path_str).is_absolute() {
        std::path::PathBuf::from(path_str)
    } else {
        match fs::sanitize_path(&base, path_str) {
            Ok(p) => p,
            Err(_) => return (StatusCode::FORBIDDEN, Json(json!({ "error": "invalid path" }))).into_response(),
        }
    };

    let Ok(content) = tokio::fs::read(&full_path).await else {
        return (StatusCode::NOT_FOUND, Json(json!({ "error": "file not found" }))).into_response();
    };

    let file_name = full_path
        .file_name()
        .unwrap_or_default()
        .to_string_lossy();

    Response::builder()
        .status(StatusCode::OK)
        .header(header::CONTENT_TYPE, "application/octet-stream")
        .header(
            header::CONTENT_DISPOSITION,
            format!("attachment; filename=\"{}\"", file_name),
        )
        .body(Body::from(content))
        .unwrap()
}

async fn read_file(
    State(state): State<AppState>,
    Query(q): Query<FileQuery>,
) -> impl IntoResponse {
    let Some(path_str) = q.path.as_deref() else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "path required" })),
        );
    };

    let Some((base, _)) = resolve_base_from_query(&state, q.session.as_deref(), q.workspace_id.as_deref(), q.workspace.as_deref()).await else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "workspace or session not found" })),
        );
    };

    // For session mode, paths may be absolute
    let content = if std::path::Path::new(path_str).is_absolute() {
        tokio::fs::read_to_string(path_str).await.map_err(|e| anyhow!(e))
    } else {
        fs::read_file(&base, path_str).await
    };

    match content {
        Ok(content) => (StatusCode::OK, Json(json!({ "content": content }))),
        Err(e) => {
            error!("read_file failed: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": e.to_string() })),
            )
        }
    }
}

async fn write_file(
    State(state): State<AppState>,
    Query(q): Query<FileQuery>,
    Json(req): Json<WriteRequest>,
) -> impl IntoResponse {
    let Some(path_str) = q.path.as_deref() else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "path required" })),
        );
    };

    let Some((base, _)) = resolve_base_from_query(&state, q.session.as_deref(), q.workspace_id.as_deref(), q.workspace.as_deref()).await else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "workspace or session not found" })),
        );
    };

    // For session mode, paths may be absolute
    let result: Result<(), anyhow::Error> = if std::path::Path::new(path_str).is_absolute() {
        // Ensure parent directory exists
        if let Some(parent) = std::path::Path::new(path_str).parent() {
            let _ = tokio::fs::create_dir_all(parent).await;
        }
        tokio::fs::write(path_str, req.content.as_bytes()).await.map_err(|e| anyhow!(e))
    } else {
        fs::write_file(&base, path_str, req.content.as_bytes()).await
    };

    match result {
        Ok(()) => (StatusCode::OK, Json(json!({ "ok": true }))),
        Err(e) => {
            error!("write_file failed: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": e.to_string() })),
            )
        }
    }
}

async fn mkdir(
    State(state): State<AppState>,
    Json(req): Json<serde_json::Value>,
) -> impl IntoResponse {
    let session_id = req.get("session").and_then(|v| v.as_str());
    let workspace_id = req.get("workspace_id").and_then(|v| v.as_str());
    let project_id = req.get("workspace").and_then(|v| v.as_str());
    let path = req.get("path").and_then(|v| v.as_str()).unwrap_or("");
    let name = req.get("name").and_then(|v| v.as_str()).unwrap_or("");

    let Some((base, _)) = resolve_base_from_query(&state, session_id, workspace_id, project_id).await else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "workspace or session not found" })),
        );
    };

    let dir_path = if path.is_empty() || path == "." {
        name.to_string()
    } else {
        format!("{}/{}", path.trim_end_matches('/'), name)
    };

    match fs::create_dir(&base, &dir_path).await {
        Ok(()) => (StatusCode::OK, Json(json!({ "ok": true }))),
        Err(e) => {
            error!("mkdir failed: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": e.to_string() })),
            )
        }
    }
}

async fn rename(
    State(state): State<AppState>,
    Json(req): Json<RenameRequest>,
) -> impl IntoResponse {
    let Some((base, _)) = resolve_base_from_query(&state, req.session.as_deref(), req.workspace_id.as_deref(), req.workspace.as_deref()).await else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "workspace or session not found" })),
        );
    };

    // Compute new path: replace the file/dir name in the original path
    let old_path = std::path::Path::new(&req.path);
    let new_rel = match old_path.parent() {
        Some(parent) if !parent.as_os_str().is_empty() => {
            format!(
                "{}/{}",
                parent.to_string_lossy().trim_end_matches('/'),
                req.new_name
            )
        }
        _ => req.new_name.clone(),
    };

    match fs::move_path(&base, &req.path, &new_rel).await {
        Ok(()) => (StatusCode::OK, Json(json!({ "ok": true }))),
        Err(e) => {
            error!("rename failed: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": e.to_string() })),
            )
        }
    }
}

async fn move_files(
    State(state): State<AppState>,
    Json(req): Json<MoveRequest>,
) -> impl IntoResponse {
    let Some((base, _)) = resolve_base_from_query(&state, req.session.as_deref(), req.workspace_id.as_deref(), req.workspace.as_deref()).await else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "workspace or session not found" })),
        );
    };

    for p in &req.paths {
        let file_name = std::path::Path::new(p)
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_default();
        let dest = format!(
            "{}/{}",
            req.destination.trim_end_matches('/'),
            file_name
        );
        if let Err(e) = fs::move_path(&base, p, &dest).await {
            error!("move failed: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": e.to_string() })),
            );
        }
    }

    (StatusCode::OK, Json(json!({ "ok": true })))
}

async fn copy_files(
    State(state): State<AppState>,
    Json(req): Json<CopyRequest>,
) -> impl IntoResponse {
    let Some((base, _)) = resolve_base_from_query(&state, req.session.as_deref(), req.workspace_id.as_deref(), req.workspace.as_deref()).await else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "workspace or session not found" })),
        );
    };

    match fs::copy_paths(&base, &req.paths, &req.destination).await {
        Ok(()) => (StatusCode::OK, Json(json!({ "ok": true }))),
        Err(e) => {
            error!("copy failed: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": e.to_string() })),
            )
        }
    }
}

async fn search_files(
    State(state): State<AppState>,
    Query(q): Query<SearchQuery>,
) -> impl IntoResponse {
    let rel_path = q.path.as_deref().unwrap_or("");

    let Some((base, _)) = resolve_base_from_query(&state, q.session.as_deref(), q.workspace_id.as_deref(), q.workspace.as_deref()).await else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "workspace or session not found" })),
        );
    };

    match fs::search_files(&base, rel_path, &q.q).await {
        Ok(entries) => (StatusCode::OK, Json(json!(entries))),
        Err(e) => {
            error!("search failed: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": e.to_string() })),
            )
        }
    }
}