omniterm 0.2.13

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
pub mod repo;

use serde::Serialize;
use tokio::process::Command;

#[derive(Debug, Clone, Serialize)]
pub struct WorktreeInfo {
    pub path: String,
    pub branch: Option<String>,
    pub bare: bool,
    pub detached: bool,
}

/// Check if the given path is inside a git work tree.
pub async fn is_git_repo(path: &str) -> bool {
    let Ok(output) =
        Command::new("git").args(["-C", path, "rev-parse", "--is-inside-work-tree"]).output().await
    else {
        return false;
    };
    String::from_utf8_lossy(&output.stdout).trim() == "true"
}

/// Whether the directory at `path` contains a `.gitignore` file.
///
/// Used to warn the user before initializing a fresh repo: `init_repo`
/// stages everything (`git add -A`), so without ignore rules the initial
/// commit may include build artifacts, secrets, or other files the user
/// didn't intend to track.
pub fn has_gitignore(path: &str) -> bool {
    std::path::Path::new(path).join(".gitignore").is_file()
}

/// Initialize a git repository at `path` and create an initial commit.
///
/// Needed when a project directory isn't a git repo yet but the user wants
/// to create worktrees. `git worktree add` technically works on an empty
/// repo (git infers `--orphan`), but the resulting worktree would contain
/// none of the project files — so we do the standard thing: `git init`,
/// stage everything, and commit. Uses a local (repo-scoped) identity if the
/// user has no global `user.name`/`user.email`, never touching the global
/// config. No-op when the path is already a git repo with commits.
pub async fn init_repo(path: &str) -> anyhow::Result<()> {
    // git init is idempotent on an existing repo.
    let init = Command::new("git").args(["-C", path, "init"]).output().await?;
    if !init.status.success() {
        let stderr = String::from_utf8_lossy(&init.stderr);
        anyhow::bail!("git init failed: {}", stderr.trim());
    }

    // If the repo already has a HEAD, there's nothing to initialize.
    let head =
        Command::new("git").args(["-C", path, "rev-parse", "--verify", "HEAD"]).output().await?;
    if head.status.success() {
        return Ok(());
    }

    // `git commit` aborts without an identity. Prefer the user's existing
    // (global or local) config; only fall back to a repo-scoped identity so
    // the initial commit succeeds without mutating the user's global config.
    for key in ["user.name", "user.email"] {
        let probe = Command::new("git").args(["-C", path, "config", key]).output().await?;
        let missing = !probe.status.success() || probe.stdout.is_empty();
        if missing {
            let fallback = if key == "user.name" { "omniterm" } else { "omniterm@localhost" };
            let set =
                Command::new("git").args(["-C", path, "config", key, fallback]).output().await?;
            if !set.status.success() {
                let stderr = String::from_utf8_lossy(&set.stderr);
                anyhow::bail!("git config {} failed: {}", key, stderr.trim());
            }
        }
    }

    let add = Command::new("git").args(["-C", path, "add", "-A"]).output().await?;
    if !add.status.success() {
        let stderr = String::from_utf8_lossy(&add.stderr);
        anyhow::bail!("git add failed: {}", stderr.trim());
    }

    // --allow-empty handles a directory with no trackable files (e.g. only
    // ignored files) so the repo still gets a usable HEAD for worktrees.
    let commit = Command::new("git")
        .args(["-C", path, "commit", "--allow-empty", "-m", "Initial commit"])
        .output()
        .await?;
    if !commit.status.success() {
        let stderr = String::from_utf8_lossy(&commit.stderr);
        anyhow::bail!("git commit failed: {}", stderr.trim());
    }

    Ok(())
}

/// Discover all git worktrees for the repository at the given path.
/// Runs `git worktree list --porcelain` and parses the output.
pub async fn discover_worktrees(path: &str) -> anyhow::Result<Vec<WorktreeInfo>> {
    let output =
        Command::new("git").args(["-C", path, "worktree", "list", "--porcelain"]).output().await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git worktree list failed: {}", stderr);
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    Ok(parse_worktree_list(&stdout))
}

/// Get the current branch name at `repo_path`.
pub async fn current_branch(repo_path: &str) -> anyhow::Result<String> {
    let output = Command::new("git")
        .args(["-C", repo_path, "rev-parse", "--abbrev-ref", "HEAD"])
        .output()
        .await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git rev-parse failed: {}", stderr.trim());
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// List all local branches in the repository at `repo_path`.
/// Runs `git branch --format='%(refname:short)'`.
pub async fn list_branches(repo_path: &str) -> anyhow::Result<Vec<String>> {
    let output = Command::new("git")
        .args(["-C", repo_path, "branch", "--format=%(refname:short)"])
        .output()
        .await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git branch failed: {}", stderr.trim());
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    Ok(stdout.lines().map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect())
}

/// Remove a git worktree at `target_path`.
/// Uses `--force` to skip the uncommitted-changes check (the user has
/// already confirmed the irreversible action in the frontend).
pub async fn remove_worktree(repo_path: &str, target_path: &str) -> anyhow::Result<()> {
    let output = Command::new("git")
        .args(["-C", repo_path, "worktree", "remove", "--force", target_path])
        .output()
        .await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git worktree remove failed: {}", stderr.trim());
    }

    Ok(())
}

/// Force-delete the local branch `branch` in the repository at `repo_path`.
/// Runs `git branch -D -- <branch>`.
///
/// `-D` (not `-d`) because a worktree branch is by definition not merged into
/// the current HEAD; the user has already acknowledged the irreversible action
/// in the frontend. The `--` terminator keeps a branch name that starts with
/// `-` from being parsed as an option.
pub async fn delete_branch(repo_path: &str, branch: &str) -> anyhow::Result<()> {
    let output =
        Command::new("git").args(["-C", repo_path, "branch", "-D", "--", branch]).output().await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git branch -D failed: {}", stderr.trim());
    }

    Ok(())
}

/// Add a new git worktree to the repository at `repo_path`.
/// Runs `git worktree add -b <branch> <target_path> [base]`.
pub async fn add_worktree(
    repo_path: &str,
    branch: &str,
    target_path: &str,
    base: Option<&str>,
    detach: bool,
) -> anyhow::Result<()> {
    let mut args: Vec<&str> = vec!["-C", repo_path, "worktree", "add"];

    if detach {
        args.push("--detach");
    }

    args.push("-b");
    args.push(branch);
    args.push(target_path);

    if let Some(base_ref) = base {
        args.push(base_ref);
    }

    let output = Command::new("git").args(&args).output().await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git worktree add failed: {}", stderr.trim());
    }

    Ok(())
}

fn parse_worktree_list(raw: &str) -> Vec<WorktreeInfo> {
    raw.trim()
        .split("\n\n")
        .filter(|chunk| !chunk.is_empty())
        .filter_map(|chunk| {
            let mut info =
                WorktreeInfo { path: String::new(), branch: None, bare: false, detached: false };
            for line in chunk.lines() {
                let mut parts = line.splitn(2, ' ');
                let key = parts.next().unwrap_or("");
                let value = parts.next().unwrap_or("").trim();
                match key {
                    "worktree" => info.path = value.to_string(),
                    "branch" => {
                        info.branch =
                            Some(value.strip_prefix("refs/heads/").unwrap_or(value).to_string());
                    }
                    "bare" => info.bare = true,
                    "detached" => info.detached = true,
                    _ => {}
                }
            }
            if info.path.is_empty() { None } else { Some(info) }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    static TMP_COUNTER: AtomicU32 = AtomicU32::new(0);

    /// Create a fresh empty directory under the system temp dir for tests
    /// that need to run real git commands.
    fn temp_dir() -> std::path::PathBuf {
        let n = TMP_COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir =
            std::env::temp_dir().join(format!("omniterm-git-test-{}-{}", std::process::id(), n));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[tokio::test]
    async fn test_init_repo_creates_head() {
        let dir = temp_dir();
        init_repo(dir.to_str().unwrap()).await.unwrap();
        assert!(is_git_repo(dir.to_str().unwrap()).await);
        let output = Command::new("git")
            .args(["-C", dir.to_str().unwrap(), "rev-parse", "--verify", "HEAD"])
            .output()
            .await
            .unwrap();
        assert!(output.status.success(), "HEAD should exist after init_repo");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[tokio::test]
    async fn test_init_repo_stages_existing_files() {
        let dir = temp_dir();
        std::fs::write(dir.join("hello.txt"), "world").unwrap();
        init_repo(dir.to_str().unwrap()).await.unwrap();
        // The staged file should be committed, so it shows up in `git ls-files`.
        let output = Command::new("git")
            .args(["-C", dir.to_str().unwrap(), "ls-files"])
            .output()
            .await
            .unwrap();
        let files = String::from_utf8_lossy(&output.stdout);
        assert!(files.contains("hello.txt"), "existing file should be committed");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[tokio::test]
    async fn test_init_repo_idempotent_on_existing_repo() {
        let dir = temp_dir();
        init_repo(dir.to_str().unwrap()).await.unwrap();
        let first_head = Command::new("git")
            .args(["-C", dir.to_str().unwrap(), "rev-parse", "HEAD"])
            .output()
            .await
            .unwrap();
        let first = String::from_utf8_lossy(&first_head.stdout).to_string();

        // Second call should be a no-op and keep the same HEAD.
        init_repo(dir.to_str().unwrap()).await.unwrap();
        let second_head = Command::new("git")
            .args(["-C", dir.to_str().unwrap(), "rev-parse", "HEAD"])
            .output()
            .await
            .unwrap();
        let second = String::from_utf8_lossy(&second_head.stdout).to_string();
        assert_eq!(first, second, "init_repo must not create a second commit");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_has_gitignore_detects_file() {
        let dir = temp_dir();
        assert!(!has_gitignore(dir.to_str().unwrap()), "no .gitignore yet");
        std::fs::write(dir.join(".gitignore"), "node_modules\n").unwrap();
        assert!(has_gitignore(dir.to_str().unwrap()), ".gitignore should be detected");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// Regression guard for the "deleted worktree still shows up as a base
    /// branch" bug: `git worktree remove` deletes the checkout but keeps the
    /// branch ref, so the branch stays in `list_branches` (the base-branch
    /// dropdown's data source) until `delete_branch` is called explicitly.
    #[tokio::test]
    async fn test_remove_worktree_keeps_branch_until_delete_branch() {
        let dir = temp_dir();
        let repo = dir.to_str().unwrap().to_string();
        init_repo(&repo).await.unwrap();

        let wt_path = dir.with_extension("wt");
        let wt = wt_path.to_str().unwrap().to_string();
        add_worktree(&repo, "feature-xyz", &wt, None, false).await.unwrap();
        assert!(list_branches(&repo).await.unwrap().contains(&"feature-xyz".to_string()));

        remove_worktree(&repo, &wt).await.unwrap();
        assert!(!wt_path.exists(), "worktree directory should be gone");
        assert!(
            list_branches(&repo).await.unwrap().contains(&"feature-xyz".to_string()),
            "git keeps the branch ref after `worktree remove` — this is the bug's root cause"
        );

        delete_branch(&repo, "feature-xyz").await.unwrap();
        assert!(
            !list_branches(&repo).await.unwrap().contains(&"feature-xyz".to_string()),
            "delete_branch must remove the branch from the base-branch list"
        );

        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// The delete-worktree handler resolves the branch by matching the client's
    /// path against `discover_worktrees` output. Guard that the path a worktree
    /// is created with round-trips byte-identically, otherwise the lookup
    /// silently finds nothing and the branch is never deleted.
    #[tokio::test]
    async fn test_discover_worktrees_resolves_branch_for_created_path() {
        let dir = temp_dir();
        let repo = dir.to_str().unwrap().to_string();
        init_repo(&repo).await.unwrap();

        let wt_path = dir.with_extension("wt");
        let wt = wt_path.to_str().unwrap().to_string();
        add_worktree(&repo, "feature-abc", &wt, None, false).await.unwrap();

        let list = discover_worktrees(&repo).await.unwrap();
        let entry = list
            .iter()
            .find(|w| w.path == wt)
            .expect("created worktree path must match discover_worktrees output verbatim");
        assert_eq!(entry.branch.as_deref(), Some("feature-abc"));

        std::fs::remove_dir_all(&wt_path).ok();
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[tokio::test]
    async fn test_delete_branch_fails_for_unknown_branch() {
        let dir = temp_dir();
        let repo = dir.to_str().unwrap().to_string();
        init_repo(&repo).await.unwrap();
        assert!(
            delete_branch(&repo, "no-such-branch").await.is_err(),
            "deleting a missing branch must surface an error, not silently succeed"
        );
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_parse_worktree_list_single() {
        let input = "worktree /home/user/repo\nHEAD abc123\nbranch refs/heads/main\n";
        let result = parse_worktree_list(input);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].path, "/home/user/repo");
        assert_eq!(result[0].branch.as_deref(), Some("main"));
        assert!(!result[0].bare);
        assert!(!result[0].detached);
    }

    #[test]
    fn test_parse_worktree_list_multiple() {
        let input = "\
worktree /home/user/repo
HEAD abc123
branch refs/heads/main

worktree /home/user/repo-dev
HEAD def456
branch refs/heads/dev

worktree /home/user/repo-feature
HEAD ghi789
detached
";
        let result = parse_worktree_list(input);
        assert_eq!(result.len(), 3);
        assert_eq!(result[0].branch.as_deref(), Some("main"));
        assert_eq!(result[1].branch.as_deref(), Some("dev"));
        assert!(result[2].detached);
        assert_eq!(result[2].branch, None);
    }
}