Skip to main content

vtcode_commons/tool_headlines/
session_poll.rs

1//! Shared session poll/wait run identity for transcript coalescing.
2//!
3//! A long command is polled once per wait round-trip, so one build can
4//! produce a dozen `Wait for command session` headers while it runs. Both
5//! transcript surfaces (CLI renderer, desktop app) collapse consecutive
6//! follow-ups for one session into a single header instead. This module owns
7//! the run predicate so the surfaces can never disagree on what coalesces:
8//! poll-like follow-ups (wait/poll/read) carrying a session id. Launches,
9//! stdin sends, closes, and inspects always keep their own row.
10
11use serde_json::Value;
12
13use super::{READ_COMMAND_SESSION, WAIT_FOR_COMMAND_SESSION, lookup_string, session_followup_title};
14
15/// Identity of one coalescible poll run: the session plus the action label.
16///
17/// The label comes from the same reader as the row title, so key and title
18/// agree by construction; matching on the shared consts (never retyped
19/// literals) keeps that agreement compile-checked.
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub struct SessionPollKey {
22    pub session_id: String,
23    pub label: &'static str,
24}
25
26/// Extract the coalescing key for a session poll/wait invocation.
27///
28/// `tool_name` is a registry name (`write_stdin`, `command_session_internal`,
29/// `read_pty_session`, ...). Returns `None` for anything that is not a
30/// session wait/poll/read or that carries no session id.
31#[must_use]
32pub fn session_poll_key(tool_name: &str, args: &Value) -> Option<SessionPollKey> {
33    let title = session_followup_title(tool_name, args)?;
34    let label = if title == WAIT_FOR_COMMAND_SESSION {
35        WAIT_FOR_COMMAND_SESSION
36    } else if title == READ_COMMAND_SESSION {
37        READ_COMMAND_SESSION
38    } else {
39        return None;
40    };
41    let session_id = lookup_string(args, "session_id")?;
42    Some(SessionPollKey { session_id, label })
43}
44
45/// Compact progress tick for a follow-up poll/wait (`×3 · waited 12s`).
46///
47/// Both surfaces phrase follow-ups identically: the desktop survivor title
48/// suffixes `×N`, and the CLI prints one tick line per follow-up. Elapsed
49/// time under a second is omitted (attempts alone carry fast runs); totals
50/// render rounded to whole seconds.
51#[must_use]
52pub fn poll_run_tick(attempts: usize, waited_secs: f64) -> String {
53    if waited_secs >= 1.0 {
54        format!("×{attempts} · waited {waited_secs:.0}s")
55    } else {
56        format!("×{attempts}")
57    }
58}
59
60#[cfg(test)]
61mod tests {
62    use serde_json::json;
63
64    use super::*;
65
66    fn key(tool: &str, args: Value) -> Option<SessionPollKey> {
67        session_poll_key(tool, &args)
68    }
69
70    #[test]
71    fn poll_key_covers_session_waits_and_reads_only() {
72        let wait = json!({"session_id": "run-1", "action": "wait", "wait_timeout_seconds": 8});
73        assert_eq!(
74            key("write_stdin", wait),
75            Some(SessionPollKey {
76                session_id: "run-1".into(),
77                label: WAIT_FOR_COMMAND_SESSION
78            })
79        );
80        // Case-insensitive actions and the other poll spellings join the run.
81        for (tool, args, label) in [
82            ("write_stdin", json!({"session_id": "run-1", "action": "WAIT"}), WAIT_FOR_COMMAND_SESSION),
83            ("write_stdin", json!({"session_id": "run-1", "action": "poll"}), READ_COMMAND_SESSION),
84            ("write_stdin", json!({"session_id": "run-1"}), READ_COMMAND_SESSION),
85            ("write_stdin", json!({"session_id": "run-1", "action": "write", "input": ""}), READ_COMMAND_SESSION),
86            ("command_session_internal", json!({"session_id": "s", "action": "wait"}), WAIT_FOR_COMMAND_SESSION),
87            ("command_session_internal", json!({"session_id": "s", "action": "poll"}), READ_COMMAND_SESSION),
88            ("read_pty_session", json!({"session_id": "s"}), READ_COMMAND_SESSION),
89        ] {
90            let got = key(tool, args.clone()).unwrap_or_else(|| panic!("{tool} {args} coalesces"));
91            assert_eq!(got.label, label, "{tool} {args} coalesces under its row label");
92        }
93    }
94
95    #[test]
96    fn poll_tick_shows_attempts_and_whole_seconds() {
97        assert_eq!(poll_run_tick(2, 0.0), "×2");
98        // Sub-second totals omit the elapsed half (both sides of 1s).
99        assert_eq!(poll_run_tick(2, 0.9), "×2");
100        assert_eq!(poll_run_tick(2, 1.0), "×2 · waited 1s");
101        // Totals render rounded from accumulated fractional waits.
102        assert_eq!(poll_run_tick(3, 7.06), "×3 · waited 7s");
103        assert_eq!(poll_run_tick(7, 61.4), "×7 · waited 61s");
104    }
105
106    #[test]
107    fn poll_key_rejects_non_poll_calls() {
108        // Sends, launches, lifecycle actions, and session-less calls keep rows.
109        for (tool, args) in [
110            ("write_stdin", json!({"session_id": "run-1", "action": "write", "input": "ls"})),
111            ("write_stdin", json!({"action": "wait"})),
112            ("write_stdin", json!({"session_id": "run-1", "action": "close"})),
113            ("write_stdin", json!({"session_id": "run-1", "action": "inspect"})),
114            ("write_stdin", json!({"session_id": "run-1", "action": "terminate"})),
115            ("command_session_internal", json!({"session_id": "s", "action": "run", "cmd": "ls"})),
116            ("command_session_internal", json!({"session_id": "s", "action": "close"})),
117            ("send_pty_input", json!({"session_id": "s"})),
118            ("exec_command", json!({"command": "ls"})),
119            ("read_file", json!({"path": "a.rs"})),
120        ] {
121            assert!(key(tool, args.clone()).is_none(), "{tool} {args} keeps its row");
122        }
123    }
124}