Compare commits

...

7 Commits

6 changed files with 330 additions and 55 deletions

View File

@@ -3,10 +3,16 @@
# Detaches the client if all panes in the window are dead afterwards. # Detaches the client if all panes in the window are dead afterwards.
agents=() agents=()
command -v claude &>/dev/null && agents+=(claude) agent_names=(
command -v opencode &>/dev/null && agents+=(opencode) claude
command -v agy &>/dev/null && agents+=(agy) pi
command -v codex &>/dev/null && agents+=(codex) opencode
codex
agy
)
for agent_name in ${agent_names[@]}; do
command -v $agent_name &>/dev/null && agents+=($agent_name)
done
if [ ${#agents[@]} -eq 0 ]; then if [ ${#agents[@]} -eq 0 ]; then
echo "No agent commands found (claude, opencode, gemini)" echo "No agent commands found (claude, opencode, gemini)"

133
agent-nav.sh Executable file
View File

@@ -0,0 +1,133 @@
#!/usr/bin/env bash
# Drive the agent popup from the windows of the session underneath it rather
# than from the agent session's own window list. Bound inside the agent session
# to <prefix>C-n and <prefix>C-p ("next"/"prev") and to <prefix>0..9 (a window
# index) -- see tmux.conf.
#
# Root windows with no agent window are stepped over when cycling and do nothing
# when named by index, so the popup and the session below it never disagree.
# Neither ever creates an agent window; only <prefix>A does. Both the client
# underneath and the popup move, so closing the popup leaves you where you went.
set -e
target=${1:-next}
us=$'\x1f'
# Fall back to plain window cycling within the agent session when there is no
# usable client underneath (popup opened before this was configured, or the
# recorded client has gone away).
fallback() {
case $target in
next) tmux next-window -t agent ;;
prev) tmux previous-window -t agent ;;
*) tmux select-window -t "agent:$target" 2>/dev/null || true ;;
esac
exit 0
}
popup_client=$(tmux display-message -p '#{@agent_popup_client}' 2>/dev/null || true)
[ -n "$popup_client" ] || fallback
# The session and window underneath the popup, as the client sees them now.
client_info=$(tmux list-clients -F "#{client_name}$us#{session_name}$us#{window_id}" \
| awk -v FS="$us" -v client="$popup_client" '$1 == client { print $2 FS $3; exit }')
[ -n "$client_info" ] || fallback
IFS=$us read -r client_session client_window <<<"$client_info"
# Every agent window, with what it is keyed to.
agent_ids=()
agent_dirs=()
agent_origins=()
while IFS=$us read -r window_id dir origin; do
[ -n "$dir" ] || continue
agent_ids+=("$window_id")
agent_dirs+=("$dir")
agent_origins+=("$origin")
done < <(tmux list-windows -t agent \
-F "#{window_id}$us#{@agent_dir}$us#{@agent_origin_window}" 2>/dev/null || true)
[ ${#agent_ids[@]} -gt 0 ] || exit 0
# The agent window serving a root window: by recorded origin first, then by the
# directory its first pane sits in. Mirrors agent-sync.sh's resolution, reversed.
agent_window_for() {
local root_window=$1 start_path=$2 current_path=$3 i
for i in "${!agent_ids[@]}"; do
if [ -n "${agent_origins[$i]}" ] && [ "${agent_origins[$i]}" = "$root_window" ]; then
printf '%s\n' "${agent_ids[$i]}"
return 0
fi
done
for i in "${!agent_ids[@]}"; do
if [ "${agent_dirs[$i]}" = "$start_path" ] || [ "${agent_dirs[$i]}" = "$current_path" ]; then
printf '%s\n' "${agent_ids[$i]}"
return 0
fi
done
return 1
}
# Move the client underneath and the popup together. The agent window is re-keyed
# to the window being moved to, so the sync hook that the select below fires
# agrees with what happened here instead of dragging the client back to wherever
# that window was last opened from.
move_to() { # move_to <root window id> <agent window id>
tmux set-window-option -t "$2" @agent_origin_window "$1"
tmux select-window -t "$1"
tmux select-window -t "$2"
exit 0
}
# The underlying session's windows, in its own order, each with its index and its
# first pane's directory. Panes are listed grouped by window in index order.
root_windows=()
root_indexes=()
root_paths=()
seen_window=""
while IFS=$us read -r window_id window_index start_path current_path; do
[ "$window_id" != "$seen_window" ] || continue
seen_window=$window_id
root_windows+=("$window_id")
root_indexes+=("$window_index")
root_paths+=("$start_path$us$current_path")
done < <(tmux list-panes -s -t "$client_session" \
-F "#{window_id}$us#{window_index}$us#{pane_start_path}$us#{pane_current_path}" \
2>/dev/null || true)
count=${#root_windows[@]}
[ "$count" -gt 0 ] || exit 0
# <prefix>0..9: the window with that index in the session underneath. Doing
# nothing when it has no agent window keeps the popup and that session in step.
if [ -n "$target" ] && [ -z "${target//[0-9]/}" ]; then
for i in "${!root_windows[@]}"; do
[ "${root_indexes[$i]}" = "$target" ] || continue
IFS=$us read -r start_path current_path <<<"${root_paths[$i]}"
target_agent=$(agent_window_for "${root_windows[$i]}" "$start_path" "$current_path") || exit 0
move_to "${root_windows[$i]}" "$target_agent"
done
exit 0
fi
# Where the client sits in that order.
current=0
for i in "${!root_windows[@]}"; do
if [ "${root_windows[$i]}" = "$client_window" ]; then
current=$i
break
fi
done
if [ "$target" = prev ]; then step=-1; else step=1; fi
# Walk in that direction for the first window with an agent window, wrapping.
# Landing back on the starting window means nothing else has one: selecting it
# again is a no-op, which is the wanted behaviour.
i=$current
for _ in $(seq 1 "$count"); do
i=$(( (i + step + count) % count ))
target_root=${root_windows[$i]}
IFS=$us read -r start_path current_path <<<"${root_paths[$i]}"
target_agent=$(agent_window_for "$target_root" "$start_path" "$current_path") || continue
move_to "$target_root" "$target_agent"
done

90
agent-sync.sh Executable file
View File

@@ -0,0 +1,90 @@
#!/usr/bin/env bash
# Move the client that opened the agent popup to the root window matching the
# agent session's current window. Installed by agent.sh as the agent session's
# session-window-changed hook, so it runs for any window change made inside the
# popup: <prefix>C-n, <prefix>C-p, select-window, choose-tree or the mouse.
#
# Set @agent_follow_session to "off" to keep the opening client in the session
# it is already on, never switching it to the session owning the match.
set -e
# Fields are joined with a unit separator, not a tab: `read` folds runs of tabs
# and spaces even when IFS names them, so an unset option in the middle would
# silently shift every field after it.
us=$'\x1f'
# Everything recorded about the agent session's current window, in one
# round-trip. Format lookups rather than show-option, so unset user options come
# back empty instead of logging "invalid option" into the tmux message log.
state=$(tmux display-message -p -t agent "#{session_attached}$us#{@agent_dir}\
$us#{@agent_origin_window}$us#{@agent_popup_client}$us#{@agent_follow_session}" \
2>/dev/null || true)
IFS=$us read -r attached agent_dir origin_window popup_client follow <<<"$state"
# Only sync while a popup is actually attached. Without this guard the
# detach-client + kill-window agent-cmd.sh performs when an agent exits would
# drag the root client to whichever window tmux picks next.
[ "${attached:-0}" -gt 0 ] || exit 0
[ -n "$agent_dir" ] || exit 0
# An empty session means the recorded client has since gone away.
client_session=""
if [ -n "$popup_client" ]; then
client_session=$(tmux list-clients -F "#{client_name}$us#{session_name}" \
| awk -v FS="$us" -v client="$popup_client" '$1 == client { print $2; exit }')
fi
target_window=""
target_session=""
# Prefer the recorded origin window, as long as it still exists.
if [ -n "$origin_window" ]; then
while IFS=$us read -r window_id session_name; do
if [ "$window_id" = "$origin_window" ] && [ "$session_name" != agent ]; then
target_window=$window_id
target_session=$session_name
break
fi
done < <(tmux list-windows -a -F "#{window_id}$us#{session_name}")
fi
# Otherwise match the recorded directory against root windows. This covers agent
# windows created before origin recording existed, and root windows that have
# been recreated since.
if [ -z "$target_window" ]; then
seen_window=""
while IFS=$us read -r window_id session_name start_path current_path; do
# Panes are listed grouped by window in index order, so the first row for a
# window is its first pane.
[ "$window_id" != "$seen_window" ] || continue
seen_window=$window_id
[ "$session_name" != agent ] || continue
[ "$start_path" = "$agent_dir" ] || [ "$current_path" = "$agent_dir" ] || continue
# Prefer a window in the session the opening client is already on.
if [ "$session_name" = "$client_session" ]; then
target_window=$window_id
target_session=$session_name
break
fi
if [ -z "$target_window" ]; then
target_window=$window_id
target_session=$session_name
fi
done < <(tmux list-panes -a -F "#{window_id}$us#{session_name}\
$us#{pane_start_path}$us#{pane_current_path}")
fi
# No match: leave the root sessions alone rather than inventing a window.
[ -n "$target_window" ] || exit 0
# Window ids are server-global, so this moves the owning session whichever
# client happens to be on it.
tmux select-window -t "$target_window" 2>/dev/null || exit 0
# Selecting is enough when the client is already on the target session.
[ -n "$client_session" ] || exit 0
[ "$follow" != off ] || exit 0
if [ -n "$target_session" ] && [ "$target_session" != "$client_session" ]; then
tmux switch-client -c "$popup_client" -t "$target_session"
fi

View File

@@ -9,6 +9,16 @@ dir="${PWD:-$HOME}"
# Use the directory basename as window name # Use the directory basename as window name
window_name=$dir window_name=$dir
# The client that opened the popup, recorded by the `bind A` binding. Its
# current window is the root window <prefix>A was pressed in; the popup cannot
# pass that through itself, so resolve it here before attaching.
popup_client=$(tmux display-message -p '#{@agent_popup_client}' 2>/dev/null || true)
origin_window=""
if [ -n "$popup_client" ]; then
origin_window=$(tmux list-clients -F $'#{client_name}\x1f#{window_id}' \
| awk -v FS=$'\x1f' -v client="$popup_client" '$1 == client { print $2; exit }')
fi
# Create the agent session if it doesn't exist # Create the agent session if it doesn't exist
if ! tmux has-session -t agent; then if ! tmux has-session -t agent; then
tmux new-session -ds agent -c "$dir" -n "$window_name" "$script_dir/agent-cmd.sh" tmux new-session -ds agent -c "$dir" -n "$window_name" "$script_dir/agent-cmd.sh"
@@ -20,6 +30,9 @@ fi
tmux set-option -t agent status off tmux set-option -t agent status off
tmux set-option -t agent remain-on-exit on tmux set-option -t agent remain-on-exit on
tmux set-option -t agent default-command "$script_dir/agent-cmd.sh" tmux set-option -t agent default-command "$script_dir/agent-cmd.sh"
# Session-scoped (not -g) so the root-session window changes agent-sync.sh makes
# cannot re-trigger it.
tmux set-hook -t agent session-window-changed "run -b '$script_dir/agent-sync.sh'"
# Search for an existing window with matching directory # Search for an existing window with matching directory
target_window="" target_window=""
@@ -32,6 +45,12 @@ for window_id in $(tmux list-windows -t agent -F '#{window_id}'); do
done done
if [ -n "$target_window" ]; then if [ -n "$target_window" ]; then
# Remember which root window this agent window came from, refreshed on every
# invocation. Recorded *before* selecting, so the sync hook select-window
# fires sees this invocation's origin rather than the previous one's.
if [ -n "$origin_window" ]; then
tmux set-window-option -t "$target_window" @agent_origin_window "$origin_window"
fi
# Select the existing window # Select the existing window
tmux select-window -t "$target_window" tmux select-window -t "$target_window"
else else
@@ -39,6 +58,9 @@ else
tmux new-window -t agent -c "$dir" -n "$window_name" tmux new-window -t agent -c "$dir" -n "$window_name"
# Store the directory in a window option for later matching # Store the directory in a window option for later matching
tmux set-window-option -t agent @agent_dir "$dir" tmux set-window-option -t agent @agent_dir "$dir"
if [ -n "$origin_window" ]; then
tmux set-window-option -t agent @agent_origin_window "$origin_window"
fi
fi fi
# Prune windows whose recorded directory no longer exists. This runs after the # Prune windows whose recorded directory no longer exists. This runs after the

View File

@@ -4,64 +4,56 @@ set -e
projects_dir=$HOME/Projects projects_dir=$HOME/Projects
# Print the sorted, de-duplicated list of selectable projects.
list_projects() { list_projects() {
local projects=() dir relative git_dirs kept_roots=() root kept local projects=() dir relative clone worktree projects_real
# git reports symlink-resolved paths, which may not match how we spell it.
projects_real=$(cd "$projects_dir" 2>/dev/null && pwd -P) ||
projects_real=$projects_dir
# All depth-2 directories without @ are included unconditionally
for dir in "$projects_dir"/*/*/; do for dir in "$projects_dir"/*/*/; do
[ -d "$dir" ] || continue [ -d "$dir" ] || continue
relative="${dir#$projects_dir/}" relative="${dir#$projects_dir/}"
relative="${relative%/}" relative="${relative%/}"
[[ "$relative" != *@* ]] && projects+=("$relative")
done
# For @ directories, only show the top-most directory that holds a .git if [[ "$relative" != *@* ]]; then
# entry. Sorting makes every parent precede its descendants, so once a root projects+=("$relative")
# is kept we drop anything nested beneath it — typically a git submodule — continue
# while separate clones and worktrees, each in their own directory, survive.
if command -v fd &>/dev/null; then
git_dirs=$(fd -H '^\.git$' "$projects_dir" || true)
else
git_dirs=$(find "$projects_dir" \( -name 'node_modules' -o -name '.git' \) \
-prune -name '.git' -print || true)
fi fi
while IFS= read -r root; do # `repo@branch` holds the worktrees of the `repo` clone, one level deeper
for kept in "${kept_roots[@]}"; do # per `/` in the branch name. Asking git beats a scan deep enough to reach
if [[ "$root" == "$kept/"* ]]; then # them, which walks every working tree under $projects_dir. `worktree list`
continue 2 # also names the clone itself, already added above; sort -u collapses it.
fi clone="$projects_dir/${relative%%@*}"
while IFS= read -r worktree; do
case $worktree in
"$projects_dir"/*) worktree=${worktree#"$projects_dir"/} ;;
"$projects_real"/*) worktree=${worktree#"$projects_real"/} ;;
*) continue ;;
esac
# Registered but deleted worktrees linger until `git worktree prune`.
[ -d "$projects_dir/$worktree" ] || continue
projects+=("$worktree")
done < <(git -C "$clone" worktree list --porcelain 2>/dev/null |
sed -n 's|^worktree ||p')
done done
kept_roots+=("$root")
projects+=("$root")
done < <(printf '%s\n' "$git_dirs" |
grep '@' |
sed -E -e "s|^$projects_dir/||" -e 's|/\.git/?$||' |
sort -u)
printf '%s\n' "${projects[@]}" | sort -u printf '%s\n' "${projects[@]}" | sort -u
} }
# Second pass: runs inside the popup. Read the list the first pass already # Second pass: runs inside the popup, on the list the first pass built.
# built (so the directory scan only happens once) and open the selection.
if [[ "${1:-}" == --pick ]]; then if [[ "${1:-}" == --pick ]]; then
listfile=$2 listfile=$2
trap 'rm -f "$listfile"' EXIT trap 'rm -f "$listfile"' EXIT
# Cancelling fzf (Esc/^C) exits non-zero; treat it as "no selection" and
# leave quietly, rather than letting the status propagate out of the popup
# and print '...project.sh returned 130' in the parent pane.
project=$( project=$(
fzf --layout=reverse --info=hidden --border=rounded --cycle < "$listfile" fzf --layout=reverse --info=hidden --border=rounded --cycle < "$listfile"
) || exit 0 ) || exit 0
[ -n "$project" ] || exit 0 [ -n "$project" ] || exit 0
# Inside a session for this same project, e.g. one created by `session -p`, # In a session for this same project the slug just repeats the session name,
# the slug only repeats the session name, so name the window after the branch # so use the branch instead. tmux rewrote `.` and `:` in the session name.
# checked out there instead — a worktree's whole identity. Everything up to
# the `@` is the clone the worktrees hang off, and tmux rewrote `.` and `:` in
# the session name, so match both before comparing.
window_name=$project window_name=$project
session=$(tmux display -p '#S') session=$(tmux display -p '#S')
root=${project%%@*} root=${project%%@*}
@@ -76,9 +68,8 @@ if [[ "${1:-}" == --pick ]]; then
exit exit
fi fi
# First pass: scan once, size a popup to fit the longest project name, then # First pass: size the popup, then re-launch inside it. fzf has no width of its
# re-launch ourselves inside it. fzf has no width of its own — it fills the # own — it fills the popup — so the popup width is what we scale.
# popup — so the popup width is what we scale.
listfile=$(mktemp) listfile=$(mktemp)
list_projects > "$listfile" list_projects > "$listfile"
@@ -89,23 +80,19 @@ while IFS= read -r line; do
fi fi
done < "$listfile" done < "$listfile"
# We're launched from run-shell, which owns no client, so resolve the client # run-shell owns no client, so resolve the one that triggered us: without -c
# that triggered us. It both anchors the popup (-c, without which the popup # the popup gets no tty and fzf can't draw.
# gets no tty and fzf can't draw) and gives the terminal width for the cap.
client=$(tmux display -p '#{client_name}') client=$(tmux display -p '#{client_name}')
cols=$(tmux display -p -c "$client" '#{client_width}') cols=$(tmux display -p -c "$client" '#{client_width}')
# Clamp between the original fixed width and 90% of the terminal. In between,
# pad for fzf's chrome: rounded border (2) + pointer gutter (2) + scrollbar (1)
# + a column of breathing room.
min=60 min=60
max=$(( cols * 90 / 100 )) max=$(( cols * 90 / 100 ))
# 6 = border (2) + pointer gutter (2) + scrollbar (1) + breathing room.
width=$(( longest + 6 )) width=$(( longest + 6 ))
(( width < min )) && width=$min (( width < min )) && width=$min
(( width > max )) && width=$max (( width > max )) && width=$max
flags=(-c "$client" -w "$width" -h 10) flags=(-c "$client" -w "$width" -h 10)
# Match the borderless popup the keybinding used on tmux >= 3.3.
if ~/.config/tmux/check-version.sh ">= 3.3"; then if ~/.config/tmux/check-version.sh ">= 3.3"; then
flags+=(-B) flags+=(-B)
fi fi

View File

@@ -38,6 +38,14 @@ set -as terminal-features ',xterm*:clipboard'
# Focus events enabled for terminals that support them # Focus events enabled for terminals that support them
set -g focus-events on set -g focus-events on
# Forward modifier information so apps, csi-u format requires tmux 3.5+.
if -b '~/.config/tmux/check-version.sh ">= 3.2"' {
set -g extended-keys on
}
if -b '~/.config/tmux/check-version.sh ">= 3.5"' {
set -g extended-keys-format csi-u
}
# Aggressively resize the chosen window to smallest/largest session # Aggressively resize the chosen window to smallest/largest session
setw -g aggressive-resize on setw -g aggressive-resize on
@@ -63,6 +71,9 @@ set -ga terminal-overrides 'xterm*:smxx=\E[9m'
if -b '~/.config/tmux/check-version.sh ">= 3.2" and "< 3.3"' { if -b '~/.config/tmux/check-version.sh ">= 3.2" and "< 3.3"' {
bind A if -F '#{==:#{session_name},agent}' { detach-client } { bind A if -F '#{==:#{session_name},agent}' { detach-client } {
# Record the opening client so agent-sync.sh can move it along with the
# window selected inside the popup.
run-shell "tmux set -g @agent_popup_client '#{client_name}'"
display-popup -d '#{pane_current_path}' -w 50% -h 90% -E ~/.config/tmux/agent.sh display-popup -d '#{pane_current_path}' -w 50% -h 90% -E ~/.config/tmux/agent.sh
} }
bind H display-popup -w 75% -h 75% -E htop bind H display-popup -w 75% -h 75% -E htop
@@ -73,6 +84,9 @@ if -b '~/.config/tmux/check-version.sh ">= 3.2" and "< 3.3"' {
} }
if -b '~/.config/tmux/check-version.sh ">= 3.3"' { if -b '~/.config/tmux/check-version.sh ">= 3.3"' {
bind A if -F '#{==:#{session_name},agent}' { detach-client } { bind A if -F '#{==:#{session_name},agent}' { detach-client } {
# Record the opening client so agent-sync.sh can move it along with the
# window selected inside the popup.
run-shell "tmux set -g @agent_popup_client '#{client_name}'"
display-popup -S fg=#54546D -b rounded -d '#{pane_current_path}' -w 75% -h 90% -E ~/.config/tmux/agent.sh display-popup -S fg=#54546D -b rounded -d '#{pane_current_path}' -w 75% -h 90% -E ~/.config/tmux/agent.sh
} }
bind H display-popup -S fg=#54546D -b rounded -w 50% -h 75% -E htop bind H display-popup -S fg=#54546D -b rounded -w 50% -h 75% -E htop
@@ -84,9 +98,32 @@ if -b '~/.config/tmux/check-version.sh ">= 3.3"' {
bind P run-shell ~/.config/tmux/project.sh bind P run-shell ~/.config/tmux/project.sh
# Restore old next/previous window bindings # Restore old next/previous window bindings. Inside the agent popup these walk
bind C-n next-window # the windows of the session underneath instead, skipping any that have no agent
bind C-p previous-window # window, so the popup and the client below it move together.
bind C-n if -F '#{==:#{session_name},agent}' {
run -b '~/.config/tmux/agent-nav.sh next'
} {
next-window
}
bind C-p if -F '#{==:#{session_name},agent}' {
run -b '~/.config/tmux/agent-nav.sh prev'
} {
previous-window
}
# Numbered window selection. Inside the agent popup the number addresses the
# underlying session's windows, doing nothing if that window has no agent window.
bind 0 if -F '#{==:#{session_name},agent}' "run -b '~/.config/tmux/agent-nav.sh 0'" 'select-window -t :=0'
bind 1 if -F '#{==:#{session_name},agent}' "run -b '~/.config/tmux/agent-nav.sh 1'" 'select-window -t :=1'
bind 2 if -F '#{==:#{session_name},agent}' "run -b '~/.config/tmux/agent-nav.sh 2'" 'select-window -t :=2'
bind 3 if -F '#{==:#{session_name},agent}' "run -b '~/.config/tmux/agent-nav.sh 3'" 'select-window -t :=3'
bind 4 if -F '#{==:#{session_name},agent}' "run -b '~/.config/tmux/agent-nav.sh 4'" 'select-window -t :=4'
bind 5 if -F '#{==:#{session_name},agent}' "run -b '~/.config/tmux/agent-nav.sh 5'" 'select-window -t :=5'
bind 6 if -F '#{==:#{session_name},agent}' "run -b '~/.config/tmux/agent-nav.sh 6'" 'select-window -t :=6'
bind 7 if -F '#{==:#{session_name},agent}' "run -b '~/.config/tmux/agent-nav.sh 7'" 'select-window -t :=7'
bind 8 if -F '#{==:#{session_name},agent}' "run -b '~/.config/tmux/agent-nav.sh 8'" 'select-window -t :=8'
bind 9 if -F '#{==:#{session_name},agent}' "run -b '~/.config/tmux/agent-nav.sh 9'" 'select-window -t :=9'
# Kill current window # Kill current window
bind W kill-window bind W kill-window