Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

22.9 KB
Raw Blame
#!/usr/bin/env bash
#
# electron-dev.sh β€” Manage Electron dev environment(s) for testing
#
# Single instance (legacy, backward compatible):
#   ./electron-dev.sh start        # CDP 9222, default userData, default Vite port
#   ./electron-dev.sh stop
#   ./electron-dev.sh status
#   ./electron-dev.sh restart
#
# Instance pool (concurrent isolated instances β€” e.g. one git worktree each):
#   ./electron-dev.sh start <id>   # CDP 9222+id, Vite 5173+id, own userData + IPC id
#   ./electron-dev.sh start <id> -- <app args>
#                                  # …and hand <app args> to the app itself, e.g.
#                                  #   start 11 -- /Users/me/code/repo   (cold start)
#   ./electron-dev.sh stop <id>    # stop ONLY instance <id> (never touches siblings)
#   ./electron-dev.sh stop --all   # stop every pool instance
#   ./electron-dev.sh status <id>
#   ./electron-dev.sh list         # list running pool instances
#
# Each pool instance <id> gets, all env-driven so instances never collide:
#   CDP port   = CDP_BASE + id   (9222 + id)
#   Vite port  = VITE_BASE + id  (5173 + id)   β†’ needs LOBE_DESKTOP_VITE_PORT support
#   userData   = $POOL_DIR/ud-<id> (login state seeded from the saved snapshot)
#   IPC id     = lobehub-desktop-dev-<cdp port> β†’ needs LOBE_IPC_ID support
#   label      = checkout name + #<id>, shown on every window (dev builds only)
# Ports, profile env, renderer readiness and login state come from the shared
# module apps/desktop/scripts/devInstance.mts (via devInstanceCli.mts), which
# other multi-checkout launchers import too β€” fix them there, not here.
# Drive each with a DISTINCT agent-browser session, else the daemon reuses one
# connection across ports:  agent-browser --session s<port> --cdp <port> ...
#
# Login persistence (so you sign in ONCE, not once per run):
#   `stop` snapshots the instance's login state into $LOGIN_STATE_DIR before it
#   wipes the userData, and `start` seeds new instances from that snapshot. The
#   app's OAuth refresh token ROTATES on every boot, so only the instance that
#   booted last holds a usable one β€” the snapshot must be re-taken each run, which
#   is exactly what `stop` does. On macOS pool instances encrypt the login with
#   Chromium's mock keychain (no keychain prompt per checkout), so they cannot
#   read the user's own dev profile: the first run signs in once inside the app.
#     ./electron-dev.sh login-status      # where the login comes from + expiry
#     ./electron-dev.sh save-login <id>   # snapshot a live instance without stopping
#   If an instance is killed instead of stopped (crash, command timeout), its
#   rotated token dies with it β€” run `save-login` before anything risky.
#
# Environment variables:
#   CDP_PORT          β€” (legacy only) CDP port (default: 9222)
#   ELECTRON_LOG      β€” (legacy only) log file path (default: /tmp/electron-dev.log)
#   CDP_BASE          β€” pool CDP base (default: 9222 β†’ instance id adds on top)
#   VITE_BASE         β€” pool Vite base (default: 5173)
#   POOL_DIR          β€” pool state dir (default: /tmp/lobe-electron-pool)
#   LOBE_LOGIN_STATE_DIR β€” persistent login snapshot, survives /tmp cleanup
#                       (default: ~/.lobehub/agent-testing/electron-login)
#   KEEP_DATA=1       β€” on `stop <id>`, keep the instance's userData dir
#   SKIP_LOGIN_SAVE=1 β€” on `stop <id>`, do not snapshot the login state
#   ELECTRON_WAIT_S   β€” max seconds to wait for CDP (default: 90)
#   RENDERER_WAIT_S   β€” max seconds to wait for the SPA (default: 60)
#   SERVER_URL        β€” `start-local` target server (default: http://localhost:3010)
#
# Local server (no OAuth, no manual sign-in):
#   ./electron-dev.sh start-local [<id>]   # pool instance (default id 1) signed in to the
#                                          # local dev server as the seeded user
#   Mints an access token with the local server's own JWKS_KEY
#   (mint-desktop-login.mjs, env from the repo-root .env) and hands it to the
#   dev build through LOBE_DESKTOP_DEV_REMOTE_LOGIN. Its login is never saved
#   into the shared snapshot, which belongs to the cloud sign-in.
#
set -euo pipefail

# Capture legacy env overrides BEFORE we clobber the same-named internals.
ENV_CDP_PORT="${CDP_PORT:-}"
ENV_ELECTRON_LOG="${ELECTRON_LOG:-}"

CMD="${1:-help}"
INSTANCE="${2:-}" # empty = legacy single instance; integer = pool member

# Everything after `start <id> --` reaches the Electron app itself: `pnpm dev`
# forwards args following `--` to the app, which is how a launch with a real
# directory argument (cold start) is exercised without a packaged build.
APP_ARGS=()
if [ "${3:-}" = "--" ]; then
  shift 3
  APP_ARGS=("$@")
fi

CDP_BASE="${CDP_BASE:-9222}"
VITE_BASE="${VITE_BASE:-5173}"
ELECTRON_WAIT_S="${ELECTRON_WAIT_S:-90}"
RENDERER_WAIT_S="${RENDERER_WAIT_S:-60}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
POOL_DIR="${POOL_DIR:-/tmp/lobe-electron-pool}"
# Persistent across runs AND across /tmp cleanup β€” the pool dir is not.
LOGIN_STATE_DIR="${LOBE_LOGIN_STATE_DIR:-$HOME/.lobehub/agent-testing/electron-login}"
DEV_INSTANCE_CLI="$PROJECT_ROOT/apps/desktop/scripts/devInstanceCli.mts"

dev_instance() {
  node "$DEV_INSTANCE_CLI" "$@"
}

# Project-scoped electron path prefix used for pgrep matching in LEGACY mode only
# (pool mode never uses it β€” it would cross instances). Any Electron binary from
# this project starts with this string in its argv[0].
PROJECT_ELECTRON_PATH="${PROJECT_ROOT}/apps/desktop/node_modules/.pnpm/electron@"

# Per-instance vars, filled by derive_instance.
POOL_MODE=0
CDP_PORT=""
VITE_PORT=""
USER_DATA_DIR=""
IPC_ID=""
INSTANCE_LABEL=""
INSTANCE_ENV=()
ELECTRON_LOG=""
PIDFILE=""

# Resolve the target instance's ports/paths from its id (empty id = legacy).
derive_instance() {
  local id="$1"
  LOCAL_LOGIN_FILE=""
  if [ -z "$id" ]; then
    POOL_MODE=0
    CDP_PORT="${ENV_CDP_PORT:-$CDP_BASE}"
    VITE_PORT="" # legacy: no override, config default applies
    USER_DATA_DIR="" # legacy: default userData
    IPC_ID="" # legacy: default IPC id
    INSTANCE_LABEL="$(dev_instance checkout-label "$PROJECT_ROOT" 2>/dev/null || true)"
    ELECTRON_LOG="${ENV_ELECTRON_LOG:-/tmp/electron-dev.log}"
    PIDFILE="/tmp/electron-dev-cdp-${CDP_PORT}.pid"
  else
    [[ "$id" =~ ^[0-9]+$ ]] || {
      echo "[electron-dev] instance id must be a non-negative integer, got: $id" >&2
      exit 1
    }
    POOL_MODE=1
    CDP_PORT=$((CDP_BASE + id))
    VITE_PORT=$((VITE_BASE + id))
    USER_DATA_DIR="$POOL_DIR/ud-$id"
    INSTANCE_LABEL="$(dev_instance checkout-label "$PROJECT_ROOT" 2>/dev/null || true) #$id"
    INSTANCE_ENV=()
    local line
    while IFS= read -r line; do
      [ -n "$line" ] && INSTANCE_ENV+=("$line")
      case "$line" in LOBE_IPC_ID=*) IPC_ID="${line#LOBE_IPC_ID=}" ;; esac
    done < <(dev_instance env --cdp-port "$CDP_PORT" --renderer-port "$VITE_PORT" \
      --user-data "$USER_DATA_DIR" --label "$INSTANCE_LABEL")
    ELECTRON_LOG="$POOL_DIR/instance-$id.log"
    PIDFILE="$POOL_DIR/instance-$id.pid"
    LOCAL_LOGIN_FILE="$POOL_DIR/instance-$id.local-login.json"
  fi
}

# ── Helpers ──────────────────────────────────────────────────────────

# Print pid + every descendant pid (DFS via pgrep -P).
expand_descendants() {
  local pid="$1"
  echo "$pid"
  local children
  children=$(pgrep -P "$pid" 2>/dev/null || true)
  for c in $children; do
    expand_descendants "$c"
  done
}

# Seed PIDs for the CURRENT instance only. Pool mode scopes strictly to this
# instance (pidfile session leader + whoever holds this instance's CDP/Vite
# ports) so stopping one instance never kills a sibling. Legacy mode additionally
# sweeps the project's Electron + dev orchestrator (to tear down a stray `bun
# run dev` the user started outside this script).
find_instance_pids() {
  local pids=""

  # 1. Launcher subshell saved by a previous `start`
  if [ -f "$PIDFILE" ]; then
    local saved_pid
    saved_pid=$(cat "$PIDFILE" 2>/dev/null || true)
    if [ -n "$saved_pid" ] && kill -0 "$saved_pid" 2>/dev/null; then
      pids="$pids $saved_pid"
    fi
  fi

  # 2. Whatever is bound to this instance's CDP port
  local port_pid
  port_pid=$(lsof -ti tcp:"$CDP_PORT" -sTCP:LISTEN 2>/dev/null || true)
  pids="$pids $port_pid"

  # 3. Whatever is bound to this instance's Vite port (pool mode)
  if [ -n "$VITE_PORT" ]; then
    local vite_pid
    vite_pid=$(lsof -ti tcp:"$VITE_PORT" -sTCP:LISTEN 2>/dev/null || true)
    pids="$pids $vite_pid"
  fi

  # 4. Legacy only: broad project matching (would cross pool instances)
  if [ "$POOL_MODE" = "0" ]; then
    pids="$pids $(pgrep -f "$PROJECT_ELECTRON_PATH" 2>/dev/null || true)"
    pids="$pids $(pgrep -f "scripts/dev\\.mjs" 2>/dev/null || true)"
  fi

  # `|| true` because `grep -v '^$'` exits 1 on all-empty input, which with
  # pipefail + set -e would silently kill the caller.
  echo "$pids" | tr ' ' '\n' | sort -u | grep -v '^$' | tr '\n' ' ' || true
}

wait_for_cdp() {
  local deadline=$(($(date +%s) + ELECTRON_WAIT_S))
  echo "[electron-dev] Waiting for CDP on port ${CDP_PORT} (up to ${ELECTRON_WAIT_S}s)..."
  while [ "$(date +%s)" -lt "$deadline" ]; do
    if curl -sf --max-time 2 "http://localhost:${CDP_PORT}/json/version" >/dev/null 2>&1; then
      echo "[electron-dev] CDP is reachable."
      return 0
    fi
    if [ -f "$PIDFILE" ]; then
      local saved_pid
      saved_pid=$(cat "$PIDFILE" 2>/dev/null || true)
      if [ -n "$saved_pid" ] && ! kill -0 "$saved_pid" 2>/dev/null; then
        echo "[electron-dev] Launcher PID $saved_pid is gone before CDP came up."
        echo "[electron-dev] Last 30 lines of $ELECTRON_LOG:"
        tail -30 "$ELECTRON_LOG" 2>/dev/null || true
        return 1
      fi
    fi
    sleep 2
  done
  echo "[electron-dev] ERROR: CDP did not respond within ${ELECTRON_WAIT_S}s"
  echo "[electron-dev] Last 30 lines of $ELECTRON_LOG:"
  tail -30 "$ELECTRON_LOG" 2>/dev/null || true
  return 1
}

wait_for_renderer() {
  # Never fatal: a slow first Vite load should not tear down a reachable app.
  dev_instance wait-renderer --cdp-port "$CDP_PORT" --timeout-s "$RENDERER_WAIT_S" || true
}

# ── Login state ──────────────────────────────────────────────────────
#
# The login-bearing subset of a userData dir, the refresh-token check and the
# install-scoped settings a copy must drop live in devInstance.mts.

# 1 when the running renderer reports a signed-in user. The OAuth refresh token
# is not the only way the app holds a session (a better-auth cookie outlives it),
# so an expired token does NOT mean the instance is signed out β€” ask the app.
probe_renderer_authed() {
  dev_instance signed-in --cdp-port "$CDP_PORT" 2>/dev/null || echo 0
}

# Persist an instance's login into the snapshot so the NEXT run starts signed in.
# The refresh token rotates on every boot, so the instance's copy is the only
# valid one by the time it stops β€” capture it before the userData is wiped.
# `authed_hint=1` (from probe_renderer_authed, taken while the app was alive)
# overrides the token check, which cannot see a cookie-only session.
save_login_state() {
  local src="$1" authed_hint="${2:-0}"
  dev_instance save-login --user-data "$src" --snapshot "$LOGIN_STATE_DIR" --signed-in "$authed_hint"
}

# Seed a fresh userData dir from the snapshot saved on the last stop. No-op if
# the dir already exists.
seed_userdata() {
  dev_instance seed-login --user-data "$1" --snapshot "$LOGIN_STATE_DIR"
}

# ── Commands ─────────────────────────────────────────────────────────

do_stop() {
  local label="legacy"
  [ "$POOL_MODE" = "1" ] && label="instance $INSTANCE (cdp $CDP_PORT)"
  echo "[electron-dev] Stopping Electron dev ($label)..."

  # Ask the still-running app whether it is signed in β€” after the kill there is
  # nothing left to ask, and the on-disk token alone can't see a cookie session.
  local authed=0
  # A start-local instance holds a minted local-server login; never snapshot it.
  local skip_save="${SKIP_LOGIN_SAVE:-0}"
  [ "$POOL_MODE" = "1" ] && [ -f "$LOCAL_LOGIN_FILE" ] && skip_save=1
  if [ "$POOL_MODE" = "1" ] && [ "$skip_save" != "1" ]; then
    authed=$(probe_renderer_authed)
  fi

  local seed_pids
  seed_pids=$(find_instance_pids)

  local all_pids=""
  local pid
  for pid in $seed_pids; do
    all_pids="$all_pids $(expand_descendants "$pid")"
  done
  all_pids=$(echo "$all_pids" | tr ' ' '\n' | sort -u | grep -v '^$' | tr '\n' ' ' || true)

  if [ -z "$all_pids" ]; then
    echo "[electron-dev] No matching Electron/vite processes found."
  else
    local count
    count=$(echo "$all_pids" | tr ' ' '\n' | grep -c .)
    echo "[electron-dev] Sending SIGTERM to $count process(es): $all_pids"
    for pid in $all_pids; do kill "$pid" 2>/dev/null || true; done

    local waited=0
    while [ $waited -lt 5 ]; do
      local any_alive=0
      for pid in $all_pids; do
        if kill -0 "$pid" 2>/dev/null; then
          any_alive=1
          break
        fi
      done
      [ "$any_alive" = "0" ] && break
      sleep 1
      waited=$((waited + 1))
    done

    for pid in $all_pids; do
      if kill -0 "$pid" 2>/dev/null; then
        echo "[electron-dev] Force-killing PID $pid"
        kill -9 "$pid" 2>/dev/null || true
      fi
    done
  fi

  # Belt-and-suspenders: free this instance's CDP port.
  local port_pid
  port_pid=$(lsof -ti tcp:"$CDP_PORT" -sTCP:LISTEN 2>/dev/null || true)
  if [ -n "$port_pid" ]; then
    echo "[electron-dev] CDP port $CDP_PORT still bound by $port_pid; force-killing"
    # shellcheck disable=SC2086
    kill -9 $port_pid 2>/dev/null || true
  fi

  # Legacy only: re-sweep stray project electron (pool mode must NOT β€” sibling-safe).
  if [ "$POOL_MODE" = "0" ]; then
    local stragglers
    stragglers=$(pgrep -f "$PROJECT_ELECTRON_PATH" 2>/dev/null || true)
    if [ -n "$stragglers" ]; then
      echo "[electron-dev] Cleaning up stragglers: $stragglers"
      for pid in $stragglers; do kill -9 "$pid" 2>/dev/null || true; done
    fi
  fi

  agent-browser --session "edev$CDP_PORT" --cdp "$CDP_PORT" close 2>/dev/null || true
  rm -f "$PIDFILE"

  # Pool mode: capture the (freshly rotated) login before touching the userData,
  # then wipe it unless asked to keep it.
  if [ "$POOL_MODE" = "1" ] && [ -n "$USER_DATA_DIR" ]; then
    [ "$skip_save" = "1" ] || save_login_state "$USER_DATA_DIR" "$authed"
    if [ "${KEEP_DATA:-0}" = "1" ]; then
      echo "[electron-dev] Keeping userData: $USER_DATA_DIR"
    else
      rm -rf "$USER_DATA_DIR"
      echo "[electron-dev] Removed userData: $USER_DATA_DIR"
    fi
    rm -f "$LOCAL_LOGIN_FILE"
  fi

  echo "[electron-dev] Stopped ($label)."
}

do_status() {
  if curl -sf --max-time 2 "http://localhost:${CDP_PORT}/json/version" >/dev/null 2>&1; then
    local url
    url=$(agent-browser --session "edev$CDP_PORT" --cdp "$CDP_PORT" get url 2>&1 | tail -1 || echo "?")
    echo "[electron-dev] CDP $CDP_PORT reachable. URL: $url"
    return 0
  fi
  echo "[electron-dev] CDP $CDP_PORT NOT reachable (not started, or still loading)."
  return 2
}

do_start() {
  if curl -sf --max-time 2 "http://localhost:${CDP_PORT}/json/version" >/dev/null 2>&1; then
    echo "[electron-dev] CDP already reachable on $CDP_PORT. Skipping start (use 'restart')."
    return 0
  fi

  # Clear stale state for THIS instance/session first.
  do_stop_quiet_for_start

  # Wait for this instance's ports to release.
  local waited=0
  while [ $waited -lt 10 ]; do
    local busy=0
    lsof -i tcp:"$CDP_PORT" >/dev/null 2>&1 && busy=1
    [ -n "$VITE_PORT" ] && lsof -i tcp:"$VITE_PORT" >/dev/null 2>&1 && busy=1
    [ "$busy" = "0" ] && break
    [ $waited -eq 0 ] && echo "[electron-dev] Waiting for ports to release..."
    sleep 1
    waited=$((waited + 1))
  done

  # Env prefix + userData seeding for pool instances.
  local env_assignments=()
  if [ "$POOL_MODE" = "1" ]; then
    mkdir -p "$POOL_DIR"
    seed_userdata "$USER_DATA_DIR"
    env_assignments=("${INSTANCE_ENV[@]}")
    # Minted here, after the pre-start stop has cleared any previous instance's files.
    if [ "${START_LOCAL:-0}" = "1" ]; then
      local env_file=()
      [ -f "$PROJECT_ROOT/.env" ] && env_file=(--env-file="$PROJECT_ROOT/.env")
      node "${env_file[@]}" "$SCRIPT_DIR/mint-desktop-login.mjs" \
        --out "$LOCAL_LOGIN_FILE" --server "${SERVER_URL:-http://localhost:3010}"
      env_assignments+=("LOBE_DESKTOP_DEV_REMOTE_LOGIN=$LOCAL_LOGIN_FILE")
    fi
  else
    env_assignments=("LOBE_DESKTOP_CDP_PORT=$CDP_PORT")
    [ -n "$INSTANCE_LABEL" ] && env_assignments+=("LOBE_DESKTOP_INSTANCE_LABEL=$INSTANCE_LABEL")
  fi

  echo "[electron-dev] Starting Electron dev..."
  echo "[electron-dev]   Project:   $PROJECT_ROOT"
  echo "[electron-dev]   CDP port:  $CDP_PORT"
  [ -n "$VITE_PORT" ] && echo "[electron-dev]   Vite port: $VITE_PORT"
  [ -n "$USER_DATA_DIR" ] && echo "[electron-dev]   userData:  $USER_DATA_DIR"
  [ -n "$IPC_ID" ] && echo "[electron-dev]   IPC id:    $IPC_ID"
  [ -n "$INSTANCE_LABEL" ] && echo "[electron-dev]   Label:     $INSTANCE_LABEL"
  echo "[electron-dev]   Log:       $ELECTRON_LOG"

  mkdir -p "$(dirname "$ELECTRON_LOG")"
  : >"$ELECTRON_LOG"

  # Values reach `env` as separate argv entries, so labels and paths with spaces
  # or quotes survive without shell re-parsing. Anything after `--` is the app's
  # own argv (`pnpm dev -- …` forwards it), which lets a launch be exercised
  # with a real directory argument.
  # shellcheck disable=SC2016 # expanded by the inner bash, not here
  local launch_cmd='cd "$1" && shift && env_args=(); while [ "$#" -gt 0 ] && [ "$1" != "--" ]; do env_args+=("$1"); shift; done; if [ "$#" -gt 0 ]; then shift; fi; exec env "${env_args[@]}" pnpm dev -- "$@"'
  local app_argv=()
  [ ${#APP_ARGS[@]} -gt 0 ] && app_argv=("--" "${APP_ARGS[@]}")

  if command -v setsid >/dev/null 2>&1; then
    setsid bash -c "$launch_cmd" electron-dev "$PROJECT_ROOT/apps/desktop" "${env_assignments[@]}" \
      ${app_argv[@]+"${app_argv[@]}"} >>"$ELECTRON_LOG" 2>&1 </dev/null &
  else
    bash -c "$launch_cmd" electron-dev "$PROJECT_ROOT/apps/desktop" "${env_assignments[@]}" \
      ${app_argv[@]+"${app_argv[@]}"} >>"$ELECTRON_LOG" 2>&1 </dev/null &
  fi
  local launcher_pid=$!
  echo "$launcher_pid" >"$PIDFILE"
  echo "[electron-dev] Launcher PID (session leader): $launcher_pid"

  if ! wait_for_cdp; then
    echo "[electron-dev] Failed to bring up CDP. Cleaning up..."
    # The app never came up, so its userData is just the seed copy β€” snapshotting it
    # would overwrite a good snapshot with an unverified (possibly rejected) token.
    SKIP_LOGIN_SAVE=1 do_stop
    return 1
  fi
  wait_for_renderer || true

  if [ "$POOL_MODE" = "1" ]; then
    echo "[electron-dev] Ready! Drive it with: agent-browser --session s$CDP_PORT --cdp $CDP_PORT snapshot -i"
  else
    echo "[electron-dev] Ready! Use: agent-browser --cdp $CDP_PORT snapshot -i"
  fi
}

# Quiet stop used at the head of start β€” never wipes userData, and never
# snapshots: a leftover userData can carry a token that a LATER run has already
# rotated away, which still looks unexpired but would overwrite a good snapshot.
do_stop_quiet_for_start() {
  KEEP_DATA=1 SKIP_LOGIN_SAVE=1 do_stop >/dev/null 2>&1 || true
}

do_restart() {
  do_stop
  sleep 1
  do_start
}

do_list() {
  echo "[electron-dev] Pool instances (dir: $POOL_DIR):"
  local found=0
  if [ -d "$POOL_DIR" ]; then
    local pf id port reach
    for pf in "$POOL_DIR"/instance-*.pid; do
      [ -e "$pf" ] || continue
      found=1
      id=$(basename "$pf" | sed -E 's/instance-([0-9]+)\.pid/\1/')
      port=$((CDP_BASE + id))
      if curl -sf --max-time 2 "http://localhost:${port}/json/version" >/dev/null 2>&1; then
        reach="UP"
      else
        reach="down"
      fi
      echo "  instance $id β†’ cdp $port [$reach], vite $((VITE_BASE + id)), ud $POOL_DIR/ud-$id"
    done
  fi
  [ "$found" = "0" ] && echo "  (none)"
}

do_login_status() {
  dev_instance login-status --snapshot "$LOGIN_STATE_DIR"
}

do_stop_all() {
  local found=0
  if [ -d "$POOL_DIR" ]; then
    local pf id
    for pf in "$POOL_DIR"/instance-*.pid; do
      [ -e "$pf" ] || continue
      found=1
      id=$(basename "$pf" | sed -E 's/instance-([0-9]+)\.pid/\1/')
      INSTANCE="$id"
      derive_instance "$id"
      do_stop
    done
  fi
  [ "$found" = "0" ] && echo "[electron-dev] No pool instances to stop."
}

# ── Main ─────────────────────────────────────────────────────────────

case "$CMD" in
  start)
    derive_instance "$INSTANCE"
    do_start
    ;;
  start-local)
    derive_instance "${INSTANCE:-1}"
    if [ "$POOL_MODE" != "1" ]; then
      echo "[electron-dev] start-local needs a pool instance (it never touches your own profile)."
      exit 1
    fi
    START_LOCAL=1 do_start
    ;;
  stop)
    if [ "$INSTANCE" = "--all" ]; then
      do_stop_all
    else
      derive_instance "$INSTANCE"
      do_stop
    fi
    ;;
  status)
    derive_instance "$INSTANCE"
    do_status
    ;;
  restart)
    derive_instance "$INSTANCE"
    do_restart
    ;;
  list)
    do_list
    ;;
  save-login)
    derive_instance "$INSTANCE"
    if [ "$POOL_MODE" != "1" ]; then
      echo "[electron-dev] save-login needs a pool instance id (its userData dir)."
      exit 1
    fi
    save_login_state "$USER_DATA_DIR" "$(probe_renderer_authed)"
    ;;
  login-status)
    do_login_status
    ;;
  *)
    echo "Usage: $0 {start|stop|status|restart} [<id>]   |   $0 stop --all   |   $0 list"
    echo "       $0 save-login <id>   |   $0 login-status   |   $0 start-local [<id>]"
    echo ""
    echo "  start [<id>]      β€” Start an instance. No id = legacy single instance (CDP 9222)."
    echo "                      <id> = pool member: CDP 9222+id, Vite 5173+id, own userData"
    echo "                      (login seeded from the saved snapshot) + IPC id."
    echo "                      start <id> -- <app args> forwards args to the app"
    echo "  start-local [<id>] β€” Start pool instance <id> (default 1) signed in to the local dev"
    echo "                      server (SERVER_URL, default http://localhost:3010) as the seeded"
    echo "                      user. No OAuth; the login is never saved to the snapshot."
    echo "  stop [<id>]       β€” Stop an instance. Pool stop is sibling-safe, and snapshots the"
    echo "                      instance's login first. KEEP_DATA=1 preserves the userData;"
    echo "                      SKIP_LOGIN_SAVE=1 skips the snapshot."
    echo "  stop --all        β€” Stop every pool instance."
    echo "  status [<id>]     β€” Check whether the instance's CDP is reachable."
    echo "  restart [<id>]    β€” Stop then start."
    echo "  list              β€” List pool instances and their CDP reachability."
    echo "  save-login <id>   β€” Snapshot a live instance's login without stopping it."
    echo "  login-status      β€” Show which source will seed the next instance, and its expiry."
    exit 1
    ;;
esac