Article

Reattach to Herdr Automatically When Moshi Reconnects (No Pro Needed)

A small Zsh hook that puts my phone straight back into my running Herdr session every time Moshi reconnects over SSH.

The problem

I run Claude Code inside Herdr on my Ubuntu desktop. When I'm away from the desk I check on it from my Pixel 8 with Moshi, an SSH terminal built for coding agents.

Android kills Moshi's SSH connection soon after the app goes to the background. When I come back and reconnect, I get a plain shell. Then I type herdr, every single time.

Moshi Pro has "auto-attach after reconnect" for tmux and Herdr. I wanted the same result on the free version, without touching other SSH clients.

Why this works at all

Herdr splits into a server and clients. herdr server runs detached in its own session, with no terminal. Each herdr you run is a client that attaches to it, and several clients can attach at once.

When the phone's SSH connection drops, only the phone's client dies. The server keeps running, and so do Claude Code and every other pane. All I need on reconnect is to run herdr again, automatically, and only for Moshi.

Recognizing Moshi from the server

The shell has to know a login came from Moshi, and that took some digging. Moshi has a "MOSHI_CLIENT env" toggle in Settings, off by default. When it's on, Moshi exports MOSHI_CLIENT=1 into the remote shell, but the docs don't say how the variable gets there.

That matters because Ubuntu's sshd ships with AcceptEnv LANG LC_*. If a client sends MOSHI_CLIENT as an SSH env request, sshd throws it away. I tried it with ssh -o SendEnv=MOSHI_CLIENT and the variable arrived unset, while one named LC_MOSHI_CLIENT got through. My live Moshi shell didn't have it either.

So the hook has a fallback. I reach my desktop over Tailscale, and a device keeps the same Tailscale IP, so logins from the phone's IP also count as Moshi. Any other SSH app on that phone would trigger it too, which I can live with.

I didn't change sshd. Adding MOSHI_CLIENT to AcceptEnv is a global change and needs an sshd restart, and the IP fallback works without it.

What the hook does

The hook lives in its own file, ~/.config/zsh/moshi-herdr.zsh, and ~/.zshrc loads it with one line. At the first prompt of a login it:

  1. Exits right away unless the shell is interactive, has an SSH terminal (SSH_TTY), and is not already inside Herdr (HERDR_ENV). That keeps it away from local shells, Herdr panes, ssh host command, scp, and sftp.
  2. Checks for MOSHI_CLIENT=1, then the fallback IP list.
  3. Runs herdr, which attaches to the running default session. It only starts a new server if none is running, so it never makes a duplicate.

It runs once per login. If I detach from Herdr, I get a normal shell instead of being thrown back in. It also checks the first three prompts, not only the first, in case Moshi types the export after login instead of sending it with the connection.

Option 1: Let Claude Code do it

This is the prompt I gave Claude Code. It inspected my machine, found that MOSHI_CLIENT wasn't arriving, added the IP fallback, and tested everything without dropping my session.

I use Moshi (the Android SSH terminal app, free version) on my phone to SSH into
this Ubuntu computer and access Herdr.

The problem: When Moshi goes into the background, its SSH connection disconnects.
When I return to Moshi and reconnect, I get a fresh shell instead of automatically
returning to my existing Herdr session.

The goal: Whenever I reconnect through Moshi, automatically launch Herdr and
reattach to my existing session. I want this to work with Moshi Free, without
upgrading to Pro. Normal SSH connections from other clients should remain unaffected.

Please do the following:

1. Inspect my Ubuntu environment, determine whether I'm using Bash or Zsh, and check
   how Herdr is installed and how its session management works.
2. Investigate how Moshi identifies its SSH connections to the remote shell. Check
   whether "MOSHI_CLIENT" is available, how it is transmitted, and whether it
   requires an option enabled in the Moshi Android app. Don't assume the variable exists.
3. Check Herdr's actual CLI commands and determine the safest way to reattach to an
   existing session rather than creating a new one.
4. Configure the appropriate shell startup file ("~/.bashrc", "~/.zshrc", or
   equivalent) to automatically launch or reattach to Herdr when an interactive SSH
   session originates from Moshi.
5. Make the detection reliable. Prefer "MOSHI_CLIENT" if supported, and don't assume
   every SSH connection is from Moshi.
6. Prevent recursion, duplicate session creation, and accidental launches during
   non-interactive SSH commands, SCP, or SFTP.
7. Preserve all my existing shell configuration. Back up files before making changes
   and make the modification easy to reverse.
8. Test the configuration as thoroughly as possible without disconnecting my current
   session.
9. Explain any settings I must enable manually in the Moshi Android app.

Important: My existing Herdr session must survive SSH disconnections. The objective
is to reattach to that same workspace automatically when Moshi reconnects, not
restart Herdr or Claude Code.

Please implement the solution, not just provide instructions. If Moshi cannot be
reliably identified from the server, explain the limitation and propose the simplest
alternative, such as a dedicated SSH command or connection profile. Don't alter
global SSH server settings unless absolutely necessary, and ask before making
potentially disruptive changes.

At the end, summarize what you changed and how I can test it by switching away from
Moshi and reconnecting.

Run it from a Moshi session if you can. Claude can then read the environment of your live phone shell and see exactly what Moshi sends.

Option 2: Do it yourself

This assumes Zsh. Run echo $SHELL to check. For Bash, use the prompt above, or rebuild the hook with PROMPT_COMMAND in place of precmd.

1. Find your phone's IP

Connect from Moshi and run:

echo ${SSH_CONNECTION%% *}

That prints the IP the phone connects from. With Tailscale it starts with 100.. You can also find it in tailscale status.

2. Back up your .zshrc

cp -p ~/.zshrc ~/.zshrc.bak-pre-moshi-herdr

3. Create the hook

Replace 100.x.y.z with your phone's IP, then paste the whole block:

mkdir -p ~/.config/zsh
cat > ~/.config/zsh/moshi-herdr.zsh <<'EOF'
# moshi-herdr: reattach to the persistent Herdr session when an
# interactive SSH login comes from Moshi on the phone.
#
# Detection, in order:
#   1. MOSHI_CLIENT=1 (Moshi app: Settings > "MOSHI_CLIENT env" toggle).
#   2. Fallback: the SSH client IP is in MOSHI_HERDR_FALLBACK_IPS.
#      Empty the array to rely on MOSHI_CLIENT only.
#
# Disable for now:  touch ~/.config/moshi-herdr.disabled
# Remove:           delete the "moshi-herdr" line in ~/.zshrc

typeset -ga MOSHI_HERDR_FALLBACK_IPS=(
  100.x.y.z   # phone (Tailscale)
)
: ${MOSHI_HERDR_BIN:=herdr}   # override only for tests

# Only SSH logins with a terminal, outside Herdr, need the hook.
# Local shells, Herdr panes, `ssh host cmd`, scp and sftp stop here.
if [[ -o interactive && -n $SSH_TTY && -z $HERDR_ENV && -z $_MOSHI_HERDR_DONE ]]; then
  typeset -gi _moshi_herdr_prompts=0

  _moshi_herdr_precmd() {
    # Check the first 3 prompts, in case Moshi exports MOSHI_CLIENT
    # after login instead of sending it with the connection.
    if (( ++_moshi_herdr_prompts > 3 )); then
      add-zsh-hook -d precmd _moshi_herdr_precmd
      return
    fi

    [[ -t 0 && -t 1 ]] || return
    [[ -e ~/.config/moshi-herdr.disabled ]] && return
    command -v $MOSHI_HERDR_BIN >/dev/null || return

    local via ip=${SSH_CONNECTION%% *}
    if [[ $MOSHI_CLIENT == 1 ]]; then
      via=MOSHI_CLIENT
    elif (( ${MOSHI_HERDR_FALLBACK_IPS[(Ie)$ip]} )); then
      via="client IP $ip"
    else
      return
    fi

    # Run once per login. After you detach from Herdr, you get this shell.
    add-zsh-hook -d precmd _moshi_herdr_precmd
    export _MOSHI_HERDR_DONE=1

    if $MOSHI_HERDR_BIN status 2>/dev/null | grep -q 'status: running'; then
      print -P "%F{cyan}moshi-herdr:%f attaching to the running Herdr session ($via)"
    else
      print -P "%F{yellow}moshi-herdr:%f no Herdr server is running; starting Herdr ($via)"
    fi
    # `herdr` attaches to the persistent default session if it runs,
    # and starts it only if it does not.
    $MOSHI_HERDR_BIN
  }

  autoload -Uz add-zsh-hook
  add-zsh-hook precmd _moshi_herdr_precmd
fi
EOF

4. Load it from .zshrc

printf '\n# moshi-herdr: reattach Herdr on Moshi SSH logins (remove this line to disable)\n[[ -r ~/.config/zsh/moshi-herdr.zsh ]] && source ~/.config/zsh/moshi-herdr.zsh\n' >> ~/.zshrc
zsh -n ~/.zshrc && zsh -n ~/.config/zsh/moshi-herdr.zsh && echo "syntax OK"

5. Optional: turn on MOSHI_CLIENT

In Moshi, open Settings and turn on MOSHI_CLIENT env. If the variable reaches your shell, the attach message says (MOSHI_CLIENT) instead of (client IP ...). Once you see that, you can empty MOSHI_HERDR_FALLBACK_IPS and rely on the variable alone.

Testing it

  1. Open Moshi and connect. You should land in Herdr with a moshi-herdr: attaching... line just before it.
  2. Switch to another app long enough for the connection to drop.
  3. Go back to Moshi and reconnect. You should be in the same Herdr workspace, with Claude Code still running.
  4. From a laptop or another SSH client, connect normally. You should get a plain shell.
  5. Run scp or sftp against the machine. Both should work as before.

Turning it off

To pause it, run touch ~/.config/moshi-herdr.disabled, and delete that file to turn it back on. To remove it, delete the two moshi-herdr lines at the end of ~/.zshrc or restore ~/.zshrc.bak-pre-moshi-herdr. Nothing outside your home folder changes, so there is nothing else to undo.