vtcode-ui 0.183.0

Unified UI crate for VT Code: design system, theme registry, and TUI framework
Documentation
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
//! Session-owned terminal status projection. Never controls input or execution.

use std::collections::{BTreeMap, BTreeSet};
use std::io::{self, IsTerminal, Write};
use std::sync::{
    Mutex,
    atomic::{AtomicU64, Ordering},
};

use vtcode_commons::program_status::{
    ConEmuProgress, InteractionKind, ProgramState, ProgramStatusUpdate, clear_iterm21337, encode_clear,
    encode_conemu94, encode_iterm21337, encode_report, record_segment,
};
use vtcode_commons::ui_protocol::{ActivityState, ProgressPhase, ProgressUpdate};

use super::types::{LocalAgentEntry, LocalAgentKind};

const RECORD_CAP: usize = 64;
static NEXT_SESSION: AtomicU64 = AtomicU64::new(1);
// Owned delivery attempts, used by the canonical panic/signal restoration path.
// The state comes from the current runtime projection, not delivery success.
// Lock order: terminal operations, then this registry. No writes after restore.
static CLEANUP_RECORDS: Mutex<BTreeMap<String, ProgramState>> = Mutex::new(BTreeMap::new());

#[derive(Clone, Debug, PartialEq, Eq)]
struct Report {
    state: ProgramState,
    kind: Option<InteractionKind>,
    progress: Option<u8>,
    title: &'static str,
    message: &'static str,
}

/// Project a parent report onto the ConEmu `OSC 9;4` tab-progress state.
///
/// Blocked waits read as paused (a wait, not a failure); finished-clear
/// states remove the indicator, matching the Windows Terminal guidance to
/// clear progress on completion.
fn conemu94_for_report(report: &Report) -> ConEmuProgress {
    match report.state {
        ProgramState::Working => match report.progress {
            Some(percent) => ConEmuProgress::Normal(percent),
            None => ConEmuProgress::Indeterminate,
        },
        ProgramState::Blocked => ConEmuProgress::Paused,
        ProgramState::Error => ConEmuProgress::Error,
        ProgramState::Idle | ProgramState::Done | ProgramState::Clear => ConEmuProgress::Remove,
    }
}

pub(crate) struct ProgramStatus {
    parent: String,
    enabled: bool,
    terminal: bool,
    iterm21337: bool,
    last_iterm21337: Option<String>,
    conemu94: bool,
    last_conemu94: Option<String>,
    closed: bool,
    underlying: ProgramState,
    operation: Option<u64>,
    newest_operation: u64,
    phase: Option<ProgressPhase>,
    task_progress: Option<u8>,
    waits: BTreeMap<u64, InteractionKind>,
    children: BTreeMap<String, Report>,
    // A failed flush may still have reached the terminal. Retain owned IDs
    // for removal without treating their report contents as delivered.
    attempted: BTreeSet<String>,
    delivered: BTreeMap<String, Report>,
}

impl Default for ProgramStatus {
    fn default() -> Self {
        let nonce = NEXT_SESSION.fetch_add(1, Ordering::Relaxed);
        let origin = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        Self {
            parent: record_segment("vtcode", &format!("{}-{origin}-{nonce}", std::process::id())),
            enabled: false,
            terminal: false,
            iterm21337: false,
            last_iterm21337: None,
            conemu94: false,
            last_conemu94: None,
            closed: false,
            underlying: ProgramState::Idle,
            operation: None,
            newest_operation: 0,
            phase: None,
            task_progress: None,
            waits: BTreeMap::new(),
            children: BTreeMap::new(),
            attempted: BTreeSet::new(),
            delivered: BTreeMap::new(),
        }
    }
}

impl ProgramStatus {
    /// Set only by the real interactive runner, never a test/headless session.
    pub(crate) fn attach_terminal(&mut self) {
        // Pre-0.54 VTE parsers may mishandle unknown OSC bytes, so they stay
        // silent even though emission is otherwise on by default.
        self.terminal = io::stdin().is_terminal()
            && io::stdout().is_terminal()
            && io::stderr().is_terminal()
            && vtcode_commons::program_status::vte_allows_unknown_osc();
        self.iterm21337 = vtcode_commons::program_status::should_emit_iterm21337_now();
        self.conemu94 = vtcode_commons::program_status::should_emit_conemu94_now();
    }

    pub(crate) fn apply(&mut self, update: ProgramStatusUpdate) {
        match update {
            ProgramStatusUpdate::Configure { enabled } => {
                self.enabled = enabled;
                if !enabled {
                    self.children.clear();
                }
            }
            ProgramStatusUpdate::Wait { token, kind } => {
                self.waits.insert(token, kind);
            }
            ProgramStatusUpdate::Resume { token } => {
                self.waits.remove(&token);
            }
            ProgramStatusUpdate::Outcome(state) => {
                if matches!(
                    state,
                    ProgramState::Done | ProgramState::Error | ProgramState::Idle | ProgramState::Blocked
                ) {
                    self.underlying = state;
                    self.phase = None;
                }
            }
            ProgramStatusUpdate::Progress { percent } => {
                // Task-scoped, not turn-scoped: retained across Outcome/Finish
                // and disable/enable so the next Working re-emits the last
                // known task percent until typed metadata clears or updates
                // it. `desired()` still gates emission to working/blocked.
                // Invalid values are ignored (retain last good), matching the
                // Outcome/Begin ignore-stale pattern; explicit None clears.
                match percent {
                    None => self.task_progress = None,
                    Some(value) if value <= 100 => self.task_progress = Some(value),
                    Some(_) => {}
                }
            }
        }
    }

    pub(crate) fn activity(&mut self, state: ActivityState) {
        if state == ActivityState::Blocked {
            self.underlying = ProgramState::Blocked;
            self.phase = None;
        } else if state.is_busy() {
            self.underlying = ProgramState::Working;
        } else if state == ActivityState::Idle && self.operation.is_none() && self.underlying == ProgramState::Working {
            self.underlying = ProgramState::Idle;
        }
    }

    pub(crate) fn progress(&mut self, update: ProgressUpdate) {
        match update {
            ProgressUpdate::Begin { operation, phase } if operation.id() > self.newest_operation => {
                self.newest_operation = operation.id();
                self.operation = Some(operation.id());
                self.underlying = ProgramState::Working;
                self.phase = Some(phase);
            }
            ProgressUpdate::Phase { operation, phase }
                if self.operation == Some(operation.id()) && self.underlying == ProgramState::Working =>
            {
                self.phase = Some(phase);
            }
            ProgressUpdate::Finish { operation } if self.operation == Some(operation.id()) => {
                self.operation = None;
                self.phase = None;
                if self.underlying == ProgramState::Working {
                    self.underlying = ProgramState::Idle;
                }
            }
            _ => {}
        }
    }

    pub(crate) fn children(&mut self, entries: &[LocalAgentEntry]) {
        // The session already retains the latest Local Agents snapshot for
        // rendering. Reproject it on enable rather than maintaining an off copy.
        if !self.enabled {
            return;
        }
        let mut entries: Vec<_> = entries.iter().collect();
        entries.sort_by_key(|entry| {
            let priority = match entry.program_status {
                ProgramState::Working | ProgramState::Blocked => 0,
                ProgramState::Done | ProgramState::Error => 1,
                _ => 2,
            };
            (priority, std::cmp::Reverse(entry.updated_at), entry.kind, &entry.id)
        });
        self.children = entries
            .into_iter()
            .take(RECORD_CAP - 1)
            .map(|entry| {
                let id = format!("{}/{}", self.parent, record_segment(entry.kind.as_str(), &entry.id));
                let title = match entry.kind {
                    LocalAgentKind::Delegated => "Delegated agent",
                    LocalAgentKind::Background => "Background task",
                    LocalAgentKind::ExecSession => "Command session",
                };
                (
                    id,
                    Report {
                        state: entry.program_status,
                        kind: None,
                        progress: None,
                        title,
                        message: entry.program_status.as_str(),
                    },
                )
            })
            .collect();
    }

    fn desired(&self) -> BTreeMap<String, Report> {
        if !self.enabled {
            return BTreeMap::new();
        }
        let mut records = self.children.clone();
        let kind = self.waits.last_key_value().map(|(_, kind)| *kind);
        let state = if kind.is_some() {
            ProgramState::Blocked
        } else {
            self.underlying
        };
        let message = if let Some(kind) = kind {
            match kind {
                InteractionKind::Permission => "Waiting for permission",
                InteractionKind::Question => "Waiting for an answer",
                InteractionKind::Auth => "Waiting for authentication",
            }
        } else if state == ProgramState::Working {
            self.phase.map_or("Working", ProgressPhase::label)
        } else {
            match state {
                ProgramState::Done => "Completed",
                ProgramState::Error => "Failed",
                ProgramState::Blocked => "Waiting for guidance",
                _ => "Idle",
            }
        };
        let progress = match state {
            ProgramState::Working | ProgramState::Blocked => self.task_progress,
            _ => None,
        };
        records.insert(
            self.parent.clone(),
            Report {
                state,
                kind,
                progress,
                title: vtcode_config::constants::app::DISPLAY_NAME,
                message,
            },
        );
        if self.closed {
            records.retain(|_, report| report.state.is_finished());
        }
        records
    }

    /// Write changes only. Failed reports remain pending, including failed clears.
    fn deliver(&mut self, writer: &mut impl Write) -> anyhow::Result<()> {
        use anyhow::Context;
        let desired = self.desired();
        // Session-level iTerm2 pill follows the parent record; a missing
        // parent clears it. Precomputed before the loop moves `desired`.
        let iterm21337 = self.iterm21337.then(|| match desired.get(&self.parent) {
            Some(report) => encode_iterm21337(report.state, report.message),
            None => clear_iterm21337(),
        });
        let conemu94 = self.conemu94.then(|| match desired.get(&self.parent) {
            Some(report) => encode_conemu94(conemu94_for_report(report)),
            None => encode_conemu94(ConEmuProgress::Remove),
        });
        let removed: Vec<_> = self.attempted.iter().filter(|id| !desired.contains_key(*id)).cloned().collect();
        for id in removed {
            // Clearing a parent would also remove its retained finished children.
            // Retire an unfinished parent with idle when preserving descendants.
            let state = if id == self.parent && desired.keys().any(|key| key.starts_with(&format!("{id}/"))) {
                ProgramState::Idle
            } else {
                ProgramState::Clear
            };
            let wire = if state == ProgramState::Clear {
                encode_clear(&id)?
            } else {
                encode_report(&id, state, None, None, "", "")?
            };
            // Even a failed flush may change the terminal. A subtree clear
            // invalidates all successful-report cache entries beneath it.
            if id == self.parent && state == ProgramState::Clear {
                self.delivered.clear();
            } else {
                self.delivered.remove(&id);
            }
            writer
                .write_all(wire.as_bytes())
                .context("writing removed program status record")?;
            writer.flush().context("flushing removed program status record")?;
            if id == self.parent && state == ProgramState::Clear {
                self.attempted.clear();
                break;
            }
            self.attempted.remove(&id);
        }
        for (id, report) in desired {
            if self.delivered.get(&id) == Some(&report) {
                continue;
            }
            let wire = encode_report(&id, report.state, report.kind, report.progress, report.title, report.message)?;
            self.attempted.insert(id.clone());
            self.delivered.remove(&id);
            writer.write_all(wire.as_bytes()).context("writing program status record")?;
            writer.flush().context("flushing program status record")?;
            self.delivered.insert(id, report);
        }
        if let Some(sequence) = iterm21337
            && self.last_iterm21337.as_ref() != Some(&sequence)
        {
            writer
                .write_all(sequence.as_bytes())
                .context("writing iterm21337 session status")?;
            writer.flush().context("flushing iterm21337 session status")?;
            self.last_iterm21337 = Some(sequence);
        }
        if let Some(sequence) = conemu94
            && self.last_conemu94.as_ref() != Some(&sequence)
        {
            writer.write_all(sequence.as_bytes()).context("writing conemu94 tab progress")?;
            writer.flush().context("flushing conemu94 tab progress")?;
            self.last_conemu94 = Some(sequence);
        }
        Ok(())
    }

    pub(crate) fn flush(&mut self) {
        // A disabled session still needs to retry uncertain subtree clears.
        if !self.terminal || (!self.enabled && self.attempted.is_empty()) {
            return;
        }
        let _guard = super::panic_hook::lock_terminal_operations();
        if super::panic_hook::is_restore_claimed() {
            return;
        }
        if let Err(error) = self.deliver(&mut io::stderr().lock()) {
            tracing::warn!(error = ?error, "terminal program status delivery failed");
        }
        let mut records = CLEANUP_RECORDS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
        records.retain(|id, _| id != &self.parent && !id.starts_with(&format!("{}/", self.parent)));
        let desired = self.desired();
        records.extend(self.attempted.iter().map(|id| {
            let state = desired.get(id).map_or(ProgramState::Idle, |report| report.state);
            (id.clone(), state)
        }));
    }

    pub(crate) fn shutdown(&mut self) {
        self.closed = true;
        self.flush();
    }
}

/// Canonical restoration calls this under the terminal-operation lock.
/// Preserve finished outcomes and retire unfinished records best effort once.
pub(crate) fn cleanup_before_restore(writer: &mut impl Write) {
    let records = std::mem::take(&mut *CLEANUP_RECORDS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()));
    retire_records(&records, writer);
    if vtcode_commons::program_status::should_emit_iterm21337_now() {
        if let Err(error) = writer.write_all(clear_iterm21337().as_bytes()).and_then(|()| writer.flush()) {
            tracing::warn!(%error, "iterm21337 restoration cleanup failed");
        }
    }
    if vtcode_commons::program_status::should_emit_conemu94_now() {
        if let Err(error) = writer
            .write_all(encode_conemu94(ConEmuProgress::Remove).as_bytes())
            .and_then(|()| writer.flush())
        {
            tracing::warn!(%error, "conemu94 restoration cleanup failed");
        }
    }
}

fn retire_records(records: &BTreeMap<String, ProgramState>, writer: &mut impl Write) {
    for (id, state) in records {
        if state.is_finished() {
            continue;
        }
        let has_finished_children = records
            .iter()
            .any(|(child, state)| child.starts_with(&format!("{id}/")) && state.is_finished());
        let state = if has_finished_children {
            ProgramState::Idle
        } else {
            ProgramState::Clear
        };
        let wire = if state == ProgramState::Clear {
            encode_clear(id)
        } else {
            encode_report(id, state, None, None, "", "")
        };
        if let Err(error) = wire.and_then(|wire| {
            writer.write_all(wire.as_bytes())?;
            writer.flush()?;
            Ok(())
        }) {
            tracing::warn!(%error, "program status restoration cleanup failed");
        }
    }
}

#[cfg(test)]
mod tests;