herdr-palette 0.1.2

A Raycast/Linear-style fuzzy command palette for Herdr
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
//! Dispatch tier map + execution.
//!
//! Herdr v1's socket API can: create/focus/split/close/zoom panes, create/
//! rename/close/focus workspaces and tabs, focus agents, and invoke plugin
//! actions. It CANNOT replay an arbitrary keybinding chord, so actions like
//! `help` (`prefix+?`), `settings` (`prefix+s`), `detach` (`prefix+q`),
//! `goto`, `workspace_picker`, `toggle_sidebar`, `resize_mode`, and
//! `edit_scrollback` have no programmatic path from a plugin — they're
//! reference-only in the palette (shown greyed with their chord).
//!
//! Tier A = direct `herdr <subcommand>` (create/rename/close/focus/split/zoom).
//! Tier B = list + resolve + focus, for prev/next navigation.
//! Reference = no dispatch (keybinding-only actions).

use crate::items::Dispatch;
use anyhow::{Context, Result};
use std::process::Command;

/// Map a Herdr keybinding action name to its dispatch path, or `None` if the
/// action is keybinding-only (no socket/CLI equivalent in v1).
///
/// Action names come from `herdr_pretty_which::model::SPECS` — they're the
/// canonical Herdr action ids (e.g. `new_workspace`, `focus_pane_left`).
pub fn dispatch_for_action(action: &str) -> Option<Dispatch> {
    use Dispatch::*;
    let d = match action {
        // --- Workspaces ---
        "new_workspace" => Cli(vec_into(&["herdr", "workspace", "create", "--focus"])),
        "new_worktree" => Cli(vec_into(&["herdr", "worktree", "create", "--focus"])),
        "previous_workspace" => PrevWorkspace,
        "next_workspace" => NextWorkspace,

        // --- Tabs ---
        "new_tab" => Cli(vec_into(&["herdr", "tab", "create", "--focus"])),
        "previous_tab" => PrevTab,
        "next_tab" => NextTab,

        // --- Panes / agents ---
        "split_vertical" => Cli(vec_into(&[
            "herdr",
            "pane",
            "split",
            "--direction",
            "right",
            "--focus",
        ])),
        "split_horizontal" => Cli(vec_into(&[
            "herdr",
            "pane",
            "split",
            "--direction",
            "down",
            "--focus",
        ])),
        "zoom" | "fullscreen" => Cli(vec_into(&[
            "herdr",
            "pane",
            "zoom",
            "--current",
            "--toggle",
        ])),
        "focus_pane_left" => Cli(vec_into(&["herdr", "pane", "focus", "--direction", "left"])),
        "focus_pane_down" => Cli(vec_into(&["herdr", "pane", "focus", "--direction", "down"])),
        "focus_pane_up" => Cli(vec_into(&["herdr", "pane", "focus", "--direction", "up"])),
        "focus_pane_right" => Cli(vec_into(&[
            "herdr",
            "pane",
            "focus",
            "--direction",
            "right",
        ])),
        "previous_agent" => PrevAgent,
        "next_agent" => NextAgent,

        // --- Keybinding-only (no v1 dispatch path) ---
        // help, settings, detach, goto, workspace_picker, switch_tab,
        // switch_workspace, resize_mode, toggle_sidebar, edit_scrollback,
        // last_pane, focus_agent, navigate_* (these are workspace scroll /
        // pane-arrow passthroughs, not focus primitives), open_notification_target,
        // reload_config (has a CLI but clobbers live session — leave to chord),
        // open_worktree, remove_worktree.
        _ => return None,
    };
    Some(d)
}

/// Resolve the `herdr` binary path. `HERDR_BIN_PATH` wins, else PATH lookup.
pub fn herdr_bin() -> Result<String> {
    if let Ok(p) = std::env::var("HERDR_BIN_PATH") {
        if !p.is_empty() {
            return Ok(p);
        }
    }
    which("herdr").context("could not find `herdr` on PATH (set HERDR_BIN_PATH?)")
}

fn which(cmd: &str) -> Result<String, std::io::Error> {
    // Lightweight PATH lookup; avoids pulling in the `which` crate for one call.
    let path = std::env::var_os("PATH").unwrap_or_default();
    for dir in std::env::split_paths(&path) {
        let candidate = dir.join(cmd);
        if candidate.is_file() {
            return Ok(candidate.to_string_lossy().into_owned());
        }
    }
    Err(std::io::Error::new(
        std::io::ErrorKind::NotFound,
        format!("{cmd} not found on PATH"),
    ))
}

/// Execute a [`Dispatch`]. Spawns the resolved command(s) detached; the palette
/// closes immediately after so Herdr retains focus. Errors are surfaced but do
/// not panic.
pub fn run(dispatch: &Dispatch) -> Result<()> {
    match dispatch {
        Dispatch::Cli(argv) => {
            let strs: Vec<&str> = argv.iter().map(|s| s.as_str()).collect();
            run_argv(&strs)?;
        }
        Dispatch::FocusWorkspace(id) => {
            run_argv(&["herdr", "workspace", "focus", id])?;
        }
        Dispatch::FocusTab(id) => {
            run_argv(&["herdr", "tab", "focus", id])?;
        }
        Dispatch::FocusAgent(target) => {
            run_argv(&["herdr", "agent", "focus", target])?;
        }
        Dispatch::NextWorkspace => {
            focus_neighbor("workspace", Neighbor::Next)?;
        }
        Dispatch::PrevWorkspace => {
            focus_neighbor("workspace", Neighbor::Prev)?;
        }
        Dispatch::NextTab => {
            focus_neighbor("tab", Neighbor::Next)?;
        }
        Dispatch::PrevTab => {
            focus_neighbor("tab", Neighbor::Prev)?;
        }
        Dispatch::NextAgent => {
            focus_neighbor("agent", Neighbor::Next)?;
        }
        Dispatch::PrevAgent => {
            focus_neighbor("agent", Neighbor::Prev)?;
        }
    }
    Ok(())
}

#[derive(Clone, Copy)]
enum Neighbor {
    Next,
    Prev,
}

/// Resolve the live ordered list of `<kind>` ids, find the current one, and
/// focus its neighbor. `<kind>` ∈ {workspace, tab, agent}. For agents, "current"
/// is the focused terminal; for workspaces/tabs it's the focused entity.
fn focus_neighbor(kind: &str, neighbor: Neighbor) -> Result<()> {
    let entries = list_entries(kind)?;
    let ids: Vec<String> = entries.iter().map(|(id, _)| id.clone()).collect();
    if ids.len() < 2 {
        return Ok(()); // nothing to cycle
    }
    let current = current_id(kind)?;
    let pos = ids.iter().position(|id| id == &current).unwrap_or(0);
    let target = match neighbor {
        Neighbor::Next => (pos + 1) % ids.len(),
        Neighbor::Prev => (pos + ids.len() - 1) % ids.len(),
    };
    let id = &ids[target];
    run_argv(&["herdr", kind, "focus", id])
}

/// `herdr <kind> list` → ordered vector of (id, label). JSON is the default
/// output for all herdr list commands (no `--json` flag exists). Public so the
/// source collector can build jump targets from the same resolver the
/// prev/next dispatch path uses.
pub fn list_entries(kind: &str) -> Result<Vec<(String, String)>> {
    let out = Command::new(herdr_bin()?).args([kind, "list"]).output()?;
    if !out.status.success() {
        anyhow::bail!(
            "herdr {kind} list failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }
    let text = String::from_utf8_lossy(&out.stdout);
    extract_entries(&text, kind).context("could not parse entries from list output")
}

/// `herdr status --json`-style current-id probe. Falls back to first id if the
/// current entity can't be determined.
fn current_id(kind: &str) -> Result<String> {
    let out = Command::new(herdr_bin()?).args([kind, "list"]).output()?;
    if !out.status.success() {
        anyhow::bail!(
            "herdr {kind} list failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }
    let text = String::from_utf8_lossy(&out.stdout);
    extract_focused_id(&text, kind).context("could not determine focused id from list output")
}

/// Extract ordered (id, label) entries from a herdr JSON list envelope.
/// Id field is kind-specific: `workspace_id`, `tab_id`, or `terminal_id`.
/// Label is `label` (workspaces/tabs); for agents we synthesize
/// `<agent> · <cwd basename>` since agents have no `label` field.
fn extract_entries(text: &str, kind: &str) -> Result<Vec<(String, String)>> {
    let id_field = id_field_for_kind(kind);
    let v: serde_json::Value = serde_json::from_str(text).context("list output was not JSON")?;
    let arr = list_array_for_kind(&v, kind).context("list output had no array")?;
    let mut out = Vec::with_capacity(arr.len());
    for entry in arr {
        let id = entry
            .get(id_field)
            .and_then(|i| i.as_str())
            .map(str::to_string);
        let label = match kind {
            "agent" => {
                let agent = entry
                    .get("agent")
                    .and_then(|s| s.as_str())
                    .unwrap_or("agent");
                let cwd = entry
                    .get("cwd")
                    .and_then(|s| s.as_str())
                    .map(|c| {
                        std::path::Path::new(c)
                            .file_name()
                            .map(|f| f.to_string_lossy().into_owned())
                            .unwrap_or_else(|| c.to_string())
                    })
                    .unwrap_or_default();
                format!("{agent} · {cwd}")
            }
            _ => entry
                .get("label")
                .and_then(|s| s.as_str())
                .map(str::to_string)
                .unwrap_or_default(),
        };
        if let Some(id) = id {
            out.push((id, label));
        }
    }
    Ok(out)
}

fn extract_focused_id(text: &str, kind: &str) -> Result<String> {
    let id_field = id_field_for_kind(kind);
    let v: serde_json::Value = serde_json::from_str(text).context("list output was not JSON")?;
    let arr = list_array_for_kind(&v, kind).context("list output had no array")?;
    let fallback = arr
        .iter()
        .find_map(|entry| entry.get(id_field).and_then(|id| id.as_str()));
    arr.iter()
        .find(|entry| entry.get("focused").and_then(|focused| focused.as_bool()) == Some(true))
        .and_then(|entry| entry.get(id_field).and_then(|id| id.as_str()))
        .or(fallback)
        .map(str::to_string)
        .context("list output had no id")
}

fn list_array_for_kind<'a>(
    v: &'a serde_json::Value,
    kind: &str,
) -> Option<&'a Vec<serde_json::Value>> {
    let plural = match kind {
        "workspace" => "workspaces",
        "tab" => "tabs",
        "agent" => "agents",
        other => other,
    };
    v.get("result")
        .and_then(|r| r.get(plural))
        .and_then(|w| w.as_array())
        .or_else(|| v.as_array())
}

fn id_field_for_kind(kind: &str) -> &'static str {
    match kind {
        "workspace" => "workspace_id",
        "tab" => "tab_id",
        "agent" => "terminal_id",
        _ => "id",
    }
}

/// Run an argv, resolving `argv[0] == "herdr"` to the real binary path. String
/// slices are promoted to owned for the child.
fn run_argv(argv: &[&str]) -> Result<()> {
    let mut owned: Vec<String> = argv.iter().map(|s| s.to_string()).collect();
    if owned.first().is_some_and(|first| first == "herdr") {
        owned[0] = herdr_bin()?;
    }
    let (cmd, args) = owned.split_first().context("empty argv")?;
    Command::new(cmd).args(args).spawn()?.wait()?;
    Ok(())
}

fn vec_into(slice: &[&str]) -> Vec<String> {
    slice.iter().map(|s| s.to_string()).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dispatchable_actions_map_to_herdr_0_7_cli() {
        assert!(matches!(
            dispatch_for_action("new_workspace"),
            Some(Dispatch::Cli(_))
        ));
        assert!(matches!(
            dispatch_for_action("split_vertical"),
            Some(Dispatch::Cli(ref argv)) if argv == &vec_into(&["herdr", "pane", "split", "--direction", "right", "--focus"])
        ));
        assert!(matches!(
            dispatch_for_action("split_horizontal"),
            Some(Dispatch::Cli(ref argv)) if argv == &vec_into(&["herdr", "pane", "split", "--direction", "down", "--focus"])
        ));
        assert!(matches!(
            dispatch_for_action("focus_pane_left"),
            Some(Dispatch::Cli(ref argv)) if argv == &vec_into(&["herdr", "pane", "focus", "--direction", "left"])
        ));
        assert!(matches!(
            dispatch_for_action("zoom"),
            Some(Dispatch::Cli(ref argv)) if argv == &vec_into(&["herdr", "pane", "zoom", "--current", "--toggle"])
        ));
    }

    #[test]
    fn id_or_prompt_required_actions_are_reference_only() {
        for action in [
            "rename_workspace",
            "close_workspace",
            "rename_tab",
            "close_tab",
            "rename_pane",
            "close_pane",
            "cycle_pane_next",
            "cycle_pane_previous",
        ] {
            assert!(
                dispatch_for_action(action).is_none(),
                "{action} should stay reference-only until palette can supply the required target/prompt"
            );
        }
    }

    #[test]
    fn prev_next_map_to_neighbor_dispatch() {
        assert!(matches!(
            dispatch_for_action("next_workspace"),
            Some(Dispatch::NextWorkspace)
        ));
        assert!(matches!(
            dispatch_for_action("previous_tab"),
            Some(Dispatch::PrevTab)
        ));
        assert!(matches!(
            dispatch_for_action("next_agent"),
            Some(Dispatch::NextAgent)
        ));
    }

    #[test]
    fn keybinding_only_actions_have_no_dispatch() {
        for action in [
            "help",
            "settings",
            "detach",
            "goto",
            "workspace_picker",
            "resize_mode",
            "toggle_sidebar",
            "edit_scrollback",
            "reload_config",
        ] {
            assert!(
                dispatch_for_action(action).is_none(),
                "{action} should be reference-only"
            );
        }
    }

    #[test]
    fn extract_focused_id_uses_focused_field_before_fallback() {
        let ws = r#"{"result":{"workspaces":[{"workspace_id":"w1","label":"one","focused":false},{"workspace_id":"w2","label":"two","focused":true}]}}"#;
        assert_eq!(extract_focused_id(ws, "workspace").unwrap(), "w2");

        let agents = r#"{"result":{"agents":[{"terminal_id":"term_1","focused":false},{"terminal_id":"term_2","focused":true}]}}"#;
        assert_eq!(extract_focused_id(agents, "agent").unwrap(), "term_2");
    }

    #[test]
    fn extract_entries_maps_kind_specific_id_fields() {
        let ws = r#"{"result":{"workspaces":[{"workspace_id":"w1","label":"toolbox"}]}}"#;
        assert_eq!(
            extract_entries(ws, "workspace").unwrap(),
            vec![("w1".into(), "toolbox".into())]
        );

        let tabs = r#"{"result":{"tabs":[{"tab_id":"w1:t1","label":"logs"}]}}"#;
        assert_eq!(
            extract_entries(tabs, "tab").unwrap(),
            vec![("w1:t1".into(), "logs".into())]
        );
    }

    #[test]
    fn extract_entries_synthesizes_agent_label() {
        let agents = r#"{"result":{"agents":[{"terminal_id":"term_1","agent":"claude","cwd":"/Users/x/toolbox"}]}}"#;
        let e = extract_entries(agents, "agent").unwrap();
        assert_eq!(e.len(), 1);
        assert_eq!(e[0].0, "term_1");
        assert_eq!(e[0].1, "claude · toolbox");
    }

    #[test]
    fn extract_entries_falls_back_to_flat_array() {
        let flat = r#"[{"workspace_id":"w1","label":"a"}]"#;
        assert_eq!(
            extract_entries(flat, "workspace").unwrap(),
            vec![("w1".into(), "a".into())]
        );
    }
}