#!/usr/bin/env bash set -euo pipefail ROOT="${LLM_REPRO_ROOT:-/mnt/DATA/git/llm-repro-ui}" PYTHON="${PYTHON:-$ROOT/.venv/bin/python}" HOST="${LLM_REPRO_HOST:-127.0.0.1}" PORT="${LLM_REPRO_PORT:-8501}" OPEN_BROWSER="${OPEN_BROWSER:-1}" LOG_DIR="$ROOT/runs/dev-launcher" SERVER_LOG="$LOG_DIR/streamlit.log" URL="http://$HOST:$PORT" server_pid="" fail() { printf 'launch-dev: %s\n' "$*" >&2 exit 1 } port_is_free() { "$PYTHON" - "$1" "$2" <<'PY' import socket import sys host = sys.argv[1] port = int(sys.argv[2]) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: sock.bind((host, port)) except OSError: raise SystemExit(1) PY } wait_for_url() { "$PYTHON" - "$1" <<'PY' import sys import time import urllib.request url = sys.argv[1] deadline = time.monotonic() + 60 last_error = None while time.monotonic() < deadline: try: with urllib.request.urlopen(url, timeout=2) as response: if 200 <= response.status < 500: raise SystemExit(0) except Exception as exc: # noqa: BLE001 - printed only on timeout. last_error = exc time.sleep(1) print(f"Timed out waiting for {url}: {last_error}", file=sys.stderr) raise SystemExit(1) PY } cleanup() { if [ -n "${server_pid:-}" ] && kill -0 "$server_pid" 2>/dev/null; then kill "$server_pid" 2>/dev/null || true fi } trap cleanup EXIT INT TERM [ -x "$PYTHON" ] || fail "Python virtualenv not found at $PYTHON. Run: cd $ROOT && python -m venv .venv && . .venv/bin/activate && pip install -r requirements.txt" mkdir -p "$LOG_DIR" : > "$SERVER_LOG" port_is_free "$HOST" "$PORT" || fail "$URL is already in use" if [ -z "${OPENAI_API_KEY:-}" ] && { [ ! -f "$ROOT/.env" ] || ! grep -q '^OPENAI_API_KEY=sk-' "$ROOT/.env"; }; then printf 'Warning: OPENAI_API_KEY is not set in the environment or .env. The UI will start, but API calls need a key.\n' >&2 fi printf 'Starting LLM Reproducibility Harness at %s\n' "$URL" ( cd "$ROOT" "$PYTHON" -m streamlit run app.py \ --server.address "$HOST" \ --server.port "$PORT" \ --server.headless true ) >"$SERVER_LOG" 2>&1 & server_pid="$!" printf 'Waiting for %s\n' "$URL" wait_for_url "$URL" || { tail -n 80 "$SERVER_LOG" >&2 || true fail "Streamlit did not become reachable" } if [ "$OPEN_BROWSER" = "1" ] && command -v xdg-open >/dev/null 2>&1; then xdg-open "$URL" >/dev/null 2>&1 || true fi cat <