#!/bin/bash
# summary: Keep the taskbar and menu running throughout the session.
# starchaser shell keeper: keeps the taskbar (the cockpit: frame, notifications, password prompts, Alt+Tab, quick
# settings) and the main menu running for the whole session, and brings either one back within a second or
# two if it closes (a crash, a broken Wayland connection after a keyboard layout change, ...). Before this, a cockpit
# that died stayed gone until Super+Ctrl+R, which nothing on screen tells a first-time user.
#
#   starchaser shell keeper cockpit|menu   keep that part running (hyprland.lua starts both at sign-in). A second
#                                          keeper for the same part exits at once, so it never runs twice.
#   starchaser shell keeper restart        Super+Ctrl+R / the menu's "Restart the taskbar and menu": restart those two
#                                          only. Settings, Ask, the Welcome and a screenshot in progress stay open
#                                          (they are Quickshell programs too; the old `pkill -x qs` closed them all).
#
# Why a loop in the session and not a systemd user service: the cockpit is the password-prompt agent, and polkit only
# sends a prompt to an agent inside the seat's login session. A user service runs outside it (the same reason Settings
# started over SSH can't show a password box). Started from Hyprland, this stays in the session, and it ends with it:
# once Hyprland is gone it stops instead of restarting anything.
# A part started some other way (an older session's `qs ... -n -d`, the qa harness) is waited for, never doubled; when
# it closes, the keeper starts its own copy. Restarting never takes the keyboard: the cockpit's layers only take keys
# when you open something.
# Log: ~/.local/state/starchaser/shell-keeper.log (a few lines per restart).
# hypridle calls `refresh` after 30 seconds without input: replaced Qt/Quickshell mappings need a new process,
# not just a QML reload. This covers automatic, Settings and terminal updates, including a partly failed update.
# If a panel, lock or fullscreen app is open, leave it alone and try at the next idle transition.
set -u
# Every wait below is a sleep, and the cockpit's watch looks every 5 seconds for the whole session: bash's loadable
# sleep builtin (in the bash package) makes those waits cost no new process. Without it, the program runs as before.
enable -f /usr/lib/bash/sleep sleep 2>/dev/null || true

extra() {
    echo "starchaser shell keeper: $1 takes nothing after it (got '$2'). Run 'starchaser shell keeper --help' for more help." >&2
    exit 2
}

usage() {
    echo "Usage: starchaser shell keeper cockpit|menu|restart|refresh"
    echo
    echo "Keeps the taskbar (cockpit) and the main menu running, and restarts them if they close."
    echo "'restart' restarts just those two (what Super+Ctrl+R does). Sign-in starts it; there is no need to run it yourself."
    echo "'refresh' is called by the idle timer to load replaced desktop libraries when the shell is not in use."
}

RUN="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
STATE="${XDG_STATE_HOME:-$HOME/.local/state}/starchaser"
LOG="$STATE/shell-keeper.log"

cfg_of() {
    case "$1" in
        cockpit|menu) echo "$HOME/.config/quickshell/cockpit" ;;
        *)       return 1 ;;
    esac
}

log() {
    mkdir -p "$STATE" 2>/dev/null
    # the taskbar's and the menu's keepers share this log: one at a time, so a trim can't drop the other's line
    # or rename the other's temp file
    {
        flock 9
        printf '%s %s\n' "$(date '+%F %T')" "$*" >> "$LOG"
        # keep it small: the last 200 lines
        if [ "$(wc -l < "$LOG" 2>/dev/null || echo 0)" -gt 400 ]; then
            tail -n 200 "$LOG" > "$LOG.$$.tmp" && mv -f "$LOG.$$.tmp" "$LOG"
            rm -f "$LOG.$$.tmp"
        fi
    } 9>>"$LOG.lock" 2>/dev/null
}

# pids of running instances of a config: `qs list -p` misses an instance started through a differently spelled path
# (a symlinked folder), so every instance is listed and matched on both spellings of the path. Quickshell 0.3.2 prints
# its "locale is not UTF-8" warning on stdout, ahead of the JSON (a session without a UTF-8 locale): jq then read
# nothing, so Super+Ctrl+R killed nothing and the keeper kept starting copies that `-n` closed at once. Only the JSON
# (from its first "[" line) goes to jq.
instance_pids() {
    local cfg="$1" real
    real=$(readlink -f "$cfg" 2>/dev/null || echo "$cfg")
    qs list -a -j 2>/dev/null | sed -n '/^\[/,$p' | jq -r --arg a "$cfg/shell.qml" --arg b "$real/shell.qml" \
        '.[]? | select(.config_path == $a or .config_path == $b) | .pid' 2>/dev/null
}

# A crash handler can relaunch plain quickshell, outside the keeper's launch pattern.
# Keep copies with an explicit config argument: someone else started those deliberately.
stale_instance() {
    local pid="$1" proc_root="${KEEPER_PROC_ROOT:-/proc}" arg first=1
    [ -r "$proc_root/$pid/cmdline" ] || return 1
    # Not stale when any supported way of naming a config is present: -p/--path, -c/--config (also with =), or the
    # QS_CONFIG_PATH / QS_CONFIG_NAME / QS_MANIFEST variables. The first cmdline entry is the program itself.
    while IFS= read -r -d '' arg; do
        if [ "$first" = 1 ]; then first=0; continue; fi
        case "$arg" in -p|-c|--path|--config|--path=*|--config=*) return 1 ;; esac
    done < "$proc_root/$pid/cmdline" 2>/dev/null
    while IFS= read -r -d '' arg; do
        case "$arg" in QS_CONFIG_PATH=*|QS_CONFIG_NAME=*|QS_MANIFEST=*) return 1 ;; esac
    done < "$proc_root/$pid/environ" 2>/dev/null
    return 0
}

# Close only Starchaser-owned toolkit reporters, never another Quickshell app.
# Registered windows and handler relaunches without DUMP_FD are left to normal teardown.
reap_crash_reporters() {
    local listing registered proc pid comm uid owned
    local candidates=() proc_root="${KEEPER_PROC_ROOT:-/proc}"
    listing=$(qs list -a -j 2>/dev/null) || return
    registered=$(printf '%s\n' "$listing" | sed -n '/^\[/,$p' | jq -er \
        'if type == "array" then map(.pid | tostring) | join("\n") else error("invalid instance list") end' 2>/dev/null) || return
    uid=$(id -u)
    if [ "$proc_root" = /proc ]; then
        mapfile -t candidates < <(pgrep -u "$uid" -x 'quickshell|qs')
    else
        for proc in "$proc_root"/[0-9]*; do candidates+=("${proc##*/}"); done
    fi
    for pid in "${candidates[@]}"; do
        proc="$proc_root/$pid"
        [ -O "$proc" ] || continue
        IFS= read -r comm < "$proc/comm" 2>/dev/null || continue
        case "$comm" in quickshell|qs) ;; *) continue ;; esac
        grep -zq '^__QUICKSHELL_CRASH_DUMP_PID=' "$proc/environ" 2>/dev/null || continue
        grep -zq '^__QUICKSHELL_CRASH_DUMP_FD=' "$proc/environ" 2>/dev/null || continue
        printf '%s\n' "$registered" | grep -Fxq -- "$pid" && continue
        # Explicit launch tags prove ownership. No untagged or foreign app is closed.
        owned=0
        grep -zEq '^STARCHASER_QML_APP=(settings|welcome|ask|manual|lock|remote|versions|capture|live|firewall|recovery|greeter|personal-apps)$' "$proc/environ" 2>/dev/null && owned=1
        grep -zEq '^STARCHASER_KEEPER_PART=(cockpit|menu)$' "$proc/environ" 2>/dev/null && owned=1
        [ "$owned" = 1 ] || continue
        log "crash reporter: closing Starchaser report pid $pid"
        kill -TERM "$pid" 2>/dev/null
    done
}

# true when what the cockpit printed since byte offset $1 shows the graphics driver ran out of memory
# (Qt: "Could not create EGL surface (EGL error 0x3003)", EGL_BAD_ALLOC)
graphics_memory_full() {
    tail -c "+$(( ${1:-0} + 1 ))" "$LOG" 2>/dev/null | grep -Eqi 'EGL error 0x3003|EGL_BAD_ALLOC'
}

# taskbar layers Hyprland still shows with no program behind them: pid -1 (no client), or a pid that is not running.
# Prints one pid per such layer; nothing when hyprctl does not answer. Seen once on .16 (r169): after a restart an old
# "starchaser-bar" layer with pid -1 stayed at the same place as the new taskbar.
ghost_bar_layers() {
    local pid
    for pid in $(timeout 3 "${HYPRCTL:-hyprctl}" layers -j 2>/dev/null \
            | jq -r '.[]?.levels[]?[]? | select(.namespace == "starchaser-bar") | .pid' 2>/dev/null); do
        case "$pid" in
            -1) echo "$pid" ;;                 # never `kill -0 -1`: that asks about every process
            ''|*[!0-9]*) ;;
            *) kill -0 "$pid" 2>/dev/null || echo "$pid" ;;
        esac
    done
}

# after the taskbar closed: wait (up to ${KEEPER_LAYER_WAIT:-5} seconds) for Hyprland to drop its old bar layer before
# the new taskbar starts, so two bars never sit on top of each other; one that stays is logged, then the new one starts
wait_bar_layers_gone() {
    local waited=0 limit=$(( ${KEEPER_LAYER_WAIT:-5} * 10 )) ghosts
    ghosts=$(ghost_bar_layers)
    [ -z "$ghosts" ] && return 0
    while [ -n "$ghosts" ] && [ "$waited" -lt "$limit" ]; do
        sleep 0.1
        waited=$(( waited + 1 ))
        ghosts=$(ghost_bar_layers)
    done
    if [ -n "$ghosts" ]; then
        log "cockpit: $(printf '%s\n' "$ghosts" | wc -l) old taskbar layer(s) still on screen with no program behind them (pid $(echo $ghosts)) after $(( limit / 10 ))s; starting the new taskbar anyway"
        return 1
    fi
    log "cockpit: waited $(( waited / 10 )).$(( waited % 10 ))s for the old taskbar layer to go"
    return 0
}

# the Hyprland this session runs in: the pid its instance folder's hyprland.lock names, still running as Hyprland
# (a socket file alone proves nothing: it outlives a Hyprland that crashed)
hyprland_running() {
    local pid comm
    pid=$(head -n 1 "$RUN/hypr/$HYPRLAND_INSTANCE_SIGNATURE/hyprland.lock" 2>/dev/null)
    case "$pid" in ''|*[!0-9]*) pid="" ;; esac
    if [ -n "$pid" ]; then
        comm=$(cat "/proc/$pid/comm" 2>/dev/null)
        case "$comm" in *[Hh]yprland*) return 0 ;; esac
        return 1
    fi
    pgrep -u "$(id -u)" -x Hyprland >/dev/null 2>&1
}

# one look at whether the session is still there; why not goes to $WHY (logged when the keeper stops)
WHY=""
session_probe() {
    if [ -n "${HYPRLAND_INSTANCE_SIGNATURE:-}" ]; then
        local rc sock="$RUN/hypr/$HYPRLAND_INSTANCE_SIGNATURE/.socket.sock"
        timeout 3 "${HYPRCTL:-hyprctl}" -j version >/dev/null 2>&1
        rc=$?
        [ "$rc" -eq 0 ] && return 0
        # hyprctl can fail while Hyprland is busy (applying a keymap, a reload): its socket together with its running
        # process still means the session is there
        if [ -S "$sock" ] && hyprland_running; then
            return 0
        fi
        WHY="hyprctl exit $rc$([ "$rc" -eq 124 ] && echo ' (timed out)'), socket $([ -S "$sock" ] && echo present || echo gone), Hyprland $(hyprland_running && echo running || echo 'not running')"
        return 1
    elif [ -n "${WAYLAND_DISPLAY:-}" ]; then
        [ -S "$RUN/$WAYLAND_DISPLAY" ] || [ -S "$WAYLAND_DISPLAY" ] && return 0
        WHY="the Wayland socket $WAYLAND_DISPLAY is gone"
        return 1
    fi
    WHY="no HYPRLAND_INSTANCE_SIGNATURE or WAYLAND_DISPLAY"
    return 1
}

# the session this keeper belongs to is still running. One failed look is not enough: it ran the moment a part
# closed, which is when Hyprland is busiest (a keyboard layout change closed the taskbar, hyprctl didn't answer in
# time, and the keeper stopped for good with nothing on screen). It takes ${KEEPER_TRIES:-5} failed looks a second apart.
session_alive() {
    local try tries="${KEEPER_TRIES:-5}"
    for (( try = 1; try <= tries; try++ )); do
        session_probe && return 0
        [ "$try" -lt "$tries" ] && sleep "${KEEPER_RETRY_SLEEP:-1}"
    done
    return 1
}

# Registration failure is final inside Quickshell. Probe the cockpit's own agent;
# restart the whole process after three failed probes, so even a pending upstream
# registration callback cannot outlive its QML agent. wait in keep() below ensures
# the old process (and its polkit session registration) is gone before starting again.
watch_polkit() {
    local cfg="$1" pid="$2" failed=0 registered checks=0
    while kill -0 "$pid" 2>/dev/null; do
        sleep "${KEEPER_AGENT_SLEEP:-5}"    # the sleep builtin: a look costs no process until it asks IPC
        kill -0 "$pid" 2>/dev/null || return
        # The crash handler can re-exec our child in place as plain /usr/bin/quickshell.
        # wait "$child" would then wait forever on the stale QML. Stop that exact PID;
        # keep() waits for teardown and launches a proper qs -p cockpit. The separate
        # GUI reporter stays open until its Exit button (or a title-bar x, where the
        # compositor draws one) closes it; the sweep keeps only the newest.
        if stale_instance "$pid"; then
            log "cockpit: replacing crash-handler relaunch pid $pid"
            qs kill --pid "$pid" >/dev/null 2>&1 || kill -TERM "$pid" 2>/dev/null
            return
        fi
        # Healthy registration is final for this process. Keep the cheap exec check above (no new process), but
        # ask IPC (a qs start, the costly part) only every 10 minutes after the first successful registration.
        if [ "$failed" = -1 ]; then
            checks=$((checks + 1))
            [ "$checks" -ge "${KEEPER_HEALTHY_CHECKS:-120}" ] || continue
            checks=0
        fi
        registered=$(timeout 3 qs -p "$cfg" ipc call polkit registered 2>/dev/null) || registered=""
        registered=${registered##*$'\n'}  # discard qs locale warnings ahead of the bool
        if [ "$registered" = false ]; then
            [ "$failed" -ge 0 ] || failed=0
            failed=$((failed + 1))
        else
            if [ "$registered" = true ]; then failed=-1; else failed=0; fi
        fi
        if [ "$failed" -ge 3 ]; then
            log "cockpit: password agent did not register; restarting after process exit"
            qs kill --pid "$pid" >/dev/null 2>&1 || kill -TERM "$pid" 2>/dev/null
            return
        fi
    done
}

# A deliberate retry should not wait through a crash-loop pause.
wait_retry() {
    local name="$1" seconds="$2" i
    for (( i = 0; i < seconds; i++ )); do
        [ -e "$RUN/starchaser-shell-keeper-$name.restart" ] && return
        sleep 1
    done
}

# The menu can explain a failed restart even when the notification server is down.
report_restart() {
    local cfg menu i registered stable=0
    cfg=$(cfg_of cockpit)
    menu=$(cfg_of menu)
    for (( i = 0; i < 12; i++ )); do
        sleep 1
        registered=$(timeout 2 qs -p "$cfg" ipc call polkit registered 2>/dev/null) || registered=""
        registered=${registered##*$'\n'}
        if [ "$registered" = true ]; then
            stable=$((stable + 1))
            [ "$stable" -ge 3 ] && return
        else
            stable=0
        fi
    done
    log "cockpit: did not recover after the restart request"
    for (( i = 0; i < 3; i++ )); do
        timeout 2 qs -p "$menu" ipc call menu recovery \
            "The taskbar couldn't start. Restart the computer from Power, then try again." >/dev/null 2>&1 && return
        sleep 1
    done
}

keep() {
    local name="$1" cfg
    cfg=$(cfg_of "$name") || { usage >&2; exit 2; }
    exec 9>"$RUN/starchaser-shell-keeper-$name.lock" || exit 1
    flock -n 9 || exit 0                       # already kept: never a second keeper (or a second copy)
    local mark="$RUN/starchaser-shell-keeper-$name.restart"
    local deaths=() child=0 priorPid pid agentWatch=0 quiet=0 logSize=0 memFull=0 sw=()
    # Full graphics memory (EGL error 0x3003): the cockpit starts again with Qt Quick software rendering for the rest
    # of the session, so the taskbar stays usable instead of closing over and over. The flag lives in the runtime
    # dir, so the next sign-in starts with normal rendering. Set on the cockpit's qs command line only, never
    # exported here; the shell's app launches drop QT_QUICK_BACKEND with env -u, so opened programs keep the GPU.
    local swFlag="$RUN/starchaser-cockpit-software"
    # NVIDIA: the parts this keeper starts use the driver's implicit sync, not explicit sync (linux-drm-syncobj).
    # Suspected, not yet confirmed: Hyprland 0.56 keeps every explicit-sync timeline of a closed taskbar, and with it
    # the graphics memory of its full-screen layers. On .10 (RTX 4080), 1276 leftover timelines and 15 GB were seen
    # after ~17 restarts in one session, until no new taskbar could start (EGL error 0x3003, exit 139 over and over).
    # See qa/notes/hyprland-vram-r175.md. Other drivers ignore the variable. It is set on the qs command lines only,
    # never exported here, and the shell's app launches (AppsPanel, Apps, the menu) drop it with env -u, so the
    # programs people open keep the driver's normal sync.
    # stopped by hand: the part it keeps stays up (a new keeper waits for it, as for any copy started elsewhere)
    trap '[ "$agentWatch" -gt 0 ] && kill "$agentWatch" 2>/dev/null; exit 0' TERM INT HUP
    log "$name: keeping it running"
    reap_crash_reporters
    while session_alive; do
        priorPid=$(instance_pids "$cfg")
        if [ -n "$priorPid" ]; then
            # qs drops its instance record before process teardown finishes. Wait on
            # the actual PID too: polkit still owns the old session registration then.
            for pid in $priorPid; do
                while kill -0 "$pid" 2>/dev/null; do
                    # Recheck while waiting: a deliberately started copy can crash
                    # and re-exec in place too, retaining its PID but losing -p.
                    if stale_instance "$pid"; then
                        log "$name: closing stale instance pid $pid (no -p argument)"
                        qs kill --pid "$pid" >/dev/null 2>&1 || kill -TERM "$pid" 2>/dev/null
                    fi
                    session_alive || return
                    sleep 0.3
                done
            done
            reap_crash_reporters
            continue
        fi
        local start
        start=$(date +%s)
        rm -f "$mark"                          # a restart request that found a copy started elsewhere is used up
        # Starchaser owns crash notices. Never show the toolkit's foreign reporter.
        if [ "$name" = menu ]; then
            __NV_DISABLE_EXPLICIT_SYNC=1 QS_DISABLE_CRASH_HANDLER=1 MENU_DAEMON=1 qs -p "$cfg" -n >/dev/null 2>&1 9>&- &
        else
            logSize=$(stat -c %s "$LOG" 2>/dev/null || echo 0)
            sw=()
            [ -e "$swFlag" ] && sw=(QT_QUICK_BACKEND=software)
            env "${sw[@]}" __NV_DISABLE_EXPLICIT_SYNC=1 QS_DISABLE_CRASH_HANDLER=1 STARCHASER_KEEPER_PART=cockpit qs -p "$cfg" -n >>"$LOG" 2>&1 9>&- &
        fi
        child=$!
        if [ "$name" = cockpit ]; then
            watch_polkit "$cfg" "$child" 9>&- &
            agentWatch=$!
        fi
        wait "$child"
        local rc=$?
        reap_crash_reporters
        if [ "$agentWatch" -gt 0 ]; then
            kill "$agentWatch" 2>/dev/null
            wait "$agentWatch" 2>/dev/null
            agentWatch=0
        fi
        child=0
        session_alive || break                 # signed out: the session's end closed it, nothing to bring back
        [ "$name" = cockpit ] && wait_bar_layers_gone
        # a menu that closed while open (a crash, or toggle.sh's kill) skipped its own clean-up: undo its dimming of
        # the window behind (shell.qml leaves the commands in this file while it is open)
        if [ -f "$RUN/starchaser-menu-unfade.sh" ]; then
            sh "$RUN/starchaser-menu-unfade.sh" >/dev/null 2>&1
            rm -f "$RUN/starchaser-menu-unfade.sh"
        fi
        local now
        now=$(date +%s)
        if [ -e "$mark" ] && [ "$(stat -c %Y "$mark" 2>/dev/null || echo 0)" -ge "$start" ]; then
            rm -f "$mark"
            deaths=()
            log "$name: restarted on request"
            sleep 0.3
            continue
        fi
        if [ $(( now - start )) -lt 3 ] && [ -n "$(instance_pids "$cfg")" ]; then
            continue                           # another copy had just started (-n): wait for that one above
        fi
        # read the log before log() below can trim it (the byte offset would then point past the end)
        memFull=0
        if [ "$name" = cockpit ] && graphics_memory_full "$logSize"; then memFull=1; fi
        if [ "$name" = cockpit ]; then starchaser satellite shell-exit >>"$LOG" 2>&1; fi
        log "$name: closed after $(( now - start ))s (exit $rc); starting it again"
        if [ "$name" = cockpit ]; then
            if [ "$memFull" -gt 0 ]; then
                log "cockpit: graphics memory may be full (EGL error 0x3003): close heavy programs or windows, or restart the computer if it keeps closing"
                if [ ! -e "$swFlag" ] && : > "$swFlag" 2>/dev/null; then
                    log "cockpit: starting it with software drawing until the next sign-in, so the taskbar keeps working"
                fi
                quiet=1
            elif [ $(( now - start )) -lt 60 ]; then
                quiet=1                        # closed within a minute of starting: no report window for the next try
            else
                quiet=0
            fi
        fi
        # a part that keeps closing right away: every restart in a row would flash the screen, so after 5 closes
        # within a minute it waits 30 seconds before the next try (it never gives up for good)
        local kept=() t
        for t in "${deaths[@]}" "$now"; do [ $(( now - t )) -lt 60 ] && kept+=("$t"); done
        deaths=("${kept[@]}")
        if [ "${#deaths[@]}" -ge 5 ]; then
            log "$name: closed 5 times within a minute; waiting 30 seconds"
            deaths=()
            wait_retry "$name" 30
        else
            wait_retry "$name" 1
        fi
    done
    log "$name: the session ended ($WHY); stopping"
}

# Does any of this account's Quickshell processes map a deleted Qt library or Quickshell itself? Shell builtins only
# (hypridle runs the refresh at every idle transition, and the exact check below starts a dozen programs). A yes here
# only lets the exact check run, which looks at the taskbar's and the menu's own instances.
any_replaced_libraries() {
    local proc_root="$1" dir comm line
    for dir in "$proc_root"/[0-9]*; do
        { read -r comm < "$dir/comm"; } 2>/dev/null || continue
        case "$comm" in qs|quickshell) ;; *) continue ;; esac
        { exec 8< "$dir/maps"; } 2>/dev/null || continue
        while IFS= read -r line <&8; do
            case "$line" in
                *" (deleted)")
                    if [[ $line =~ /(libQt[56][^/[:space:]]*\.so[^[:space:]]*|quickshell|qs|qt[56]/[^[:space:]]*\.so[^[:space:]]*)\ \(deleted\)$ ]]; then
                        exec 8<&-
                        return 0
                    fi ;;
            esac
        done
        exec 8<&-
    done
    return 1
}

# Only called at an idle transition. Package names (including the Updates page's DESKTOP group) say what was
# installed, not whether this process still uses it. A deleted executable, Qt library or Qt/QML plugin does.
refresh_after_update() {
    # Every early return here means "no reload right now", not a failure: hypridle calls this on each idle
    # transition, and a quiet no-op has to exit 0 (a bare `return` after a failed test would exit 1).
    local name cfg pid stale=0 answer listing lock real_lock clients
    local proc_root="${KEEPER_PROC_ROOT:-/proc}"
    [ -e "$RUN/starchaser-shell-idle" ] || return 0
    # almost every idle transition has nothing to reload: say so without starting a single program
    any_replaced_libraries "$proc_root" || return 0
    session_probe || return 0
    [ -e /var/lib/pacman/db.lck ] && return 0
    for name in cockpit menu; do
        cfg=$(cfg_of "$name")
        for pid in $(instance_pids "$cfg"); do
            if grep -Eq '/(libQt[56][^/[:space:]]*\.so[^[:space:]]*|quickshell|qs|qt[56]/[^[:space:]]*\.so[^[:space:]]*) \(deleted\)$' \
                    "$proc_root/$pid/maps" 2>/dev/null; then stale=1; fi
        done
    done
    [ "$stale" -eq 1 ] || return 0
    # Fail closed on missing or unreadable state. Ask every lock instance (a preview can coexist with the lock).
    pgrep -u "$(id -u)" -x hyprlock >/dev/null 2>&1 && return 0
    lock="$HOME/.config/quickshell/lock/shell.qml"
    real_lock=$(readlink -f "$lock" 2>/dev/null || echo "$lock")
    listing=$(qs list -a -j 2>/dev/null | sed -n '/^\[/,$p')
    listing=$(printf '%s\n' "$listing" | jq -er 'if type == "array" then . else error("invalid instance list") end') || return 0
    for pid in $(printf '%s\n' "$listing" | jq -r --arg a "$lock" --arg b "$real_lock" \
            '.[] | select(.config_path == $a or .config_path == $b) | .pid'); do
        answer=$(timeout 3 qs ipc --pid "$pid" call lock locked 2>/dev/null) || return 0
        [ "${answer##*$'\n'}" = false ] || return 0
    done
    clients=$(timeout 3 "${HYPRCTL:-hyprctl}" -j clients 2>/dev/null) || return 0
    printf '%s\n' "$clients" | jq -e 'type == "array" and all(.[]; (.fullscreen // 0) < 2 and (.fullscreenClient // 0) < 2)' >/dev/null 2>&1 || return 0
    for name in cockpit menu; do
        cfg=$(cfg_of "$name")
        answer=$(timeout 3 qs -p "$cfg" ipc call "$name" canReload 2>/dev/null) || return 0
        [ "${answer##*$'\n'}" = true ] || return 0
    done
    # Input may have resumed while the IPC checks were running: hypridle removes the mark on any input.
    [ -e "$RUN/starchaser-shell-idle" ] || return 0
    log "shell: loading replaced desktop libraries while idle"
    restart
}

restart() {
    local name cfg pid
    # The restart marks come first, before anything slow. toggle.sh holds a press while a mark is fresh and sends it
    # to the new menu. Super+Ctrl+R then Super+K at once (Super+K matrix case "c d0"): with the crash-reporter sweep
    # ahead of the marks (round 89, 0.2-0.6 s in a VM), the press reached the old menu, opened it, passed toggle.sh's
    # check, and then that menu was closed: nothing on screen.
    for name in cockpit menu; do
        : > "$RUN/starchaser-shell-keeper-$name.restart" 2>/dev/null
    done
    for name in cockpit menu; do
        cfg=$(cfg_of "$name")
        for pid in $(instance_pids "$cfg"); do
            qs kill --pid "$pid" >/dev/null 2>&1 || kill -TERM "$pid" 2>/dev/null
        done
    done
    # Retire a pre-merge menu keeper before closing its instance, or it would start it again.
    for pid in $(pgrep -u "$(id -u)" -f '[s]tarchaser-shell-keeper menu$'); do
        [ "$pid" = "$$" ] || kill -TERM "$pid" 2>/dev/null
    done
    for pid in $(instance_pids "$HOME/.config/quickshell/keybinds"); do
        qs kill --pid "$pid" >/dev/null 2>&1 || kill -TERM "$pid" 2>/dev/null
    done
    reap_crash_reporters
    # a session from before the keeper (or one whose keeper was stopped by hand): start it now. A keeper already
    # running exits at once and the running one restarts its part.
    setsid -f "$0" cockpit >/dev/null 2>&1 < /dev/null
    report_restart >/dev/null 2>&1 < /dev/null &
}

case "${1:-}" in
    cockpit|menu) (( $# == 1 )) || extra "$1" "$2"; keep cockpit ;;
    restart)      (( $# == 1 )) || extra "$1" "$2"; restart ;;
    refresh)      (( $# == 1 )) || extra "$1" "$2"; refresh_after_update ;;
    -h|--help|help) usage ;;
    *)            echo "starchaser shell keeper: unknown command '${1:-}'. Run 'starchaser shell keeper --help' for more help." >&2; usage >&2; exit 2 ;;
esac
