Skip to content

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

Add dev server URL column to `wt list` (#288)

Maximilian Roosd72d6d8042f9
diff --git a/docs/content/config.md b/docs/content/config.md
index 1cf1ad4db..6f74852a2 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -149,7 +149,7 @@ See [wt hook](@/hook.md#user-hooks) for complete documentation.
## Project config
-The project config defines lifecycle hooks — commands that run at specific points during worktree operations. This file is checked into version control and shared across the team.
+The project config defines lifecycle hooks and project-specific settings. This file is checked into version control and shared across the team.
Create `.config/wt.toml` in the repository root:
@@ -164,6 +164,17 @@ lint = "npm run lint"
See [wt hook](@/hook.md) for complete documentation on hook types, execution order, template variables, and [JSON context](@/hook.md#json-context).
+### Dev server URL
+
+The `[list]` section adds a URL column to `wt list`:
+
+```toml
+[list]
+url = "http://localhost:{{ branch | hash_port }}"
+```
+
+URLs are dimmed when the port isn't listening. The template supports `{{ branch }}` with filters `hash_port` (port 10000-19999) and `sanitize` (filesystem-safe).
+
## Shell integration
Worktrunk needs shell integration to change directories when switching worktrees. Install with:
diff --git a/docs/content/list.md b/docs/content/list.md
index 8ec55b901..dabe06ee7 100644
--- a/docs/content/list.md
+++ b/docs/content/list.md
@@ -81,6 +81,7 @@ $ wt list --format=json
| main…± | Line diffs since the merge-base with the default branch (`--full`) |
| Path | Worktree directory |
| Remote⇅ | Commits ahead/behind tracking branch |
+| URL | Dev server URL from project config (dimmed if port not listening) |
| CI | Pipeline status (`--full`) |
| Commit | Short hash (8 chars) |
| Age | Time since last commit |
@@ -175,6 +176,8 @@ wt list --format=json | jq '.[] | select(.main_state == "integrated" or .main_st
| `is_current` | boolean | Is the current worktree |
| `is_previous` | boolean | Previous worktree from wt switch |
| `ci` | object | CI status (see below, absent when no CI) |
+| `url` | string | Dev server URL from project config (absent when not configured) |
+| `url_active` | boolean | Whether the URL's port is listening (absent when not configured) |
| `statusline` | string | Pre-formatted status with ANSI colors |
| `symbols` | string | Raw status symbols without colors (e.g., `"!?↓"`) |
diff --git a/src/cli.rs b/src/cli.rs
index 2eb2a71df..204d974c7 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -1299,7 +1299,7 @@ See [wt hook](@/hook.md#user-hooks) for complete documentation.
## Project config
-The project config defines lifecycle hooks — commands that run at specific points during worktree operations. This file is checked into version control and shared across the team.
+The project config defines lifecycle hooks and project-specific settings. This file is checked into version control and shared across the team.
Create `.config/wt.toml` in the repository root:
@@ -1314,6 +1314,17 @@ lint = "npm run lint"
See [wt hook](@/hook.md) for complete documentation on hook types, execution order, template variables, and [JSON context](@/hook.md#json-context).
+### Dev server URL
+
+The `[list]` section adds a URL column to `wt list`:
+
+```toml
+[list]
+url = "http://localhost:{{ branch | hash_port }}"
+```
+
+URLs are dimmed when the port isn't listening. The template supports `{{ branch }}` with filters `hash_port` (port 10000-19999) and `sanitize` (filesystem-safe).
+
## Shell integration
Worktrunk needs shell integration to change directories when switching worktrees. Install with:
@@ -1914,6 +1925,7 @@ $ wt list --format=json
| main…± | Line diffs since the merge-base with the default branch (`--full`) |
| Path | Worktree directory |
| Remote⇅ | Commits ahead/behind tracking branch |
+| URL | Dev server URL from project config (dimmed if port not listening) |
| CI | Pipeline status (`--full`) |
| Commit | Short hash (8 chars) |
| Age | Time since last commit |
@@ -2008,6 +2020,8 @@ wt list --format=json | jq '.[] | select(.main_state == "integrated" or .main_st
| `is_current` | boolean | Is the current worktree |
| `is_previous` | boolean | Previous worktree from wt switch |
| `ci` | object | CI status (see below, absent when no CI) |
+| `url` | string | Dev server URL from project config (absent when not configured) |
+| `url_active` | boolean | Whether the URL's port is listening (absent when not configured) |
| `statusline` | string | Pre-formatted status with ANSI colors |
| `symbols` | string | Raw status symbols without colors (e.g., `"!?↓"`) |
diff --git a/src/commands/list/CLAUDE.md b/src/commands/list/CLAUDE.md
new file mode 100644
index 000000000..4bf3fba03
--- /dev/null
+++ b/src/commands/list/CLAUDE.md
@@ -0,0 +1,94 @@
+# List Command Architecture
+
+## Skeleton-First Rendering
+
+The `wt list` command uses skeleton-first rendering: a placeholder table appears
+immediately (~50ms), then cells fill in as data arrives. This gives users
+instant feedback even when git operations are slow.
+
+**The skeleton must render as fast as possible.** Every operation before the
+skeleton adds perceived latency. Users notice 50ms vs 150ms.
+
+## Rendering Phases
+
+### Phase 1: Pre-Skeleton (KEEP THIS MINIMAL)
+
+Operations that MUST complete before showing anything:
+
+1. `git worktree list` — enumerate worktrees
+2. `git config worktrunk.default-branch` — identify main branch for sorting
+3. `git show -s --format='%H %ct'` — batch timestamp fetch for sorting
+4. `git rev-parse --is-bare-repository` — layout decision (show Path column?)
+5. Path canonicalization — detect current worktree (no git command)
+6. Project config check — read `.config/wt.toml` to check if URL column needed
+7. Layout calculation — column widths from branch/path lengths (no git command)
+
+With `--branches`/`--remotes`:
+- `git for-each-ref refs/heads` / `refs/remotes`
+
+**DO NOT add operations here without very good reason.** Template expansion,
+per-item computations, network I/O — all must wait until after skeleton.
+
+### Phase 2: Skeleton Render
+
+The skeleton shows:
+- Branch names (known from worktree list)
+- Paths (known from worktree list)
+- Placeholder gutter symbols (`·`)
+- Loading indicators for computed columns
+
+### Phase 3: Post-Skeleton
+
+Everything else runs after the skeleton appears:
+
+- Previous branch lookup (`get_switch_previous`)
+- Integration target calculation
+- URL template expansion (parallelized in task spawning)
+- All background tasks (status, diffs, CI, URL health checks)
+
+These operations update cells progressively as they complete.
+
+**URL column example:** The skeleton allocates space for the URL column (width
+estimated from template + longest branch in Phase 1). URL template expansion
+happens in task spawning (Phase 3), parallelized across worktrees. Two-phase
+update:
+
+1. URL appears immediately in normal styling (sent before health check task)
+2. If health check fails (port not listening), URL dims
+
+This ensures URLs appear as fast as possible — users see the URL right away,
+then it dims only if the dev server isn't running.
+
+## Adding New Features
+
+When adding a new column or feature, ask:
+
+1. **Does it need data before skeleton?** Usually no. The skeleton can show a
+ placeholder or omit the column until data arrives.
+
+2. **Can template expansion wait?** Yes. Expand templates post-skeleton, then
+ update the relevant cells.
+
+3. **Does it require file I/O?** If so, it belongs post-skeleton. Reading config
+ files, checking file existence, etc. all add latency.
+
+**Default answer: defer to post-skeleton.** Only add pre-skeleton operations
+when the skeleton literally cannot render without the data (e.g., we need branch
+names to show anything useful).
+
+## Benchmarking Skeleton Time
+
+```bash
+WORKTRUNK_SKELETON_ONLY=1 hyperfine 'wt list'
+```
+
+This exits immediately after rendering the skeleton, measuring pure skeleton
+latency. Target: <60ms.
+
+## Code Structure
+
+- `collect.rs` — orchestrates collection, manages pre/post-skeleton phases
+- `collect_progressive_impl.rs` — background task definitions and execution
+- `render.rs` — row formatting, skeleton rows, cell rendering
+- `layout.rs` — column width calculation
+- `progressive_table.rs` — terminal rendering with in-place updates
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index e41b7e760..a5f6b738e 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -17,10 +17,12 @@
//! 4. `git branch` / `git branch -r` — only if `--branches` / `--remotes` flags
//! 5. `git show -s --format='%H %ct'` — batch timestamp fetch for sorting
//! 6. `git rev-parse --is-bare-repository` — for layout (path column visibility)
+//! 7. Project config check — only reads file to check if URL column needed (no expansion)
//!
//! **Deferred until after skeleton:**
//! - `get_switch_previous()` — previous branch detection (updates gutter symbol)
//! - `effective_integration_target()` — upstream vs local target check
+//! - URL template expansion — parallelized in task spawning
//! - All computed fields (ahead/behind, diffs, CI status, etc.)
//!
//! When adding new features, ask: "Can this be computed after skeleton?" If yes, defer it.
@@ -164,6 +166,14 @@ pub(super) enum TaskResult {
item_idx: usize,
pr_status: Option<PrStatus>,
},
+ /// URL status (expanded URL and health check result)
+ UrlStatus {
+ item_idx: usize,
+ /// Expanded URL from template (None if no template or no branch)
+ url: Option<String>,
+ /// Whether the port is listening (None if no URL or couldn't parse port)
+ active: Option<bool>,
+ },
}
impl TaskResult {
@@ -182,7 +192,8 @@ impl TaskResult {
| TaskResult::GitOperation { item_idx, .. }
| TaskResult::UserMarker { item_idx, .. }
| TaskResult::Upstream { item_idx, .. }
- | TaskResult::CiStatus { item_idx, .. } => *item_idx,
+ | TaskResult::CiStatus { item_idx, .. }
+ | TaskResult::UrlStatus { item_idx, .. } => *item_idx,
}
}
}
@@ -338,6 +349,10 @@ fn apply_default(items: &mut [ListItem], status_contexts: &mut [StatusContext],
// Some(None) means "loaded but no CI"
items[idx].pr_status = Some(None);
}
+ TaskKind::UrlStatus => {
+ // URL is set at item creation, only default url_active
+ items[idx].url_active = None;
+ }
}
}
@@ -523,6 +538,18 @@ fn drain_results(
// Wrap in Some() to indicate "loaded" (Some(None) = no CI, Some(Some(status)) = has CI)
item.pr_status = Some(pr_status);
}
+ TaskResult::UrlStatus { url, active, .. } => {
+ // Two-phase URL rendering:
+ // 1. First result (from spawning code): url=Some, active=None → URL appears in normal styling
+ // 2. Second result (from health check): url=None, active=Some → dims if inactive
+ // Only update non-None fields to preserve values from earlier results.
+ if url.is_some() {
+ item.url = url;
+ }
+ if active.is_some() {
+ item.url_active = active;
+ }
+ }
}
// Invoke callback (progressive mode re-renders rows, buffered mode does nothing)
@@ -694,6 +721,15 @@ pub fn collect(
// Pre-compute is_bare for path mismatch checks (avoids redundant git calls in the loop)
let is_bare = repo.is_bare().unwrap_or(false);
+ // Check if URL template is configured (for layout column allocation).
+ // Template expansion is deferred to post-skeleton to minimize time-to-skeleton.
+ let url_template = repo
+ .worktree_root()
+ .ok()
+ .and_then(|root| worktrunk::config::ProjectConfig::load(root).ok().flatten())
+ .and_then(|config| config.list)
+ .and_then(|list| list.url);
+
// Initialize worktree items with identity fields and None for computed fields
let mut all_items: Vec<ListItem> = sorted_worktrees
.iter()
@@ -721,6 +757,7 @@ pub fn collect(
WorktreeData::from_worktree(wt, is_main, is_current, is_previous);
worktree_data.path_mismatch = path_mismatch;
+ // URL expanded post-skeleton to minimize time-to-skeleton
ListItem {
head: wt.head.clone(),
branch: wt.branch.clone(),
@@ -733,6 +770,8 @@ pub fn collect(
is_ancestor: None,
upstream: None,
pr_status: None,
+ url: None,
+ url_active: None,
status_symbols: None,
display: DisplayFields::default(),
kind: ItemKind::Worktree(Box::new(worktree_data)),
@@ -740,7 +779,7 @@ pub fn collect(
})
.collect();
- // Initialize branch items (local and remote)
+ // Initialize branch items (local and remote) - URLs expanded post-skeleton
let branch_start_idx = all_items.len();
all_items.extend(
branches_without_worktrees
@@ -755,16 +794,27 @@ pub fn collect(
.map(|(name, sha)| ListItem::new_branch(sha.clone(), name.clone())),
);
+ // If no URL template configured, add UrlStatus to skip_tasks
+ let mut effective_skip_tasks = skip_tasks.clone();
+ if url_template.is_none() {
+ effective_skip_tasks.insert(TaskKind::UrlStatus);
+ }
+
// Calculate layout from items (worktrees, local branches, and remote branches)
- let layout =
- super::layout::calculate_layout_from_basics(&all_items, skip_tasks, &main_worktree.path);
+ let layout = super::layout::calculate_layout_from_basics(
+ &all_items,
+ &effective_skip_tasks,
+ &main_worktree.path,
+ url_template.as_deref(),
+ );
// Single-line invariant: use safe width to prevent line wrapping
let max_width = super::layout::get_safe_list_width();
// Create collection options from skip set
let options = super::collect_progressive_impl::CollectOptions {
- skip_tasks: skip_tasks.clone(), // Clone for thread spawns
+ skip_tasks: effective_skip_tasks,
+ url_template: url_template.clone(),
};
// Track expected results per item - populated as spawns are queued
@@ -842,6 +892,9 @@ pub fn collect(
// Deferred until after skeleton to avoid blocking initial render.
let integration_target = repo.effective_integration_target(&default_branch);
+ // Note: URL template expansion is deferred to task spawning (in collect_worktree_progressive
+ // and collect_branch_progressive). This parallelizes the work and minimizes time-to-skeleton.
+
// Pre-start fsmonitor daemons on macOS to avoid auto-start races.
//
// Git's builtin fsmonitor on macOS has race conditions under parallel load that can
@@ -1184,6 +1237,8 @@ pub fn build_worktree_item(
is_ancestor: None,
upstream: None,
pr_status: None,
+ url: None,
+ url_active: None,
status_symbols: None,
display: DisplayFields::default(),
kind: ItemKind::Worktree(Box::new(WorktreeData::from_worktree(
diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rs
index 7ca5870dd..31b284674 100644
--- a/src/commands/list/collect_progressive_impl.rs
+++ b/src/commands/list/collect_progressive_impl.rs
@@ -41,6 +41,10 @@ pub struct CollectOptions {
/// - Task spawning (in `collect_worktree_progressive`/`collect_branch_progressive`)
/// - Column visibility (layout filters columns via `ColumnSpec::requires_task`)
pub skip_tasks: std::collections::HashSet<super::collect::TaskKind>,
+
+ /// URL template from project config (e.g., "http://localhost:{{ branch | hash_port }}").
+ /// Expanded per-item in task spawning (post-skeleton) to minimize time-to-skeleton.
+ pub url_template: Option<String>,
}
/// Context for task computation. Cloned and moved into spawned threads.
@@ -58,6 +62,9 @@ pub struct TaskContext {
/// May be upstream (e.g., "origin/main") if it's ahead of local, catching remotely-merged branches.
pub target: Option<String>,
pub item_idx: usize,
+ /// Expanded URL for this item (from project config template).
+ /// UrlStatusTask uses this to check if the port is listening.
+ pub item_url: Option<String>,
}
impl TaskContext {
@@ -185,6 +192,10 @@ impl TaskSpawner {
if !skip.contains(&TaskKind::WouldMergeAdd) {
self.spawn::<WouldMergeAddTask>(scope, ctx);
}
+ // URL status only runs if this item has a URL
+ if !skip.contains(&TaskKind::UrlStatus) && ctx.item_url.is_some() {
+ self.spawn::<UrlStatusTask>(scope, ctx);
+ }
}
}
@@ -540,6 +551,57 @@ impl Task for CiStatusTask {
}
}
+/// Task 13: URL health check (port availability).
+///
+/// The URL itself is sent immediately after template expansion (in spawning code)
+/// so it appears in normal styling right away. This task only checks if the port
+/// is listening, and if not, the URL dims.
+pub struct UrlStatusTask;
+
+impl Task for UrlStatusTask {
+ const KIND: TaskKind = TaskKind::UrlStatus;
+
+ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
+ use std::net::{SocketAddr, TcpStream};
+ use std::time::Duration;
+
+ // URL already sent in spawning code; this task only checks port availability
+ let Some(ref url) = ctx.item_url else {
+ return Ok(TaskResult::UrlStatus {
+ item_idx: ctx.item_idx,
+ url: None,
+ active: None,
+ });
+ };
+
+ // Parse port from URL and check if it's listening
+ let active = parse_port_from_url(url).map(|port| {
+ // Quick TCP connect check with 50ms timeout
+ let addr = SocketAddr::from(([127, 0, 0, 1], port));
+ TcpStream::connect_timeout(&addr, Duration::from_millis(50)).is_ok()
+ });
+
+ // Return only active status (url=None to avoid overwriting the already-sent URL)
+ Ok(TaskResult::UrlStatus {
+ item_idx: ctx.item_idx,
+ url: None,
+ active,
+ })
+ }
+}
+
+/// Parse port number from a URL string (e.g., "http://localhost:12345" -> 12345)
+fn parse_port_from_url(url: &str) -> Option<u16> {
+ // Strip scheme
+ let url = url
+ .strip_prefix("http://")
+ .or_else(|| url.strip_prefix("https://"))?;
+ // Extract host:port (before path, query, or fragment)
+ let host_port = url.split(&['/', '?', '#'][..]).next()?;
+ let (_host, port_str) = host_port.rsplit_once(':')?;
+ port_str.parse().ok()
+}
+
// ============================================================================
// Collection Entry Points
// ============================================================================
@@ -561,6 +623,25 @@ pub fn collect_worktree_progressive(
tx: Sender<Result<TaskResult, TaskError>>,
expected_results: &Arc<ExpectedResults>,
) {
+ // Expand URL template for this item (deferred from pre-skeleton)
+ let item_url = options.url_template.as_ref().and_then(|template| {
+ wt.branch.as_ref().and_then(|branch| {
+ let mut vars = std::collections::HashMap::new();
+ vars.insert("branch", branch.as_str());
+ worktrunk::config::expand_template(template, &vars, false).ok()
+ })
+ });
+
+ // Send URL immediately (before health check) so it appears in normal styling right away.
+ // The health check task will later send url_active to dim if inactive.
+ if let Some(ref url) = item_url {
+ let _ = tx.send(Ok(TaskResult::UrlStatus {
+ item_idx,
+ url: Some(url.clone()),
+ active: None,
+ }));
+ }
+
let ctx = TaskContext {
repo_path: wt.path.clone(),
commit_sha: wt.head.clone(),
@@ -568,6 +649,7 @@ pub fn collect_worktree_progressive(
default_branch: Some(default_branch.to_string()),
target: Some(target.to_string()),
item_idx,
+ item_url,
};
let spawner = TaskSpawner::new(tx, expected_results.clone());
@@ -601,6 +683,23 @@ pub fn collect_branch_progressive(
tx: Sender<Result<TaskResult, TaskError>>,
expected_results: &Arc<ExpectedResults>,
) {
+ // Expand URL template for this item (deferred from pre-skeleton)
+ let item_url = options.url_template.as_ref().and_then(|template| {
+ let mut vars = std::collections::HashMap::new();
+ vars.insert("branch", branch_name);
+ worktrunk::config::expand_template(template, &vars, false).ok()
+ });
+
+ // Send URL immediately (before health check) so it appears in normal styling right away.
+ // The health check task will later send url_active to dim if inactive.
+ if let Some(ref url) = item_url {
+ let _ = tx.send(Ok(TaskResult::UrlStatus {
+ item_idx,
+ url: Some(url.clone()),
+ active: None,
+ }));
+ }
+
let ctx = TaskContext {
repo_path: repo_path.to_path_buf(),
commit_sha: commit_sha.to_string(),
@@ -608,6 +707,7 @@ pub fn collect_branch_progressive(
default_branch: Some(default_branch.to_string()),
target: Some(target.to_string()),
item_idx,
+ item_url,
};
let spawner = TaskSpawner::new(tx, expected_results.clone());
@@ -805,4 +905,37 @@ mod tests {
"should show modified symbol for worktree modification"
);
}
+
+ #[test]
+ fn test_parse_port_from_url_basic() {
+ assert_eq!(parse_port_from_url("http://localhost:12345"), Some(12345));
+ assert_eq!(parse_port_from_url("https://localhost:8080"), Some(8080));
+ }
+
+ #[test]
+ fn test_parse_port_from_url_with_path() {
+ assert_eq!(
+ parse_port_from_url("http://localhost:12345/path/to/page"),
+ Some(12345)
+ );
+ assert_eq!(parse_port_from_url("http://localhost:3000/"), Some(3000));
+ }
+
+ #[test]
+ fn test_parse_port_from_url_no_port() {
+ assert_eq!(parse_port_from_url("http://localhost"), None);
+ assert_eq!(parse_port_from_url("http://localhost/path"), None);
+ }
+
+ #[test]
+ fn test_parse_port_from_url_no_scheme() {
+ // Without http:// or https:// prefix, returns None
+ assert_eq!(parse_port_from_url("localhost:8080"), None);
+ }
+
+ #[test]
+ fn test_parse_port_from_url_edge_cases() {
+ assert_eq!(parse_port_from_url("http://127.0.0.1:9000"), Some(9000));
+ assert_eq!(parse_port_from_url("http://0.0.0.0:5000"), Some(5000));
+ }
}
diff --git a/src/commands/list/columns.rs b/src/commands/list/columns.rs
index 66eea22fd..9bea9f4d1 100644
--- a/src/commands/list/columns.rs
+++ b/src/commands/list/columns.rs
@@ -11,9 +11,10 @@ pub enum ColumnKind {
BranchDiff,
Path,
Upstream,
- Time,
+ Url, // Dev server URL from project config template
CiStatus,
Commit,
+ Time,
Message,
}
@@ -90,21 +91,34 @@ pub const COLUMN_SPECS: &[ColumnSpec] = &[
None,
7,
),
+ ColumnSpec::new(
+ ColumnKind::Url,
+ super::layout::HEADER_URL,
+ 8,
+ Some(TaskKind::UrlStatus),
+ 8,
+ ),
ColumnSpec::new(
ColumnKind::CiStatus,
super::layout::HEADER_CI,
- 8,
+ 9,
Some(TaskKind::CiStatus),
- 8,
+ 9,
+ ),
+ ColumnSpec::new(
+ ColumnKind::Commit,
+ super::layout::HEADER_COMMIT,
+ 10,
+ None,
+ 10,
),
- ColumnSpec::new(ColumnKind::Commit, super::layout::HEADER_COMMIT, 9, None, 9),
- ColumnSpec::new(ColumnKind::Time, super::layout::HEADER_AGE, 10, None, 10),
+ ColumnSpec::new(ColumnKind::Time, super::layout::HEADER_AGE, 11, None, 11),
ColumnSpec::new(
ColumnKind::Message,
super::layout::HEADER_MESSAGE,
- 11,
+ 12,
None,
- 11,
+ 12,
),
];
@@ -125,6 +139,7 @@ mod tests {
ColumnKind::BranchDiff,
ColumnKind::Path,
ColumnKind::Upstream,
+ ColumnKind::Url,
ColumnKind::CiStatus,
ColumnKind::Commit,
ColumnKind::Time,
@@ -149,6 +164,12 @@ mod tests {
.unwrap();
assert_eq!(branch_diff.requires_task, Some(TaskKind::BranchDiff));
+ let url = COLUMN_SPECS
+ .iter()
+ .find(|c| c.kind == ColumnKind::Url)
+ .unwrap();
+ assert_eq!(url.requires_task, Some(TaskKind::UrlStatus));
+
let ci_status = COLUMN_SPECS
.iter()
.find(|c| c.kind == ColumnKind::CiStatus)
@@ -157,7 +178,10 @@ mod tests {
// All other columns should not require a background task to render
for spec in COLUMN_SPECS {
- if spec.kind != ColumnKind::BranchDiff && spec.kind != ColumnKind::CiStatus {
+ if spec.kind != ColumnKind::BranchDiff
+ && spec.kind != ColumnKind::Url
+ && spec.kind != ColumnKind::CiStatus
+ {
assert!(
spec.requires_task.is_none(),
"{:?} unexpectedly requires a task",
diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rs
index 464b82162..ce31fe3ec 100644
--- a/src/commands/list/json_output.rs
+++ b/src/commands/list/json_output.rs
@@ -82,6 +82,14 @@ pub struct JsonItem {
#[serde(skip_serializing_if = "Option::is_none")]
pub ci: Option<JsonCi>,
+ /// Dev server URL from project config template
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub url: Option<String>,
+
+ /// Whether the dev server URL's port is listening
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub url_active: Option<bool>,
+
/// Pre-formatted statusline for statusline tools (tmux, starship)
#[serde(skip_serializing_if = "Option::is_none")]
pub statusline: Option<String>,
@@ -342,6 +350,8 @@ impl JsonItem {
is_current,
is_previous,
ci,
+ url: item.url.clone(),
+ url_active: item.url_active,
statusline,
symbols,
}
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rs
index 4b84d805a..0df9070d5 100644
--- a/src/commands/list/layout.rs
+++ b/src/commands/list/layout.rs
@@ -196,6 +196,7 @@ pub const HEADER_AHEAD_BEHIND: &str = "main↕";
pub const HEADER_BRANCH_DIFF: &str = "main…±";
pub const HEADER_PATH: &str = "Path";
pub const HEADER_UPSTREAM: &str = "Remote⇅";
+pub const HEADER_URL: &str = "URL";
pub const HEADER_AGE: &str = "Age";
pub const HEADER_CI: &str = "CI";
pub const HEADER_COMMIT: &str = "Commit";
@@ -259,6 +260,7 @@ pub struct ColumnWidths {
pub branch: usize,
pub status: usize, // Includes both git status symbols and user-defined status
pub time: usize,
+ pub url: usize,
pub ci_status: usize,
pub message: usize,
pub ahead_behind: DiffWidths,
@@ -275,6 +277,7 @@ pub struct ColumnDataFlags {
pub ahead_behind: bool,
pub branch_diff: bool,
pub upstream: bool,
+ pub url: bool,
pub ci_status: bool,
pub path: bool, // True if any worktree has path_mismatch (path doesn't match template)
}
@@ -332,6 +335,7 @@ impl ColumnKind {
ColumnKind::BranchDiff => flags.branch_diff,
ColumnKind::Path => flags.path,
ColumnKind::Upstream => flags.upstream,
+ ColumnKind::Url => flags.url,
ColumnKind::Time => true,
ColumnKind::CiStatus => flags.ci_status,
ColumnKind::Commit => true,
@@ -351,6 +355,7 @@ impl ColumnKind {
ColumnKind::Status => ColumnIdeal::text(widths.status),
ColumnKind::Path => ColumnIdeal::text(max_path_width),
ColumnKind::Time => ColumnIdeal::text(widths.time),
+ ColumnKind::Url => ColumnIdeal::text(widths.url),
ColumnKind::CiStatus => ColumnIdeal::text(widths.ci_status),
ColumnKind::Commit => ColumnIdeal::text(commit_width),
ColumnKind::Message => None,
@@ -447,6 +452,33 @@ struct PendingColumn<'a> {
format: ColumnFormat,
}
+/// Estimate URL column width by expanding the template with a sample branch.
+///
+/// Uses the longest branch name to get an accurate width estimate for the URL column.
+/// Falls back to 22 chars ("http://localhost:12345") if expansion fails.
+fn estimate_url_width(url_template: Option<&str>, longest_branch: Option<&str>) -> usize {
+ let Some(template) = url_template else {
+ return 0;
+ };
+
+ // Try to expand the template with the longest branch name
+ if let Some(branch) = longest_branch {
+ let mut vars = std::collections::HashMap::new();
+ vars.insert("branch", branch);
+ if let Ok(expanded) = worktrunk::config::expand_template(template, &vars, false) {
+ return expanded.width();
+ }
+ }
+
+ // Fallback: estimate based on template structure
+ // {{ branch | hash_port }} becomes a 5-digit port (10000-19999)
+ // {{ branch }} becomes the branch name (unknown length, use 10 as average)
+ template
+ .replace("{{ branch | hash_port }}", "12345")
+ .replace("{{ branch }}", "feature-xx")
+ .len()
+}
+
/// Build pre-allocated column width estimates.
///
/// Uses generous fixed allocations for expensive-to-compute columns (status, diffs, time, CI)
@@ -456,6 +488,7 @@ fn build_estimated_widths(
max_branch: usize,
skip_tasks: &HashSet<TaskKind>,
has_path_mismatch: bool,
+ url_width: usize,
) -> LayoutMetadata {
// Fixed widths for slow columns (require expensive git operations)
// Values exceeding these widths use compact notation (K suffix)
@@ -483,14 +516,24 @@ fn build_estimated_widths(
ahead_behind: true,
branch_diff: !skip_tasks.contains(&TaskKind::BranchDiff),
upstream: true,
+ url: !skip_tasks.contains(&TaskKind::UrlStatus),
ci_status: !skip_tasks.contains(&TaskKind::CiStatus),
path: has_path_mismatch,
};
+ // URL width estimated from template + longest branch (or fallback)
+ // When url_width is 0 (no template), don't allocate any space for URL column
+ let url_estimate = if url_width > 0 {
+ fit_header(HEADER_URL, url_width)
+ } else {
+ 0
+ };
+
let widths = ColumnWidths {
branch: max_branch,
status: status_fixed,
time: age_estimate,
+ url: url_estimate,
ci_status: ci_estimate,
message: 50, // Will be flexible during allocation
// Commit counts (Arrows): compact notation, 2 digits covers up to 99
@@ -720,12 +763,20 @@ fn allocate_columns_with_priority(
/// - Age: 4 chars ("11mo" short format)
/// - CI: 1 char (indicator symbol)
/// - Message: flexible (20-100 chars)
+/// - URL: estimated from template + longest branch
pub fn calculate_layout_from_basics(
items: &[super::model::ListItem],
skip_tasks: &HashSet<TaskKind>,
main_worktree_path: &Path,
+ url_template: Option<&str>,
) -> LayoutConfig {
- calculate_layout_with_width(items, skip_tasks, get_safe_list_width(), main_worktree_path)
+ calculate_layout_with_width(
+ items,
+ skip_tasks,
+ get_safe_list_width(),
+ main_worktree_path,
+ url_template,
+ )
}
/// Calculate layout with explicit width (for contexts like skim where available width differs)
@@ -734,16 +785,16 @@ pub fn calculate_layout_with_width(
skip_tasks: &HashSet<TaskKind>,
terminal_width: usize,
main_worktree_path: &Path,
+ url_template: Option<&str>,
) -> LayoutConfig {
// Calculate actual widths for things we know
// Include branch names from both worktrees and standalone branches
- let max_branch = items
+ let longest_branch = items
.iter()
.filter_map(|item| item.branch.as_deref())
- .map(|b| b.width())
- .max()
- .unwrap_or(0);
+ .max_by_key(|b| b.width());
+ let max_branch = longest_branch.map(|b| b.width()).unwrap_or(0);
let max_branch = fit_header(HEADER_BRANCH, max_branch);
let path_data_width = items
@@ -764,8 +815,11 @@ pub fn calculate_layout_with_width(
.filter_map(|item| item.worktree_data())
.any(|data| data.path_mismatch);
+ // Estimate URL width from template + longest branch
+ let url_width = estimate_url_width(url_template, longest_branch);
+
// Build pre-allocated width estimates (same as buffered mode)
- let metadata = build_estimated_widths(max_branch, skip_tasks, has_path_mismatch);
+ let metadata = build_estimated_widths(max_branch, skip_tasks, has_path_mismatch, url_width);
let commit_width = fit_header(HEADER_COMMIT, COMMIT_HASH_WIDTH);
@@ -833,6 +887,7 @@ mod tests {
ahead_behind: true,
branch_diff: true,
upstream: true,
+ url: true,
ci_status: true,
path: true,
};
@@ -842,6 +897,7 @@ mod tests {
ahead_behind: false,
branch_diff: false,
upstream: false,
+ url: false,
ci_status: false,
path: false,
};
@@ -864,6 +920,8 @@ mod tests {
assert!(!ColumnKind::BranchDiff.has_data(&all_false));
assert!(ColumnKind::Upstream.has_data(&all_true));
assert!(!ColumnKind::Upstream.has_data(&all_false));
+ assert!(ColumnKind::Url.has_data(&all_true));
+ assert!(!ColumnKind::Url.has_data(&all_false));
assert!(ColumnKind::CiStatus.has_data(&all_true));
assert!(!ColumnKind::CiStatus.has_data(&all_false));
assert!(ColumnKind::Path.has_data(&all_true));
@@ -936,6 +994,7 @@ mod tests {
branch: 15,
status: 8,
time: 4,
+ url: 0,
ci_status: 2,
message: 50,
ahead_behind: DiffWidths {
@@ -999,7 +1058,8 @@ mod tests {
// Test that build_estimated_widths() returns correct pre-allocated estimates
// Empty skip set means all tasks are computed (equivalent to --full)
// has_path_mismatch=true to test the path flag is passed through
- let metadata = build_estimated_widths(20, &HashSet::new(), true);
+ // url_width=0 since we're not testing URL column here
+ let metadata = build_estimated_widths(20, &HashSet::new(), true, 0);
let widths = metadata.widths;
// Line diffs (Signs variant: +/-) allocate 3 digits for 100-999 range
@@ -1091,6 +1151,8 @@ mod tests {
is_ancestor: None,
upstream: Some(UpstreamStatus::from_parts(Some("origin".to_string()), 4, 2)),
pr_status: None,
+ url: None,
+ url_active: None,
status_symbols: Some(StatusSymbols::default()),
display: DisplayFields::default(),
kind: ItemKind::Worktree(Box::new(WorktreeData {
@@ -1114,7 +1176,7 @@ mod tests {
.into_iter()
.collect();
let main_worktree_path = PathBuf::from("/test");
- let layout = calculate_layout_from_basics(&items, &skip_tasks, &main_worktree_path);
+ let layout = calculate_layout_from_basics(&items, &skip_tasks, &main_worktree_path, None);
assert!(
!layout.columns.is_empty(),
@@ -1187,6 +1249,8 @@ mod tests {
is_ancestor: None,
upstream: Some(UpstreamStatus::default()),
pr_status: None,
+ url: None,
+ url_active: None,
status_symbols: Some(StatusSymbols::default()),
display: DisplayFields::default(),
kind: ItemKind::Worktree(Box::new(WorktreeData {
@@ -1210,7 +1274,7 @@ mod tests {
.into_iter()
.collect();
let main_worktree_path = PathBuf::from("/home/user/project");
- let layout = calculate_layout_from_basics(&items, &skip_tasks, &main_worktree_path);
+ let layout = calculate_layout_from_basics(&items, &skip_tasks, &main_worktree_path, None);
assert!(
layout
@@ -1224,4 +1288,59 @@ mod tests {
// Path visibility depends on terminal width and column priorities
// At narrow widths (80 columns default in tests), Path may not fit
}
+
+ #[test]
+ fn test_estimate_url_width_no_template() {
+ // No template returns 0
+ assert_eq!(estimate_url_width(None, Some("feature")), 0);
+ assert_eq!(estimate_url_width(None, None), 0);
+ }
+
+ #[test]
+ fn test_estimate_url_width_with_hash_port() {
+ let template = "http://localhost:{{ branch | hash_port }}";
+
+ // With a branch name, expands template and measures
+ let width = estimate_url_width(Some(template), Some("feature"));
+ // "http://localhost:" (17) + 5-digit port = 22
+ assert_eq!(width, 22);
+
+ // Longer branch doesn't affect hash_port width (always 5 digits)
+ let width = estimate_url_width(Some(template), Some("very-long-feature-branch-name"));
+ assert_eq!(width, 22);
+ }
+
+ #[test]
+ fn test_estimate_url_width_with_branch_variable() {
+ let template = "http://localhost:8080/{{ branch }}";
+
+ // Width includes the branch name
+ let width = estimate_url_width(Some(template), Some("feature"));
+ // "http://localhost:8080/" (22) + "feature" (7) = 29
+ assert_eq!(width, 29);
+
+ // Longer branch increases width
+ let width = estimate_url_width(Some(template), Some("long-feature-branch"));
+ // "http://localhost:8080/" (22) + "long-feature-branch" (19) = 41
+ assert_eq!(width, 41);
+ }
+
+ #[test]
+ fn test_estimate_url_width_fallback() {
+ let template = "http://localhost:{{ branch | hash_port }}";
+
+ // No branch name triggers fallback estimation
+ let width = estimate_url_width(Some(template), None);
+ // Fallback replaces {{ branch | hash_port }} with "12345"
+ // "http://localhost:12345" = 22
+ assert_eq!(width, 22);
+ }
+
+ #[test]
+ fn test_estimate_url_width_static_template() {
+ // Template with no variables
+ let template = "http://localhost:3000";
+ let width = estimate_url_width(Some(template), Some("feature"));
+ assert_eq!(width, 21);
+ }
}
diff --git a/src/commands/list/model.rs b/src/commands/list/model.rs
index 38d31fdaa..13e12572c 100644
--- a/src/commands/list/model.rs
+++ b/src/commands/list/model.rs
@@ -234,6 +234,14 @@ pub struct ListItem {
/// CI/PR status: None = not loaded, Some(None) = no CI, Some(Some(status)) = has CI
pub pr_status: Option<Option<PrStatus>>,
+
+ /// Dev server URL computed from project config template
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub url: Option<String>,
+ /// Whether the URL's port is actively listening
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub url_active: Option<bool>,
+
/// Git status symbols - None until all dependencies are ready.
/// Note: This field is not serialized directly. JSON output converts to JsonItem first.
#[serde(skip)]
@@ -271,6 +279,8 @@ impl ListItem {
is_ancestor: None,
upstream: None,
pr_status: None,
+ url: None,
+ url_active: None,
status_symbols: None,
display: DisplayFields::default(),
kind: ItemKind::Branch,
diff --git a/src/commands/list/render.rs b/src/commands/list/render.rs
index f5ac75d44..d1c4d4590 100644
--- a/src/commands/list/render.rs
+++ b/src/commands/list/render.rs
@@ -645,6 +645,26 @@ impl ColumnLayout {
cell
}
+ ColumnKind::Url => {
+ // URL column: shows dev server URL from project config template
+ // - dim if not available/active
+ // - normal if available and active
+ match (&ctx.item.url, ctx.item.url_active) {
+ (None, _) => StyledLine::new(), // No URL configured
+ (Some(url), Some(true)) => {
+ // Active: normal styling
+ let mut cell = StyledLine::new();
+ cell.push_raw(url.clone());
+ cell.truncate_to_width(self.width)
+ }
+ (Some(url), _) => {
+ // Not active or unknown: dim styling
+ let mut cell = StyledLine::new();
+ cell.push_styled(url.clone(), Style::new().dimmed());
+ cell.truncate_to_width(self.width)
+ }
+ }
+ }
ColumnKind::CiStatus => {
// Check display field first for pending indicators during progressive rendering
// (works for both worktrees and branches)
diff --git a/src/commands/select.rs b/src/commands/select.rs
index cd753a6da..8c67d583e 100644
--- a/src/commands/select.rs
+++ b/src/commands/select.rs
@@ -847,6 +847,7 @@ pub fn handle_select() -> anyhow::Result<()> {
&skip_tasks,
skim_list_width,
&list_data.main_worktree_path,
+ None, // URL column not shown in select
);
// Render header using layout system (need both plain and styled text for skim)
diff --git a/src/config/mod.rs b/src/config/mod.rs
index ab1e88d81..f1a381533 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -25,7 +25,9 @@ mod user;
// Re-export public types
pub use commands::{Command, CommandConfig, CommandPhase};
pub use expansion::{expand_template, sanitize_branch_name};
-pub use project::{ProjectConfig, find_unknown_keys as find_unknown_project_keys};
+pub use project::{
+ ProjectConfig, ProjectListConfig, find_unknown_keys as find_unknown_project_keys,
+};
pub use user::{
CommitGenerationConfig, StageMode, UserProjectConfig, WorktrunkConfig,
find_unknown_keys as find_unknown_user_keys, get_config_path, set_config_path,
diff --git a/src/config/project.rs b/src/config/project.rs
index ace25f7e7..55cc539c4 100644
--- a/src/config/project.rs
+++ b/src/config/project.rs
@@ -7,6 +7,38 @@ use serde::{Deserialize, Serialize};
use super::commands::CommandConfig;
+/// Project-level configuration for `wt list` output.
+///
+/// This is distinct from user-level `ListConfig` which controls CLI defaults.
+/// Project-level config is for project-specific features like dev server URLs.
+///
+/// # Example
+///
+/// ```toml
+/// [list]
+/// url = "http://localhost:{{ branch | hash_port }}"
+/// ```
+#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
+pub struct ProjectListConfig {
+ /// URL template for dev server links shown in `wt list`.
+ ///
+ /// Available variable: `{{ branch }}` (the branch name).
+ /// Available filters: `{{ branch | hash_port }}` (deterministic port 10000-19999),
+ /// `{{ branch | sanitize }}` (filesystem-safe name).
+ ///
+ /// The URL is displayed with health-check styling: dim if the port is not
+ /// listening, normal if it is.
+ #[serde(default)]
+ pub url: Option<String>,
+}
+
+impl ProjectListConfig {
+ /// Returns true if any list configuration is set.
+ pub fn is_configured(&self) -> bool {
+ self.url.is_some()
+ }
+}
+
/// Project-specific configuration with hooks.
///
/// This config is stored at `<repo>/.config/wt.toml` within the repository and
@@ -91,6 +123,10 @@ pub struct ProjectConfig {
#[serde(default, rename = "pre-remove")]
pub pre_remove: Option<CommandConfig>,
+ /// Configuration for `wt list` output
+ #[serde(default)]
+ pub list: Option<ProjectListConfig>,
+
/// Captures unknown fields for validation warnings
#[serde(flatten, default, skip_serializing)]
unknown: std::collections::HashMap<String, toml::Value>,
@@ -147,6 +183,7 @@ mod tests {
assert!(config.pre_merge.is_none());
assert!(config.post_merge.is_none());
assert!(config.pre_remove.is_none());
+ assert!(config.list.is_none());
}
// ============================================================================
@@ -228,6 +265,45 @@ pre-remove = "echo bye"
assert!(config.pre_remove.is_some());
}
+ // ============================================================================
+ // ListConfig Tests
+ // ============================================================================
+
+ #[test]
+ fn test_deserialize_list_url() {
+ let contents = r#"
+[list]
+url = "http://localhost:{{ branch | hash_port }}"
+"#;
+ let config: ProjectConfig = toml::from_str(contents).unwrap();
+ assert!(config.list.is_some());
+ let list = config.list.unwrap();
+ assert_eq!(
+ list.url.as_deref(),
+ Some("http://localhost:{{ branch | hash_port }}")
+ );
+ assert!(list.is_configured());
+ }
+
+ #[test]
+ fn test_deserialize_list_empty() {
+ let contents = r#"
+[list]
+"#;
+ let config: ProjectConfig = toml::from_str(contents).unwrap();
+ assert!(config.list.is_some());
+ let list = config.list.unwrap();
+ assert!(list.url.is_none());
+ assert!(!list.is_configured());
+ }
+
+ #[test]
+ fn test_list_config_default() {
+ let config = ProjectListConfig::default();
+ assert!(config.url.is_none());
+ assert!(!config.is_configured());
+ }
+
// ============================================================================
// find_unknown_keys Tests
// ============================================================================
diff --git a/tests/integration_tests/list_config.rs b/tests/integration_tests/list_config.rs
index 8c921350e..d33fb91bc 100644
--- a/tests/integration_tests/list_config.rs
+++ b/tests/integration_tests/list_config.rs
@@ -175,3 +175,202 @@ fn test_list_no_config(repo: TestRepo, temp_home: TempDir) {
assert_cmd_snapshot!(cmd);
});
}
+
+/// Test `wt list` with project config URL template
+#[rstest]
+fn test_list_project_url_column(repo: TestRepo, temp_home: TempDir) {
+ // Create project config with URL template
+ repo.write_project_config(
+ r#"[list]
+url = "http://localhost:{{ branch | hash_port }}"
+"#,
+ );
+
+ // Create user config
+ let global_config_dir = temp_home.path().join(".config").join("worktrunk");
+ fs::create_dir_all(&global_config_dir).unwrap();
+ fs::write(
+ global_config_dir.join("config.toml"),
+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"
+"#,
+ )
+ .unwrap();
+
+ let settings = setup_snapshot_settings_with_home(&repo, &temp_home);
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.clean_cli_env(&mut cmd);
+ set_temp_home_env(&mut cmd, temp_home.path());
+ cmd.arg("list").current_dir(repo.root_path());
+
+ assert_cmd_snapshot!(cmd);
+ });
+}
+
+/// Test `wt list --format=json` includes URL fields when template configured
+#[rstest]
+fn test_list_json_url_fields(repo: TestRepo, temp_home: TempDir) {
+ // Create project config with URL template
+ repo.write_project_config(
+ r#"[list]
+url = "http://localhost:{{ branch | hash_port }}"
+"#,
+ );
+
+ // Create user config
+ let global_config_dir = temp_home.path().join(".config").join("worktrunk");
+ fs::create_dir_all(&global_config_dir).unwrap();
+ fs::write(
+ global_config_dir.join("config.toml"),
+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"
+"#,
+ )
+ .unwrap();
+
+ let mut cmd = wt_command();
+ repo.clean_cli_env(&mut cmd);
+ set_temp_home_env(&mut cmd, temp_home.path());
+ cmd.args(["list", "--format=json"])
+ .current_dir(repo.root_path());
+
+ let output = cmd.output().unwrap();
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ // Parse JSON and verify URL fields
+ let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
+ let items = json.as_array().unwrap();
+ assert!(!items.is_empty());
+
+ let first = &items[0];
+ // URL should be present and contain the hash_port result
+ assert!(first.get("url").is_some());
+ let url = first["url"].as_str().unwrap();
+ assert!(url.starts_with("http://localhost:"));
+ // Port should be 5 digits (10000-19999)
+ let port: u16 = url.split(':').next_back().unwrap().parse().unwrap();
+ assert!((10000..=19999).contains(&port));
+
+ // url_active should be present (false since no server listening)
+ assert!(first.get("url_active").is_some());
+ assert_eq!(first["url_active"].as_bool(), Some(false));
+}
+
+/// Test `wt list --format=json` has null URL fields when no template configured
+#[rstest]
+fn test_list_json_no_url_without_template(repo: TestRepo, temp_home: TempDir) {
+ // Create user config WITHOUT URL template
+ let global_config_dir = temp_home.path().join(".config").join("worktrunk");
+ fs::create_dir_all(&global_config_dir).unwrap();
+ fs::write(
+ global_config_dir.join("config.toml"),
+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"
+"#,
+ )
+ .unwrap();
+
+ let mut cmd = wt_command();
+ repo.clean_cli_env(&mut cmd);
+ set_temp_home_env(&mut cmd, temp_home.path());
+ cmd.args(["list", "--format=json"])
+ .current_dir(repo.root_path());
+
+ let output = cmd.output().unwrap();
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ // Parse JSON and verify URL fields are null
+ let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
+ let items = json.as_array().unwrap();
+ assert!(!items.is_empty());
+
+ let first = &items[0];
+ // URL should be null when no template configured
+ assert!(first["url"].is_null());
+ assert!(first["url_active"].is_null());
+}
+
+/// Test URL column with --branches flag
+#[rstest]
+fn test_list_url_with_branches_flag(repo: TestRepo, temp_home: TempDir) {
+ // Create a branch without a worktree
+ let mut cmd = std::process::Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["branch", "feature"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ // Create project config with URL template
+ repo.write_project_config(
+ r#"[list]
+url = "http://localhost:{{ branch | hash_port }}"
+"#,
+ );
+
+ // Create user config
+ let global_config_dir = temp_home.path().join(".config").join("worktrunk");
+ fs::create_dir_all(&global_config_dir).unwrap();
+ fs::write(
+ global_config_dir.join("config.toml"),
+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"
+"#,
+ )
+ .unwrap();
+
+ let mut cmd = wt_command();
+ repo.clean_cli_env(&mut cmd);
+ set_temp_home_env(&mut cmd, temp_home.path());
+ cmd.args(["list", "--branches", "--format=json"])
+ .current_dir(repo.root_path());
+
+ let output = cmd.output().unwrap();
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ // Parse JSON and verify both worktree and branch have URLs
+ let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
+ let items = json.as_array().unwrap();
+ assert_eq!(items.len(), 2); // main worktree + feature branch
+
+ // Both items should have URLs
+ for item in items {
+ let url = item["url"].as_str().unwrap();
+ assert!(url.starts_with("http://localhost:"));
+ }
+}
+
+/// Test URL with {{ branch }} variable (not hash_port)
+#[rstest]
+fn test_list_url_with_branch_variable(repo: TestRepo, temp_home: TempDir) {
+ // Create project config with {{ branch }} in URL
+ repo.write_project_config(
+ r#"[list]
+url = "http://localhost:8080/{{ branch }}"
+"#,
+ );
+
+ // Create user config
+ let global_config_dir = temp_home.path().join(".config").join("worktrunk");
+ fs::create_dir_all(&global_config_dir).unwrap();
+ fs::write(
+ global_config_dir.join("config.toml"),
+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"
+"#,
+ )
+ .unwrap();
+
+ let mut cmd = wt_command();
+ repo.clean_cli_env(&mut cmd);
+ set_temp_home_env(&mut cmd, temp_home.path());
+ cmd.args(["list", "--format=json"])
+ .current_dir(repo.root_path());
+
+ let output = cmd.output().unwrap();
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ // Parse JSON and verify URL contains branch name
+ let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
+ let items = json.as_array().unwrap();
+ let first = &items[0];
+
+ let url = first["url"].as_str().unwrap();
+ assert_eq!(url, "http://localhost:8080/main");
+}
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
index 0e903c9b5..8aacd7f7c 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -8,7 +8,7 @@ info:
env:
CLICOLOR_FORCE: "1"
COLUMNS: "150"
- GIT_CONFIG_GLOBAL: ""
+ GIT_EDITOR: ""
RUST_LOG: warn
SOURCE_DATE_EPOCH: "1735776000"
WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml
@@ -162,8 +162,7 @@ See wt hook for complete documentation.
Project config
-The project config defines lifecycle hooks — commands that run at specific points during worktree operations. This file is checked into version
-control and shared across the team.
+The project config defines lifecycle hooks and project-specific settings. This file is checked into version control and shared across the team.
Create .config/wt.toml in the repository root:
@@ -176,6 +175,16 @@ Create .config/wt.toml in the repository root:
See wt hook for complete documentation on hook types, execution order, template variables, and JSON context.
+Dev server URL
+
+The [list] section adds a URL column to wt list:
+
+ [list]
+ url = "http://localhost:{{ branch | hash_port }}"
+
+URLs are dimmed when the port isn't listening. The template supports {{ branch }} with filters hash_port (port 10000-19999) and sanitize
+(filesystem-safe).
+
Shell integration
Worktrunk needs shell integration to change directories when switching worktrees. Install with:
diff --git a/tests/snapshots/integration__integration_tests__help__help_list_long.snap b/tests/snapshots/integration__integration_tests__help__help_list_long.snap
index 2defbe467..53af7cca4 100644
--- a/tests/snapshots/integration__integration_tests__help__help_list_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_list_long.snap
@@ -8,7 +8,7 @@ info:
env:
CLICOLOR_FORCE: "1"
COLUMNS: "150"
- GIT_CONFIG_GLOBAL: ""
+ GIT_EDITOR: ""
RUST_LOG: warn
SOURCE_DATE_EPOCH: "1735776000"
WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml
@@ -85,19 +85,20 @@ Output as JSON for scripting:
Columns
- Column Shows
- ─────── ────────────────────────────────────────────────────────────────
- Branch Branch name
- Status Compact symbols (see below)
- HEAD± Uncommitted changes: +added -deleted lines
- main↕ Commits ahead/behind default branch
- main…± Line diffs since the merge-base with the default branch (--full)
- Path Worktree directory
- Remote⇅ Commits ahead/behind tracking branch
- CI Pipeline status (--full)
- Commit Short hash (8 chars)
- Age Time since last commit
- Message Last commit message (truncated)
+ Column Shows
+ ─────── ─────────────────────────────────────────────────────────────────
+ Branch Branch name
+ Status Compact symbols (see below)
+ HEAD± Uncommitted changes: +added -deleted lines
+ main↕ Commits ahead/behind default branch
+ main…± Line diffs since the merge-base with the default branch (--full)
+ Path Worktree directory
+ Remote⇅ Commits ahead/behind tracking branch
+ URL Dev server URL from project config (dimmed if port not listening)
+ CI Pipeline status (--full)
+ Commit Short hash (8 chars)
+ Age Time since last commit
+ Message Last commit message (truncated)
Note: main↕ and main…± refer to the default branch (header label stays main for compactness). main…± uses a merge-base (three-dot) diff.
@@ -188,6 +189,8 @@ Query structured data with --format=json:
is_current boolean Is the current worktree
is_previous boolean Previous worktree from wt switch
ci object CI status (see below, absent when no CI)
+ url string Dev server URL from project config (absent when not configured)
+ url_active boolean Whether the URL's port is listening (absent when not configured)
statusline string Pre-formatted status with ANSI colors
symbols string Raw status symbols without colors (e.g., "!?↓")
diff --git a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
index f5759ecbd..739d30d45 100644
--- a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
@@ -8,7 +8,7 @@ info:
env:
CLICOLOR_FORCE: "1"
COLUMNS: "80"
- GIT_CONFIG_GLOBAL: ""
+ GIT_EDITOR: ""
RUST_LOG: warn
SOURCE_DATE_EPOCH: "1735776000"
WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml
@@ -88,19 +88,20 @@ Output as JSON for scripting:
Columns
- Column Shows
- ─────── ────────────────────────────────────────────────────────────────
- Branch Branch name
- Status Compact symbols (see below)
- HEAD± Uncommitted changes: +added -deleted lines
- main↕ Commits ahead/behind default branch
- main…± Line diffs since the merge-base with the default branch (--full)
- Path Worktree directory
- Remote⇅ Commits ahead/behind tracking branch
- CI Pipeline status (--full)
- Commit Short hash (8 chars)
- Age Time since last commit
- Message Last commit message (truncated)
+ Column Shows
+ ─────── ─────────────────────────────────────────────────────────────────
+ Branch Branch name
+ Status Compact symbols (see below)
+ HEAD± Uncommitted changes: +added -deleted lines
+ main↕ Commits ahead/behind default branch
+ main…± Line diffs since the merge-base with the default branch (--full)
+ Path Worktree directory
+ Remote⇅ Commits ahead/behind tracking branch
+ URL Dev server URL from project config (dimmed if port not listening)
+ CI Pipeline status (--full)
+ Commit Short hash (8 chars)
+ Age Time since last commit
+ Message Last commit message (truncated)
Note: main↕ and main…± refer to the default branch (header label stays
main for compactness). main…± uses a merge-base (three-dot) diff.
@@ -197,14 +198,18 @@ when clean) |
| main | object | Relationship to the default branch (see below, absent when
is_main) |
| remote | object | Tracking branch info (see below, absent when no tracking)
- ─────────── ─────── ───────────────────────────────────────────────
- worktree object Worktree metadata (see below)
- is_main boolean Is the main worktree
- is_current boolean Is the current worktree
- is_previous boolean Previous worktree from wt switch
- ci object CI status (see below, absent when no CI)
- statusline string Pre-formatted status with ANSI colors
- symbols string Raw status symbols without colors (e.g., "!?↓")
+ ─────────── ─────── ────────────────────────────────────────
+ worktree object Worktree metadata (see below)
+ is_main boolean Is the main worktree
+ is_current boolean Is the current worktree
+ is_previous boolean Previous worktree from wt switch
+ ci object CI status (see below, absent when no CI)
+| url | string | Dev server URL from project config (absent when not
+configured) |
+| url_active | boolean | Whether the URL's port is listening (absent when not
+configured) |
+ statusline string Pre-formatted status with ANSI colors
+ symbols string Raw status symbols without colors (e.g., "!?↓")
commit object
diff --git a/tests/snapshots/integration__integration_tests__list_config__list_project_url_column.snap b/tests/snapshots/integration__integration_tests__list_config__list_project_url_column.snap
new file mode 100644
index 000000000..7c94ffd51
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list_config__list_project_url_column.snap
@@ -0,0 +1,35 @@
+---
+source: tests/integration_tests/list_config.rs
+info:
+ program: wt
+ args:
+ - list
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ 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
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+ Branch Status HEAD± main↕ Path Remote⇅ URL Commit Age Message
+@ main ? ^ . http://localhost:12107 a1e809f5 1d Initial commit
+
+○ Showing 1 worktree, 1 with changes
+
+----- stderr -----