vtcode_commons/
program_status.rs1use anyhow::{Result, ensure};
4use base64::{Engine, engine::general_purpose::STANDARD};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum ProgramState {
9 Idle,
10 Working,
11 Blocked,
12 Done,
13 Error,
14 Clear,
15}
16
17impl ProgramState {
18 pub const fn as_str(self) -> &'static str {
19 match self {
20 Self::Idle => "idle",
21 Self::Working => "working",
22 Self::Blocked => "blocked",
23 Self::Done => "done",
24 Self::Error => "error",
25 Self::Clear => "clear",
26 }
27 }
28
29 pub const fn is_finished(self) -> bool {
30 matches!(self, Self::Done | Self::Error)
31 }
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum InteractionKind {
37 Permission,
38 Question,
39 Auth,
40}
41
42impl InteractionKind {
43 pub const fn as_str(self) -> &'static str {
44 match self {
45 Self::Permission => "permission",
46 Self::Question => "question",
47 Self::Auth => "auth",
48 }
49 }
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum ProgramStatusUpdate {
55 Configure {
56 enabled: bool,
57 },
58 Wait {
59 token: u64,
60 kind: InteractionKind,
61 },
62 Resume {
63 token: u64,
64 },
65 Outcome(ProgramState),
66 Progress {
69 percent: Option<u8>,
70 },
71}
72
73pub fn record_segment(kind: &str, source: &str) -> String {
75 use sha2::{Digest, Sha256};
76 let mut hash = Sha256::new();
77 hash.update(kind.as_bytes());
78 hash.update([0]);
79 hash.update(source.as_bytes());
80 let digest = hash.finalize();
81 let mut segment = String::with_capacity(31);
82 segment.push('t');
83 for byte in digest.iter().take(15) {
84 for nibble in [byte >> 4, byte & 0x0f] {
85 segment.push(char::from(if nibble < 10 { b'0' + nibble } else { b'a' + nibble - 10 }));
86 }
87 }
88 segment
89}
90
91fn valid_segment(segment: &str) -> bool {
92 (1..=32).contains(&segment.len())
93 && segment
94 .bytes()
95 .all(|byte| byte.is_ascii_alphanumeric() || b"_.+-".contains(&byte))
96}
97
98fn encode_text(text: &str, limit: usize) -> Result<String> {
99 ensure!(text.len() <= limit, "program status text exceeds byte limit");
100 ensure!(!text.chars().any(char::is_control), "program status text contains controls");
101 let text: String = text
103 .chars()
104 .filter(
105 |c| !matches!(c, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}'),
106 )
107 .collect();
108 Ok(STANDARD.encode(text))
109}
110
111pub const MIN_VTE_VERSION_WITH_SAFE_OSC: u32 = 5400;
118
119pub fn vte_version_allows_unknown_osc(raw: Option<&str>) -> bool {
121 let Some(raw) = raw else {
122 return true;
123 };
124 match raw.trim().parse::<u32>() {
125 Ok(version) => version >= MIN_VTE_VERSION_WITH_SAFE_OSC,
126 Err(_) => true,
127 }
128}
129
130pub fn vte_allows_unknown_osc() -> bool {
132 vte_version_allows_unknown_osc(std::env::var("VTE_VERSION").ok().as_deref())
133}
134
135const MAX_ITERM21337_DETAIL_CHARS: usize = 200;
137
138pub fn iterm21337_status(state: ProgramState) -> (&'static str, &'static str) {
145 match state {
146 ProgramState::Idle | ProgramState::Done | ProgramState::Error | ProgramState::Clear => ("Idle", "#00d75f"),
147 ProgramState::Working => ("Working", "#ff9500"),
148 ProgramState::Blocked => ("Waiting", "#5f87ff"),
149 }
150}
151
152pub fn encode_iterm21337(state: ProgramState, detail: &str) -> String {
157 let (label, indicator) = iterm21337_status(state);
158 format!(
159 "\x1b]21337;status={label};indicator={indicator};status-color=;detail={}\x07",
160 sanitize_iterm21337_detail(detail)
161 )
162}
163
164pub fn clear_iterm21337() -> String {
166 "\x1b]21337;status=;indicator=;status-color=;detail=\x07".to_string()
167}
168
169fn sanitize_iterm21337_detail(detail: &str) -> String {
170 let mut clean = String::with_capacity(detail.len());
171 for ch in detail.chars().filter(|ch| !ch.is_control()).take(MAX_ITERM21337_DETAIL_CHARS) {
172 if matches!(ch, ';' | '\\') {
173 clean.push('\\');
174 }
175 clean.push(ch);
176 }
177 clean
178}
179
180pub fn should_emit_iterm21337(iterm_session: bool, tmux_session: bool, screen_session: bool) -> bool {
183 iterm_session && !tmux_session && !screen_session
184}
185
186pub fn should_emit_iterm21337_now() -> bool {
189 should_emit_iterm21337(
190 std::env::var("ITERM_SESSION_ID").is_ok(),
191 std::env::var("TMUX").is_ok(),
192 std::env::var("STY").is_ok(),
193 )
194}
195
196pub fn encode_report(
203 id: &str,
204 state: ProgramState,
205 kind: Option<InteractionKind>,
206 progress: Option<u8>,
207 title: &str,
208 message: &str,
209) -> Result<String> {
210 ensure!(
211 id.len() <= 128 && id.split('/').count() <= 8 && id.split('/').all(valid_segment),
212 "invalid program status id"
213 );
214 let title = encode_text(title, 192)?;
215 let message = encode_text(message, 2048)?;
216 let mut report = format!("\x1b]7501;state={}:id={id}:app=vtcode", state.as_str());
217 if state == ProgramState::Blocked
218 && let Some(kind) = kind
219 {
220 report.push_str(":kind=");
221 report.push_str(kind.as_str());
222 }
223 if matches!(state, ProgramState::Working | ProgramState::Blocked)
224 && let Some(percent) = progress
225 && percent <= 100
226 {
227 report.push_str(":progress=");
228 report.push_str(&percent.to_string());
229 }
230 report.push_str(":title=");
231 report.push_str(&title);
232 report.push_str(":msg=");
233 report.push_str(&message);
234 report.push_str("\x1b\\");
235 ensure!(report.len() <= 4096, "program status report exceeds byte limit");
236 Ok(report)
237}
238
239#[cfg(test)]
240mod tests;