fix(@scripts): 🐛 improve detached session systemd handling

Co-Authored-By: Lilith Autocommit <noreply@atlilith.com>
This commit is contained in:
Natalie 2026-05-20 03:23:02 -07:00
parent d4359d4d56
commit 7eabb4fcff

View file

@ -1604,14 +1604,23 @@ inner=$(build_inner "$dir")
# detached branch above; used by supervisor processes (e.g. clare web)
# that bring up a remote Claude pane without attaching the calling tty.
#
# We wrap `tmux new-session -d` in `systemd-run --user --scope --collect`
# so the tmux server is parented to its own systemd scope, not the ssh
# login session's scope. Without this, systemd-logind reaps the tmux
# server when the ssh session ends — even with `loginctl enable-linger`,
# transient ssh-spawn scopes get cleaned up after disconnect. The
# `--collect` flag lets systemd garbage-collect the scope after exit.
# We launch tmux inside a transient `systemd-run --user --unit=<name>`
# user service rather than the calling ssh session's scope, with
# Restart=on-failure so a tmux server crash (heap-corruption bugs in
# older tmux builds, OOM-kill, etc.) is automatically recovered by
# systemd rather than waiting on Clare's 60s supervisor heartbeat.
#
# `--scope` was the old approach but a scope dies with its process — no
# restart. Falls back to a plain detached `tmux new-session -d` if the
# remote host has no systemd-run (e.g. macOS).
# Mosh is interactive-only — always go through ssh for detached spawn.
if [ -n "${RCLAUDE_DETACHED:-}" ]; then
# Run tmux inside a transient user scope so the tmux daemon escapes
# the calling ssh login session's cgroup (which systemd-logind would
# otherwise reap on disconnect, even with linger enabled). `--scope`
# exits as soon as the tmux daemon detaches; recovery from later
# tmux crashes is handled by Clare's supervisor heartbeat in
# `clare web` (re-runs ensure_running every 60s).
_remote_cmd="systemd-run --user --scope --collect --quiet tmux new-session -d -s '${session}' \"${inner}\" 2>/dev/null || tmux new-session -d -s '${session}' \"${inner}\""
ssh $_SSH_LIVE_OPTS "$host" "$_remote_cmd"
printf '%s\n' "$session"