Skip to content

feat(switch): keep the alt-r picker cursor on the removed row's slot - #3199

Merged
max-sixty merged 2 commits into
mainfrom
picker-remove-sticky-cursor
Jun 24, 2026
Merged

max-sixty merged 2 commits into
mainfrom
picker-remove-sticky-cursor

Conversation

@max-sixty

Copy link
Copy Markdown
Owner

Sticky cursor after alt-r removal in the switch picker

Removing a worktree with alt-r in the wt switch picker used to snap the cursor back to the first row every time, because skim clears item_list on every reload (skim #1695). Removing several rows in a row was jarring — the selection jumped to the top after each one. Now the cursor stays on the slot the removed row vacated: the row that slides up into its place (the "next" item), or the new last row when the removed row was last.

Why it's done this way

skim 4.8 offers no clean lever for "keep the cursor after reload":

  • handle_reload calls item_list.clear() (resets the cursor to the top) unless no_clear_if_empty is set — and that flag is the wrong tool: the matcher runs once on the just-cleared empty pool and writes an empty Replace, which re-empties the list and resets the cursor anyway. Its stale-keeping path is also gated on interactive mode, which the picker isn't.
  • select-row(n) looks promising but only inserts into the multi-select set; it never moves the cursor.
  • down(n) / first / last take a fixed integer parsed at bind-time, so the bind string can't carry the dynamic pre-removal index.

The lever that does work is Action::Custom(ActionCallback): its callback runs with &mut App, and App.item_list exposes public cursor methods. After a removal, PickerCollector::invoke injects a Custom action (through skim's event sender — the same render_tx the progressive handler already uses) that, once the reloaded rows land, repositions via jump_to_first() + scroll_by(target). Because the reload repopulates item_list asynchronously (reader → matcher → render), the action re-arms itself until the rows exist, and stops once the matcher has settled on an empty result so removing the sole match of an active query can't spin the event loop. Sleeping inside the callback isn't an option — ActionCallback::call blocks on the future, so an await would hold &mut App and starve the very render that loads the rows.

Where to look

Everything is in src/commands/picker/mod.rs:

  • sticky_reposition_target — pure index math (removed shared_items position → item_list data-row index), unit-tested.
  • reposition_cursor_action — the self-re-arming Action::Custom, gated on item_list.count() with a matcher-settled stop and a hard backstop.
  • PickerCollector::invoke — computes the target and injects the action.
  • The PickerCollector / module docstrings explain the skim mechanics.

Limitations

Under an active fuzzy query the displayed order diverges from shared_items order, so the landing row is approximate — a valid nearby row, clamped into range, rather than the exact next row. The no-query case (the common one) is exact.

Testing

Unit test covers the index math (including the removed-last-row and header-only edge cases). Behavior was verified interactively against a multi-worktree repo via tmux: middle-row removal lands on the next row, last-row removal lands on the new last row, a sequence of removals from one position keeps the cursor planted, rapid-fire removals never reset to the top, and removing the sole match of a query leaves the picker fully responsive (no spin). Full TUI behavior isn't unit-testable without a PTY, so that surface relies on the interactive checks.

This was written by Claude Code on behalf of max

max-sixty and others added 2 commits June 23, 2026 22:32
skim clears item_list on every reload (skim #1695), so removing a worktree
with alt-r snapped the cursor back to the first row each time — jarring when
removing several in a row. After a removal the cursor now stays on the slot
the removed row vacated (the next item, or the new last row).

skim exposes no "set cursor to index N" action, so PickerCollector::invoke
injects an Action::Custom that repositions via ItemList's public cursor API
(jump_to_first + scroll_by) once the reloaded rows land. It re-arms until the
async repopulation finishes and stops once the matcher settles on an empty
result, so removing the sole match of a query can't spin the event loop.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The reposition logic runs only inside skim's event loop, so unit tests can't
reach it. Two PTY tests drive the real picker: one removes the first non-current
worktree and asserts the cursor sticks to the row that slides up (so the switch
lands there, not back on the current worktree); the other removes the sole match
of a query and asserts the picker stays responsive once the matcher settles
empty. Together they exercise reposition_cursor_action's reposition, re-arm, and
give-up paths, covering the codecov/patch gap.

The sticky test reads the list to learn the picker's commit-recency row order, so
the assertion doesn't depend on which worktree sorts first.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cursor-stickiness mechanism is well-constructed: the index math in sticky_reposition_target is clean and unit-tested, and reposition_cursor_action's self-re-arm with a matcher-settled stop (plus the REPOSITION_MAX_ATTEMPTS backstop) is a sensible way to ride out skim's async repopulation without holding &mut App across an await. The two new PTY tests close the coverage gap on the parts that only run inside skim's event loop. No code issues to flag — i32::try_from(target).unwrap_or(i32::MAX) is panic-safe, the Arc<AtomicUsize> counters are correctly shared across re-arms, and the try_send best-effort degrades to a top-reset cursor rather than breaking.

One process note, not a code concern: src/commands/picker/mod.rs is on worktrunk's data-loss surface — it routes the force-removal path (deletion_mode.is_force(), force_worktree, delete_branch_if_safe, the do_removal/prepare_removal handlers). Per this repo's reviewer policy, a diff editing such a file isn't one I auto-approve; I'm leaving the merge call to you.

For what it's worth, I verified this diff doesn't touch the deletion semantics: the items.retain(|item| item.output().as_ref() != selected_output) predicate (which row is dropped) is byte-identical context — the surrounding block is just reorganized to also record removed_pos — and do_removal/prepare_removal/the force fields are untouched. The change is purely in-memory cursor positioning layered on top of the existing removal flow.

One thing worth confirming interactively (you note you already did the tmux checks): in the no-query path the reposition keys off shared_items order, and the count() > 0 branch lands as soon as any rows arrive. That's exact only if the reloaded worktree rows land in a single batch (which the sticky test relies on via "both worktree rows land in one skeleton batch"). If skim ever streamed them incrementally, the cursor could settle on a partial last row before the rest arrive — harmless (clamped, never out of range), just potentially off by a row. The --prs / fuzzy-query approximation you already document under Limitations.

@max-sixty
max-sixty merged commit 599c4ba into main Jun 24, 2026
36 checks passed
@max-sixty
max-sixty deleted the picker-remove-sticky-cursor branch June 24, 2026 17:25
max-sixty added a commit that referenced this pull request Jun 25, 2026
… removed (#3211)

## Summary

In the `wt switch` interactive picker, pressing `alt-r` dropped a row
optimistically and then removed the worktree on a background thread.
When the removal didn't actually remove the target — a worktree that
became dirty, or a branch-only row whose unmerged branch `SafeDelete`
keeps — the worktree/branch was preserved by design (data safety holds),
but the displayed row had already vanished. The list showed a removal
that never happened, and the row that did come back flickered off and
on.

This closes the producer→consumer loop so a row's presence always
matches reality, and decides as much as possible **up front** so the
common cases never flicker.

## Approach

The key observation: `prepare_worktree_removal` — which `invoke` already
calls synchronously on skim's event loop — *already* computes whether a
removal will succeed (`ensure_clean` for worktrees, `integration_reason`
for branch-only rows, from the same `Repository::integration_reason`
that `delete_branch_if_safe` later consults). So the outcome is knowable
before the row is dropped; we don't need to run the removal to find out.

Two complementary mechanisms, duals of each other:

- **`removal_will_remove_target`** (predict, *before* dropping). A
worktree always removes (it passed `ensure_clean`); a branch-only row
removes only when `delete_branch_if_safe` would (integrated, or force,
never `Keep`). `invoke` drops the row and removes in the background only
when removal is predicted. An **unmerged branch-only row** — the one
case that reliably flickered under the optimistic drop — now stays put
and surfaces the canonical `Branch X retained; has unmerged changes` +
`To delete the unmerged branch, run wt remove -D X` info/hint that `wt
remove` itself prints, decided synchronously with no background work.

- **`removal_target_still_present`** + **`restore_failed_removal`**
(observe, *after*). The data-safety backstop for failures the up-front
prediction can't see, because they're genuinely asynchronous: a
clean-check race against `ensure_clean`, a failing approved `pre-remove`
hook, or a branch that raced integrated→unmerged. These are decided from
**primary evidence** — does the worktree directory or branch ref still
exist after `do_removal`? — not from the removal's `Result`, which is
the wrong signal in both directions (a `RemovedWorktree` removal can
return `Err` after the worktree is already trashed when a
`post-remove`/`post-switch` hook fails to render/spawn during the
announcer flush; a refusal returns `Ok` while keeping the target). When
the target survives, the row is re-inserted at its slot, a `Kept X —
could not remove it` warning is stashed, and the picker reloads so the
cursor lands back on the row.

The happy path (successful removal) and the sticky-cursor reposition
from #3199 are untouched.

### Behavior matrix

| `alt-r` on… | target after | row |
|------|----------------------|-----|
| clean worktree (common case) | gone | drops, no flicker |
| worktree, dirty at `alt-r` | present | not dropped (caught by
`prepare`, no flicker) |
| **unmerged branch-only row** | **present** | **stays put, no flicker**
— surfaces `retained; unmerged` |
| branch-only, integrated | gone | drops, no flicker |
| worktree clean→dirty race / failing approved `pre-remove` | present |
dropped → restored (rare async backstop) |
| branch raced integrated→unmerged | present | dropped → restored (rare
async backstop) |

The only residual flicker is the genuinely-rare async races in the last
two rows, which can't be known up front and where restoring is the
data-safety backstop.

## Key files

Most changes are in `src/commands/picker/mod.rs`:
`removal_will_remove_target` (the up-front predictor) and
`removal_target_still_present` (the after-the-fact observer), with
`invoke` dispatching to `drop_and_remove_in_background` or
`keep_unremovable_row`, plus `restore_failed_removal` /
`removal_failure_subject` for the backstop path and a single
`send_reposition` helper for cursor moves. The canonical "retained;
unmerged" message is shared with `wt remove` via
`retained_unmerged_branch_messages` in `src/output/handlers.rs`, so the
two emit paths can't drift.

## Testing

`cargo run -- hook pre-merge --yes` passes (4191 tests, clippy, fmt).
New/updated coverage:

- `test_removal_will_remove_target` — the predictor's matrix (worktree,
integrated/unmerged/force/keep branch-only).
- `test_invoke_keeps_unmerged_branch_only_row` — synchronous keep
through `invoke`: row never dropped, canonical hint stashed, branch
preserved.
- `test_invoke_restores_row_when_removal_fails` — the backstop,
end-to-end through `invoke` via an approved-yet-failing `pre-remove`
hook.
- `test_switch_picker_alt_r_keeps_unmerged_branch_row` — a real-PTY
integration test that filters to an unmerged branch, presses `alt-r`,
and asserts the row survives (the inverse of the existing "removed row
empties the list" test). #3199's sticky-cursor PTY test still passes.

> _This was written by Claude Code on behalf of max_

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
social4hyq pushed a commit to social4hyq/homebrew-core that referenced this pull request Sep 20, 2026
worktrunk 0.62.0

Created-by: HarmonybrewBot
Commit-by: HarmonybrewBot
Merged-by: HarmonybrewBot
Description: Created by `brew bump`

---

Created with `brew bump-formula-pr`.<details>
  <summary>release notes</summary>
  <pre>## Release Notes

### Improved

- **Browse open PRs/MRs in the `wt switch` picker, with live CI**: The picker now streams a live CI/review-status column per row — priming from the local cache, then fetching live (it previously showed only cached numbers with no network). A new `--prs` flag adds the repository's open PRs (GitHub) / MRs (GitLab) as rows alongside your worktrees, each with `pr` / `comments` / `log` preview tabs loaded from the forge in the background; selecting one fetches its branch and switches. Rows whose branch is already shown aren't duplicated, so `--prs` differs from plain `wt switch` only by the extra rows. [Docs](https://worktrunk.dev/switch/) ([#3128](max-sixty/worktrunk#3128), [#3169](max-sixty/worktrunk#3169), [#3189](max-sixty/worktrunk#3189), [#3252](max-sixty/worktrunk#3252))

- **`main…±` diff column shows by default in `wt list`**: The `main…±` column (lines changed since the merge-base with the default branch) now renders in the default `wt list` and picker, served from a persistent cache rather than a history walk. `--full` now adds only the columns that reach off-machine — CI status and LLM branch summaries — and `wt list --format=json` populates `main.diff` for every item, not just under `--full`. ([#3236](max-sixty/worktrunk#3236))

- **`[list] columns` selects and orders the columns `wt list` shows**: A new `[list] columns` user-config key (also settable via `--config-set`) takes an ordered array of column names — built-in (`branch`, `status`, `ci`, `path`, …) and `[list.custom-columns]` headers alike — and renders exactly those, in that order. Where v0.61.0's custom columns *add* columns, this *selects and reorders* the whole set; omit the key for the default layout. (`WORKTRUNK__LIST__COLUMNS` isn't supported yet and warns if set.) ([#3141](max-sixty/worktrunk#3141))

- **Picker PR preview shows full PR/MR detail**: The `pr` tab now renders the PR/MR title, markdown description, author, draft state, comment count, bold branch name, and underlined URL for any row whose branch has an open PR — not just `--prs` rows — and the `comments` tab fetches the real thread. The title and description ride the CI fetch the picker already makes; the comment thread is fetched lazily in the background, once per row. ([#3167](max-sixty/worktrunk#3167), [#3197](max-sixty/worktrunk#3197), [#3223](max-sixty/worktrunk#3223), [#3195](max-sixty/worktrunk#3195), [#3231](max-sixty/worktrunk#3231))

- **Interactive picker runs on Windows**: The `wt switch` picker was Unix-only because its preview-tab keys shelled out through a per-process state file `cmd.exe` lacks; tab state moved to an in-memory atomic with native skim callbacks, lifting the platform gate. ([#3217](max-sixty/worktrunk#3217))

- **Picker keyboard shortcuts**: `Alt-y` copies the selected branch name, `Alt-o` opens the row's PR/MR in the browser, and `Alt-r` refreshes the list (picking up worktrees created or removed elsewhere). (Breaking: in the picker, remove moved from `Alt-r` to `Alt-x`) ([#3233](max-sixty/worktrunk#3233))

- **Picker uses the full terminal**: List height scales with the terminal (a roughly even split with the preview, minimum 3 rows) instead of a fixed 12-row cap, the table lays out at full width so toggling the preview off with `Alt-p` reveals the freed columns with no reflow, and a scrollbar appears when the list overflows. ([#3205](max-sixty/worktrunk#3205), [#3214](max-sixty/worktrunk#3214), [#3198](max-sixty/worktrunk#3198))

- **Picker filters on more of each row**: Typing a gutter sigil filters by row kind (`+` for linked worktrees, `@` for the current one), the fuzzy matcher ranks on the distinguishing path segment rather than the shared parent prefix, and rows with a PR/MR also match on its number, title, and author. ([#3143](max-sixty/worktrunk#3143), [#3208](max-sixty/worktrunk#3208), [#3252](max-sixty/worktrunk#3252))

- **Picker visual polish**: The legend recolored to dim-cyan and reordered so navigation leads, and preview loading placeholders moved to the dim-hint style (`↳` transient, `○` settled, `▲` failed). ([#3237](max-sixty/worktrunk#3237), [#3253](max-sixty/worktrunk#3253))

- **"Still waiting" status for slow commit-message generation**: A configured `commit.generation` command captures stdout, so a slow or hung LLM previously showed nothing while `wt step commit`/`squash` waited. After a 2s delay worktrunk now shows a dim, in-place `○ Waiting for the commit message (Ns)` status, escalating at 10s to reveal the exact shell-escaped invocation in a gutter beneath it; the block clears on completion, mirroring `wt list`'s stall footer. ([#3178](max-sixty/worktrunk#3178))

- **"Still waiting" status extended to more slow commands**: The same waiting status now covers three more foreground commands that were silent while a captured subprocess ran — the `wt config show --full` commit-generation self-test, the `wt switch pr:`/`mr:` host lookup, and the `wt config show --full` version check. The version check no longer caps its fetch at an aggressive 5s, instead showing the status while a slow-but-working request completes (with a generous ceiling so a non-interactive run can't hang). ([#3183](max-sixty/worktrunk#3183))

- **`wt config state logs profile` performance profiler**: A new subcommand turns a `-vv` `[wt-trace]` capture (a path argument, `-` for stdin, or the default `trace.log`) into a performance profile: subprocess time by command shape, the slowest calls, parallelism and peak concurrency, redundant cache-miss re-runs, and — for `wt list`/picker captures — derived latencies and a collect timeline. `--format=json` emits the same data, and every `-vv` bug-report bundle now inlines a rendered profile. ([#3184](max-sixty/worktrunk#3184), [#3186](max-sixty/worktrunk#3186))

- **`WORKTRUNK_VERBOSE` env var**: `WORKTRUNK_VERBOSE=0|1|2` mirrors `-v`/`-vv`, combined with any flag via `max` (the env sets a floor the flag can raise). Unlike the flags it's honored on the shell-completion path, which returns before flag parsing — so a slow tab-completion can be profiled for the first time. ([#3166](max-sixty/worktrunk#3166))

- **Aliases inherit the wrapped command's completion**: An alias that forwards `{{ args }}` to a single `wt` command (`co = "wt switch {{ args }}"`) now completes that command's arguments and flags — `wt co <Tab>` completes branches like `wt switch <Tab>` — instead of a generic stub. Bare dispatchers and multi-`{{ args }}` aliases keep the stub. ([#3172](max-sixty/worktrunk#3172), thanks @yzx9)

- **`wt step copy-ignored --require-include`**: A new `--require-include` flag makes the copy a no-op unless a `.worktreeinclude` file exists in the source worktree (matching Claude Code desktop, where that file is required), reporting why it skipped as a hint in text mode and a `reason` field in `--format=json`. ([#3196](max-sixty/worktrunk#3196), thanks @yzx9)

- **`wt step tether` honors `-C`**: The global `-C <path>` flag now sets the tethered command's working directory (`wt step tether -C frontend -- npm run dev`); teardown still watches the worktree root, so the command is reaped when the worktree is removed. ([#3207](max-sixty/worktrunk#3207))

- **Statusline rate-limit pace color grades by severity**: The pace segment's color now deepens (dim → dim-yellow → yellow) with the projected throttling severity, so an early-window burst stays muted while a costly projected lockout stands out. The displayed pace number is unchanged. ([#3229](max-sixty/worktrunk#3229))

### Fixed

- **Picker `Alt-x` removal updates the row in place**: Removing a worktree no longer re-collects the whole list (a flicker that reset the cursor to the top): an unmerged worktree's row morphs into a branch-only row while the worktree is removed in the background, and a merged worktree's row drops with the cursor landing on the row that slid up. A removal that can't safely happen — the current or main worktree, or a dirty or locked one — is declined with the same diagnostic `wt remove` prints, rather than a dead keypress or a disruptive `cd` home. The post-removal cursor lands by row identity, so it stays correct even under an active filter. ([#3262](max-sixty/worktrunk#3262), [#3199](max-sixty/worktrunk#3199), [#3211](max-sixty/worktrunk#3211), [#3225](max-sixty/worktrunk#3225))

- **Picker preview refreshes when its background fetch lands**: A diff/log/PR-view fetch that completed after its triggering keystroke used to sit unshown until the next keypress; the pane now updates on its own when the fetch lands. ([#3247](max-sixty/worktrunk#3247))

- **Picker rows stay aligned while filtering**: Typing a filter no longer slides the matched row left and drops its leading sigil, and `Alt-l`/`Alt-h` no longer scroll the list off its gutter. ([#3213](max-sixty/worktrunk#3213), [#3226](max-sixty/worktrunk#3226))

- **fish completions no longer recurse to the call-stack limit**: With worktrunk's fish lazy-load wrapper installed, co

See merge request: Harmonybrew/homebrew-core!12862
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants