omni-dev 0.31.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, and Datadog.
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
//! The worktrees daemon service.
//!
//! Maintains the live, authoritative set of repos/worktrees open across *every*
//! VS Code window, fed by a first-party companion extension that reports from
//! each window over the daemon's control socket. The resident daemon is the
//! rendezvous point the per-window extension sandbox cannot replace: each window
//! can see only its own `workspace.workspaceFolders`, so a single process
//! aggregating those registrations is the only cross-window source of truth.
//! See ADR-0040.
//!
//! Like the Snowflake service this is a cheap, in-memory adapter — no async
//! setup, no secret persisted. The registry lives behind a [`std::sync::Mutex`]
//! that is **never held across an `.await`** (the Snowflake rule); every op is
//! pure CPU under the lock, so liveness reaping happens inline on each read
//! rather than from a background task.

use std::collections::{BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::Duration;

use anyhow::{anyhow, bail, Context, Result};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::daemon::service::{DaemonService, MenuAction, MenuItem, MenuSnapshot, ServiceStatus};

/// The worktrees service name (the control-socket routing key).
pub const SERVICE_NAME: &str = "worktrees";

/// How long a window may go silent before it ages out of the registry. Three
/// missed ~10s heartbeats; a window that crashed without firing `unregister`
/// disappears on the next read. The resident process is what makes this
/// liveness correct — a flat shared file could not reap stale entries.
const DEFAULT_TTL: Duration = Duration::from_secs(30);

/// Environment override for the VS Code launcher used by the "focus" tray
/// action, for when the daemon runs under launchd with a minimal `PATH`.
const VSCODE_BIN_ENV: &str = "OMNI_DEV_VSCODE_BIN";

/// A `register` request from a companion extension. The companion owns its
/// `key` (a per-`activate()` UUID) so the daemon never has to reason about
/// whether `vscode.env.sessionId` is unique per window; everything else is
/// best-effort metadata.
#[derive(Debug, Clone, Deserialize)]
struct RegisterRequest {
    /// Stable per-window identity, generated by the companion on activation.
    key: String,
    /// Absolute paths of the window's workspace folders.
    #[serde(default)]
    folders: Vec<PathBuf>,
    /// Repository root or name, when the window has one.
    #[serde(default)]
    repo: Option<String>,
    /// The window title, for display.
    #[serde(default)]
    title: Option<String>,
    /// The reporting extension-host process id.
    #[serde(default)]
    pid: Option<u32>,
}

/// One open window's live registration. Serialized verbatim into `list` /
/// `status` payloads; consumers compute age from `last_seen` (RFC 3339).
#[derive(Debug, Clone, Serialize)]
struct WindowEntry {
    /// The companion-owned per-window key.
    key: String,
    /// Absolute workspace-folder paths.
    folders: Vec<PathBuf>,
    /// Repository root or name, if reported.
    #[serde(skip_serializing_if = "Option::is_none")]
    repo: Option<String>,
    /// Window title, if reported.
    #[serde(skip_serializing_if = "Option::is_none")]
    title: Option<String>,
    /// Reporting extension-host pid, if reported.
    #[serde(skip_serializing_if = "Option::is_none")]
    pid: Option<u32>,
    /// When the daemon last heard from this window (register or heartbeat).
    last_seen: DateTime<Utc>,
}

/// Hosts the cross-window worktree registry as a [`DaemonService`].
pub struct WorktreesService {
    /// Open windows keyed by their companion-owned `key`.
    windows: Mutex<HashMap<String, WindowEntry>>,
    /// How long an entry survives without a heartbeat.
    ttl: Duration,
}

impl WorktreesService {
    /// Creates the service with the default liveness TTL. Cheap — no I/O.
    #[must_use]
    pub fn new() -> Self {
        Self {
            windows: Mutex::new(HashMap::new()),
            ttl: DEFAULT_TTL,
        }
    }

    /// Locks the registry, recovering from a poisoned mutex (a panic in a prior
    /// critical section must not wedge the whole service).
    fn lock(&self) -> MutexGuard<'_, HashMap<String, WindowEntry>> {
        self.windows.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Reaps stale entries, then returns the live set sorted for deterministic
    /// output. Holds the lock only for pure-CPU work.
    fn live_entries(&self, now: DateTime<Utc>) -> Vec<WindowEntry> {
        let mut windows = self.lock();
        reap(&mut windows, self.ttl, now);
        sorted_entries(&windows)
    }
}

impl Default for WorktreesService {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl DaemonService for WorktreesService {
    fn name(&self) -> &'static str {
        SERVICE_NAME
    }

    async fn handle(&self, op: &str, payload: Value) -> Result<Value> {
        let now = Utc::now();
        match op {
            "register" => {
                let req: RegisterRequest =
                    serde_json::from_value(payload).context("invalid `register` payload")?;
                if req.key.trim().is_empty() {
                    bail!("`register` requires a non-empty `key`");
                }
                let mut windows = self.lock();
                reap(&mut windows, self.ttl, now);
                windows.insert(
                    req.key.clone(),
                    WindowEntry {
                        key: req.key,
                        folders: req.folders,
                        repo: req.repo,
                        title: req.title,
                        pid: req.pid,
                        last_seen: now,
                    },
                );
                Ok(json!({ "ok": true }))
            }
            "heartbeat" => {
                let key = require_key(&payload, "heartbeat")?;
                let mut windows = self.lock();
                reap(&mut windows, self.ttl, now);
                // `known: false` tells a window that started before the daemon —
                // or survived a daemon restart — to re-`register`, since the
                // registry is in-memory and has no record of it.
                let known = match windows.get_mut(key) {
                    Some(entry) => {
                        entry.last_seen = now;
                        true
                    }
                    None => false,
                };
                Ok(json!({ "known": known }))
            }
            "unregister" => {
                let key = require_key(&payload, "unregister")?;
                let mut windows = self.lock();
                let removed = windows.remove(key).is_some();
                reap(&mut windows, self.ttl, now);
                Ok(json!({ "removed": removed }))
            }
            "list" => Ok(json!({ "windows": self.live_entries(now) })),
            other => bail!("unknown worktrees op: {other}"),
        }
    }

    fn menu(&self) -> MenuSnapshot {
        let entries = self.live_entries(Utc::now());
        let items = if entries.is_empty() {
            vec![MenuItem::Label("No open windows".to_string())]
        } else {
            window_menu_items(&entries)
        };
        MenuSnapshot {
            title: "Worktrees".to_string(),
            items,
        }
    }

    async fn menu_action(&self, action_id: &str) -> Result<()> {
        if let Some(key) = action_id.strip_prefix("focus:") {
            // Resolve the folder under the lock, then drop it before spawning —
            // never hold the mutex across the process launch.
            let folder = {
                let windows = self.lock();
                windows.get(key).and_then(|e| e.folders.first().cloned())
            };
            let folder = folder
                .ok_or_else(|| anyhow!("no open window with key {key} (it may have closed)"))?;
            focus_window(&folder)?;
            return Ok(());
        }
        bail!("unknown worktrees menu action: {action_id}")
    }

    async fn status(&self) -> ServiceStatus {
        let entries = self.live_entries(Utc::now());
        let repos: BTreeSet<&str> = entries.iter().filter_map(|e| e.repo.as_deref()).collect();
        ServiceStatus {
            name: SERVICE_NAME.to_string(),
            healthy: true,
            summary: format!("{} window(s) across {} repo(s)", entries.len(), repos.len()),
            detail: json!({ "windows": entries }),
        }
    }

    async fn shutdown(&self) {
        // In-memory only; nothing to drain or persist.
    }
}

/// Extracts a required string `key` from an op payload, erroring with the op
/// name when it is absent or not a string.
fn require_key<'a>(payload: &'a Value, op: &str) -> Result<&'a str> {
    payload
        .get("key")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow!("`{op}` requires `key`"))
}

/// Removes entries last seen longer than `ttl` ago. Pure CPU; the caller holds
/// the registry lock but never `.await`s while holding it.
fn reap(windows: &mut HashMap<String, WindowEntry>, ttl: Duration, now: DateTime<Utc>) {
    let max_age = ttl.as_secs() as i64;
    windows.retain(|_, e| (now - e.last_seen).num_seconds() <= max_age);
}

/// Snapshots the registry into a stably-ordered vector (by repo, then key) so
/// `list`/`status`/`menu` output is deterministic despite `HashMap` ordering.
fn sorted_entries(windows: &HashMap<String, WindowEntry>) -> Vec<WindowEntry> {
    let mut entries: Vec<WindowEntry> = windows.values().cloned().collect();
    entries.sort_by(|a, b| a.repo.cmp(&b.repo).then_with(|| a.key.cmp(&b.key)));
    entries
}

/// A short human name for a window: its repo, else its first folder's basename,
/// else a placeholder.
fn display_name(entry: &WindowEntry) -> String {
    if let Some(repo) = &entry.repo {
        return repo.clone();
    }
    if let Some(folder) = entry.folders.first() {
        return folder.file_name().map_or_else(
            || folder.display().to_string(),
            |n| n.to_string_lossy().into_owned(),
        );
    }
    "(no folder)".to_string()
}

/// Builds the tray items for a non-empty window list: a label per window, a
/// separator, then a "Focus" action per window that has a folder to open.
fn window_menu_items(entries: &[WindowEntry]) -> Vec<MenuItem> {
    let mut items = Vec::new();
    for entry in entries {
        let name = display_name(entry);
        let label = match &entry.title {
            Some(title) if title != &name => format!("{name} · {title}"),
            _ => name,
        };
        items.push(MenuItem::Label(label));
    }
    items.push(MenuItem::Separator);
    for entry in entries {
        // No folder means nothing for `code` to open, so omit the action.
        if !entry.folders.is_empty() {
            items.push(MenuItem::Action(MenuAction {
                id: format!("focus:{}", entry.key),
                label: format!("Focus {}", display_name(entry)),
                enabled: true,
            }));
        }
    }
    items
}

/// Well-known absolute locations for the VS Code launcher, tried in order so a
/// daemon running under launchd (with a minimal `PATH`) still finds it.
const CODE_BINARY_CANDIDATES: &[&str] = &[
    "/usr/local/bin/code",
    "/opt/homebrew/bin/code",
    "/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code",
    "/usr/bin/code",
];

/// Focuses (or opens, since VS Code reuses an already-open window) `folder` in
/// VS Code by spawning its CLI, resolved via [`resolve_code_binary`].
fn focus_window(folder: &Path) -> Result<()> {
    focus_window_with(&resolve_code_binary(), folder)
}

/// Spawns `program` on `folder` after validating the folder. Split out from
/// [`focus_window`] so the validation and spawn paths are testable with an
/// explicit launcher (no environment or installed-editor dependency).
///
/// Best-effort and non-blocking: the spawned child is reaped on a detached
/// thread so a long-lived daemon does not accumulate zombies one per focus.
fn focus_window_with(program: &Path, folder: &Path) -> Result<()> {
    // Workspace-folder paths are absolute; requiring it also rules out a path
    // that begins with `-` being parsed by `code` as a flag.
    if !folder.is_absolute() {
        bail!(
            "refusing to focus a non-absolute folder path: {}",
            folder.display()
        );
    }
    if !folder.is_dir() {
        bail!("worktree folder no longer exists: {}", folder.display());
    }
    // Detach the launcher's stdio so its output never interleaves into the
    // long-lived daemon's own stdout/stderr (or the test harness's).
    let child = Command::new(program)
        .arg(folder)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .with_context(|| {
            format!(
                "failed to launch `{}` to focus {}",
                program.display(),
                folder.display()
            )
        })?;
    // Reap the child without blocking so it never lingers as a zombie.
    std::thread::spawn(move || {
        let mut child = child;
        let _ = child.wait();
    });
    Ok(())
}

/// Resolves the VS Code launcher from the real environment: the
/// `OMNI_DEV_VSCODE_BIN` override, then [`CODE_BINARY_CANDIDATES`], then bare
/// `code` on `PATH`. The pure resolution logic lives in
/// [`resolve_code_binary_from`] for testing.
fn resolve_code_binary() -> PathBuf {
    resolve_code_binary_from(std::env::var_os(VSCODE_BIN_ENV), CODE_BINARY_CANDIDATES)
}

/// Pure launcher resolution: `env_override` wins; otherwise the first existing
/// `candidate`; otherwise bare `code`.
fn resolve_code_binary_from(
    env_override: Option<std::ffi::OsString>,
    candidates: &[&str],
) -> PathBuf {
    if let Some(path) = env_override {
        return PathBuf::from(path);
    }
    for candidate in candidates {
        let path = Path::new(candidate);
        if path.exists() {
            return path.to_path_buf();
        }
    }
    PathBuf::from("code")
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    fn register_payload(key: &str, repo: Option<&str>, folder: &str) -> Value {
        json!({
            "key": key,
            "folders": [folder],
            "repo": repo,
            "title": format!("{key}-title"),
            "pid": 1234,
        })
    }

    /// Pulls the `windows` array out of a `list`/`status` payload.
    fn windows_of(payload: &Value) -> &Vec<Value> {
        payload
            .get("windows")
            .and_then(Value::as_array)
            .expect("windows array")
    }

    #[tokio::test]
    async fn name_and_unknown_op() {
        let svc = WorktreesService::new();
        assert_eq!(svc.name(), "worktrees");
        assert!(svc.handle("frobnicate", Value::Null).await.is_err());
    }

    #[tokio::test]
    async fn list_is_empty_initially() {
        let svc = WorktreesService::new();
        let payload = svc.handle("list", Value::Null).await.unwrap();
        assert_eq!(payload, json!({ "windows": [] }));
    }

    #[tokio::test]
    async fn register_then_list_round_trips() {
        let svc = WorktreesService::new();
        let reply = svc
            .handle("register", register_payload("w1", Some("repo-a"), "/tmp/a"))
            .await
            .unwrap();
        assert_eq!(reply, json!({ "ok": true }));

        let payload = svc.handle("list", Value::Null).await.unwrap();
        let windows = windows_of(&payload);
        assert_eq!(windows.len(), 1);
        assert_eq!(windows[0].get("key").and_then(Value::as_str), Some("w1"));
        assert_eq!(
            windows[0].get("repo").and_then(Value::as_str),
            Some("repo-a")
        );
        assert!(windows[0].get("last_seen").is_some());
    }

    #[tokio::test]
    async fn register_is_idempotent_upsert() {
        let svc = WorktreesService::new();
        svc.handle("register", register_payload("w1", Some("repo-a"), "/tmp/a"))
            .await
            .unwrap();
        // Re-registering the same key updates rather than duplicates.
        svc.handle("register", register_payload("w1", Some("repo-b"), "/tmp/b"))
            .await
            .unwrap();
        let payload = svc.handle("list", Value::Null).await.unwrap();
        let windows = windows_of(&payload);
        assert_eq!(windows.len(), 1);
        assert_eq!(
            windows[0].get("repo").and_then(Value::as_str),
            Some("repo-b")
        );
    }

    #[tokio::test]
    async fn register_requires_key() {
        let svc = WorktreesService::new();
        assert!(svc.handle("register", json!({})).await.is_err());
        assert!(svc
            .handle("register", json!({ "key": "  " }))
            .await
            .is_err());
    }

    #[tokio::test]
    async fn heartbeat_reports_known_and_unknown() {
        let svc = WorktreesService::new();
        // Unknown before registration: the window must re-register.
        let unknown = svc
            .handle("heartbeat", json!({ "key": "w1" }))
            .await
            .unwrap();
        assert_eq!(unknown, json!({ "known": false }));

        svc.handle("register", register_payload("w1", None, "/tmp/a"))
            .await
            .unwrap();
        let known = svc
            .handle("heartbeat", json!({ "key": "w1" }))
            .await
            .unwrap();
        assert_eq!(known, json!({ "known": true }));
        assert!(svc.handle("heartbeat", json!({})).await.is_err());
    }

    #[tokio::test]
    async fn unregister_removes() {
        let svc = WorktreesService::new();
        svc.handle("register", register_payload("w1", None, "/tmp/a"))
            .await
            .unwrap();
        let gone = svc
            .handle("unregister", json!({ "key": "w1" }))
            .await
            .unwrap();
        assert_eq!(gone, json!({ "removed": true }));
        // Removing again is a no-op success.
        let again = svc
            .handle("unregister", json!({ "key": "w1" }))
            .await
            .unwrap();
        assert_eq!(again, json!({ "removed": false }));
        assert!(svc.handle("unregister", json!({})).await.is_err());
    }

    #[test]
    fn reap_evicts_only_stale_entries() {
        let now = Utc::now();
        let mut windows = HashMap::new();
        windows.insert(
            "fresh".to_string(),
            WindowEntry {
                key: "fresh".to_string(),
                folders: vec![],
                repo: None,
                title: None,
                pid: None,
                last_seen: now - chrono::Duration::seconds(5),
            },
        );
        windows.insert(
            "stale".to_string(),
            WindowEntry {
                key: "stale".to_string(),
                folders: vec![],
                repo: None,
                title: None,
                pid: None,
                last_seen: now - chrono::Duration::seconds(120),
            },
        );
        reap(&mut windows, DEFAULT_TTL, now);
        assert!(windows.contains_key("fresh"));
        assert!(!windows.contains_key("stale"));
    }

    #[test]
    fn sorted_entries_orders_by_repo_then_key() {
        let now = Utc::now();
        let mut windows = HashMap::new();
        for (key, repo) in [("z", "repo-a"), ("a", "repo-b"), ("m", "repo-a")] {
            windows.insert(
                key.to_string(),
                WindowEntry {
                    key: key.to_string(),
                    folders: vec![],
                    repo: Some(repo.to_string()),
                    title: None,
                    pid: None,
                    last_seen: now,
                },
            );
        }
        let entries = sorted_entries(&windows);
        let ordered: Vec<(&str, &str)> = entries
            .iter()
            .map(|e| (e.key.as_str(), e.repo.as_deref().unwrap()))
            .collect();
        assert_eq!(
            ordered,
            vec![("m", "repo-a"), ("z", "repo-a"), ("a", "repo-b")]
        );
    }

    #[test]
    fn display_name_prefers_repo_then_folder_basename() {
        let base = WindowEntry {
            key: "k".to_string(),
            folders: vec![PathBuf::from("/home/me/project")],
            repo: Some("my-repo".to_string()),
            title: None,
            pid: None,
            last_seen: Utc::now(),
        };
        assert_eq!(display_name(&base), "my-repo");

        let no_repo = WindowEntry {
            repo: None,
            ..base.clone()
        };
        assert_eq!(display_name(&no_repo), "project");

        let nothing = WindowEntry {
            repo: None,
            folders: vec![],
            ..base.clone()
        };
        assert_eq!(display_name(&nothing), "(no folder)");

        // A folder with no basename (the filesystem root) falls back to its
        // displayed path rather than panicking or yielding an empty name.
        let rootish = WindowEntry {
            repo: None,
            folders: vec![PathBuf::from("/")],
            ..base
        };
        assert_eq!(display_name(&rootish), "/");
    }

    #[test]
    fn default_constructs_an_empty_service() {
        let svc = WorktreesService::default();
        assert!(svc.lock().is_empty());
    }

    #[test]
    fn window_menu_items_label_omits_redundant_title_and_skips_folderless_actions() {
        let now = Utc::now();
        let entries = vec![
            // Title differs from the repo name → "name · title".
            WindowEntry {
                key: "k1".to_string(),
                folders: vec![PathBuf::from("/tmp/a")],
                repo: Some("repo".to_string()),
                title: Some("a branch".to_string()),
                pid: None,
                last_seen: now,
            },
            // Title equals the display name → label is just the name (the
            // `_ => name` arm), and no folder means no Focus action.
            WindowEntry {
                key: "k2".to_string(),
                folders: vec![],
                repo: Some("solo".to_string()),
                title: Some("solo".to_string()),
                pid: None,
                last_seen: now,
            },
        ];
        let items = window_menu_items(&entries);
        let labels: Vec<&str> = items
            .iter()
            .filter_map(|i| match i {
                MenuItem::Label(t) => Some(t.as_str()),
                _ => None,
            })
            .collect();
        assert!(labels.contains(&"repo · a branch"));
        assert!(labels.contains(&"solo")); // not "solo · solo"

        let action_ids: Vec<&str> = items
            .iter()
            .filter_map(|i| match i {
                MenuItem::Action(a) => Some(a.id.as_str()),
                _ => None,
            })
            .collect();
        // Only the folder-bearing window gets a Focus action.
        assert_eq!(action_ids, vec!["focus:k1"]);
    }

    #[tokio::test]
    async fn menu_and_status_shapes() {
        let svc = WorktreesService::new();
        // Empty.
        let menu = svc.menu();
        assert_eq!(menu.title, "Worktrees");
        assert!(matches!(
            menu.items.first(),
            Some(MenuItem::Label(text)) if text == "No open windows"
        ));
        let status = svc.status().await;
        assert_eq!(status.name, "worktrees");
        assert!(status.healthy);
        assert_eq!(status.summary, "0 window(s) across 0 repo(s)");

        // With two windows in the same repo.
        svc.handle("register", register_payload("w1", Some("repo-a"), "/tmp/a"))
            .await
            .unwrap();
        svc.handle("register", register_payload("w2", Some("repo-a"), "/tmp/b"))
            .await
            .unwrap();
        let status = svc.status().await;
        assert_eq!(status.summary, "2 window(s) across 1 repo(s)");

        let menu = svc.menu();
        // Two labels + a separator + two focus actions.
        assert!(menu.items.iter().any(|i| matches!(i, MenuItem::Separator)));
        let action_ids: Vec<&str> = menu
            .items
            .iter()
            .filter_map(|i| match i {
                MenuItem::Action(a) => Some(a.id.as_str()),
                _ => None,
            })
            .collect();
        assert!(action_ids.contains(&"focus:w1"));
        assert!(action_ids.contains(&"focus:w2"));
    }

    #[tokio::test]
    async fn menu_action_rejects_unknown_and_missing_window() {
        let svc = WorktreesService::new();
        assert!(svc.menu_action("bogus").await.is_err());
        // A focus for a key with no registration errors rather than spawning.
        assert!(svc.menu_action("focus:nope").await.is_err());
        svc.shutdown().await;
    }

    /// Restores `OMNI_DEV_VSCODE_BIN` on drop. Only this test reads the variable
    /// (via `resolve_code_binary` → `focus_window`), so there is no cross-test
    /// race despite the process-global mutation.
    struct VscodeBinGuard(Option<std::ffi::OsString>);
    impl Drop for VscodeBinGuard {
        fn drop(&mut self) {
            match self.0.take() {
                Some(v) => std::env::set_var(VSCODE_BIN_ENV, v),
                None => std::env::remove_var(VSCODE_BIN_ENV),
            }
        }
    }

    #[tokio::test]
    async fn menu_action_focus_resolves_folder_and_spawns() {
        let dir = tempfile::tempdir().unwrap();
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w1", "folders": [dir.path()], "repo": "r" }),
        )
        .await
        .unwrap();

        // Point the launcher at a harmless binary so the spawn deterministically
        // succeeds and the focus path returns Ok.
        let _g = VscodeBinGuard(std::env::var_os(VSCODE_BIN_ENV));
        std::env::set_var(VSCODE_BIN_ENV, "/bin/sh");
        svc.menu_action("focus:w1").await.unwrap();
    }

    #[test]
    fn focus_window_with_validates_folder_then_spawns() {
        let dir = tempfile::tempdir().unwrap();
        // Non-absolute and missing-directory folders are rejected before spawn.
        assert!(focus_window_with(Path::new("/bin/sh"), Path::new("relative/dir")).is_err());
        assert!(
            focus_window_with(Path::new("/bin/sh"), Path::new("/no/such/abs/dir/xyzzy")).is_err()
        );
        // A valid absolute directory spawns the launcher successfully.
        focus_window_with(Path::new("/bin/sh"), dir.path()).unwrap();
        // A missing launcher surfaces the spawn error (with context), not Ok.
        assert!(focus_window_with(Path::new("/no/such/launcher/xyzzy"), dir.path()).is_err());
    }

    #[test]
    fn resolve_code_binary_from_prefers_env_then_candidate_then_fallback() {
        // Env override wins outright.
        assert_eq!(
            resolve_code_binary_from(Some("/custom/code".into()), &["/usr/bin/code"]),
            PathBuf::from("/custom/code")
        );
        // No override: the first existing candidate is chosen.
        let existing = tempfile::NamedTempFile::new().unwrap();
        let existing_path = existing.path().to_str().unwrap();
        assert_eq!(
            resolve_code_binary_from(None, &["/no/such/candidate/xyzzy", existing_path]),
            PathBuf::from(existing_path)
        );
        // Nothing exists: fall back to bare `code` on PATH.
        assert_eq!(
            resolve_code_binary_from(None, &["/no/such/candidate/xyzzy"]),
            PathBuf::from("code")
        );
        // The real-env wrapper resolves without panicking.
        let _ = resolve_code_binary();
    }
}