Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

feat: add instant events and parallelize fsmonitor starts (#554)

Maximilian Roos98477c271304
diff --git a/src/bin/analyze-trace.rs b/src/bin/analyze-trace.rs
index e6a1a39a0..9d6245817 100644
--- a/src/bin/analyze-trace.rs
+++ b/src/bin/analyze-trace.rs
@@ -11,6 +11,9 @@
//! # Analyze with SQL (requires: curl -LO https://get.perfetto.dev/trace_processor)
//! trace_processor trace.json -Q 'SELECT COUNT(*), SUM(dur)/1e6 as cpu_ms FROM slice'
//! trace_processor trace.json -Q 'SELECT name, COUNT(*) as n, SUM(dur)/1e6 as ms FROM slice GROUP BY name ORDER BY ms DESC'
+//!
+//! # Find milestone events (instant events have dur=0)
+//! trace_processor trace.json -Q 'SELECT name, ts/1e6 as ms FROM slice WHERE dur = 0'
//! ```
use std::io::{IsTerminal, Read};
@@ -31,6 +34,9 @@ use worktrunk::trace;
# - Open trace.json in chrome://tracing or https://ui.perfetto.dev
# - Query with: trace_processor trace.json -Q 'SELECT * FROM slice LIMIT 10'
+ # Find milestone events (instant events have dur=0)
+ trace_processor trace.json -Q 'SELECT name, ts/1e6 as ms FROM slice WHERE dur = 0'
+
# Install trace_processor for SQL analysis:
curl -LO https://get.perfetto.dev/trace_processor && chmod +x trace_processor
"#)]
@@ -73,6 +79,7 @@ fn main() {
eprintln!();
eprintln!("Trace lines should look like:");
eprintln!(" [wt-trace] ts=1234567890 tid=3 cmd=\"git status\" dur=12.3ms ok=true");
+ eprintln!(" [wt-trace] ts=1234567890 tid=3 event=\"Showed skeleton\"");
eprintln!();
eprintln!("To capture traces, run with RUST_LOG=debug:");
eprintln!(" RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace");
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index f11395a03..0a0196c2b 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -694,6 +694,7 @@ pub fn collect(
skip_expensive_for_stale: bool,
) -> anyhow::Result<Option<super::model::ListData>> {
use super::progressive_table::ProgressiveTable;
+ worktrunk::shell_exec::trace_instant("List collect started");
// Phase 1: Get worktree list (required for everything else)
let worktrees = repo.list_worktrees().context("Failed to list worktrees")?;
@@ -923,6 +924,7 @@ pub fn collect(
max_width,
);
table.render_skeleton()?;
+ worktrunk::shell_exec::trace_instant("Skeleton rendered");
Some(table)
} else {
None
@@ -934,6 +936,7 @@ pub fn collect(
}
// === Post-skeleton computations (deferred to minimize time-to-skeleton) ===
+ worktrunk::shell_exec::trace_instant("Post-skeleton started");
// Compute previous_branch and update is_previous on items
let previous_branch = repo.get_switch_previous();
@@ -994,12 +997,13 @@ pub fn collect(
#[cfg(target_os = "macos")]
{
if repo.is_builtin_fsmonitor_enabled() {
- for wt in &sorted_worktrees {
- // Skip prunable worktrees (directory missing)
+ // Parallelize daemon starts - explicit `start` is safe to call concurrently
+ // (each returns quickly if daemon already running for that worktree).
+ sorted_worktrees.par_iter().for_each(|wt| {
if !wt.is_prunable() {
repo.start_fsmonitor_daemon_at(&wt.path);
}
- }
+ });
}
}
@@ -1047,6 +1051,7 @@ pub fn collect(
Vec::new()
};
+ worktrunk::shell_exec::trace_instant("Spawning worker thread");
std::thread::spawn(move || {
use super::collect_progressive_impl::{work_items_for_branch, work_items_for_worktree};
@@ -1082,6 +1087,7 @@ pub fn collect(
all_work_items.sort_by_key(|item| item.kind.is_network());
// Phase 2: Execute all work items in parallel
+ worktrunk::shell_exec::trace_instant("Parallel execution started");
all_work_items.into_par_iter().for_each(|item| {
worktrunk::shell_exec::set_command_timeout(command_timeout);
let result = item.execute();
@@ -1095,6 +1101,7 @@ pub fn collect(
// Track completed results for footer progress
let mut completed_results = 0;
let mut progress_overflow = false;
+ let mut first_result_traced = false;
// Drain task results with conditional progressive rendering
let drain_outcome = drain_results(
@@ -1103,6 +1110,12 @@ pub fn collect(
&mut errors,
&expected_results,
|item_idx, item, ctx| {
+ // Trace first result arrival
+ if !first_result_traced {
+ first_result_traced = true;
+ worktrunk::shell_exec::trace_instant("First result received");
+ }
+
// Compute/recompute status symbols as data arrives (both modes).
// This is idempotent and updates status as new data (like upstream) arrives.
if let Some(ref target) = integration_target {
@@ -1149,6 +1162,7 @@ pub fn collect(
}
},
);
+ worktrunk::shell_exec::trace_instant("All results drained");
// Handle timeout if it occurred
if let DrainOutcome::TimedOut {
@@ -1299,6 +1313,7 @@ pub fn collect(
// - Progressive + Non-TTY: rendered final table (no intermediate output)
// - Buffered: rendered final table
// JSON mode (render_table=false): no rendering, data returned for serialization
+ worktrunk::shell_exec::trace_instant("List collect complete");
Ok(Some(super::model::ListData {
items,
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index 1388c8796..c0fbcf80a 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -182,6 +182,43 @@ pub fn set_command_timeout(timeout: Option<Duration>) {
COMMAND_TIMEOUT.with(|t| t.set(timeout));
}
+/// Emit an instant trace event (a milestone marker with no duration).
+///
+/// Instant events appear as vertical lines in Chrome Trace Format visualization tools
+/// (chrome://tracing, Perfetto). Use them to mark significant moments in execution:
+///
+/// ```text
+/// [wt-trace] ts=1234567890 tid=3 event="Showed skeleton"
+/// ```
+///
+/// # Example
+///
+/// ```ignore
+/// use worktrunk::shell_exec::trace_instant;
+///
+/// // Mark when the skeleton UI was displayed
+/// trace_instant("Showed skeleton");
+///
+/// // Or with more context
+/// trace_instant("Progressive render: headers complete");
+/// ```
+pub fn trace_instant(event: &str) {
+ use std::time::{SystemTime, UNIX_EPOCH};
+
+ let start_time_us = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_micros() as u64)
+ .unwrap_or(0);
+ let tid = thread_id_number();
+
+ log::debug!(
+ "[wt-trace] ts={} tid={} event=\"{}\"",
+ start_time_us,
+ tid,
+ event
+ );
+}
+
/// Execute a command with timing and debug logging.
///
/// This is the **only** way to run external commands in worktrunk. All command execution
diff --git a/src/trace/chrome.rs b/src/trace/chrome.rs
index f5baed8b7..3fc048acf 100644
--- a/src/trace/chrome.rs
+++ b/src/trace/chrome.rs
@@ -3,6 +3,11 @@
//! Converts trace entries to Chrome Trace Event Format JSON, which can be
//! visualized in chrome://tracing or <https://ui.perfetto.dev>.
//!
+//! # Event Types
+//!
+//! - **Complete events** (`ph: "X"`): Command executions with duration
+//! - **Instant events** (`ph: "I"`): Milestones without duration (e.g., "Showed skeleton")
+//!
//! # Usage
//!
//! ```bash
@@ -17,19 +22,27 @@
use serde::Serialize;
-use super::TraceEntry;
+use super::{TraceEntry, TraceEntryKind};
/// A Chrome Trace Event in the Trace Event Format.
+///
+/// Uses `#[serde(skip_serializing_if)]` to emit the correct fields for each phase:
+/// - Complete events ("X"): have `dur`, no `s`
+/// - Instant events ("I"): have `s` (scope), no `dur`
#[derive(Debug, Serialize)]
struct TraceEvent {
/// Event name (displayed in the UI)
name: String,
- /// Phase: "X" for complete events (with duration)
+ /// Phase: "X" for complete events, "I" for instant events
ph: &'static str,
/// Timestamp in microseconds since epoch
ts: u64,
- /// Duration in microseconds (for "X" phase events)
- dur: u64,
+ /// Duration in microseconds (for "X" phase events only)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ dur: Option<u64>,
+ /// Scope for instant events: "g" (global), "p" (process), or "t" (thread)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ s: Option<&'static str>,
/// Process ID (we use 1 for all events since wt is single-process)
pid: u32,
/// Thread ID
@@ -38,7 +51,8 @@ struct TraceEvent {
#[serde(skip_serializing_if = "Option::is_none")]
cat: Option<String>,
/// Custom arguments (shown when event is selected in UI)
- args: TraceEventArgs,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ args: Option<TraceEventArgs>,
}
/// Custom arguments attached to trace events.
@@ -47,11 +61,11 @@ struct TraceEventArgs {
/// Worktree context (if any)
#[serde(skip_serializing_if = "Option::is_none")]
context: Option<String>,
- /// Whether the command succeeded
+ /// Whether the command succeeded (always true for instant events)
success: bool,
- /// Duration in milliseconds (human-readable)
- #[serde(rename = "duration_ms")]
- duration_ms: f64,
+ /// Duration in milliseconds (human-readable, only for command events)
+ #[serde(rename = "duration_ms", skip_serializing_if = "Option::is_none")]
+ duration_ms: Option<f64>,
}
/// The top-level Chrome Trace Format structure.
@@ -72,36 +86,64 @@ struct ChromeTrace {
///
/// Returns pretty-printed JSON suitable for chrome://tracing or Perfetto.
/// Entries without timestamp/thread data use 0 as fallback.
+///
+/// # Event Types
+///
+/// - Command entries become Complete events (`"ph": "X"`) with duration
+/// - Instant entries become Instant events (`"ph": "I"`) with global scope
pub fn to_chrome_trace(entries: &[TraceEntry]) -> String {
let trace_events: Vec<TraceEvent> = entries
.iter()
.map(|entry| {
let ts = entry.start_time_us.unwrap_or(0);
let tid = entry.thread_id.unwrap_or(0);
- let dur = entry.duration.as_micros() as u64;
-
- // Categorize by program type
- let cat = if entry.command.starts_with("git ") {
- Some("git".to_string())
- } else if entry.command.starts_with("gh ") || entry.command.starts_with("glab ") {
- Some("network".to_string())
- } else {
- None
- };
-
- TraceEvent {
- name: entry.command.clone(),
- ph: "X", // Complete event (has duration)
- ts,
- dur,
- pid: 1, // Single process
- tid,
- cat,
- args: TraceEventArgs {
- context: entry.context.clone(),
- success: entry.is_success(),
- duration_ms: entry.duration.as_secs_f64() * 1000.0,
- },
+
+ match &entry.kind {
+ TraceEntryKind::Command {
+ command, duration, ..
+ } => {
+ // Categorize by program type
+ let cat = if command.starts_with("git ") {
+ Some("git".to_string())
+ } else if command.starts_with("gh ") || command.starts_with("glab ") {
+ Some("network".to_string())
+ } else {
+ None
+ };
+
+ TraceEvent {
+ name: command.clone(),
+ ph: "X", // Complete event (has duration)
+ ts,
+ dur: Some(duration.as_micros() as u64),
+ s: None,
+ pid: 1,
+ tid,
+ cat,
+ args: Some(TraceEventArgs {
+ context: entry.context.clone(),
+ success: entry.is_success(),
+ duration_ms: Some(duration.as_secs_f64() * 1000.0),
+ }),
+ }
+ }
+ TraceEntryKind::Instant { name } => {
+ TraceEvent {
+ name: name.clone(),
+ ph: "I", // Instant event (no duration)
+ ts,
+ dur: None,
+ s: Some("g"), // Global scope - shows across all threads
+ pid: 1,
+ tid,
+ cat: Some("milestone".to_string()),
+ args: Some(TraceEventArgs {
+ context: entry.context.clone(),
+ success: true,
+ duration_ms: None,
+ }),
+ }
+ }
}
})
.collect();
@@ -122,7 +164,7 @@ mod tests {
use super::*;
use crate::trace::{TraceEntry, TraceResult};
- fn make_entry(
+ fn make_command_entry(
command: &str,
duration_ms: u64,
start_time_us: Option<u64>,
@@ -130,9 +172,26 @@ mod tests {
) -> TraceEntry {
TraceEntry {
context: Some("feature".to_string()),
- command: command.to_string(),
- duration: Duration::from_millis(duration_ms),
- result: TraceResult::Completed { success: true },
+ kind: TraceEntryKind::Command {
+ command: command.to_string(),
+ duration: Duration::from_millis(duration_ms),
+ result: TraceResult::Completed { success: true },
+ },
+ start_time_us,
+ thread_id,
+ }
+ }
+
+ fn make_instant_entry(
+ name: &str,
+ start_time_us: Option<u64>,
+ thread_id: Option<u64>,
+ ) -> TraceEntry {
+ TraceEntry {
+ context: None,
+ kind: TraceEntryKind::Instant {
+ name: name.to_string(),
+ },
start_time_us,
thread_id,
}
@@ -141,9 +200,9 @@ mod tests {
#[test]
fn test_to_chrome_trace_with_timestamps() {
let entries = vec![
- make_entry("git status", 10, Some(1000000), Some(1)),
- make_entry("git diff", 20, Some(1000000), Some(2)),
- make_entry("git log", 15, Some(1010000), Some(1)),
+ make_command_entry("git status", 10, Some(1000000), Some(1)),
+ make_command_entry("git diff", 20, Some(1000000), Some(2)),
+ make_command_entry("git log", 15, Some(1010000), Some(1)),
];
let json = to_chrome_trace(&entries);
@@ -172,8 +231,8 @@ mod tests {
fn test_to_chrome_trace_without_timestamps() {
// Old format entries without ts/tid get 0 as fallback
let entries = vec![
- make_entry("git status", 10, None, None),
- make_entry("git diff", 20, None, None),
+ make_command_entry("git status", 10, None, None),
+ make_command_entry("git diff", 20, None, None),
];
let json = to_chrome_trace(&entries);
@@ -191,10 +250,10 @@ mod tests {
#[test]
fn test_category_assignment() {
let entries = vec![
- make_entry("git status", 10, Some(0), Some(1)),
- make_entry("gh pr list", 100, Some(0), Some(2)),
- make_entry("glab mr list", 100, Some(0), Some(3)),
- make_entry("echo hello", 1, Some(0), Some(4)),
+ make_command_entry("git status", 10, Some(0), Some(1)),
+ make_command_entry("gh pr list", 100, Some(0), Some(2)),
+ make_command_entry("glab mr list", 100, Some(0), Some(3)),
+ make_command_entry("echo hello", 1, Some(0), Some(4)),
];
let json = to_chrome_trace(&entries);
@@ -209,7 +268,7 @@ mod tests {
#[test]
fn test_args_include_context() {
- let entries = vec![make_entry("git status", 10, Some(0), Some(1))];
+ let entries = vec![make_command_entry("git status", 10, Some(0), Some(1))];
let json = to_chrome_trace(&entries);
let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
@@ -219,4 +278,65 @@ mod tests {
assert_eq!(events[0]["args"]["success"], true);
assert_eq!(events[0]["args"]["duration_ms"], 10.0);
}
+
+ // ========================================================================
+ // Instant event tests
+ // ========================================================================
+
+ #[test]
+ fn test_instant_event() {
+ let entries = vec![make_instant_entry(
+ "Showed skeleton",
+ Some(1000000),
+ Some(1),
+ )];
+
+ let json = to_chrome_trace(&entries);
+ let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
+ let events = parsed["traceEvents"].as_array().unwrap();
+
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0]["name"], "Showed skeleton");
+ assert_eq!(events[0]["ph"], "I"); // Instant event
+ assert_eq!(events[0]["ts"], 1000000);
+ assert_eq!(events[0]["s"], "g"); // Global scope
+ assert_eq!(events[0]["cat"], "milestone");
+ assert!(events[0]["dur"].is_null()); // No duration for instant events
+ assert_eq!(events[0]["args"]["success"], true);
+ assert!(events[0]["args"]["duration_ms"].is_null());
+ }
+
+ #[test]
+ fn test_mixed_events() {
+ let entries = vec![
+ make_instant_entry("Started", Some(1000000), Some(1)),
+ make_command_entry("git status", 10, Some(1000100), Some(1)),
+ make_instant_entry("Showed skeleton", Some(1010000), Some(1)),
+ make_command_entry("git diff", 20, Some(1010100), Some(2)),
+ make_instant_entry("Done", Some(1030000), Some(1)),
+ ];
+
+ let json = to_chrome_trace(&entries);
+ let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
+ let events = parsed["traceEvents"].as_array().unwrap();
+
+ assert_eq!(events.len(), 5);
+
+ // Check instant events
+ assert_eq!(events[0]["ph"], "I");
+ assert_eq!(events[0]["name"], "Started");
+
+ assert_eq!(events[2]["ph"], "I");
+ assert_eq!(events[2]["name"], "Showed skeleton");
+
+ assert_eq!(events[4]["ph"], "I");
+ assert_eq!(events[4]["name"], "Done");
+
+ // Check command events
+ assert_eq!(events[1]["ph"], "X");
+ assert_eq!(events[1]["name"], "git status");
+
+ assert_eq!(events[3]["ph"], "X");
+ assert_eq!(events[3]["name"], "git diff");
+ }
}
diff --git a/src/trace/mod.rs b/src/trace/mod.rs
index 246b10a77..85e83693d 100644
--- a/src/trace/mod.rs
+++ b/src/trace/mod.rs
@@ -13,12 +13,22 @@
//!
//! ```bash
//! # Generate Chrome Trace Format
-//! RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace --format=chrome > trace.json
+//! RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace > trace.json
//!
//! # Visualize: open trace.json in chrome://tracing or https://ui.perfetto.dev
//!
//! # Analyze with SQL (requires: curl -LO https://get.perfetto.dev/trace_processor)
//! trace_processor trace.json -Q 'SELECT name, COUNT(*), SUM(dur)/1e6 as ms FROM slice GROUP BY name'
+//!
+//! # Find milestone events (instant events have dur=0)
+//! trace_processor trace.json -Q 'SELECT name, ts/1e6 as ms FROM slice WHERE dur = 0'
+//!
+//! # Time from start to skeleton render
+//! trace_processor trace.json -Q "
+//! SELECT (skeleton.ts - start.ts)/1e6 as skeleton_ms
+//! FROM slice start, slice skeleton
+//! WHERE start.name = 'List collect started'
+//! AND skeleton.name = 'Skeleton rendered'"
//! ```
pub mod chrome;
@@ -26,4 +36,4 @@ pub mod parse;
// Re-export main types for convenience
pub use chrome::to_chrome_trace;
-pub use parse::{TraceEntry, TraceResult, parse_line, parse_lines};
+pub use parse::{TraceEntry, TraceEntryKind, TraceResult, parse_line, parse_lines};
diff --git a/src/trace/parse.rs b/src/trace/parse.rs
index c6cb7f562..16185c958 100644
--- a/src/trace/parse.rs
+++ b/src/trace/parse.rs
@@ -7,23 +7,43 @@
//! [wt-trace] ts=1234567890 tid=3 context=main cmd="git merge-base" dur=100.0ms err="fatal: ..."
//! ```
//!
+//! Instant events (milestones without duration) use this format:
+//! ```text
+//! [wt-trace] ts=1234567890 tid=3 event="Showed skeleton"
+//! ```
+//!
//! The `ts` (timestamp in microseconds since epoch) and `tid` (thread ID) fields
//! enable concurrency analysis and Chrome Trace Format export for visualizing
//! thread utilization in tools like chrome://tracing or Perfetto.
use std::time::Duration;
+/// The kind of trace entry: command execution or instant event.
+#[derive(Debug, Clone, PartialEq)]
+pub enum TraceEntryKind {
+ /// A command execution with duration and result
+ Command {
+ /// Full command string (e.g., "git status --porcelain")
+ command: String,
+ /// Command duration
+ duration: Duration,
+ /// Command result
+ result: TraceResult,
+ },
+ /// An instant event (milestone marker with no duration)
+ Instant {
+ /// Event name (e.g., "Showed skeleton")
+ name: String,
+ },
+}
+
/// A parsed trace entry from a wt-trace log line.
#[derive(Debug, Clone, PartialEq)]
pub struct TraceEntry {
/// Optional context (typically worktree name for git commands)
pub context: Option<String>,
- /// Full command string (e.g., "git status --porcelain")
- pub command: String,
- /// Command duration
- pub duration: Duration,
- /// Command result
- pub result: TraceResult,
+ /// The kind of trace entry
+ pub kind: TraceEntryKind,
/// Start timestamp in microseconds since Unix epoch (for Chrome Trace Format)
pub start_time_us: Option<u64>,
/// Thread ID that executed this command (for concurrency analysis)
@@ -41,21 +61,70 @@ pub enum TraceResult {
impl TraceEntry {
/// Extract the program name (first word of command).
+ /// Returns empty string for instant events.
pub fn program(&self) -> &str {
- self.command.split_whitespace().next().unwrap_or("")
+ match &self.kind {
+ TraceEntryKind::Command { command, .. } => {
+ command.split_whitespace().next().unwrap_or("")
+ }
+ TraceEntryKind::Instant { .. } => "",
+ }
}
/// Extract git subcommand if this is a git command.
- /// Returns None if not a git command.
+ /// Returns None if not a git command or if this is an instant event.
pub fn git_subcommand(&self) -> Option<&str> {
- let mut parts = self.command.split_whitespace();
- let program = parts.next()?;
- if program == "git" { parts.next() } else { None }
+ match &self.kind {
+ TraceEntryKind::Command { command, .. } => {
+ let mut parts = command.split_whitespace();
+ let program = parts.next()?;
+ if program == "git" { parts.next() } else { None }
+ }
+ TraceEntryKind::Instant { .. } => None,
+ }
}
/// Returns true if the command succeeded.
+ /// Instant events always return true.
pub fn is_success(&self) -> bool {
- matches!(self.result, TraceResult::Completed { success: true })
+ match &self.kind {
+ TraceEntryKind::Command { result, .. } => {
+ matches!(result, TraceResult::Completed { success: true })
+ }
+ TraceEntryKind::Instant { .. } => true,
+ }
+ }
+
+ /// Returns the command string if this is a command entry.
+ pub fn command(&self) -> Option<&str> {
+ match &self.kind {
+ TraceEntryKind::Command { command, .. } => Some(command),
+ TraceEntryKind::Instant { .. } => None,
+ }
+ }
+
+ /// Returns the event name if this is an instant event.
+ pub fn event_name(&self) -> Option<&str> {
+ match &self.kind {
+ TraceEntryKind::Command { .. } => None,
+ TraceEntryKind::Instant { name } => Some(name),
+ }
+ }
+
+ /// Returns the duration if this is a command entry.
+ pub fn duration(&self) -> Option<Duration> {
+ match &self.kind {
+ TraceEntryKind::Command { duration, .. } => Some(*duration),
+ TraceEntryKind::Instant { .. } => None,
+ }
+ }
+
+ /// Returns the display name for this entry.
+ pub fn display_name(&self) -> &str {
+ match &self.kind {
+ TraceEntryKind::Command { command, .. } => command,
+ TraceEntryKind::Instant { name } => name,
+ }
}
}
@@ -63,6 +132,10 @@ impl TraceEntry {
///
/// Returns `None` if the line doesn't match the expected format.
/// The `[wt-trace]` marker can appear anywhere in the line (to handle log prefixes).
+///
+/// Supports two formats:
+/// - Command events: `cmd="..." dur=...ms ok=true/false` or `err="..."`
+/// - Instant events: `event="..."`
pub fn parse_line(line: &str) -> Option<TraceEntry> {
// Find the [wt-trace] marker anywhere in the line
let marker = "[wt-trace] ";
@@ -72,6 +145,7 @@ pub fn parse_line(line: &str) -> Option<TraceEntry> {
// Parse key=value pairs
let mut context = None;
let mut command = None;
+ let mut event = None;
let mut duration = None;
let mut result = None;
let mut start_time_us = None;
@@ -109,6 +183,7 @@ pub fn parse_line(line: &str) -> Option<TraceEntry> {
match key {
"context" => context = Some(value.to_string()),
"cmd" => command = Some(value.to_string()),
+ "event" => event = Some(value.to_string()),
"dur" => {
// Parse "123.4ms"
let ms_str = value.strip_suffix("ms")?;
@@ -134,11 +209,22 @@ pub fn parse_line(line: &str) -> Option<TraceEntry> {
}
}
+ // Determine the entry kind based on what was parsed
+ let kind = if let Some(event_name) = event {
+ // Instant event
+ TraceEntryKind::Instant { name: event_name }
+ } else {
+ // Command event - requires cmd, dur, and result
+ TraceEntryKind::Command {
+ command: command?,
+ duration: duration?,
+ result: result?,
+ }
+ };
+
Some(TraceEntry {
context,
- command: command?,
- duration: duration?,
- result: result?,
+ kind,
start_time_us,
thread_id,
})
@@ -159,8 +245,8 @@ mod tests {
let entry = parse_line(line).unwrap();
assert_eq!(entry.context, None);
- assert_eq!(entry.command, "git status");
- assert_eq!(entry.duration, Duration::from_secs_f64(0.0123));
+ assert_eq!(entry.command(), Some("git status"));
+ assert_eq!(entry.duration(), Some(Duration::from_secs_f64(0.0123)));
assert!(entry.is_success());
}
@@ -171,7 +257,7 @@ mod tests {
let entry = parse_line(line).unwrap();
assert_eq!(entry.context, Some("main".to_string()));
- assert_eq!(entry.command, "git merge-base HEAD origin/main");
+ assert_eq!(entry.command(), Some("git merge-base HEAD origin/main"));
assert_eq!(entry.git_subcommand(), Some("merge-base"));
}
@@ -182,8 +268,8 @@ mod tests {
assert!(!entry.is_success());
assert!(matches!(
- entry.result,
- TraceResult::Error { message } if message == "fatal: bad revision"
+ &entry.kind,
+ TraceEntryKind::Command { result: TraceResult::Error { message }, .. } if message == "fatal: bad revision"
));
}
@@ -194,8 +280,11 @@ mod tests {
assert!(!entry.is_success());
assert!(matches!(
- entry.result,
- TraceResult::Completed { success: false }
+ &entry.kind,
+ TraceEntryKind::Command {
+ result: TraceResult::Completed { success: false },
+ ..
+ }
));
}
@@ -219,7 +308,7 @@ mod tests {
// Real output has thread ID prefix like "[a] "
let line = r#"[a] [wt-trace] cmd="git status" dur=5.0ms ok=true"#;
let entry = parse_line(line).unwrap();
- assert_eq!(entry.command, "git status");
+ assert_eq!(entry.command(), Some("git status"));
}
#[test]
@@ -228,7 +317,7 @@ mod tests {
let line =
r#"[wt-trace] future_field=xyz cmd="git status" dur=5.0ms ok=true extra=ignored"#;
let entry = parse_line(line).unwrap();
- assert_eq!(entry.command, "git status");
+ assert_eq!(entry.command(), Some("git status"));
assert!(entry.is_success());
}
@@ -237,7 +326,7 @@ mod tests {
// Trailing whitespace should be handled (exercises trim_start + break)
let line = "[wt-trace] cmd=\"git status\" dur=5.0ms ok=true ";
let entry = parse_line(line).unwrap();
- assert_eq!(entry.command, "git status");
+ assert_eq!(entry.command(), Some("git status"));
}
#[test]
@@ -250,8 +339,8 @@ more noise
"#;
let entries = parse_lines(input);
assert_eq!(entries.len(), 2);
- assert_eq!(entries[0].command, "git status");
- assert_eq!(entries[1].command, "git diff");
+ assert_eq!(entries[0].command(), Some("git status"));
+ assert_eq!(entries[1].command(), Some("git diff"));
}
#[test]
@@ -262,7 +351,7 @@ more noise
assert_eq!(entry.start_time_us, Some(1736600000000000));
assert_eq!(entry.thread_id, Some(5));
assert_eq!(entry.context, Some("feature".to_string()));
- assert_eq!(entry.command, "git status");
+ assert_eq!(entry.command(), Some("git status"));
assert!(entry.is_success());
}
@@ -274,7 +363,7 @@ more noise
assert_eq!(entry.start_time_us, None);
assert_eq!(entry.thread_id, None);
- assert_eq!(entry.command, "git status");
+ assert_eq!(entry.command(), Some("git status"));
}
#[test]
@@ -286,4 +375,72 @@ more noise
assert_eq!(entry.start_time_us, Some(1736600000000000));
assert_eq!(entry.thread_id, None);
}
+
+ // ========================================================================
+ // Instant event tests
+ // ========================================================================
+
+ #[test]
+ fn test_parse_instant_event() {
+ let line = r#"[wt-trace] ts=1736600000000000 tid=3 event="Showed skeleton""#;
+ let entry = parse_line(line).unwrap();
+
+ assert_eq!(entry.start_time_us, Some(1736600000000000));
+ assert_eq!(entry.thread_id, Some(3));
+ assert_eq!(entry.event_name(), Some("Showed skeleton"));
+ assert_eq!(entry.command(), None);
+ assert_eq!(entry.duration(), None);
+ assert!(entry.is_success()); // Instant events are always "successful"
+ }
+
+ #[test]
+ fn test_parse_instant_event_with_context() {
+ let line = r#"[wt-trace] ts=1736600000000000 tid=3 context=main event="Skeleton rendered""#;
+ let entry = parse_line(line).unwrap();
+
+ assert_eq!(entry.context, Some("main".to_string()));
+ assert_eq!(entry.event_name(), Some("Skeleton rendered"));
+ }
+
+ #[test]
+ fn test_parse_instant_event_minimal() {
+ // Instant event with only the required field
+ let line = r#"[wt-trace] event="Started""#;
+ let entry = parse_line(line).unwrap();
+
+ assert_eq!(entry.event_name(), Some("Started"));
+ assert_eq!(entry.start_time_us, None);
+ assert_eq!(entry.thread_id, None);
+ }
+
+ #[test]
+ fn test_display_name() {
+ // Command entry
+ let cmd_line = r#"[wt-trace] cmd="git status" dur=5.0ms ok=true"#;
+ let cmd_entry = parse_line(cmd_line).unwrap();
+ assert_eq!(cmd_entry.display_name(), "git status");
+
+ // Instant event
+ let event_line = r#"[wt-trace] event="Showed skeleton""#;
+ let event_entry = parse_line(event_line).unwrap();
+ assert_eq!(event_entry.display_name(), "Showed skeleton");
+ }
+
+ #[test]
+ fn test_parse_lines_mixed() {
+ let input = r#"
+[wt-trace] event="Started"
+[wt-trace] cmd="git status" dur=10.0ms ok=true
+[wt-trace] event="Showed skeleton"
+[wt-trace] cmd="git diff" dur=20.0ms ok=true
+[wt-trace] event="Done"
+"#;
+ let entries = parse_lines(input);
+ assert_eq!(entries.len(), 5);
+ assert_eq!(entries[0].event_name(), Some("Started"));
+ assert_eq!(entries[1].command(), Some("git status"));
+ assert_eq!(entries[2].event_name(), Some("Showed skeleton"));
+ assert_eq!(entries[3].command(), Some("git diff"));
+ assert_eq!(entries[4].event_name(), Some("Done"));
+ }
}
diff --git a/tests/integration_tests/analyze_trace.rs b/tests/integration_tests/analyze_trace.rs
index f1acc8003..aab3b55c9 100644
--- a/tests/integration_tests/analyze_trace.rs
+++ b/tests/integration_tests/analyze_trace.rs
@@ -7,10 +7,11 @@ use std::process::{Command, Stdio};
#[test]
fn test_analyze_trace_from_stdin() {
let sample_trace = r#"[wt-trace] ts=1000000 tid=1 cmd="git status" dur=10.0ms ok=true
-[wt-trace] ts=1000000 tid=2 cmd="git status" dur=15.0ms ok=true
-[wt-trace] ts=1010000 tid=1 cmd="git diff" dur=100.0ms ok=true
-[wt-trace] ts=1020000 tid=2 cmd="git merge-base HEAD main" dur=500.0ms ok=true
-[wt-trace] ts=1030000 tid=1 cmd="gh pr list" dur=200.0ms ok=true"#;
+[wt-trace] ts=1010000 tid=1 cmd="git status" dur=15.0ms ok=true
+[wt-trace] ts=1025000 tid=1 cmd="git diff" dur=100.0ms ok=true
+[wt-trace] ts=1025000 tid=2 event="Showed skeleton"
+[wt-trace] ts=1125000 tid=1 cmd="git merge-base HEAD main" dur=500.0ms ok=true
+[wt-trace] ts=1625000 tid=1 cmd="gh pr list" dur=200.0ms ok=true"#;
let mut child = Command::new(env!("CARGO_BIN_EXE_analyze-trace"))
.stdin(Stdio::piped())
@@ -32,28 +33,28 @@ fn test_analyze_trace_from_stdin() {
let stdout = String::from_utf8_lossy(&output.stdout);
- // Should be valid JSON with Chrome Trace Format structure
- let parsed: serde_json::Value =
- serde_json::from_str(&stdout).expect("Output should be valid JSON");
+ // Verify it's valid Chrome Trace Format JSON
+ let json: serde_json::Value = serde_json::from_str(&stdout).expect("Should output valid JSON");
+ assert_eq!(json["displayTimeUnit"], "ms", "Should have displayTimeUnit");
assert!(
- parsed["traceEvents"].is_array(),
+ json["traceEvents"].is_array(),
"Should have traceEvents array"
);
- assert_eq!(
- parsed["displayTimeUnit"], "ms",
- "Should have displayTimeUnit"
- );
- let events = parsed["traceEvents"].as_array().unwrap();
- assert_eq!(events.len(), 5, "Should have 5 trace events");
+ let events = json["traceEvents"].as_array().unwrap();
+ assert_eq!(events.len(), 6, "Should have 6 events");
- // Check first event structure
+ // Check command events
assert_eq!(events[0]["name"], "git status");
assert_eq!(events[0]["ph"], "X"); // Complete event
- assert_eq!(events[0]["ts"], 1000000);
- assert_eq!(events[0]["tid"], 1);
- assert_eq!(events[0]["cat"], "git");
+ assert!(events[0]["dur"].is_number()); // Has duration
+
+ // Check instant event
+ assert_eq!(events[3]["name"], "Showed skeleton");
+ assert_eq!(events[3]["ph"], "I"); // Instant event
+ assert_eq!(events[3]["s"], "g"); // Global scope
+ assert!(events[3]["dur"].is_null()); // No duration
}
/// Test that the binary shows usage when run interactively without input.
@@ -107,18 +108,19 @@ fn test_analyze_trace_empty_input() {
/// Test reading from a file.
#[test]
fn test_analyze_trace_from_file() {
- // Create a temporary file with trace data
+ // Create a temp file with sample trace data
let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
- let log_path = temp_dir.path().join("trace.log");
+ let log_file = temp_dir.path().join("trace.log");
let sample_trace = r#"[wt-trace] ts=1000000 tid=1 cmd="git rev-parse" dur=5.0ms ok=true
[wt-trace] ts=1005000 tid=1 cmd="git status" dur=10.0ms ok=true
-[wt-trace] ts=1015000 tid=2 cmd="git diff" dur=20.0ms ok=true"#;
+[wt-trace] ts=1015000 tid=1 event="Skeleton displayed"
+[wt-trace] ts=1015000 tid=2 cmd="git diff" dur=50.0ms ok=true"#;
- std::fs::write(&log_path, sample_trace).expect("Failed to write temp file");
+ std::fs::write(&log_file, sample_trace).expect("Failed to write sample log");
let output = Command::new(env!("CARGO_BIN_EXE_analyze-trace"))
- .arg(&log_path)
+ .arg(&log_file)
.output()
.expect("Failed to run analyze-trace");
@@ -126,11 +128,15 @@ fn test_analyze_trace_from_file() {
let stdout = String::from_utf8_lossy(&output.stdout);
- // Should be valid Chrome Trace Format JSON
- let parsed: serde_json::Value =
- serde_json::from_str(&stdout).expect("Output should be valid JSON");
+ // Verify it's valid Chrome Trace Format JSON
+ let json: serde_json::Value = serde_json::from_str(&stdout).expect("Should output valid JSON");
+
+ assert!(json["traceEvents"].is_array(), "Should have traceEvents");
+ let events = json["traceEvents"].as_array().unwrap();
+ assert_eq!(events.len(), 4, "Should have 4 events");
- let events = parsed["traceEvents"].as_array().unwrap();
- assert_eq!(events.len(), 3, "Should have 3 trace events");
+ // Check we have both command and instant events
assert_eq!(events[0]["name"], "git rev-parse");
+ assert_eq!(events[2]["name"], "Skeleton displayed");
+ assert_eq!(events[2]["ph"], "I"); // Instant event
}