omniterm 0.2.5

Web-based tmux terminal manager — one browser tab to watch and drive your AI coding agents
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
use anyhow::anyhow;
use axum::{
    Json, Router,
    body::Body,
    extract::{Multipart, Query, State},
    http::{StatusCode, header},
    response::{IntoResponse, Response},
    routing::{get, post},
};
use serde::Deserialize;
use serde_json::json;
use tracing::error;

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

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 {
        Some("mtime") => fs::SortKey::Mtime,
        Some("size") => fs::SortKey::Size,
        _ => fs::SortKey::Name,
    };
    let desc = order == Some("desc");
    (key, desc)
}

/// Resolve base path from session ID.
///
/// Returns `(base_path, tmux_session_name_or_empty)`. The second value is the
/// tmux session name for `runtime_kind='tmux'` sessions, and `""` (empty) for
/// `runtime_kind='acp'` sessions — which **do not have a tmux session**, so
/// FileManager must read the session's `workspace_path` directly (the agent
/// process cwd was fixed in commit 27d815f to actually be that path).
///
/// For tmux sessions, falls back to re-creating the tmux session at
/// `workspace_path` if `pane_cwd` fails (e.g. tmux server restart).
///
/// **历史 bug**:此前 ACP session 的 `tmux_session_name` 是 NULL,
/// `SELECT tmux_session_name` 返回 None  → 整个函数返 None  →
/// `/files?session=…` 返回 404 "session not found or tmux unavailable",
/// FileManager 加载 ACP session 的文件列表永远报错。修复后识别
/// runtime_kind=acp 走 workspace_path 分支。
pub async fn resolve_session_base(state: &AppState, session_id: &str) -> Option<(String, String)> {
    // 一次性取 session 关键字段,避免多次往返
    let row: (String, Option<String>, String) = sqlx::query_as(
        "SELECT runtime_kind, tmux_session_name, workspace_path FROM sessions WHERE id = ?",
    )
    .bind(session_id)
    .fetch_optional(&state.db)
    .await
    .ok()
    .flatten()?;

    let (runtime_kind, tmux_name_opt, workspace_path) = row;

    // ACP session:没有 tmux 会话,直接用 session 的 workspace_path 作为
    // FileManager 起点。这与 agent 子进程 OS cwd 修复(commit 27d815f)
    // 保持一致——agent 看到的是 workspace_path,FileManager 也展示
    // workspace_path,UI 与 agent 实际文件上下文统一。
    //
    // 未来若引入非 tmux/非 acp 的新 runtime_kind,未设置 tmux_name 但
    // 仍要求跟随会话工作区:也走此分支(`tmux_name_opt.is_none()`)。
    if runtime_kind == "acp" || tmux_name_opt.is_none() {
        tracing::debug!(
            "session {} is non-tmux (runtime_kind={}), using workspace_path={} as FileManager cwd",
            session_id,
            runtime_kind,
            workspace_path
        );
        return Some((workspace_path, String::new()));
    }

    // 走到这里说明是 tmux 会话。tmux_name_opt 一定是 Some
    // (上面已 early-return None 分支)。
    let tmux_name = tmux_name_opt.expect("checked above");

    // 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 project_root = resolve_project_root(state, project_id).await?;
    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": fs::display_path_str(&cwd), "is_outside_workspace": true }),
                ),
            );
        }

        // Determine if CWD is outside workspace.
        // canonicalize 两侧后再比较,避免 Windows 上分隔符(G:\ vs g:/)与大小写差异误判
        let is_outside =
            if let Some(ws_root) = resolve_session_workspace_root(&state, session_id).await {
                match (
                    std::path::Path::new(&cwd).canonicalize(),
                    std::path::Path::new(&ws_root).canonicalize(),
                ) {
                    (Ok(c), Ok(r)) => !c.starts_with(&r),
                    _ => !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": fs::display_path(&canonical), "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": fs::display_path_str(&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": fs::display_path(&canonical), "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 {
        (
            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 {
            // 绝对路径与相对路径的拼接形式一致,clippy 复核后合并分支
            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();
            }
        }
    };

    // Directories are packed into a zip archive on the fly.
    let is_dir = tokio::fs::metadata(&full_path).await.map(|m| m.is_dir()).unwrap_or(false);

    if is_dir {
        let dir_name = full_path.file_name().unwrap_or_default().to_string_lossy().into_owned();

        // Zip packing is CPU/IO bound; run it off the async runtime.
        let packed = match tokio::task::spawn_blocking(move || zip_directory(&full_path)).await {
            Ok(Ok(bytes)) => bytes,
            Ok(Err(e)) => {
                error!("zip directory failed: {}", e);
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(json!({ "error": e.to_string() })),
                )
                    .into_response();
            }
            Err(e) => {
                error!("zip task panicked: {}", e);
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(json!({ "error": "zip packing failed" })),
                )
                    .into_response();
            }
        };

        return Response::builder()
            .status(StatusCode::OK)
            .header(header::CONTENT_TYPE, "application/zip")
            .header(
                header::CONTENT_DISPOSITION,
                format!("attachment; filename=\"{}.zip\"", dir_name),
            )
            .body(Body::from(packed))
            .unwrap();
    }

    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()
}

/// Recursively pack `dir` into an in-memory zip archive.
/// Entry paths are relative to `dir`'s parent so the top-level folder
/// name is preserved when extracted.
fn zip_directory(dir: &std::path::Path) -> anyhow::Result<Vec<u8>> {
    use std::io::{Read, Write};
    use zip::write::SimpleFileOptions;

    let mut buf: Vec<u8> = Vec::new();
    {
        let mut zw = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));
        let options = SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Deflated)
            .unix_permissions(0o644);

        let mut stack: Vec<std::path::PathBuf> = vec![dir.to_path_buf()];
        while let Some(current) = stack.pop() {
            let mut entries =
                std::fs::read_dir(&current).map_err(|e| anyhow!("read dir failed: {}", e))?;
            while let Some(entry) = entries.next().transpose()? {
                let path = entry.path();
                // Zip entry path preserves the top-level folder name.
                let rel = path
                    .strip_prefix(dir.parent().unwrap_or(dir))
                    .unwrap_or(&path)
                    .to_string_lossy()
                    .replace('\\', "/");

                let meta = std::fs::symlink_metadata(&path)?;
                if meta.is_dir() {
                    zw.add_directory(format!("{}/", rel), options)?;
                    stack.push(path);
                } else if meta.is_file() {
                    zw.start_file(rel, options)?;
                    let mut f = std::fs::File::open(&path)?;
                    let mut chunk = Vec::new();
                    f.read_to_end(&mut chunk)?;
                    zw.write_all(&chunk)?;
                }
                // Skip symlinks/other types to keep the archive portable.
            }
        }
        zw.finish()?;
    }
    Ok(buf)
}

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() })))
        }
    }
}

#[cfg(test)]
mod zip_tests {
    use super::zip_directory;
    use std::io::Read;
    use std::path::Path;

    #[test]
    fn packs_directory_into_valid_zip() {
        let dir = std::env::temp_dir().join("ot_ziptest_mod");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("sub")).unwrap();
        std::fs::write(dir.join("a.txt"), b"hello").unwrap();
        std::fs::write(dir.join("sub").join("b.txt"), b"world").unwrap();

        let bytes = zip_directory(&dir).expect("zip should succeed");
        assert!(!bytes.is_empty());

        // Verify it's a valid zip by reading entries back.
        let mut cursor = std::io::Cursor::new(bytes);
        let mut archive = zip::ZipArchive::new(&mut cursor).expect("valid zip archive");
        let mut names = Vec::new();
        for i in 0..archive.len() {
            let mut f = archive.by_index(i).unwrap();
            let name = f.name().to_string();
            names.push(name.clone());
            if name.ends_with("a.txt") {
                let mut buf = String::new();
                f.read_to_string(&mut buf).unwrap();
                assert_eq!(buf, "hello");
            }
            if name.ends_with("b.txt") {
                let mut buf = String::new();
                f.read_to_string(&mut buf).unwrap();
                assert_eq!(buf, "world");
            }
        }
        assert!(names.iter().any(|n| n.ends_with("a.txt")), "a.txt present: {:?}", names);
        assert!(names.iter().any(|n| n.ends_with("sub/b.txt")), "sub/b.txt present: {:?}", names);
        assert!(
            names.iter().any(|n| n.ends_with("ot_ziptest_mod/") || n.contains("ot_ziptest_mod")),
            "top folder preserved: {:?}",
            names
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[allow(dead_code)]
    fn _assert_path(_: &Path) {}
}