plannotator-tui 0.10.0

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
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
//! `plannotator-tui herdr open` (and `last`, `terminal`, `review`): resolve what to open, where
//! feedback goes, and how the pane is placed, then run `herdr plugin pane open`. One command for humans (manifest actions)
//! and agents (the skill). `plan` and `argv` are pure; only `run` touches a process.

use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{Context, Result};
use plannotator_tui_hosts::Host;

use super::context::{HerdrEnv, Target};
use crate::config::{Config, Placement, SplitDirection};

/// Command-line inputs to the launcher.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct OpenArgs {
    pub(crate) path: Option<PathBuf>,
    pub(crate) placement: Option<Placement>,
    pub(crate) deliver_to: Option<String>,
    /// `last` only: open the newest reply without offering the picker first.
    pub(crate) newest: bool,
    /// `open` only: a gated review, with Approve beside Send (decision 17).
    pub(crate) gate: bool,
    /// `open --gate` only: where the pane publishes the decision; absolute.
    pub(crate) result_file: Option<PathBuf>,
}

/// A fully resolved launch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Launch {
    /// File or folder plannotator-tui opens.
    pub(crate) file: PathBuf,
    /// The pane's working directory: the file's folder, or the folder itself.
    pub(crate) cwd: PathBuf,
    pub(crate) placement: Placement,
    pub(crate) direction: SplitDirection,
    /// Popup `(width, height)`.
    pub(crate) popup: (String, String),
    /// The pane a split opens next to.
    pub(crate) target_pane: Option<String>,
    pub(crate) deliver: Option<Target>,
    /// The plugin id to open under: whatever plugin ships this binary.
    pub(crate) plugin: String,
    /// Open an agent's last message instead of `file`.
    pub(crate) message: Option<AgentMessage>,
    /// The agent's session as Herdr reports it: a transcript path or a host-specific id.
    pub(crate) session: Option<AgentSession>,
    /// Open the newest reply straight away instead of showing the picker.
    pub(crate) newest: bool,
    /// Open a pane's recent terminal output instead of `file`.
    pub(crate) terminal: Option<TerminalRead>,
    /// A gated review of `file`, and where its decision is published.
    pub(crate) gate: bool,
    pub(crate) result_file: Option<PathBuf>,
    /// A code review of the repository at `file`, in this scope (`PLANNOTATOR_TUI_REVIEW`).
    pub(crate) review: Option<String>,
}

/// Which pane's output the opened pane reads, and how much of it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TerminalRead {
    pub(crate) pane: String,
    pub(crate) lines: u32,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AgentMessage {
    pub(crate) host: String,
    pub(crate) pid: Option<u32>,
}

/// `agent_session` from `herdr agent get`: the exact transcript when Herdr knows it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum AgentSession {
    Path(String),
    Id(String),
}

/// Parse `herdr agent get <pane>` JSON for its `agent_session`, when present.
pub(crate) fn agent_session(agent_get_json: &str) -> Option<AgentSession> {
    let json: serde_json::Value = serde_json::from_str(agent_get_json).ok()?;
    let session = json.pointer("/result/agent/agent_session")?;
    let value = session.get("value")?.as_str()?;
    if value.trim().is_empty() {
        return None;
    }
    match session.get("kind")?.as_str()? {
        "path" => Some(AgentSession::Path(value.to_owned())),
        "id" => Some(AgentSession::Id(value.to_owned())),
        _ => None,
    }
}

/// Parse `herdr agent get <pane>` JSON for a host with a transcript reader.
fn agent_host(agent_get_json: &str) -> Option<&'static str> {
    let json: serde_json::Value = serde_json::from_str(agent_get_json).ok()?;
    let label = json.pointer("/result/agent/agent")?.as_str()?;
    Host::ALL.into_iter().find(|host| host.label() == label).map(Host::label)
}

/// A supported host plus the exact session reference Herdr reported.
pub(crate) fn agent_identity(agent_get_json: &str) -> Option<(String, AgentSession)> {
    Some((agent_host(agent_get_json)?.to_owned(), agent_session(agent_get_json)?))
}

/// The agent process behind a pane, from `herdr pane process-info --pane <id>` JSON: the
/// foreground process whose name is a known agent, else the group leader. Returns
/// `(pid, host)` where host is the label `plannotator-tui last --host` accepts.
pub(crate) fn agent_pid(process_info_json: &str) -> Option<(u32, String)> {
    let json: serde_json::Value = serde_json::from_str(process_info_json).ok()?;
    let info = json.pointer("/result/process_info")?;
    let processes = info.get("foreground_processes")?.as_array()?;
    let name_of = |p: &serde_json::Value| p.get("name").and_then(|n| n.as_str()).unwrap_or("").to_owned();
    let pid_of = |p: &serde_json::Value| p.get("pid").and_then(serde_json::Value::as_u64).map(|n| n as u32);
    for process in processes {
        let name = name_of(process);
        if let Some(host) = known_host(&name) {
            return pid_of(process).map(|pid| (pid, host.to_owned()));
        }
    }
    // No process we can read: report the group leader under its own name, so the pane can
    // say "<name> is not supported" and fall back to the screen.
    let leader = info.get("foreground_process_group_id").and_then(serde_json::Value::as_u64)?;
    let process = processes.iter().find(|p| pid_of(p) == Some(leader as u32))?;
    let name = name_of(process);
    let host = program_name(&name).to_owned();
    pid_of(process).map(|pid| (pid, if host.is_empty() { "claude".to_owned() } else { host }))
}

/// A process name without its directory (`/` or `\`) or Windows `.exe` suffix:
/// `C:\tools\agy.exe` and `/usr/bin/agy` are both `agy`.
fn program_name(name: &str) -> &str {
    let base = name.rsplit(['/', '\\']).next().unwrap_or(name);
    match base.rsplit_once('.') {
        Some((stem, extension)) if extension.eq_ignore_ascii_case("exe") => stem,
        _ => base,
    }
}

/// Agents whose transcripts the hosts crate can read, by process name.
pub(crate) fn known_host(name: &str) -> Option<&'static str> {
    match program_name(name) {
        "claude" => Some("claude"),
        "codex" => Some("codex"),
        "pi" => Some("pi"),
        "opencode" => Some("opencode"),
        "agy" => Some("agy"),
        _ => None,
    }
}

/// Resolve a `last` launch. An exact Herdr session needs no process metadata; otherwise the
/// caller supplies the pane's process info as the fallback.
pub(crate) fn plan_last(
    env: &HerdrEnv,
    config: &Config,
    args: OpenArgs,
    cwd: &Path,
    process_info_json: Option<&str>,
    agent_get_json: Option<&str>,
) -> Result<Launch> {
    let newest = args.newest;
    let mut launch = plan(env, config, OpenArgs { path: None, ..args }, cwd)?;
    launch.newest = newest;
    let pane = launch.deliver.as_ref().map(|t| t.pane.clone()).or_else(|| launch.target_pane.clone());
    let Some(pane) = pane else {
        anyhow::bail!("no agent pane to read: not focused on one and no --deliver-to")
    };
    launch.file.clone_from(&launch.cwd);
    if let Some((host, session)) = agent_get_json.and_then(agent_identity) {
        launch.message = Some(AgentMessage { host, pid: None });
        launch.session = Some(session);
        return Ok(launch);
    }
    let process_info = process_info_json
        .with_context(|| format!("no exact agent session or process info for pane {pane}"))?;
    let Some((pid, process_host)) = agent_pid(process_info) else {
        anyhow::bail!("no agent process found in pane {pane}");
    };
    let host = agent_get_json.and_then(agent_host).unwrap_or(&process_host).to_owned();
    launch.message = Some(AgentMessage { host, pid: Some(pid) });
    Ok(launch)
}

/// Resolve a `terminal` launch: the reviewed pane's output opens in the doc pane, and feedback
/// goes where it would for `last` — the focused pane when an agent runs there, or
/// `--deliver-to` — else to the clipboard.
pub(crate) fn plan_terminal(
    env: &HerdrEnv,
    config: &Config,
    args: OpenArgs,
    cwd: &Path,
    read: TerminalRead,
) -> Result<Launch> {
    let mut launch = plan(env, config, OpenArgs { path: None, newest: false, ..args }, cwd)?;
    launch.file.clone_from(&launch.cwd);
    // A split opens beside the pane being reviewed, whoever receives the feedback.
    launch.target_pane = Some(read.pane.clone());
    launch.terminal = Some(read);
    Ok(launch)
}

/// A `file://` URL as a local path; anything else is not ours to open.
fn file_url_path(url: &str) -> Option<PathBuf> {
    let rest = url.strip_prefix("file://")?;
    // `file:///abs` → `/abs`; `file://host/abs` → `/abs` for localhost only.
    let path = match rest.find('/') {
        Some(0) => rest,
        Some(slash) if matches!(&rest[..slash], "" | "localhost") => &rest[slash..],
        _ => return None,
    };
    let decoded = percent_decode(path);
    // Windows: `file:///C:/x` carries a leading slash before the drive letter.
    #[cfg(windows)]
    let decoded = match decoded.as_bytes() {
        [b'/', drive, b':', ..] if drive.is_ascii_alphabetic() => {
            decoded.get(1..).unwrap_or_default().to_owned()
        }
        _ => decoded,
    };
    Some(PathBuf::from(decoded))
}

fn percent_decode(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        let decoded = (bytes.get(i) == Some(&b'%'))
            .then(|| s.get(i + 1..i + 3))
            .flatten()
            .and_then(|hex| u8::from_str_radix(hex, 16).ok());
        if let Some(byte) = decoded {
            out.push(byte);
            i += 3;
        } else {
            out.extend(bytes.get(i..=i).unwrap_or_default());
            i += 1;
        }
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Resolve every input per the contract. `cwd` is the launcher process's directory.
pub(crate) fn plan(env: &HerdrEnv, config: &Config, args: OpenArgs, cwd: &Path) -> Result<Launch> {
    let context = env.context.as_ref();
    let placement = match (args.placement, env.placement.as_deref()) {
        (Some(p), _) => p,
        (None, Some(text)) => text.parse().context("PLANNOTATOR_TUI_PLACEMENT")?,
        // Mirror imports ordinary panes, not the remote client's overlays. Herdr
        // 0.8.2 also places overlays in its globally active tab, which may differ
        // from the invoking mirror. A targeted split reaches the intended tab.
        (None, None)
            if config.herdr.placement == Placement::Overlay
                && context.and_then(|c| c.invocation_source.as_deref()) == Some("mirror") =>
        {
            Placement::Split
        }
        (None, None) => config.herdr.placement,
    };

    let file = args
        .path
        .or_else(|| context.and_then(|c| c.clicked_url.as_deref()).and_then(file_url_path))
        .or_else(|| context.and_then(|c| c.focused_pane_cwd.clone()).map(PathBuf::from))
        .or_else(|| context.and_then(|c| c.workspace_cwd.clone()).map(PathBuf::from))
        .unwrap_or_else(|| cwd.to_path_buf());
    let file = if file.is_absolute() { file } else { cwd.join(file) };
    let dir = if file.is_dir() {
        file.clone()
    } else {
        file.parent().map_or_else(|| cwd.to_path_buf(), Path::to_path_buf)
    };

    let deliver = match args.deliver_to {
        Some(pane) => Some(Target { pane, agent: None }),
        // With a context (a manifest action) the focused pane counts only when an agent
        // runs there. Without one, the caller is an agent running the skill from its own
        // pane, and HERDR_PANE_ID is that pane.
        None if env.context.is_some() => env.focused_agent_pane(),
        None => env.pane_id.clone().map(|pane| Target { pane, agent: None }),
    };
    let target_pane = deliver
        .as_ref()
        .map(|t| t.pane.clone())
        .or_else(|| context.and_then(|c| c.focused_pane_id.clone()))
        .or_else(|| env.pane_id.clone());

    Ok(Launch {
        file,
        cwd: dir,
        placement,
        direction: config.herdr.split_direction,
        popup: (config.herdr.popup_width.clone(), config.herdr.popup_height.clone()),
        target_pane,
        deliver,
        plugin: env.plugin_id.clone().unwrap_or_else(|| "annotate".to_owned()),
        message: None,
        session: None,
        newest: false,
        terminal: None,
        gate: args.gate,
        result_file: args.result_file,
        review: None,
    })
}

#[cfg_attr(not(unix), allow(dead_code, reason = "code review is unix only"))]
/// The folder `herdr review` looks for a repository in: the focused pane's, else the
/// workspace's, else the launcher's own.
pub(crate) fn review_folder(env: &HerdrEnv, cwd: &Path) -> PathBuf {
    let context = env.context.as_ref();
    context
        .and_then(|c| c.focused_pane_cwd.clone())
        .or_else(|| context.and_then(|c| c.workspace_cwd.clone()))
        .map_or_else(|| cwd.to_path_buf(), PathBuf::from)
}

#[cfg_attr(not(unix), allow(dead_code, reason = "code review is unix only"))]
/// Resolve a `review` launch of the repository at `root` (already checked to have changes)
/// in `scope`. Delivery and placement resolve as for `open`.
pub(crate) fn plan_review(
    env: &HerdrEnv,
    config: &Config,
    args: OpenArgs,
    root: &Path,
    scope: String,
) -> Result<Launch> {
    let args =
        OpenArgs { path: Some(root.to_path_buf()), newest: false, gate: false, result_file: None, ..args };
    let mut launch = plan(env, config, args, root)?;
    launch.cwd = root.to_path_buf();
    launch.review = Some(scope);
    Ok(launch)
}

/// The `herdr` arguments for a launch.
pub(crate) fn argv(launch: &Launch) -> Vec<String> {
    let mut out: Vec<String> = ["plugin", "pane", "open", "--plugin", &launch.plugin, "--entrypoint", "doc"]
        .into_iter()
        .map(str::to_owned)
        .collect();
    out.extend(["--placement".to_owned(), launch.placement.to_string()]);
    match launch.placement {
        Placement::Split => {
            out.extend(["--direction".to_owned(), launch.direction.to_string()]);
            if let Some(pane) = &launch.target_pane {
                out.extend(["--target-pane".to_owned(), pane.clone()]);
            }
        }
        Placement::Popup => {
            out.extend(["--width".to_owned(), launch.popup.0.clone()]);
            out.extend(["--height".to_owned(), launch.popup.1.clone()]);
        }
        Placement::Overlay => {}
    }
    out.push("--focus".to_owned());
    out.extend(["--cwd".to_owned(), launch.cwd.display().to_string()]);
    match (&launch.message, &launch.terminal) {
        (_, Some(terminal)) => {
            out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_TERMINAL_PANE={}", terminal.pane)]);
            out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_TERMINAL_LINES={}", terminal.lines)]);
        }
        (Some(message), None) => {
            if let Some(pid) = message.pid {
                out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_MESSAGE_PID={pid}")]);
            }
            out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_HOST={}", message.host)]);
            if launch.newest {
                out.extend(["--env".to_owned(), "PLANNOTATOR_TUI_NEWEST=1".to_owned()]);
            }
            out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_CWD={}", launch.cwd.display())]);
            match &launch.session {
                Some(AgentSession::Path(p)) => {
                    out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_SESSION={p}")]);
                }
                Some(AgentSession::Id(id)) => {
                    out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_SESSION_ID={id}")]);
                }
                None => {}
            }
        }
        (None, None) if let Some(scope) = &launch.review => {
            out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_REVIEW={scope}")]);
            out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_REPO={}", launch.file.display())]);
        }
        (None, None) => {
            out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_FILE={}", launch.file.display())]);
            if launch.gate {
                out.extend(["--env".to_owned(), "PLANNOTATOR_TUI_GATE=1".to_owned()]);
            }
            if let Some(file) = launch.result_file.as_ref().filter(|_| launch.gate) {
                out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_RESULT_FILE={}", file.display())]);
            }
        }
    }
    if let Some(target) = &launch.deliver {
        out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_DELIVER_TO={}", target.pane)]);
        if let Some(agent) = &target.agent {
            out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_DELIVER_AGENT={agent}")]);
        }
    }
    out
}

/// `herdr pane process-info --pane <pane>`, raw JSON.
pub(crate) fn process_info(env: &HerdrEnv, pane: &str) -> Result<String> {
    let output = Command::new(&env.bin)
        .args(["pane", "process-info", "--pane", pane])
        .output()
        .with_context(|| format!("running {} pane process-info", env.bin.display()))?;
    if !output.status.success() {
        anyhow::bail!("herdr pane process-info {pane}: {}", String::from_utf8_lossy(&output.stderr).trim());
    }
    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

/// `herdr agent get <pane>`, raw JSON; `None` when the pane has no agent Herdr can describe.
pub(crate) fn agent_get(env: &HerdrEnv, pane: &str) -> Option<String> {
    let output = Command::new(&env.bin).args(["agent", "get", pane]).output().ok()?;
    output.status.success().then(|| String::from_utf8_lossy(&output.stdout).into_owned())
}

/// Run the launch through `bin`. Herdr's own stdout/stderr pass through.
pub(crate) fn run(env: &HerdrEnv, launch: &Launch) -> Result<()> {
    if !env.in_herdr {
        anyhow::bail!("not inside Herdr (HERDR_ENV is not set)");
    }
    let status = Command::new(&env.bin)
        .args(argv(launch))
        .status()
        .with_context(|| format!("running {}", env.bin.display()))?;
    if !status.success() {
        anyhow::bail!("herdr plugin pane open failed with {status}");
    }
    Ok(())
}

#[cfg(test)]
mod tests;