plannotator-tui 0.11.6

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
441
442
443
444
445
446
447
448
//! `plannotator-tui rex last|open|terminal|find|review`: find the agent in a Rex block and open
//! plannotator-tui in a tab of its own, beside the block (a split) or over it (a popup), wired
//! to send feedback back to the block. Each is an ordinary pane, so it keeps Rex's frame and
//! theme. `foreground`,
//! `reported_host` and `argv` are pure; only `run` touches Rex.

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

use anyhow::{Context, Result};
use serde_json::Value;

use super::agent::{AGENT_VAR, BLOCK_VAR, PI_SESSION_VAR, PID_VAR, SUBMIT_VAR};
use super::command::Rex;
use crate::config::RexPlacement;
use crate::herdr::launch::known_host;

/// What the opened pane reviews.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Review {
    /// The agent's recent replies; `newest` skips the picker.
    Last { newest: bool },
    /// A file or folder; the block's directory when `None`. With a [`Gate`], the review can
    /// be approved, as `herdr open --gate` does.
    Open(Option<PathBuf>, Option<Gate>),
    /// The block's last `lines` lines of output.
    Terminal { lines: u32 },
    /// The newest Markdown file named in the block's last `lines` lines of output. `run`
    /// turns it into an `Open`.
    Find { lines: u32 },
    /// A code review of the repository at `repo`, already checked to have changes in `scope`
    /// (as [`crate::review::scope`] writes it).
    #[cfg_attr(not(unix), allow(dead_code, reason = "code review is unix only"))]
    Code { scope: String, repo: PathBuf },
}

/// `rex open --gate`: Approve beside Send, and where the decision is published.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Gate {
    pub(crate) result_file: Option<PathBuf>,
}

/// How feedback reaches the agent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Handoff {
    /// As its next message.
    Send,
    /// Into its prompt, for you to edit and submit.
    Paste,
}

/// The program in the foreground of a block, from `com.superlogical.terminal.process` JSON.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Foreground {
    pub(crate) pid: u32,
    pub(crate) cwd: Option<PathBuf>,
    /// The agent's host label when the program is one the hosts crate can read.
    pub(crate) host: Option<&'static str>,
}

/// Read the foreground process. Rex reports the binary's file name, which for Claude Code is
/// its version number, so the name it was invoked by is checked first. An agent run by an
/// interpreter, such as pi under `node`, is named only by its `script`, if at all; `run` asks
/// the agent's own status report first.
pub(crate) fn foreground(process: &Value) -> Option<Foreground> {
    let fg = process.get("foreground")?;
    let pid = u32::try_from(fg.get("pid")?.as_u64()?).ok()?;
    let host = ["argv0", "invoked_path", "name", "path", "script"]
        .iter()
        .filter_map(|key| fg.get(*key).and_then(Value::as_str))
        .find_map(known_host);
    let cwd = fg.get("cwd").and_then(Value::as_str).map(PathBuf::from);
    Some(Foreground { pid, cwd, host })
}

/// The agent process `pid` says it is, from `program_status` JSON: the app of a record that
/// process owns. Rex keeps records of programs that have exited, so only the owner counts.
pub(crate) fn reported_host(status: &Value, pid: u32) -> Option<&'static str> {
    let records = status.get("records")?.as_array()?;
    records
        .iter()
        .filter(|r| r.pointer("/owner/pid").and_then(Value::as_u64) == Some(u64::from(pid)))
        .flat_map(|r| ["effective_app", "app"].map(|key| r.get(key).and_then(Value::as_str)))
        .flatten()
        .find_map(|app| if app == "claude-code" { Some("claude") } else { known_host(app) })
}

/// The argv the pane runs: `env` sets the delivery target, then `plannotator-tui rex pane`
/// opens the review. Without an agent in the block, feedback goes to the clipboard.
pub(crate) fn argv(
    exe: &Path,
    block: &str,
    fg: &Foreground,
    review: &Review,
    handoff: Handoff,
) -> Result<Vec<String>> {
    let mut args = vec!["/usr/bin/env".to_owned()];
    if let Some(host) = fg.host {
        args.push(format!("{BLOCK_VAR}={block}"));
        args.push(format!("{AGENT_VAR}={host}"));
        args.push(format!("{PID_VAR}={}", fg.pid));
        if handoff == Handoff::Paste {
            args.push(format!("{SUBMIT_VAR}=0"));
        }
    }
    args.extend([exe.display().to_string(), "rex".to_owned(), "pane".to_owned()]);
    match review {
        Review::Last { newest } => {
            let host = fg.host.context("no supported agent runs in this block")?;
            args.extend(["last".to_owned(), "--pid".to_owned(), fg.pid.to_string()]);
            args.extend(["--host".to_owned(), host.to_owned()]);
            if *newest {
                args.push("--newest".to_owned());
            }
        }
        Review::Open(path, gate) => {
            let path = path.clone().or_else(|| fg.cwd.clone()).context("no file or folder to open")?;
            args.extend(["open".to_owned(), path.display().to_string()]);
            if let Some(gate) = gate {
                args.push("--gate".to_owned());
                if let Some(file) = &gate.result_file {
                    args.extend(["--result-file".to_owned(), file.display().to_string()]);
                }
            }
        }
        Review::Terminal { lines } => {
            args.extend(["terminal", "--block", block, "--lines"].map(str::to_owned));
            args.push(lines.to_string());
        }
        Review::Find { .. } => anyhow::bail!("a find review is resolved to an open before the split"),
        Review::Code { scope, repo } => {
            args.extend(["review".to_owned(), scope.clone(), repo.display().to_string()]);
        }
    }
    Ok(args)
}

/// The Markdown file a `Find` names: the newest one in the block's last `lines` lines.
fn newest_markdown(rex: &Rex, block: &str, fg: &Foreground, lines: u32) -> Result<PathBuf> {
    let text = super::terminal::read(rex, block, lines)?;
    let home = std::env::var_os("HOME").map(PathBuf::from);
    super::paths::markdown_files(&text, fg.cwd.as_deref(), home.as_deref())
        .into_iter()
        .next()
        .with_context(|| format!("no Markdown file named in the last {lines} lines of block {block}"))
}

/// The program in the foreground of `block`. The agent is the one its status report names, else
/// the one its process names; a status Rex cannot give leaves the process to decide.
pub(crate) fn agent(rex: &Rex, block: &str) -> Result<Foreground> {
    let process = rex.terminal_method(block, "process")?;
    let mut fg = foreground(&process).with_context(|| format!("block {block} has no foreground process"))?;
    if let Ok(status) = rex.terminal_method(block, "program_status") {
        fg.host = reported_host(&status, fg.pid).or(fg.host);
    }
    Ok(fg)
}

/// Open the review beside or over `block`.
pub(crate) fn run(
    rex: &Rex,
    block: &str,
    review: &Review,
    handoff: Handoff,
    placement: RexPlacement,
) -> Result<()> {
    let fg = agent(rex, block)?;
    let review = match review {
        Review::Find { lines } => Review::Open(Some(newest_markdown(rex, block, &fg, *lines)?), None),
        other => other.clone(),
    };
    open(rex, block, &fg, &review, handoff, placement)
}

/// Open `review`, resolved, beside or over `block`, where `fg` runs. A code review starts in the
/// repository's root; anything else in the block's folder.
pub(crate) fn open(
    rex: &Rex,
    block: &str,
    fg: &Foreground,
    review: &Review,
    handoff: Handoff,
    placement: RexPlacement,
) -> Result<()> {
    let exe = std::env::current_exe().context("finding the plannotator-tui binary")?;
    let mut args = argv(&exe, block, fg, review, handoff)?;
    if placement == RexPlacement::Tab {
        returning_to(&mut args, block);
    }
    // The pane checks the session in the registry the launcher found it in.
    let registry = crate::pi::root();
    if let Some(session) = pi_session(fg, review, &registry) {
        args.insert(1, format!("{PI_SESSION_VAR}={session}"));
        args.insert(1, format!("{}={}", crate::pi::SESSIONS_DIR_VAR, registry.display()));
    }
    let cwd = match review {
        Review::Code { repo, .. } => Some(repo.as_path()),
        _ => fg.cwd.as_deref(),
    };
    super::place::open(rex, block, placement, cwd, &args, &tab_label(fg, review))
}

/// The Pi session a `last` review of a Pi shows, when `registry` lists a running one for its
/// process. The pane checks Pi is still in it before sending.
fn pi_session(fg: &Foreground, review: &Review, registry: &Path) -> Option<String> {
    if fg.host != Some("pi") || !matches!(review, Review::Last { .. }) {
        return None;
    }
    crate::pi::live_entry_for_pid(registry, fg.pid).map(|entry| entry.id)
}

/// The block a review in a tab of its own shows again when it ends: when a tab closes, Rex
/// shows a neighbouring tab, which need not be the agent's.
pub(crate) const RETURN_VAR: &str = "PLANNOTATOR_TUI_REX_RETURN";

/// Have the pane `args` runs (`/usr/bin/env …`) show `block` again when the review ends.
fn returning_to(args: &mut Vec<String>, block: &str) {
    args.insert(1, format!("{RETURN_VAR}={block}"));
}

/// A tab's label: `Annotate · ` and the file or folder an `open` reviews, else the agent,
/// else the block's folder.
fn tab_label(fg: &Foreground, review: &Review) -> String {
    let name = |path: &Path| path.file_name().map(|n| n.to_string_lossy().into_owned());
    let what = match review {
        Review::Open(path, _) => path.as_deref().or(fg.cwd.as_deref()).and_then(name),
        Review::Code { repo, .. } => fg.host.map(str::to_owned).or_else(|| name(repo)),
        _ => fg.host.map(str::to_owned).or_else(|| fg.cwd.as_deref().and_then(name)),
    };
    // Rex takes a window label of up to 128 characters.
    what.map_or_else(
        || "Annotate".to_owned(),
        |what| format!("Annotate · {what}").chars().take(128).collect(),
    )
}

#[cfg(test)]
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
mod tests {
    use super::*;

    #[test]
    fn only_a_last_review_of_a_running_registered_pi_is_pinned_to_its_session() {
        let registry = std::env::temp_dir().join(format!("plannotator-tui-rex-pin-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&registry);
        crate::pi::write_test_entry(&registry, "session-1", 73139, true);
        crate::pi::write_test_entry(&registry, "gone", 73140, false);
        let pi = |pid| Foreground { pid, cwd: None, host: Some("pi") };
        let last = Review::Last { newest: false };
        assert_eq!(pi_session(&pi(73139), &last, &registry).as_deref(), Some("session-1"));
        assert_eq!(pi_session(&pi(73140), &last, &registry), None, "a Pi that is gone pins nothing");
        assert_eq!(pi_session(&pi(73141), &last, &registry), None, "no extension: no pin");
        let open = Review::Open(Some(PathBuf::from("/p/plan.md")), None);
        assert_eq!(pi_session(&pi(73139), &open, &registry), None, "a file review is not pinned");
        let claude = Foreground { pid: 73139, cwd: None, host: Some("claude") };
        assert_eq!(pi_session(&claude, &last, &registry), None);
        std::fs::remove_dir_all(registry).ok();
    }

    /// `com.superlogical.terminal.process` for a block running Claude Code, as Rex reports it.
    const CLAUDE: &str = r#"{"last_exit":null,"child":{"pid":59515,"name":"login"},"foreground":{"pid":60223,"name":"2.1.308","path":"/Users/me/.local/share/claude/versions/2.1.308","invoked_path":"/Users/me/.local/bin/claude","argv0":"claude","cwd":"/Users/me/project"}}"#;
    const SHELL: &str = r#"{"foreground":{"pid":700,"name":"fish","argv0":"-fish","cwd":"/Users/me"}}"#;
    /// pi as installed by npm, run by `node` (Rex 1913): nothing but the status names it.
    const PI_NODE: &str = r#"{"last_exit":null,"foreground":{"pid":73139,"user_id":501,"user":"me","name":"node","path":"/Users/me/.local/share/fnm/node-versions/v24.15.0/installation/bin/node","invoked_path":"/Users/me/.local/share/fnm/node-versions/v24.15.0/installation/bin/node","argv0":"node","script":"/Users/me/.local/share/fnm/node-versions/v24.15.0/installation/lib/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli.js","cwd":"/Users/me/project"},"home":"/Users/me"}"#;
    const PI_STATUS: &str = r#"{"records":[{"state":"idle","app":"pi","effective_app":"pi","updated_at":"2026-11-10T00:25:21.924601-05:00","owner":{"pid":73139,"name":"node"}}]}"#;

    fn parse(json: &str) -> Foreground {
        foreground(&serde_json::from_str(json).expect("json")).expect("a foreground process")
    }

    #[test]
    fn claude_code_is_found_by_its_invoked_name_not_its_versioned_binary() {
        let fg = parse(CLAUDE);
        assert_eq!(fg.pid, 60223);
        assert_eq!(fg.host, Some("claude"));
        assert_eq!(fg.cwd.as_deref(), Some(Path::new("/Users/me/project")));
        assert_eq!(parse(SHELL).host, None);
    }

    fn status(json: &str) -> Value {
        serde_json::from_str(json).expect("json")
    }

    #[test]
    fn an_agent_under_an_interpreter_is_named_by_its_own_status_report() {
        let fg = parse(PI_NODE);
        assert_eq!(fg.host, None, "node and cli.js name no agent");
        assert_eq!(reported_host(&status(PI_STATUS), fg.pid), Some("pi"));
        let claude = r#"{"records":[{"state":"working","app":"claude-code","owner":{"pid":60223}}]}"#;
        assert_eq!(reported_host(&status(claude), 60223), Some("claude"));
    }

    #[test]
    fn a_status_left_by_another_process_names_no_agent() {
        assert_eq!(reported_host(&status(PI_STATUS), 700), None);
        let unknown = r#"{"records":[{"state":"working","app":"terraform","owner":{"pid":700}}]}"#;
        assert_eq!(reported_host(&status(unknown), 700), None);
        assert_eq!(reported_host(&status(r#"{"records":[]}"#), 700), None);
    }

    #[test]
    fn a_script_names_the_agent_when_its_file_is_called_after_it() {
        let script = r#"{"foreground":{"pid":9,"name":"node","argv0":"node","script":"/opt/bin/pi"}}"#;
        assert_eq!(parse(script).host, Some("pi"));
    }

    #[test]
    fn last_reads_the_agents_pid_and_sends_back_to_its_block() {
        let args = argv(
            Path::new("/bin/pt"),
            "block:b",
            &parse(CLAUDE),
            &Review::Last { newest: true },
            Handoff::Send,
        )
        .expect("argv");
        assert_eq!(
            args,
            [
                "/usr/bin/env",
                "PLANNOTATOR_TUI_REX_BLOCK=block:b",
                "PLANNOTATOR_TUI_DELIVER_AGENT=claude",
                "PLANNOTATOR_TUI_REX_PID=60223",
                "/bin/pt",
                "rex",
                "pane",
                "last",
                "--pid",
                "60223",
                "--host",
                "claude",
                "--newest"
            ]
        );
        assert!(
            argv(
                Path::new("/bin/pt"),
                "block:b",
                &parse(SHELL),
                &Review::Last { newest: false },
                Handoff::Send
            )
            .is_err()
        );
    }

    #[test]
    fn open_without_an_agent_reviews_the_blocks_folder_and_copies_to_the_clipboard() {
        let args =
            argv(Path::new("/bin/pt"), "block:b", &parse(SHELL), &Review::Open(None, None), Handoff::Send)
                .expect("argv");
        assert_eq!(args, ["/usr/bin/env", "/bin/pt", "rex", "pane", "open", "/Users/me"]);
    }

    #[test]
    fn pasting_is_passed_on_only_where_there_is_an_agent_to_paste_into() {
        let paste = |json| {
            argv(Path::new("/bin/pt"), "block:b", &parse(json), &Review::Open(None, None), Handoff::Paste)
                .expect("argv")
        };
        assert!(paste(CLAUDE).contains(&"PLANNOTATOR_TUI_REX_SUBMIT=0".to_owned()));
        assert!(!paste(SHELL).iter().any(|arg| arg.starts_with("PLANNOTATOR_TUI_REX")));
    }

    #[test]
    fn a_gated_open_hands_the_gate_and_its_result_file_to_the_pane() {
        let gated = |gate| {
            let review = Review::Open(Some(PathBuf::from("/p/plan.md")), Some(gate));
            argv(Path::new("/bin/pt"), "block:b", &parse(CLAUDE), &review, Handoff::Send).expect("argv")
        };
        let tail = |args: &[String]| args.iter().skip_while(|a| *a != "open").cloned().collect::<Vec<_>>();
        assert_eq!(tail(&gated(Gate::default())), ["open", "/p/plan.md", "--gate"]);
        let published = gated(Gate { result_file: Some(PathBuf::from("/p/decision.json")) });
        assert_eq!(tail(&published), ["open", "/p/plan.md", "--gate", "--result-file", "/p/decision.json"]);
        assert!(published.contains(&"PLANNOTATOR_TUI_REX_BLOCK=block:b".to_owned()), "the agent hears it");
    }

    #[test]
    fn a_code_review_names_its_scope_and_repository_and_sends_to_the_blocks_agent() {
        let review = Review::Code { scope: "base:origin/main".to_owned(), repo: PathBuf::from("/p/repo") };
        let args =
            argv(Path::new("/bin/pt"), "block:b", &parse(CLAUDE), &review, Handoff::Send).expect("argv");
        assert_eq!(
            args,
            [
                "/usr/bin/env",
                "PLANNOTATOR_TUI_REX_BLOCK=block:b",
                "PLANNOTATOR_TUI_DELIVER_AGENT=claude",
                "PLANNOTATOR_TUI_REX_PID=60223",
                "/bin/pt",
                "rex",
                "pane",
                "review",
                "base:origin/main",
                "/p/repo"
            ]
        );
        let shell =
            argv(Path::new("/bin/pt"), "block:b", &parse(SHELL), &review, Handoff::Send).expect("argv");
        assert_eq!(
            shell,
            ["/usr/bin/env", "/bin/pt", "rex", "pane", "review", "base:origin/main", "/p/repo"]
        );
    }

    #[test]
    fn a_terminal_review_reads_the_block_from_inside_the_split() {
        let args = argv(
            Path::new("/bin/pt"),
            "block:b",
            &parse(SHELL),
            &Review::Terminal { lines: 80 },
            Handoff::Send,
        )
        .expect("argv");
        assert_eq!(
            args,
            ["/usr/bin/env", "/bin/pt", "rex", "pane", "terminal", "--block", "block:b", "--lines", "80"]
        );
    }

    #[test]
    fn a_review_in_a_tab_knows_the_block_to_show_again_when_it_ends() {
        let review = Review::Open(Some(PathBuf::from("/Users/me/project/plan.md")), Some(Gate::default()));
        let mut args =
            argv(Path::new("/bin/pt"), "block:b", &parse(CLAUDE), &review, Handoff::Send).expect("argv");
        returning_to(&mut args, "block:b");
        assert_eq!(
            args.get(..3),
            Some(
                &["/usr/bin/env", "PLANNOTATOR_TUI_REX_RETURN=block:b", "PLANNOTATOR_TUI_REX_BLOCK=block:b"]
                    .map(String::from)[..]
            )
        );
        assert_eq!(args.iter().rev().take(2).collect::<Vec<_>>(), ["--gate", "/Users/me/project/plan.md"]);
    }

    #[test]
    fn a_tab_is_named_for_the_file_it_opens_else_the_agent_else_the_folder() {
        let open = |path: Option<&str>| Review::Open(path.map(PathBuf::from), None);
        assert_eq!(tab_label(&parse(CLAUDE), &open(Some("/Users/me/project/plan.md"))), "Annotate · plan.md");
        assert_eq!(tab_label(&parse(CLAUDE), &open(None)), "Annotate · project");
        assert_eq!(tab_label(&parse(CLAUDE), &Review::Last { newest: false }), "Annotate · claude");
        let code = Review::Code { scope: "uncommitted".to_owned(), repo: PathBuf::from("/p/repo") };
        assert_eq!(tab_label(&parse(CLAUDE), &code), "Annotate · claude");
        assert_eq!(tab_label(&parse(SHELL), &code), "Annotate · repo");
        assert_eq!(tab_label(&parse(SHELL), &Review::Terminal { lines: 80 }), "Annotate · me");
    }
}