Skip to content

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

Show pipeline structure in alias announcements (#2092)

Maximilian Roos7b91a71c371f
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index 9dd68dd0c..6f3a91822 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -15,6 +15,26 @@
//! In pipelines, templates referencing `vars.*` use lazy expansion — deferred
//! until execution time so prior steps can set vars via git config.
//!
+//! ## Why concurrent execution isn't shared with `run_pipeline`
+//!
+//! Both alias and background pipeline runners need "spawn N commands, wait for
+//! all". They use different primitives because their leaf executors differ:
+//!
+//! - Aliases call `execute_shell_command` (the unified streaming executor),
+//! which is *blocking* — it streams stdout/stderr to the terminal and only
+//! returns once the child exits. Concurrency therefore needs OS threads
+//! (`thread::scope`), one thread per command.
+//! - The background pipeline runner spawns shell processes directly with
+//! stdout/stderr redirected to per-command log files. The `Child` handle is
+//! the concurrency primitive — no threads needed.
+//!
+//! Bridging the two would require either making `execute_shell_command`
+//! return a non-blocking handle (invasive — entangles signal forwarding,
+//! ANSI reset, and `Cmd` streaming), or running background commands in
+//! threads they don't need. Neither pays for the abstraction. The pipeline
+//! summary formatter, on the other hand, is shared via
+//! `hooks::format_pipeline_summary_from_names`.
+//!
//! ## Trust model
//!
//! User-config aliases are trusted (skip approval). Project-config aliases
@@ -41,6 +61,8 @@ use crate::commands::command_approval::approve_alias_commands;
use crate::commands::command_executor::{
CommandContext, build_hook_context, expand_shell_template, wait_first_error,
};
+use crate::commands::force_serial_concurrent;
+use crate::commands::hooks::format_pipeline_summary_from_names;
use crate::output::execute_shell_command;
/// Built-in `wt step` subcommand names. Aliases with these names are
@@ -174,6 +196,37 @@ fn find_closest_match<'a>(input: &str, candidates: &[&'a str]) -> Option<&'a str
.map(|(name, _)| name)
}
+/// Format the "Running alias …" announcement.
+///
+/// For pipelines or concurrent groups with named commands, includes a summary
+/// of the structure (e.g., `Running alias deploy: install; build, lint`).
+/// When all commands are unnamed, falls back to the bare form
+/// (`Running alias deploy`) — aliases have no natural fallback label for
+/// unnamed steps the way hooks use `user`/`project`.
+///
+/// Sibling of `format_command_label` in `commands/mod.rs`, which builds the
+/// non-pipeline `Running {type} {name}` form for hooks. Both apply bold
+/// styling to the alias/command name — keep them in sync if styling evolves.
+fn format_alias_announcement(name: &str, cmd_config: &CommandConfig) -> String {
+ let step_names: Vec<Vec<Option<&str>>> = cmd_config
+ .steps()
+ .iter()
+ .map(|step| match step {
+ HookStep::Single(cmd) => vec![cmd.name.as_deref()],
+ HookStep::Concurrent(cmds) => cmds.iter().map(|c| c.name.as_deref()).collect(),
+ })
+ .collect();
+
+ let summary =
+ format_pipeline_summary_from_names(&step_names, |n| cformat!("<bold>{n}</>"), |_| None);
+
+ if summary.is_empty() {
+ cformat!("Running alias <bold>{name}</>")
+ } else {
+ cformat!("Running alias <bold>{name}</>: {summary}")
+ }
+}
+
/// Run a configured alias by name.
///
/// Looks up the alias in merged config (project config + user config),
@@ -315,7 +368,7 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {
eprintln!(
"{}",
- progress_message(cformat!("Running alias <bold>{}</>", opts.name))
+ progress_message(format_alias_announcement(&opts.name, cmd_config))
);
// Pass the parent shell's directive file through so inner `wt` invocations
@@ -339,15 +392,22 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {
match step {
HookStep::Single(cmd) => exec.run(cmd)?,
HookStep::Concurrent(cmds) => {
- std::thread::scope(|s| {
- let handles: Vec<_> =
- cmds.iter().map(|cmd| s.spawn(|| exec.run(cmd))).collect();
- wait_first_error(
- handles
- .into_iter()
- .map(|h| h.join().expect("alias command thread panicked")),
- )
- })?;
+ if force_serial_concurrent() {
+ // Test-only path: deterministic ordering for snapshots.
+ for cmd in cmds {
+ exec.run(cmd)?;
+ }
+ } else {
+ std::thread::scope(|s| {
+ let handles: Vec<_> =
+ cmds.iter().map(|cmd| s.spawn(|| exec.run(cmd))).collect();
+ wait_first_error(
+ handles
+ .into_iter()
+ .map(|h| h.join().expect("alias command thread panicked")),
+ )
+ })?;
+ }
}
}
}
@@ -400,11 +460,83 @@ impl AliasExecCtx<'_> {
#[cfg(test)]
mod tests {
use super::*;
+ use ansi_str::AnsiStr;
fn parse(args: &[&str]) -> anyhow::Result<AliasOptions> {
AliasOptions::parse(args.iter().map(|s| s.to_string()).collect())
}
+ /// Parse a TOML snippet of the form `cmd = ...` into a CommandConfig.
+ /// CommandConfig has no public multi-step constructor, so round-tripping
+ /// through TOML is the simplest way to build pipeline fixtures.
+ fn cfg_from_toml(toml_str: &str) -> CommandConfig {
+ #[derive(serde::Deserialize)]
+ struct Wrap {
+ cmd: CommandConfig,
+ }
+ toml::from_str::<Wrap>(toml_str).unwrap().cmd
+ }
+
+ #[test]
+ fn test_format_alias_announcement_single_unnamed() {
+ let cfg = cfg_from_toml(r#"cmd = "echo hi""#);
+ let msg = format_alias_announcement("deploy", &cfg);
+ insta::assert_snapshot!(msg.ansi_strip(), @"Running alias deploy");
+ }
+
+ #[test]
+ fn test_format_alias_announcement_pipeline_all_unnamed() {
+ // Pipeline of unnamed strings → no summary suffix.
+ let cfg = cfg_from_toml(r#"cmd = ["echo a", "echo b"]"#);
+ let msg = format_alias_announcement("deploy", &cfg);
+ insta::assert_snapshot!(msg.ansi_strip(), @"Running alias deploy");
+ }
+
+ #[test]
+ fn test_format_alias_announcement_concurrent_named() {
+ // Single concurrent step (named table form).
+ let cfg = cfg_from_toml(
+ r#"
+[cmd]
+build = "cargo build"
+test = "cargo test"
+"#,
+ );
+ let msg = format_alias_announcement("check", &cfg);
+ insta::assert_snapshot!(msg.ansi_strip(), @"Running alias check: build, test");
+ }
+
+ #[test]
+ fn test_format_alias_announcement_pipeline_named() {
+ // Pipeline: serial named step then concurrent named step.
+ let cfg = cfg_from_toml(
+ r#"
+cmd = [
+ { install = "npm install" },
+ { build = "npm run build", lint = "npm run lint" },
+]
+"#,
+ );
+ let msg = format_alias_announcement("deploy", &cfg);
+ insta::assert_snapshot!(msg.ansi_strip(), @"Running alias deploy: install; build, lint");
+ }
+
+ #[test]
+ fn test_format_alias_announcement_mixed_named_unnamed() {
+ // Pipeline mixing anonymous strings and named steps. Unnamed entries
+ // are skipped from the summary (aliases have no fallback label).
+ let cfg = cfg_from_toml(
+ r#"
+cmd = [
+ "echo first",
+ { build = "cargo build", test = "cargo test" },
+]
+"#,
+ );
+ let msg = format_alias_announcement("ci", &cfg);
+ insta::assert_snapshot!(msg.ansi_strip(), @"Running alias ci: build, test");
+ }
+
#[test]
fn test_parse() {
use insta::assert_debug_snapshot;
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 8c23544e7..4b643b1dd 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -189,59 +189,89 @@ pub struct SourcedStep {
pub display_path: Option<PathBuf>,
}
-/// Format a summary description of a pipeline for display.
+/// Format a pipeline summary from per-step command names.
///
-/// Named steps show as `source:name`; unnamed steps are collapsed into a single
-/// `source ×N` count. Serial steps are separated by `;`, concurrent steps by `,`.
-/// Example: "user:install; user:build, user:lint"
+/// `step_names[i]` is the list of commands in step `i`; `Some(name)` for named
+/// commands, `None` for unnamed. Serial steps are joined by `;`, concurrent
+/// commands within a step by `,`. Contiguous runs of unnamed commands (across
+/// steps, until the next named command) are collapsed into a single
+/// `label_unnamed(count)` entry; return `None` from that closure to drop
+/// unnamed commands entirely.
///
-/// TODO: The `source:` prefix on named steps may be too verbose when only one
-/// source is present (e.g., `user:bg` vs just `bg`). Consider prefixing only
-/// when both user and project hooks exist for the same hook type.
-fn format_pipeline_summary(steps: &[SourcedStep]) -> String {
- // All steps in a group share the same source.
- let source_label = steps[0].source.to_string();
-
- // Collect named labels per step (None = unnamed).
+/// Shared by hook announcements (where unnamed commands collapse to
+/// `user ×N`) and alias announcements (which skip unnamed commands since
+/// aliases have no natural fallback label).
+pub(crate) fn format_pipeline_summary_from_names(
+ step_names: &[Vec<Option<&str>>],
+ label_named: impl Fn(&str) -> String,
+ label_unnamed: impl Fn(usize) -> Option<String>,
+) -> String {
let mut parts: Vec<String> = Vec::new();
let mut unnamed_count: usize = 0;
- for step in steps {
- let step_names: Vec<Option<&str>> = match &step.step {
- PreparedStep::Single(cmd) => vec![cmd.name.as_deref()],
- PreparedStep::Concurrent(cmds) => cmds.iter().map(|c| c.name.as_deref()).collect(),
- };
-
- let named: Vec<_> = step_names
- .iter()
- .filter_map(|n| n.map(|name| cformat!("<bold>{source_label}:{name}</>")))
- .collect();
- unnamed_count += step_names.iter().filter(|n| n.is_none()).count();
+ for step in step_names {
+ let mut named = Vec::new();
+ for entry in step {
+ match entry {
+ Some(name) => named.push(label_named(name)),
+ None => unnamed_count += 1,
+ }
+ }
if !named.is_empty() {
// Flush any pending unnamed count before named labels.
- if unnamed_count > 0 {
- parts.push(format_unnamed(&source_label, unnamed_count));
- unnamed_count = 0;
+ if unnamed_count > 0
+ && let Some(s) = label_unnamed(unnamed_count)
+ {
+ parts.push(s);
}
+ unnamed_count = 0;
parts.push(named.join(", "));
}
}
// Flush trailing unnamed count.
- if unnamed_count > 0 {
- parts.push(format_unnamed(&source_label, unnamed_count));
+ if unnamed_count > 0
+ && let Some(s) = label_unnamed(unnamed_count)
+ {
+ parts.push(s);
}
parts.join("; ")
}
-fn format_unnamed(source_label: &str, count: usize) -> String {
- if count == 1 {
- cformat!("<bold>{source_label}</>")
- } else {
- cformat!("<bold>{source_label}</> ×{count}")
- }
+/// Format a summary description of a hook pipeline for display.
+///
+/// Named steps show as `source:name`; unnamed steps are collapsed into a single
+/// `source ×N` count. Serial steps are separated by `;`, concurrent steps by `,`.
+/// Example: "user:install; user:build, user:lint"
+///
+/// TODO: The `source:` prefix on named steps may be too verbose when only one
+/// source is present (e.g., `user:bg` vs just `bg`). Consider prefixing only
+/// when both user and project hooks exist for the same hook type.
+fn format_pipeline_summary(steps: &[SourcedStep]) -> String {
+ // All steps in a group share the same source.
+ let source_label = steps[0].source.to_string();
+
+ let step_names: Vec<Vec<Option<&str>>> = steps
+ .iter()
+ .map(|step| match &step.step {
+ PreparedStep::Single(cmd) => vec![cmd.name.as_deref()],
+ PreparedStep::Concurrent(cmds) => cmds.iter().map(|c| c.name.as_deref()).collect(),
+ })
+ .collect();
+
+ format_pipeline_summary_from_names(
+ &step_names,
+ |name| cformat!("<bold>{source_label}:{name}</>"),
+ |count| {
+ Some(if count == 1 {
+ cformat!("<bold>{source_label}</>")
+ } else {
+ cformat!("<bold>{source_label}</> ×{count}")
+ })
+ },
+ )
}
/// Announce and spawn background hooks for one or more hook types.
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 21166b41b..510e1bbd5 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -77,6 +77,16 @@ pub(crate) fn format_command_label(command_type: &str, name: Option<&str>) -> St
}
}
+/// Force concurrent steps to run serially. Test-only escape hatch — set via
+/// `WORKTRUNK_TEST_SERIAL_CONCURRENT=1` to make output ordering deterministic
+/// for snapshot tests, mirroring how `RAYON_NUM_THREADS=1` is used elsewhere.
+///
+/// Honored by both alias `HookStep::Concurrent` execution and the background
+/// pipeline runner's concurrent groups.
+pub(crate) fn force_serial_concurrent() -> bool {
+ std::env::var_os("WORKTRUNK_TEST_SERIAL_CONCURRENT").is_some()
+}
+
/// Show detailed diffstat for a given commit range.
///
/// Displays the diff statistics (file changes, insertions, deletions) in a gutter format.
diff --git a/src/commands/run_pipeline.rs b/src/commands/run_pipeline.rs
index 96a6dd9b3..103cbb80e 100644
--- a/src/commands/run_pipeline.rs
+++ b/src/commands/run_pipeline.rs
@@ -183,13 +183,20 @@ fn spawn_shell_command(
/// Waits every spawned child before returning. If any failed, the first
/// failure (in spawn order) is returned, matching the serial-step bail
/// format. Per-command output already lives in each command's log file.
+///
+/// When `WORKTRUNK_TEST_SERIAL_CONCURRENT=1` is set, each command's child is
+/// awaited before the next is spawned so output ordering is deterministic for
+/// snapshot tests. The serial path bails on the first failure rather than
+/// running every child to completion (the test hatch is for ordering, not
+/// error semantics).
fn run_concurrent_group(
commands: &[super::pipeline_spec::PipelineCommandSpec],
spec: &PipelineSpec,
repo: &Repository,
cmd_index: &mut usize,
) -> anyhow::Result<()> {
- let mut children = Vec::with_capacity(commands.len());
+ let serial = super::force_serial_concurrent();
+ let mut children = Vec::with_capacity(if serial { 0 } else { commands.len() });
for cmd in commands {
let log_name = command_log_name(cmd.name.as_deref(), *cmd_index);
@@ -199,9 +206,23 @@ fn run_concurrent_group(
let expanded = expand_shell_template(&cmd.template, &cmd_ctx, repo, label)?;
let cmd_json =
serde_json::to_string(&*cmd_ctx).context("failed to serialize step context")?;
- let child = spawn_shell_command(&expanded, &spec.worktree_path, &cmd_json, log_file)?;
- children.push((cmd.name.clone(), expanded, child));
+ let mut child = spawn_shell_command(&expanded, &spec.worktree_path, &cmd_json, log_file)?;
*cmd_index += 1;
+
+ if serial {
+ let status = child
+ .wait()
+ .with_context(|| format!("failed to wait for: {expanded}"))?;
+ if !status.success() {
+ bail!(
+ "command failed with {}: {}",
+ format_exit(status.code()),
+ cmd.name.as_deref().unwrap_or(&expanded),
+ );
+ }
+ } else {
+ children.push((cmd.name.clone(), expanded, child));
+ }
}
wait_first_error(children.into_iter().map(
diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rs
index 8dda05273..6286c782c 100644
--- a/tests/integration_tests/post_start_commands.rs
+++ b/tests/integration_tests/post_start_commands.rs
@@ -1354,3 +1354,84 @@ approved-commands = ["echo PROJECT > project_marker.txt"]
let project = fs::read_to_string(worktree_path.join("project_marker.txt")).unwrap();
assert!(project.contains("PROJECT"));
}
+
+/// `WORKTRUNK_TEST_SERIAL_CONCURRENT=1` makes the background pipeline runner's
+/// concurrent group run commands one at a time in declaration order. The two
+/// commands append to the same file, so a deterministic ordering proves they
+/// ran serially (a true concurrent run could interleave the appends). The
+/// failing-first-command variant additionally exercises the bail-on-failure
+/// path inside the serial branch — second never gets to run.
+#[rstest]
+fn test_post_start_concurrent_serial_force(repo: TestRepo) {
+ repo.write_project_config(
+ r#"[post-start]
+first = "echo FIRST >> serial_order.txt"
+second = "echo SECOND >> serial_order.txt"
+"#,
+ );
+ repo.commit("Add concurrent post-start");
+
+ repo.write_test_approvals(
+ r#"[projects."../origin"]
+approved-commands = [
+ "echo FIRST >> serial_order.txt",
+ "echo SECOND >> serial_order.txt",
+]
+"#,
+ );
+
+ let temp_home = TempDir::new().unwrap();
+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["--create", "feature"], None);
+ cmd.env("WORKTRUNK_TEST_SERIAL_CONCURRENT", "1");
+ set_temp_home_env(&mut cmd, temp_home.path());
+ let _ = cmd.output().unwrap();
+
+ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
+ let order_file = worktree_path.join("serial_order.txt");
+ wait_for_file_lines(&order_file, 2);
+
+ let content = fs::read_to_string(&order_file).unwrap();
+ assert_eq!(
+ content, "FIRST\nSECOND\n",
+ "serial run should append in declaration order"
+ );
+}
+
+#[rstest]
+fn test_post_start_concurrent_serial_bails_on_failure(repo: TestRepo) {
+ // First command writes a marker then fails; second writes a marker that
+ // would always exist if it ran. Serial mode bails after the first failure,
+ // so the second marker should be absent.
+ repo.write_project_config(
+ r#"[post-start]
+first = "echo FIRST > first_marker.txt && false"
+second = "echo SECOND > second_marker.txt"
+"#,
+ );
+ repo.commit("Add failing post-start");
+
+ repo.write_test_approvals(
+ r#"[projects."../origin"]
+approved-commands = [
+ "echo FIRST > first_marker.txt && false",
+ "echo SECOND > second_marker.txt",
+]
+"#,
+ );
+
+ let temp_home = TempDir::new().unwrap();
+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["--create", "feature"], None);
+ cmd.env("WORKTRUNK_TEST_SERIAL_CONCURRENT", "1");
+ set_temp_home_env(&mut cmd, temp_home.path());
+ let _ = cmd.output().unwrap();
+
+ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
+ wait_for_file_content(&worktree_path.join("first_marker.txt"));
+
+ // Wait for any trailing background work, then assert the second never ran.
+ thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
+ assert!(
+ !worktree_path.join("second_marker.txt").exists(),
+ "serial mode should bail on first failure — second command must not run"
+ );
+}
diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rs
index f93116ea6..7502f7e6b 100644
--- a/tests/integration_tests/step_alias.rs
+++ b/tests/integration_tests/step_alias.rs
@@ -598,6 +598,35 @@ new-branch = "'{wt_toml}' switch --create alias-created"
);
}
+/// Pipeline aliases announce their structure: named serial and concurrent
+/// steps appear in the "Running alias" line, joined by `;` and `,`.
+///
+/// `WORKTRUNK_TEST_SERIAL_CONCURRENT=1` forces the concurrent step to run
+/// commands sequentially (in declaration order) so the snapshot captures a
+/// deterministic interleaving — analogous to how `RAYON_NUM_THREADS=1` is
+/// used in `step_prune` tests.
+#[rstest]
+fn test_alias_pipeline_announcement(mut repo: TestRepo) {
+ repo.write_test_config(
+ r#"
+[aliases]
+deploy = [
+ { install = "echo INSTALL" },
+ { build = "echo BUILD", lint = "echo LINT" },
+]
+"#,
+ );
+ repo.commit("initial");
+ let feature_path = repo.add_worktree("feature");
+
+ let settings = setup_snapshot_settings(&repo);
+ let _guard = settings.bind_to_scope();
+
+ let mut cmd = make_snapshot_cmd(&repo, "step", &["deploy"], Some(&feature_path));
+ cmd.env("WORKTRUNK_TEST_SERIAL_CONCURRENT", "1");
+ assert_cmd_snapshot!(cmd);
+}
+
/// Concurrent alias steps (named table) execute all commands
#[rstest]
fn test_alias_concurrent_steps(mut repo: TestRepo) {
diff --git a/tests/snapshots/integration__integration_tests__step_alias__alias_pipeline_announcement.snap b/tests/snapshots/integration__integration_tests__step_alias__alias_pipeline_announcement.snap
new file mode 100644
index 000000000..a7bdaed09
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_alias__alias_pipeline_announcement.snap
@@ -0,0 +1,51 @@
+---
+source: tests/integration_tests/step_alias.rs
+info:
+ program: wt
+ args:
+ - step
+ - deploy
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SERIAL_CONCURRENT: "1"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Running alias deploy: install; build, lint
+INSTALL
+BUILD
+LINT