if [ "$PREVIOUS_SESSION_ID" != "" ]; then # Spawned as a new window/terminal for an existing remote session (by the # niri/hyprland keybind). Inherit that session's working directory: find a # live shell whose SSH_SESSION_ID (carried in its environment) matches and # cd to its cwd. Then drop the hint so child shells don't keep jumping back. _best_pid=0 _prev_cwd="" for _environ in /proc/[0-9]*/environ; do _pid=${_environ%/environ} _pid=${_pid#/proc/} # cat (not a < redirect) so unreadable/ptrace-protected environ files # fail quietly into the pipe instead of raising a shell error. if cat "$_environ" 2>/dev/null | tr '\0' '\n' | grep -Fxq "SSH_SESSION_ID=$PREVIOUS_SESSION_ID"; then [ "$(cat /proc/$_pid/comm 2>/dev/null)" = zsh ] || continue _c=$(readlink -e /proc/$_pid/cwd 2>/dev/null) || continue if [ -n "$_c" ] && [ "$_pid" -gt "$_best_pid" ]; then _best_pid=$_pid _prev_cwd=$_c fi fi done [ -n "$_prev_cwd" ] && cd "$_prev_cwd" unset _best_pid _prev_cwd _environ _pid _c PREVIOUS_SESSION_ID fi function run_waypipe() { if [ -z "$1" ]; then echo "usage: run_waypipe " >&2 return 1 fi local SSH_SESSION_ID=$RANDOM REMOTE_PATH # Map the current path relative to $HOME so it resolves to the remote user's # home even when the username differs (the remote shell expands $HOME). if [[ "$PWD" == "$HOME" || "$PWD" == "$HOME"/* ]]; then REMOTE_PATH="\$HOME${PWD#$HOME}" else REMOTE_PATH="$PWD" fi # cd into the mirrored path before the interactive shell starts, so the cwd # is never carried in an inherited env var (which would leak to every child # shell and override the cwd of new zellij panes). SSH_SESSION_ID stays in # the environment on purpose: it is the token the WM keybind above uses to # locate this session's shells later. waypipe -n ssh -t "$1" "cd \"$REMOTE_PATH\" 2>/dev/null; exec env SSH_SESSION_ID=$SSH_SESSION_ID zsh --login" } alias s='run_waypipe'