From 48250813d9b2e584d77e154951fc304b4dea4d6c Mon Sep 17 00:00:00 2001 From: Serg Dort Date: Sun, 8 Mar 2026 22:41:33 +0000 Subject: [PATCH 1/3] feat(cli): add web daemon supervisor controls --- .agents/notes.md | 2 + .env.example | 2 +- AGENTS.md | 16 +- README.md | 13 +- apps/cli/src/cli.ts | 186 ++++-- apps/cli/src/error.ts | 10 + apps/cli/src/web.ts | 1213 +++++++++++++++++++++++++++++++++++++ apps/cli/test/web.test.ts | 400 ++++++++++++ docs/CLI_REFERENCE.md | 24 +- 9 files changed, 1807 insertions(+), 59 deletions(-) create mode 100644 apps/cli/src/error.ts create mode 100644 apps/cli/src/web.ts create mode 100644 apps/cli/test/web.test.ts diff --git a/.agents/notes.md b/.agents/notes.md index 249d058..f671cbe 100644 --- a/.agents/notes.md +++ b/.agents/notes.md @@ -51,3 +51,5 @@ [0] Drizzle SQLite migrator runs migrations in a transaction; `PRAGMA foreign_keys=OFF` inside migration SQL may not disable FK checks. Table-copy migrations should filter/clean orphan rows explicitly (e.g., `INNER JOIN` parents) instead of relying on that pragma. [0] CI `validate` workflow currently runs `format:check`, `lint`, `test`, and `apps/web` build. Before pushing, run all four locally to avoid fast-follow CI fix commits. [0] `stash db doctor` does not create parent directories for a missing DB path; if `STASH_DB_PATH` points to a non-existent directory, command can fail with `unable to open database file`. +[0] Prefer explicit named types over `ReturnType` in production code/tests for readability and easier review comments. +[0] `tithe web` parity means flag-based daemon controls (`--daemon`, `--status`, `--stop`), not `start`/`stop` subcommands; mirror that CLI shape when porting its web supervisor flow into `stash`. diff --git a/.env.example b/.env.example index 50e0bf4..ae96db0 100644 --- a/.env.example +++ b/.env.example @@ -1,7 +1,7 @@ STASH_DB_PATH=~/.stash/stash.db # Optional: # STASH_AUDIO_DIR=~/.stash/audio -# STASH_WEB_HOST=127.0.0.1 +# STASH_WEB_HOST=0.0.0.0 # STASH_API_PORT=4173 # STASH_PWA_PORT=5173 # STASH_AUTO_TAGS_ENABLED=true diff --git a/AGENTS.md b/AGENTS.md index c6b698b..0b1089d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -107,7 +107,8 @@ pnpm exec playwright install chromium ``` Web server defaults (overridable in `.env` or CLI flags): -- `STASH_WEB_HOST=127.0.0.1` +- `STASH_WEB_HOST=0.0.0.0` is the recommended daemon/Tailnet-friendly override. +- When `STASH_WEB_HOST` is unset, foreground `stash web` defaults to `127.0.0.1` and `stash web --daemon` defaults to `0.0.0.0`. - `STASH_API_PORT=4173` - `STASH_PWA_PORT=5173` @@ -332,8 +333,17 @@ Updates should include: - Auto-tags env controls: - `STASH_AUTO_TAGS_ENABLED`, `STASH_AUTO_TAGS_MAX`, `STASH_AUTO_TAGS_MIN_SCORE` - `STASH_AUTO_TAGS_MODEL`, `STASH_AUTO_TAGS_BACKEND`, `STASH_AUTO_TAGS_PYTHON`, `STASH_AUTO_TAGS_HELPER` -- `stash web` now accepts `--host`, `--api-port`, `--pwa-port` (`--port` removed). -- `stash web` runs split listeners (API + PWA) and fails fast on port conflicts or identical API/PWA ports. +- `stash web` now supports foreground and daemon control flags: + - `stash web` / `stash web --foreground` run attached in the current terminal. + - `stash web --daemon` starts a detached supervisor that restarts the combined web runner on unexpected exit. + - `stash web --status` reads daemon state/log metadata. + - `stash web --stop` sends `SIGTERM` to the daemon supervisor and waits for shutdown. +- `stash web` accepts `--host`, `--api-port`, `--pwa-port`; `--status`/`--stop` reject host/port overrides. +- `stash web --daemon` is idempotent for agent callers: a second start returns the existing daemon state instead of failing. +- `stash web` keeps API + PWA in one runtime process; the daemon supervises that single runner rather than separate API/PWA children. +- `stash web` persists daemon files under `~/.stash/` with workspace fallback `.stash/` (`web-daemon.pid`, `web-daemon.log`, `web-daemon.state.json`). +- `stash web` startup/status output includes local URLs and best-effort Tailnet URLs from `tailscale status --json`; loopback binds warn that Tailnet access is unavailable. +- `stash web` still fails fast on identical API/PWA ports. - Web dev (`apps/web` Vite) reads the same root `.env` port variables and uses strict port binding. - `pnpm run dev:stack` starts API (`pnpm run dev:api`, default API port `4173`) and Vite HMR (`pnpm run dev:web`, default `5173`) together for frontend hot reload. - Web UI uses a single mobile-first, single-column layout path across all viewport sizes; desktop split-pane rendering paths were intentionally removed. diff --git a/README.md b/README.md index d3741d1..929c1ed 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ Web UI behavior: You can configure these via `.env`: ```bash -STASH_WEB_HOST=127.0.0.1 +STASH_WEB_HOST=0.0.0.0 STASH_API_PORT=4173 STASH_PWA_PORT=5173 ``` @@ -63,8 +63,19 @@ Or override at runtime: ```bash stash web --host 127.0.0.1 --api-port 4173 --pwa-port 5173 +stash web --daemon --host 0.0.0.0 --api-port 4173 --pwa-port 5173 +stash --json web --status +stash --json web --stop ``` +Runtime notes: +- `stash web` runs in the foreground by default; `stash web --foreground` is an explicit alias. +- `stash web --daemon` starts a detached supervisor that restarts the combined web runner if it crashes or is killed unexpectedly. +- `stash web --status` and `stash web --stop` mirror the `tithe` control flow and cannot be combined with host/port overrides. +- daemon state lives under `~/.stash/` with workspace fallback `.stash/` (`web-daemon.pid`, `web-daemon.log`, `web-daemon.state.json`). +- daemon startup/status output includes localhost URLs plus best-effort Tailnet URLs from `tailscale status --json`. +- when `STASH_WEB_HOST` is unset, foreground `stash web` defaults to `127.0.0.1`; daemon mode defaults to `0.0.0.0` for remote/Tailnet access. + ### Web Development (Vite HMR) Use this for frontend hot reloading: diff --git a/apps/cli/src/cli.ts b/apps/cli/src/cli.ts index 387c2dc..9cd914d 100644 --- a/apps/cli/src/cli.ts +++ b/apps/cli/src/cli.ts @@ -16,6 +16,8 @@ import { runMigrations, type StashItem as CoreStashItem, } from "@stash/core" +import { CliError } from "./error.js" +import { runWebCommand, runWebRunnerCommand, runWebSupervisorCommand } from "./web.js" const CLI_DIR = path.dirname(fileURLToPath(import.meta.url)) const DEFAULT_MIGRATIONS_DIR = resolveExistingPath([ @@ -28,7 +30,6 @@ const DEFAULT_WEB_DIST_DIR = resolveExistingPath([ path.resolve(CLI_DIR, "../../../../apps/web/dist"), path.resolve(process.cwd(), "apps/web/dist"), ]) -const DEFAULT_WEB_HOST = process.env.STASH_WEB_HOST ?? "127.0.0.1" const DEFAULT_API_PORT = process.env.STASH_API_PORT ? parsePort(process.env.STASH_API_PORT) : 4173 const DEFAULT_PWA_PORT = process.env.STASH_PWA_PORT ? parsePort(process.env.STASH_PWA_PORT) : 5173 const DEFAULT_TTS_VOICE = "tts_models/en/vctk/vits|p241" // Coqui male voice @@ -68,17 +69,6 @@ type StartedWebStack = { type StartWebStackFn = (options: StartWebStackOptions) => Promise -class CliError extends Error { - code: string - exitCode: number - - constructor(message: string, code: string, exitCode: number) { - super(message) - this.code = code - this.exitCode = exitCode - } -} - function parsePositiveInt(value: string): number { const parsed = Number.parseInt(value, 10) if (!Number.isInteger(parsed) || parsed < 1) { @@ -315,7 +305,7 @@ Quick Reference: stash tts status [--json] stash tts doctor [--json] stash jobs worker [--poll-ms ] [--once] [--json] - stash web [--host ] [--api-port ] [--pwa-port ] + stash web [--daemon|--foreground|--status|--stop] [--host ] [--api-port ] [--pwa-port ] [--json] stash db migrate [--json] [--migrations-dir ] stash db doctor [--json] [--migrations-dir ] [--limit ] @@ -1067,51 +1057,143 @@ jobsCommand program .command("web") .description("Run local web frontend (PWA) + REST API servers") - .option("--host ", "Host to bind API and PWA servers", DEFAULT_WEB_HOST) - .option("--api-port ", "Port to bind API server", parsePort, DEFAULT_API_PORT) - .option("--pwa-port ", "Port to bind PWA server", parsePort, DEFAULT_PWA_PORT) - .action(async (options: { host: string; apiPort: number; pwaPort: number }) => { - return runDbAction(false, async () => { - if (options.apiPort === options.pwaPort) { - throw new CliError("API and PWA ports must be different.", "VALIDATION_ERROR", 2) - } - - const dbPath = resolveDbPath(program.opts().dbPath as string) - const migrationsDir = resolveMigrationsDir() - const startWebStack = await loadStartWebStack() - const web = await startWebStack({ - host: options.host, - apiPort: options.apiPort, - pwaPort: options.pwaPort, - dbPath, - migrationsDir, - webDistDir: DEFAULT_WEB_DIST_DIR, - audioDir: resolveAudioDir(process.env.STASH_AUDIO_DIR ?? DEFAULT_AUDIO_DIR), + .option("--host ", "Host to bind API and PWA servers") + .option("--api-port ", "Port to bind API server", parsePort) + .option("--pwa-port ", "Port to bind PWA server", parsePort) + .option("--daemon", "Run in background daemon mode with auto-restart") + .option("--status", "Show background web daemon status") + .option("--stop", "Stop background web daemon") + .option("--foreground", "Run in the foreground even when daemon controls are available") + .option("--json", "Print machine-readable JSON output") + .action( + async (options: { + host?: string + apiPort?: number + pwaPort?: number + daemon?: boolean + status?: boolean + stop?: boolean + foreground?: boolean + json?: boolean + }) => { + const jsonMode = Boolean(options.json) + return runDbAction(jsonMode, async () => { + await runWebCommand( + { + host: options.host, + apiPort: options.apiPort, + pwaPort: options.pwaPort, + daemon: options.daemon, + status: options.status, + stop: options.stop, + foreground: options.foreground, + }, + { + json: jsonMode, + dbPath: resolveDbPath(program.opts().dbPath as string), + migrationsDir: resolveMigrationsDir(), + webDistDir: DEFAULT_WEB_DIST_DIR, + audioDir: resolveAudioDir(process.env.STASH_AUDIO_DIR ?? DEFAULT_AUDIO_DIR), + defaultApiPort: DEFAULT_API_PORT, + defaultPwaPort: DEFAULT_PWA_PORT, + envHost: process.env.STASH_WEB_HOST, + loadStartWebStack, + }, + ) }) + }, + ) + +program + .command("web-supervisor") + .description("Internal daemon supervisor for stash web --daemon") + .option("--host ", "Host to bind API and PWA servers") + .option("--api-port ", "Port to bind API server", parsePort) + .option("--pwa-port ", "Port to bind PWA server", parsePort) + .requiredOption("--db-path ", "Path to SQLite database file") + .requiredOption("--migrations-dir ", "Path to migrations directory") + .requiredOption("--web-dist-dir ", "Path to built web assets") + .requiredOption("--audio-dir ", "Path to generated audio directory") + .option("--run-id ", "Daemon run identifier") + .action( + async (options: { + host?: string + apiPort?: number + pwaPort?: number + dbPath: string + migrationsDir: string + webDistDir: string + audioDir: string + runId?: string + }) => { + return runDbAction(false, async () => { + if (!options.host || options.apiPort === undefined || options.pwaPort === undefined) { + throw new CliError( + "web-supervisor requires --host, --api-port, and --pwa-port.", + "VALIDATION_ERROR", + 2, + ) + } - process.stdout.write(`stash web running\n`) - process.stdout.write(`API: http://${web.api.host}:${web.api.port}\n`) - process.stdout.write(`PWA: http://${web.pwa.host}:${web.pwa.port}\n`) + await runWebSupervisorCommand({ + host: options.host, + apiPort: options.apiPort, + pwaPort: options.pwaPort, + dbPath: options.dbPath, + migrationsDir: options.migrationsDir, + webDistDir: options.webDistDir, + audioDir: options.audioDir, + runId: options.runId, + }) + }) + }, + ) - await new Promise((resolve) => { - const stop = (): void => { - web - .close() - .catch(() => { - // Ignore shutdown errors during signal handling. - }) - .finally(() => { - process.off("SIGINT", stop) - process.off("SIGTERM", stop) - resolve() - }) +program + .command("web-runner") + .description("Internal daemon worker for stash web --daemon") + .option("--host ", "Host to bind API and PWA servers") + .option("--api-port ", "Port to bind API server", parsePort) + .option("--pwa-port ", "Port to bind PWA server", parsePort) + .requiredOption("--db-path ", "Path to SQLite database file") + .requiredOption("--migrations-dir ", "Path to migrations directory") + .requiredOption("--web-dist-dir ", "Path to built web assets") + .requiredOption("--audio-dir ", "Path to generated audio directory") + .action( + async (options: { + host?: string + apiPort?: number + pwaPort?: number + dbPath: string + migrationsDir: string + webDistDir: string + audioDir: string + }) => { + return runDbAction(false, async () => { + if (!options.host || options.apiPort === undefined || options.pwaPort === undefined) { + throw new CliError( + "web-runner requires --host, --api-port, and --pwa-port.", + "VALIDATION_ERROR", + 2, + ) } - process.on("SIGINT", stop) - process.on("SIGTERM", stop) + await runWebRunnerCommand( + { + host: options.host, + apiPort: options.apiPort, + pwaPort: options.pwaPort, + dbPath: options.dbPath, + migrationsDir: options.migrationsDir, + webDistDir: options.webDistDir, + audioDir: options.audioDir, + runId: undefined, + }, + loadStartWebStack, + ) }) - }) - }) + }, + ) program .command("read ") diff --git a/apps/cli/src/error.ts b/apps/cli/src/error.ts new file mode 100644 index 0000000..663d4d1 --- /dev/null +++ b/apps/cli/src/error.ts @@ -0,0 +1,10 @@ +export class CliError extends Error { + code: string + exitCode: number + + constructor(message: string, code: string, exitCode: number) { + super(message) + this.code = code + this.exitCode = exitCode + } +} diff --git a/apps/cli/src/web.ts b/apps/cli/src/web.ts new file mode 100644 index 0000000..c030346 --- /dev/null +++ b/apps/cli/src/web.ts @@ -0,0 +1,1213 @@ +import { type ChildProcess, spawn, spawnSync } from "node:child_process" +import { randomUUID } from "node:crypto" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { fileURLToPath } from "node:url" + +import { CliError } from "./error.js" + +const WEB_DAEMON_SHUTDOWN_TIMEOUT_MS = 10_000 +const WEB_DAEMON_STATUS_POLL_MS = 200 +const WEB_RESTART_BACKOFF_BASE_MS = 1_000 +const WEB_RESTART_BACKOFF_MAX_MS = 30_000 +const WEB_RESTART_STABLE_WINDOW_MS = 60_000 +const TAILSCALE_STATUS_TIMEOUT_MS = 2_000 + +const modulePath = fileURLToPath(import.meta.url) +const workspaceRoot = path.resolve(path.dirname(modulePath), "../../..") + +type DaemonLifecycleStatus = + | "starting" + | "running" + | "degraded" + | "stopping" + | "stopped" + | "crashed" + +type StartWebStackOptions = { + host: string + apiPort: number + pwaPort: number + dbPath: string + migrationsDir: string + webDistDir: string + audioDir?: string +} + +type StartedWebStack = { + api: { host: string; port: number } + pwa: { host: string; port: number } + close: () => Promise +} + +type StartWebStackFn = (options: StartWebStackOptions) => Promise + +export type WebCommandOptions = { + host: string | undefined + apiPort: number | undefined + pwaPort: number | undefined + daemon: boolean | undefined + status: boolean | undefined + stop: boolean | undefined + foreground: boolean | undefined +} + +export type WebInternalCommandOptions = { + host: string + apiPort: number + pwaPort: number + dbPath: string + migrationsDir: string + webDistDir: string + audioDir: string + runId: string | undefined +} + +export type RunWebCommandContext = { + json: boolean + dbPath: string + migrationsDir: string + webDistDir: string + audioDir: string + defaultApiPort: number + defaultPwaPort: number + envHost: string | undefined + loadStartWebStack: () => Promise +} + +type ResolvedWebRuntime = { + host: string + apiPort: number + pwaPort: number + dbPath: string + migrationsDir: string + webDistDir: string + audioDir: string +} + +type WebAccessInfo = { + bind: { + host: string + apiPort: number + pwaPort: number + } + local: { + apiUrl: string + pwaUrl: string + } + tailnet: { + host: string | undefined + apiUrl: string | undefined + pwaUrl: string | undefined + } + warning: string | undefined +} + +type WebDaemonServiceState = { + pid: number | undefined + restartCount: number + lastStartAt: string | undefined + lastExitAt: string | undefined + lastExit: + | { + code: number | null + signal: NodeJS.Signals | null + } + | undefined +} + +type WebDaemonState = { + version: 1 + runId: string + pid: number + lifecycle: "daemon" + workspaceRoot: string + startedAt: string + updatedAt: string + status: DaemonLifecycleStatus + logFile: string + access: WebAccessInfo + lastEvent?: string + service: WebDaemonServiceState +} + +type WebDaemonStatus = { + running: boolean + pid: number | undefined + pidFile: string + logFile: string + stateFile: string + state: WebDaemonState | undefined +} + +type DaemonPaths = { + dir: string + pidFile: string + logFile: string + stateFile: string +} + +type RunWebStackOutputMode = "foreground" | "runner" + +type RunnerLifecycleContext = { + runtime: ResolvedWebRuntime + access: WebAccessInfo +} + +type SupervisorServiceRuntime = { + restartCount: number + failureStreak: number + child: ChildProcess | undefined + startedAtMs: number | undefined +} + +const nowIso = (): string => new Date().toISOString() + +const printJson = (value: unknown): void => { + process.stdout.write(`${JSON.stringify(value, null, 2)}\n`) +} + +const trimTrailingDot = (value: string): string => value.replace(/\.$/, "") + +const buildUrl = (host: string, port: number): string => `http://${host}:${port}` + +const formatExit = (code: number | null, signal: NodeJS.Signals | null): string => { + if (signal) { + return `with signal ${signal}` + } + if (code === null) { + return "without an exit code" + } + return `with code ${code}` +} + +const daemonDirCandidates = (): string[] => { + const overrideDir = process.env.STASH_WEB_DAEMON_DIR?.trim() + const candidates = overrideDir + ? [path.resolve(overrideDir)] + : [path.join(os.homedir(), ".stash"), path.join(workspaceRoot, ".stash")] + + return [...new Set(candidates)] +} + +const buildDaemonPaths = (dir: string): DaemonPaths => ({ + dir, + pidFile: path.join(dir, "web-daemon.pid"), + logFile: path.join(dir, "web-daemon.log"), + stateFile: path.join(dir, "web-daemon.state.json"), +}) + +const hasDaemonStateFile = (paths: DaemonPaths): boolean => + fs.existsSync(paths.pidFile) || fs.existsSync(paths.stateFile) + +const ensureDirWritable = (dir: string): boolean => { + try { + fs.mkdirSync(dir, { recursive: true }) + fs.accessSync(dir, fs.constants.W_OK) + return true + } catch { + return false + } +} + +const resolveDaemonPaths = (mode: "read" | "write"): DaemonPaths => { + const candidates = daemonDirCandidates().map(buildDaemonPaths) + const existing = candidates.find((candidate) => hasDaemonStateFile(candidate)) + if (existing) { + return existing + } + + if (mode === "read") { + return candidates[0] as DaemonPaths + } + + const writable = candidates.find((candidate) => ensureDirWritable(candidate.dir)) + return writable ?? (candidates[0] as DaemonPaths) +} + +let cachedDaemonPaths: DaemonPaths | undefined + +const getDaemonPaths = (mode: "read" | "write" = "read"): DaemonPaths => { + if (cachedDaemonPaths) { + if (mode === "read") { + return cachedDaemonPaths + } + + if (ensureDirWritable(cachedDaemonPaths.dir)) { + return cachedDaemonPaths + } + } + + const resolved = resolveDaemonPaths(mode) + cachedDaemonPaths = resolved + return resolved +} + +const ensureDaemonDir = (): void => { + const paths = getDaemonPaths("write") + fs.mkdirSync(paths.dir, { recursive: true }) +} + +const writeJsonFile = (filePath: string, value: unknown): void => { + ensureDaemonDir() + const tempFile = `${filePath}.${process.pid}.${Date.now()}.tmp` + const serialized = JSON.stringify(value, null, 2) + fs.writeFileSync(tempFile, serialized) + + try { + if (process.platform === "win32" && fs.existsSync(filePath)) { + fs.unlinkSync(filePath) + } + fs.renameSync(tempFile, filePath) + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (process.platform === "win32" && (code === "EEXIST" || code === "EPERM")) { + fs.writeFileSync(filePath, serialized) + return + } + throw error + } finally { + if (fs.existsSync(tempFile)) { + fs.unlinkSync(tempFile) + } + } +} + +const readJsonFile = (filePath: string): T | undefined => { + try { + return JSON.parse(fs.readFileSync(filePath, "utf8")) as T + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (code === "ENOENT") { + return undefined + } + return undefined + } +} + +const readDaemonPid = (): number | undefined => { + try { + const raw = fs.readFileSync(getDaemonPaths("read").pidFile, "utf8").trim() + const pid = Number(raw) + if (!Number.isInteger(pid) || pid < 1) { + return undefined + } + return pid + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (code === "ENOENT") { + return undefined + } + return undefined + } +} + +const writeDaemonPid = (pid: number): void => { + ensureDaemonDir() + fs.writeFileSync(getDaemonPaths("write").pidFile, `${pid}\n`) +} + +const removeDaemonPidFile = (): void => { + try { + fs.unlinkSync(getDaemonPaths("read").pidFile) + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (code !== "ENOENT") { + throw error + } + } +} + +const isPidRunning = (pid: number): boolean => { + try { + process.kill(pid, 0) + return true + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (code === "ESRCH") { + return false + } + if (code === "EPERM") { + return true + } + return false + } +} + +const loadDaemonState = (): WebDaemonState | undefined => + readJsonFile(getDaemonPaths("read").stateFile) + +const persistDaemonState = (state: WebDaemonState): void => { + state.updatedAt = nowIso() + writeJsonFile(getDaemonPaths("write").stateFile, state) +} + +const isLoopbackHost = (host: string): boolean => { + const normalized = host.trim().toLowerCase() + return ( + normalized === "localhost" || + normalized === "127.0.0.1" || + normalized.startsWith("127.") || + normalized === "::1" || + normalized === "[::1]" + ) +} + +const resolveWebAccessInfo = (host: string, apiPort: number, pwaPort: number): WebAccessInfo => { + const local = { + apiUrl: buildUrl("127.0.0.1", apiPort), + pwaUrl: buildUrl("127.0.0.1", pwaPort), + } + + if (isLoopbackHost(host)) { + return { + bind: { host, apiPort, pwaPort }, + local, + tailnet: { + host: undefined, + apiUrl: undefined, + pwaUrl: undefined, + }, + warning: `Web stack is bound to ${host}; Tailnet access is unavailable unless you start it with --host 0.0.0.0.`, + } + } + + const tailscaleCli = process.env.STASH_TAILSCALE_CLI?.trim() || "tailscale" + const status = spawnSync(tailscaleCli, ["status", "--json"], { + encoding: "utf8", + timeout: TAILSCALE_STATUS_TIMEOUT_MS, + }) + + if (status.error) { + const error = status.error as NodeJS.ErrnoException + return { + bind: { host, apiPort, pwaPort }, + local, + tailnet: { + host: undefined, + apiUrl: undefined, + pwaUrl: undefined, + }, + warning: + error.code === "ENOENT" + ? "Tailscale CLI not found; Tailnet URLs are unavailable." + : `Failed to query Tailscale status: ${error.message}`, + } + } + + if (status.signal) { + return { + bind: { host, apiPort, pwaPort }, + local, + tailnet: { + host: undefined, + apiUrl: undefined, + pwaUrl: undefined, + }, + warning: `Tailscale status command timed out after ${TAILSCALE_STATUS_TIMEOUT_MS}ms.`, + } + } + + if (status.status !== 0) { + const stderr = status.stderr?.trim() + return { + bind: { host, apiPort, pwaPort }, + local, + tailnet: { + host: undefined, + apiUrl: undefined, + pwaUrl: undefined, + }, + warning: stderr + ? `Tailscale status unavailable: ${stderr}` + : "Tailscale status unavailable; Tailnet URLs are unavailable.", + } + } + + try { + const parsed = JSON.parse(status.stdout) as Record + const self = parsed.Self as Record | undefined + const backendState = + typeof parsed.BackendState === "string" ? (parsed.BackendState as string) : undefined + const dnsName = + typeof self?.DNSName === "string" ? trimTrailingDot(self.DNSName as string) : undefined + const hostName = typeof self?.HostName === "string" ? self.HostName.trim() : "" + const magicSuffix = + typeof parsed.MagicDNSSuffix === "string" ? trimTrailingDot(parsed.MagicDNSSuffix.trim()) : "" + const tailscaleIps = Array.isArray(self?.TailscaleIPs) + ? self.TailscaleIPs.filter( + (value): value is string => typeof value === "string" && value.trim().length > 0, + ) + : [] + const tailnetHost = + dnsName || + (hostName && magicSuffix ? `${hostName}.${magicSuffix}` : undefined) || + tailscaleIps[0] + + let warning: string | undefined + if (!tailnetHost) { + warning = "Tailscale is available, but no Tailnet hostname or IP was detected." + } else if (backendState && backendState !== "Running") { + warning = `Tailscale backend state is ${backendState}; Tailnet access may be unavailable.` + } + + return { + bind: { host, apiPort, pwaPort }, + local, + tailnet: { + host: tailnetHost, + apiUrl: tailnetHost ? buildUrl(tailnetHost, apiPort) : undefined, + pwaUrl: tailnetHost ? buildUrl(tailnetHost, pwaPort) : undefined, + }, + warning, + } + } catch { + return { + bind: { host, apiPort, pwaPort }, + local, + tailnet: { + host: undefined, + apiUrl: undefined, + pwaUrl: undefined, + }, + warning: "Failed to parse Tailscale status JSON; Tailnet URLs are unavailable.", + } + } +} + +const createDaemonState = ( + _runtime: ResolvedWebRuntime, + runId: string, + pid: number, + access: WebAccessInfo, +): WebDaemonState => ({ + version: 1, + runId, + pid, + lifecycle: "daemon", + workspaceRoot, + startedAt: nowIso(), + updatedAt: nowIso(), + status: "starting", + logFile: getDaemonPaths("write").logFile, + access, + service: { + pid: undefined, + restartCount: 0, + lastStartAt: undefined, + lastExitAt: undefined, + lastExit: undefined, + }, +}) + +const resolveCliEntryPath = (): string => { + if (process.argv[1]) { + return process.argv[1] + } + + const extension = path.extname(modulePath) + return path.resolve(path.dirname(modulePath), extension === ".ts" ? "cli.ts" : "cli.js") +} + +const readWebDaemonStatus = (): WebDaemonStatus => { + const paths = getDaemonPaths("read") + const state = loadDaemonState() + const pidFromFile = readDaemonPid() + const pid = pidFromFile ?? state?.pid + const running = pid !== undefined ? isPidRunning(pid) : false + + if (pidFromFile !== undefined && !running) { + removeDaemonPidFile() + } + + return { + running, + pid: running ? pid : undefined, + pidFile: paths.pidFile, + logFile: paths.logFile, + stateFile: paths.stateFile, + state, + } +} + +const sleep = async (ms: number): Promise => { + await new Promise((resolve) => { + setTimeout(resolve, ms) + }) +} + +const emitAccessSummary = (access: WebAccessInfo): void => { + process.stdout.write(`PWA local: ${access.local.pwaUrl}\n`) + process.stdout.write(`API local: ${access.local.apiUrl}\n`) + if (access.tailnet.pwaUrl) { + process.stdout.write(`PWA tailnet: ${access.tailnet.pwaUrl}\n`) + } + if (access.tailnet.apiUrl) { + process.stdout.write(`API tailnet: ${access.tailnet.apiUrl}\n`) + } + if (access.warning) { + process.stderr.write(`Warning: ${access.warning}\n`) + } +} + +const buildDaemonPayload = ( + daemon: WebDaemonStatus, + extra: Record = {}, +): Record => ({ + ok: true, + command: "web", + lifecycle: "daemon", + daemon, + ...extra, +}) + +const emitDaemonStartResult = ( + daemon: WebDaemonStatus, + alreadyRunning: boolean, + jsonMode: boolean, +): void => { + if (jsonMode) { + printJson( + buildDaemonPayload(daemon, { + already_running: alreadyRunning, + access: daemon.state?.access ?? null, + }), + ) + return + } + + if (alreadyRunning) { + process.stdout.write(`Web daemon is already running (pid ${String(daemon.pid)}).\n`) + } else { + process.stdout.write(`Started web daemon (pid ${String(daemon.pid)}).\n`) + } + process.stdout.write(`State file: ${daemon.stateFile}\n`) + process.stdout.write(`Log file: ${daemon.logFile}\n`) + if (daemon.state?.access) { + emitAccessSummary(daemon.state.access) + } + process.stdout.write("Status: stash --json web --status\n") + process.stdout.write("Stop: stash --json web --stop\n") +} + +const stopWebDaemon = async (): Promise<{ + wasRunning: boolean + stopped: boolean + pid?: number + timedOut?: boolean + permissionDenied?: boolean +}> => { + const daemon = readWebDaemonStatus() + const pid = daemon.pid + if (pid === undefined || !daemon.running) { + removeDaemonPidFile() + return { + wasRunning: false, + stopped: true, + } + } + + try { + process.kill(pid, "SIGTERM") + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (code === "ESRCH") { + removeDaemonPidFile() + return { + wasRunning: false, + stopped: true, + } + } + + if (code === "EPERM") { + return { + wasRunning: true, + stopped: false, + pid, + permissionDenied: true, + } + } + + throw error + } + + const deadline = Date.now() + WEB_DAEMON_SHUTDOWN_TIMEOUT_MS + while (Date.now() < deadline) { + if (!isPidRunning(pid)) { + removeDaemonPidFile() + return { + wasRunning: true, + stopped: true, + pid, + } + } + + await sleep(WEB_DAEMON_STATUS_POLL_MS) + } + + return { + wasRunning: true, + stopped: false, + pid, + timedOut: true, + } +} + +const buildRunnerArgs = (runtime: ResolvedWebRuntime): string[] => [ + "web-runner", + "--host", + runtime.host, + "--api-port", + String(runtime.apiPort), + "--pwa-port", + String(runtime.pwaPort), + "--db-path", + runtime.dbPath, + "--migrations-dir", + runtime.migrationsDir, + "--web-dist-dir", + runtime.webDistDir, + "--audio-dir", + runtime.audioDir, +] + +const startRunnerProcess = (runtime: ResolvedWebRuntime): ChildProcess => { + const cliEntryPath = resolveCliEntryPath() + return spawn(process.execPath, [...process.execArgv, cliEntryPath, ...buildRunnerArgs(runtime)], { + cwd: workspaceRoot, + env: { + ...process.env, + STASH_WEB_DAEMON_DIR: getDaemonPaths("write").dir, + }, + stdio: ["ignore", "inherit", "inherit"], + }) +} + +const runSupervisorLoop = async ( + runtime: ResolvedWebRuntime, + state: WebDaemonState, +): Promise => { + await new Promise((resolve, reject) => { + let settled = false + let shuttingDown = false + let restartTimer: NodeJS.Timeout | undefined + const service: SupervisorServiceRuntime = { + restartCount: 0, + failureStreak: 0, + child: undefined, + startedAtMs: undefined, + } + + const hasRunningChild = (): boolean => + service.child !== undefined && + service.child.exitCode === null && + service.child.signalCode === null + + const stopChild = (signal: NodeJS.Signals = "SIGTERM"): void => { + const child = service.child + if (!child || child.exitCode !== null || child.signalCode !== null) { + return + } + child.kill(signal) + } + + const persist = (): void => { + persistDaemonState(state) + } + + const cleanup = (): void => { + process.off("SIGINT", handleSignal) + process.off("SIGTERM", handleSignal) + if (restartTimer) { + clearTimeout(restartTimer) + restartTimer = undefined + } + } + + const finishResolve = (): void => { + if (settled) { + return + } + settled = true + cleanup() + resolve() + } + + const finishReject = (error: Error): void => { + if (settled) { + return + } + settled = true + shuttingDown = true + stopChild("SIGTERM") + cleanup() + reject(error) + } + + const refreshOverallStatus = (): void => { + if (shuttingDown) { + state.status = "stopping" + } else if (hasRunningChild()) { + state.status = "running" + } else if (state.status === "starting") { + state.status = "starting" + } else { + state.status = "degraded" + } + persist() + } + + const handleSignal = (signal: NodeJS.Signals): void => { + if (shuttingDown) { + return + } + + shuttingDown = true + state.status = "stopping" + state.lastEvent = `Received ${signal}; stopping web runner.` + persist() + + if (restartTimer) { + clearTimeout(restartTimer) + restartTimer = undefined + } + + stopChild("SIGTERM") + + if (!hasRunningChild()) { + finishResolve() + } + } + + const startRunner = (): void => { + let child: ChildProcess + try { + child = startRunnerProcess(runtime) + } catch (error) { + finishReject( + new CliError( + `Failed to start web runner process: ${error instanceof Error ? error.message : String(error)}`, + "INTERNAL_ERROR", + 1, + ), + ) + return + } + + service.child = child + service.startedAtMs = Date.now() + + state.service.pid = child.pid ?? undefined + state.service.lastStartAt = nowIso() + state.lastEvent = `Web runner started (pid ${child.pid ?? "unknown"}).` + refreshOverallStatus() + + child.once("error", (error) => { + if (settled || shuttingDown) { + return + } + + state.status = "degraded" + state.lastEvent = `Web runner process error: ${error.message}` + persist() + }) + + child.once("close", (code, signal) => { + service.child = undefined + + state.service.pid = undefined + state.service.lastExitAt = nowIso() + state.service.lastExit = { + code, + signal, + } + + if (shuttingDown) { + refreshOverallStatus() + if (!hasRunningChild()) { + finishResolve() + } + return + } + + const uptimeMs = service.startedAtMs ? Date.now() - service.startedAtMs : 0 + if (uptimeMs > WEB_RESTART_STABLE_WINDOW_MS) { + service.failureStreak = 0 + } else { + service.failureStreak += 1 + } + + service.restartCount += 1 + state.service.restartCount = service.restartCount + + const cappedExponent = Math.min(service.failureStreak, 5) + const backoffMs = Math.min( + WEB_RESTART_BACKOFF_MAX_MS, + WEB_RESTART_BACKOFF_BASE_MS * 2 ** cappedExponent, + ) + + state.status = "degraded" + state.lastEvent = `Web runner exited ${formatExit(code, signal)}. Restarting in ${backoffMs}ms.` + persist() + + restartTimer = setTimeout(() => { + restartTimer = undefined + if (shuttingDown || settled) { + return + } + startRunner() + }, backoffMs) + }) + } + + process.on("SIGINT", handleSignal) + process.on("SIGTERM", handleSignal) + + startRunner() + state.status = "running" + state.lastEvent = "Supervisor started web runner." + persist() + }) +} + +const runWebStack = async ( + lifecycleContext: RunnerLifecycleContext, + loadStartWebStack: () => Promise, + outputMode: RunWebStackOutputMode, + jsonMode: boolean, +): Promise => { + const { runtime, access } = lifecycleContext + if (runtime.apiPort === runtime.pwaPort) { + throw new CliError("API and PWA ports must be different.", "VALIDATION_ERROR", 2) + } + + const startWebStack = await loadStartWebStack() + const web = await startWebStack({ + host: runtime.host, + apiPort: runtime.apiPort, + pwaPort: runtime.pwaPort, + dbPath: runtime.dbPath, + migrationsDir: runtime.migrationsDir, + webDistDir: runtime.webDistDir, + audioDir: runtime.audioDir, + }) + + if (outputMode === "foreground") { + if (jsonMode) { + printJson({ + ok: true, + command: "web", + lifecycle: "foreground", + access, + api: { + host: web.api.host, + port: web.api.port, + }, + pwa: { + host: web.pwa.host, + port: web.pwa.port, + }, + }) + } else { + process.stdout.write("stash web running\n") + emitAccessSummary(access) + } + } else { + process.stdout.write( + `stash web runner listening on ${runtime.host} (api ${runtime.apiPort}, pwa ${runtime.pwaPort})\n`, + ) + if (access.tailnet.pwaUrl) { + process.stdout.write(`stash web runner tailnet pwa ${access.tailnet.pwaUrl}\n`) + } + if (access.warning) { + process.stderr.write(`Warning: ${access.warning}\n`) + } + } + + await new Promise((resolve) => { + let stopping = false + + const stop = (): void => { + if (stopping) { + return + } + stopping = true + web + .close() + .catch(() => { + // Ignore shutdown errors during signal handling. + }) + .finally(() => { + process.off("SIGINT", stop) + process.off("SIGTERM", stop) + resolve() + }) + } + + process.on("SIGINT", stop) + process.on("SIGTERM", stop) + }) +} + +const resolveWebRuntime = ( + options: WebCommandOptions, + context: RunWebCommandContext, + daemonMode: boolean, +): ResolvedWebRuntime => { + const host = + options.host?.trim() || context.envHost?.trim() || (daemonMode ? "0.0.0.0" : "127.0.0.1") + const apiPort = options.apiPort ?? context.defaultApiPort + const pwaPort = options.pwaPort ?? context.defaultPwaPort + + return { + host, + apiPort, + pwaPort, + dbPath: context.dbPath, + migrationsDir: context.migrationsDir, + webDistDir: context.webDistDir, + audioDir: context.audioDir, + } +} + +const validateControlOptions = (options: WebCommandOptions): void => { + const daemon = options.daemon === true + const status = options.status === true + const stop = options.stop === true + const foreground = options.foreground === true + const enabledControls = [daemon, status, stop, foreground].filter(Boolean).length + + if (enabledControls > 1) { + throw new CliError( + "Use only one of: --daemon, --status, --stop, --foreground.", + "VALIDATION_ERROR", + 2, + ) + } + + if ( + (status || stop) && + (options.host || options.apiPort !== undefined || options.pwaPort !== undefined) + ) { + throw new CliError( + "--status/--stop cannot be combined with --host, --api-port, or --pwa-port.", + "VALIDATION_ERROR", + 2, + ) + } +} + +const startWebDaemon = async (runtime: ResolvedWebRuntime, jsonMode: boolean): Promise => { + ensureDaemonDir() + const existingStatus = readWebDaemonStatus() + if (existingStatus.running) { + emitDaemonStartResult(existingStatus, true, jsonMode) + return + } + + const paths = getDaemonPaths("write") + const access = resolveWebAccessInfo(runtime.host, runtime.apiPort, runtime.pwaPort) + const runId = randomUUID() + const cliEntryPath = resolveCliEntryPath() + const logFd = fs.openSync(paths.logFile, "a") + const supervisor = spawn( + process.execPath, + [ + ...process.execArgv, + cliEntryPath, + "web-supervisor", + "--host", + runtime.host, + "--api-port", + String(runtime.apiPort), + "--pwa-port", + String(runtime.pwaPort), + "--db-path", + runtime.dbPath, + "--migrations-dir", + runtime.migrationsDir, + "--web-dist-dir", + runtime.webDistDir, + "--audio-dir", + runtime.audioDir, + "--run-id", + runId, + ], + { + cwd: workspaceRoot, + env: { + ...process.env, + STASH_WEB_DAEMON_DIR: paths.dir, + }, + detached: true, + stdio: ["ignore", logFd, logFd], + }, + ) + fs.closeSync(logFd) + + if (!supervisor.pid) { + throw new CliError("Failed to start web daemon supervisor.", "INTERNAL_ERROR", 1) + } + + writeDaemonPid(supervisor.pid) + + const state = createDaemonState(runtime, runId, supervisor.pid, access) + state.lastEvent = "Daemon supervisor spawned." + persistDaemonState(state) + + supervisor.unref() + + emitDaemonStartResult( + { + running: true, + pid: supervisor.pid, + pidFile: paths.pidFile, + logFile: paths.logFile, + stateFile: paths.stateFile, + state, + }, + false, + jsonMode, + ) +} + +export const runWebSupervisorCommand = async ( + options: WebInternalCommandOptions, +): Promise => { + const runtime: ResolvedWebRuntime = { + host: options.host, + apiPort: options.apiPort, + pwaPort: options.pwaPort, + dbPath: options.dbPath, + migrationsDir: options.migrationsDir, + webDistDir: options.webDistDir, + audioDir: options.audioDir, + } + const access = resolveWebAccessInfo(runtime.host, runtime.apiPort, runtime.pwaPort) + const state = createDaemonState(runtime, options.runId ?? randomUUID(), process.pid, access) + state.lastEvent = "Daemon supervisor booting." + + writeDaemonPid(process.pid) + persistDaemonState(state) + + try { + await runSupervisorLoop(runtime, state) + state.status = "stopped" + state.lastEvent = "Daemon supervisor stopped cleanly." + persistDaemonState(state) + } catch (error) { + state.status = "crashed" + state.lastEvent = + error instanceof Error + ? `Daemon supervisor crashed: ${error.message}` + : "Daemon supervisor crashed." + persistDaemonState(state) + throw error + } finally { + removeDaemonPidFile() + } +} + +export const runWebRunnerCommand = async ( + options: WebInternalCommandOptions, + loadStartWebStack: () => Promise, +): Promise => { + const runtime: ResolvedWebRuntime = { + host: options.host, + apiPort: options.apiPort, + pwaPort: options.pwaPort, + dbPath: options.dbPath, + migrationsDir: options.migrationsDir, + webDistDir: options.webDistDir, + audioDir: options.audioDir, + } + const access = resolveWebAccessInfo(runtime.host, runtime.apiPort, runtime.pwaPort) + await runWebStack({ runtime, access }, loadStartWebStack, "runner", false) +} + +export const runWebCommand = async ( + options: WebCommandOptions, + context: RunWebCommandContext, +): Promise => { + validateControlOptions(options) + + if (options.status) { + const daemon = readWebDaemonStatus() + if (context.json) { + printJson(buildDaemonPayload(daemon)) + return + } + + if (!daemon.running) { + process.stdout.write("Web daemon is not running.\n") + process.stdout.write(`State file: ${daemon.stateFile}\n`) + process.stdout.write(`Log file: ${daemon.logFile}\n`) + return + } + + process.stdout.write(`Web daemon is running (pid ${String(daemon.pid)}).\n`) + process.stdout.write(`State file: ${daemon.stateFile}\n`) + process.stdout.write(`Log file: ${daemon.logFile}\n`) + if (daemon.state?.access) { + emitAccessSummary(daemon.state.access) + } + return + } + + if (options.stop) { + const result = await stopWebDaemon() + if (context.json) { + printJson({ + ok: true, + command: "web", + lifecycle: "daemon", + daemon: { + stop_requested: true, + was_running: result.wasRunning, + stopped: result.stopped, + pid: result.pid, + timed_out: result.timedOut ?? false, + permission_denied: result.permissionDenied ?? false, + }, + }) + return + } + + if (!result.wasRunning) { + process.stdout.write("Web daemon was not running.\n") + return + } + + if (result.stopped) { + process.stdout.write(`Stopped web daemon (pid ${String(result.pid)}).\n`) + return + } + + if (result.permissionDenied) { + process.stdout.write( + `Permission denied while stopping web daemon (pid ${String(result.pid)}).\n`, + ) + return + } + + process.stdout.write(`Timed out while stopping web daemon (pid ${String(result.pid)}).\n`) + return + } + + const runtime = resolveWebRuntime(options, context, options.daemon === true) + if (options.daemon) { + await startWebDaemon(runtime, context.json) + return + } + + const access = resolveWebAccessInfo(runtime.host, runtime.apiPort, runtime.pwaPort) + await runWebStack({ runtime, access }, context.loadStartWebStack, "foreground", context.json) +} + +export const __testing__ = { + resolveWebAccessInfo, + readWebDaemonStatus, + buildDaemonPaths, + isLoopbackHost, +} diff --git a/apps/cli/test/web.test.ts b/apps/cli/test/web.test.ts new file mode 100644 index 0000000..5ab5ee3 --- /dev/null +++ b/apps/cli/test/web.test.ts @@ -0,0 +1,400 @@ +import net from "node:net" +import { spawnSync } from "node:child_process" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { fileURLToPath } from "node:url" + +import { describe, expect, it } from "vitest" + +import { __testing__ } from "../src/web.js" + +type RunCliOptions = { + dbPath: string + expectedCode?: number + env?: NodeJS.ProcessEnv +} + +type CliResult = { + stdout: string + stderr: string +} + +type DaemonStatusResponse = { + ok: true + command: "web" + lifecycle: "daemon" + daemon: { + running: boolean + pid?: number + pidFile: string + logFile: string + stateFile: string + state?: { + status: "starting" | "running" | "degraded" | "stopping" | "stopped" | "crashed" + access: { + local: { apiUrl: string; pwaUrl: string } + tailnet: { host?: string; apiUrl?: string; pwaUrl?: string } + warning?: string + } + } + } + already_running?: boolean + access?: { + local: { apiUrl: string; pwaUrl: string } + tailnet: { host?: string; apiUrl?: string; pwaUrl?: string } + warning?: string + } | null +} + +type DaemonStopResponse = { + ok: true + command: "web" + lifecycle: "daemon" + daemon: { + stop_requested: true + was_running: boolean + stopped: boolean + pid?: number + timed_out: boolean + permission_denied: boolean + } +} + +type ErrorResponse = { + ok: false + error: { + code: string + message: string + } +} + +const __filename = fileURLToPath(import.meta.url) +const __dirname = path.dirname(__filename) +const repoRoot = path.resolve(__dirname, "../../..") +const cliPath = path.join(repoRoot, "apps", "cli", "dist", "cli.js") + +function probeSqliteBinding(): ReturnType { + return spawnSync( + process.execPath, + [ + "-e", + "import('better-sqlite3').then((mod) => { const Database = mod.default; const db = new Database(':memory:'); db.close(); process.exit(0); }).catch((error) => { console.error(error?.message ?? String(error)); process.exit(1); })", + ], + { + cwd: repoRoot, + encoding: "utf8", + env: process.env, + }, + ) +} + +async function canBindLocalListener(): Promise { + return new Promise((resolve) => { + const server = net.createServer() + server.once("error", (error: NodeJS.ErrnoException) => { + server.close() + resolve(error.code !== "EPERM") + }) + server.listen(0, "127.0.0.1", () => { + server.close(() => resolve(true)) + }) + }) +} + +async function getFreePort(): Promise { + return new Promise((resolve, reject) => { + const server = net.createServer() + server.once("error", reject) + server.listen(0, "127.0.0.1", () => { + const address = server.address() + if (!address || typeof address !== "object") { + reject(new Error("Failed to resolve free port.")) + return + } + server.close((error) => { + if (error) { + reject(error) + return + } + resolve(address.port) + }) + }) + }) +} + +function runCli(args: string[], options: RunCliOptions): CliResult { + const { dbPath, expectedCode = 0, env = {} } = options + const result = spawnSync(process.execPath, [cliPath, ...args], { + cwd: repoRoot, + encoding: "utf8", + env: { + ...process.env, + ...env, + STASH_DB_PATH: dbPath, + }, + }) + + if (result.error) { + throw result.error + } + + if (result.status !== expectedCode) { + throw new Error( + `Command failed: node apps/cli/dist/cli.js ${args.join(" ")} +expected exit code: ${expectedCode} +actual exit code: ${String(result.status)} +stdout: +${result.stdout} +stderr: +${result.stderr}`, + ) + } + + return { + stdout: result.stdout.trim(), + stderr: result.stderr.trim(), + } +} + +function runJson(args: string[], options: RunCliOptions): T { + const { stdout } = runCli([...args, "--json"], options) + if (stdout.length === 0) { + throw new Error(`Expected JSON output for command: ${args.join(" ")}`) + } + return JSON.parse(stdout) as T +} + +function createTempDb(): { dbPath: string; cleanup: () => void } { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "stash-web-cli-")) + const dbPath = path.join(tempDir, "stash.db") + const cleanup = (): void => { + fs.rmSync(tempDir, { recursive: true, force: true }) + } + return { dbPath, cleanup } +} + +function createTempDaemonEnv(): { + env: NodeJS.ProcessEnv + cleanup: () => void + daemonDir: string +} { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "stash-web-daemon-")) + const daemonDir = path.join(tempDir, ".stash-daemon") + const audioDir = path.join(tempDir, "audio") + const tailscalePath = path.join(tempDir, "tailscale") + fs.mkdirSync(audioDir, { recursive: true }) + fs.writeFileSync( + tailscalePath, + `#!/bin/sh +cat <<'JSON' +{ + "BackendState": "Running", + "MagicDNSSuffix": "tail123.ts.net", + "Self": { + "HostName": "stash-macbook", + "DNSName": "stash-macbook.tail123.ts.net.", + "TailscaleIPs": ["100.64.0.10"] + } +} +JSON +`, + "utf8", + ) + fs.chmodSync(tailscalePath, 0o755) + + return { + daemonDir, + env: { + STASH_WEB_DAEMON_DIR: daemonDir, + STASH_AUDIO_DIR: audioDir, + STASH_TAILSCALE_CLI: tailscalePath, + }, + cleanup: () => { + fs.rmSync(tempDir, { recursive: true, force: true }) + }, + } +} + +async function waitForDaemonRunning( + dbPath: string, + env: NodeJS.ProcessEnv, + timeoutMs = 8_000, +): Promise { + const deadline = Date.now() + timeoutMs + while (Date.now() < deadline) { + const status = runJson(["web", "--status"], { dbPath, env }) + if (status.daemon.running) { + return status + } + await new Promise((resolve) => setTimeout(resolve, 200)) + } + + throw new Error("Timed out waiting for web daemon to report running status.") +} + +const sqliteProbe = probeSqliteBinding() +const sqliteProbeOutput = `${sqliteProbe.stdout}\n${sqliteProbe.stderr}` +const sqliteBindingsMissing = + sqliteProbe.status !== 0 && sqliteProbeOutput.includes("Could not locate the bindings file") +const listenerProbe = await canBindLocalListener() + +const webSuite = sqliteBindingsMissing || !listenerProbe ? describe.skip : describe + +webSuite("cli web daemon", () => { + it("starts, reports status, is idempotent, and stops cleanly", async () => { + const { dbPath, cleanup } = createTempDb() + const daemonEnv = createTempDaemonEnv() + const apiPort = await getFreePort() + const pwaPort = await getFreePort() + + try { + const started = runJson( + ["web", "--daemon", "--api-port", String(apiPort), "--pwa-port", String(pwaPort)], + { + dbPath, + env: daemonEnv.env, + }, + ) + + expect(started.ok).toBe(true) + expect(started.lifecycle).toBe("daemon") + expect(started.daemon.running).toBe(true) + expect(started.access?.local.pwaUrl).toBe(`http://127.0.0.1:${pwaPort}`) + expect(started.access?.tailnet.pwaUrl).toBe(`http://stash-macbook.tail123.ts.net:${pwaPort}`) + + const runningStatus = await waitForDaemonRunning(dbPath, daemonEnv.env) + expect(runningStatus.daemon.pid).toBeTruthy() + expect(runningStatus.daemon.state?.access.tailnet.apiUrl).toBe( + `http://stash-macbook.tail123.ts.net:${apiPort}`, + ) + + const startedAgain = runJson( + ["web", "--daemon", "--api-port", String(apiPort), "--pwa-port", String(pwaPort)], + { + dbPath, + env: daemonEnv.env, + }, + ) + expect(startedAgain.already_running).toBe(true) + expect(startedAgain.daemon.pid).toBe(runningStatus.daemon.pid) + + const stopped = runJson(["web", "--stop"], { + dbPath, + env: daemonEnv.env, + }) + expect(stopped.daemon.stop_requested).toBe(true) + expect(stopped.daemon.stopped).toBe(true) + + const stoppedStatus = runJson(["web", "--status"], { + dbPath, + env: daemonEnv.env, + }) + expect(stoppedStatus.daemon.running).toBe(false) + } finally { + try { + runJson(["web", "--stop"], { + dbPath, + env: daemonEnv.env, + }) + } catch { + // Ignore cleanup failures if the daemon never started. + } + daemonEnv.cleanup() + cleanup() + } + }) + + it("rejects invalid daemon control flag combinations and status/stop overrides", () => { + const { dbPath, cleanup } = createTempDb() + try { + const controlsError = runJson(["web", "--daemon", "--status"], { + dbPath, + expectedCode: 2, + }) + expect(controlsError.ok).toBe(false) + expect(controlsError.error.code).toBe("VALIDATION_ERROR") + + const overrideError = runJson(["web", "--status", "--api-port", "4173"], { + dbPath, + expectedCode: 2, + }) + expect(overrideError.ok).toBe(false) + expect(overrideError.error.code).toBe("VALIDATION_ERROR") + } finally { + cleanup() + } + }) +}) + +describe("web helper behavior", () => { + it("returns a loopback warning instead of Tailnet URLs when bound to localhost", () => { + const access = __testing__.resolveWebAccessInfo("127.0.0.1", 4173, 5173) + expect(access.local.pwaUrl).toBe("http://127.0.0.1:5173") + expect(access.tailnet.pwaUrl).toBeUndefined() + expect(access.warning).toContain("--host 0.0.0.0") + }) + + it("cleans up stale daemon pid files when the process is not running", () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "stash-web-status-")) + const previousDaemonDir = process.env.STASH_WEB_DAEMON_DIR + process.env.STASH_WEB_DAEMON_DIR = tempDir + + try { + const paths = __testing__.buildDaemonPaths(tempDir) + fs.mkdirSync(tempDir, { recursive: true }) + fs.writeFileSync(paths.pidFile, "999999\n", "utf8") + fs.writeFileSync( + paths.stateFile, + JSON.stringify( + { + version: 1, + runId: "stale-run", + pid: 999999, + lifecycle: "daemon", + workspaceRoot: repoRoot, + startedAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + status: "crashed", + logFile: paths.logFile, + access: { + bind: { host: "0.0.0.0", apiPort: 4173, pwaPort: 5173 }, + local: { + apiUrl: "http://127.0.0.1:4173", + pwaUrl: "http://127.0.0.1:5173", + }, + tailnet: { + host: undefined, + apiUrl: undefined, + pwaUrl: undefined, + }, + warning: "stale", + }, + service: { + pid: undefined, + restartCount: 1, + lastStartAt: undefined, + lastExitAt: undefined, + lastExit: undefined, + }, + }, + null, + 2, + ), + "utf8", + ) + + const status = __testing__.readWebDaemonStatus() + expect(status.running).toBe(false) + expect(fs.existsSync(paths.pidFile)).toBe(false) + expect(status.state?.status).toBe("crashed") + } finally { + if (previousDaemonDir === undefined) { + delete process.env.STASH_WEB_DAEMON_DIR + } else { + process.env.STASH_WEB_DAEMON_DIR = previousDaemonDir + } + fs.rmSync(tempDir, { recursive: true, force: true }) + } + }) +}) diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index faecc46..03f405f 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -185,15 +185,35 @@ pnpm run web Equivalent CLI form: ```bash -stash web [--host ] [--api-port ] [--pwa-port ] +stash web [--foreground] [--host ] [--api-port ] [--pwa-port ] [--json] +stash web --daemon [--host ] [--api-port ] [--pwa-port ] [--json] +stash web --status [--json] +stash web --stop [--json] ``` Defaults: -- `--host`: `127.0.0.1` (`STASH_WEB_HOST`) +- foreground/default `--host`: `127.0.0.1` when `STASH_WEB_HOST` is unset +- daemon default `--host`: `0.0.0.0` when `STASH_WEB_HOST` is unset +- `STASH_WEB_HOST` overrides both modes when set - `--api-port`: `4173` (`STASH_API_PORT`) - `--pwa-port`: `5173` (`STASH_PWA_PORT`) Notes: +- `--daemon`, `--status`, `--stop`, and `--foreground` are mutually exclusive. +- `--status` and `--stop` cannot be combined with `--host`, `--api-port`, or `--pwa-port`. +- `stash web --daemon` starts a detached supervisor and returns immediately. +- repeated `stash web --daemon` calls are idempotent and return the existing daemon state. +- daemon state is stored in `~/.stash/` with workspace fallback `.stash/`: + - `web-daemon.pid` + - `web-daemon.log` + - `web-daemon.state.json` +- daemon startup/status JSON includes: + - lifecycle status + - daemon pid and file paths + - bind host and resolved ports + - local URLs + - best-effort Tailnet URLs or warnings +- Tailnet URLs are derived from `tailscale status --json`; if the stack is bound to loopback, status warns that remote Tailnet access is unavailable. - API and PWA ports must be different. - Port conflicts fail fast (no automatic next-port fallback). - API listener is implemented in `apps/api` with Fastify. From e780125c79a8375fca31f58082d07f14413cd2f2 Mon Sep 17 00:00:00 2001 From: Serg Dort Date: Mon, 9 Mar 2026 20:54:28 +0000 Subject: [PATCH 2/3] fix(cli): address web daemon review comments --- README.md | 4 ++-- apps/cli/src/web.ts | 35 ++++++++++++++++++++--------------- apps/cli/test/web.test.ts | 2 ++ 3 files changed, 24 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 929c1ed..6f5e675 100644 --- a/README.md +++ b/README.md @@ -64,8 +64,8 @@ Or override at runtime: ```bash stash web --host 127.0.0.1 --api-port 4173 --pwa-port 5173 stash web --daemon --host 0.0.0.0 --api-port 4173 --pwa-port 5173 -stash --json web --status -stash --json web --stop +stash web --status --json +stash web --stop --json ``` Runtime notes: diff --git a/apps/cli/src/web.ts b/apps/cli/src/web.ts index c030346..b0c7035 100644 --- a/apps/cli/src/web.ts +++ b/apps/cli/src/web.ts @@ -228,6 +228,10 @@ const resolveDaemonPaths = (mode: "read" | "write"): DaemonPaths => { let cachedDaemonPaths: DaemonPaths | undefined +const resetDaemonPathsCache = (): void => { + cachedDaemonPaths = undefined +} + const getDaemonPaths = (mode: "read" | "write" = "read"): DaemonPaths => { if (cachedDaemonPaths) { if (mode === "read") { @@ -278,10 +282,13 @@ const readJsonFile = (filePath: string): T | undefined => { try { return JSON.parse(fs.readFileSync(filePath, "utf8")) as T } catch (error) { - const code = (error as NodeJS.ErrnoException).code - if (code === "ENOENT") { + const nodeError = error as NodeJS.ErrnoException + if (nodeError.code === "ENOENT") { return undefined } + process.stderr.write( + `Failed to read JSON file at ${filePath}: ${nodeError.message ?? String(error)}\n`, + ) return undefined } } @@ -476,12 +483,7 @@ const resolveWebAccessInfo = (host: string, apiPort: number, pwaPort: number): W } } -const createDaemonState = ( - _runtime: ResolvedWebRuntime, - runId: string, - pid: number, - access: WebAccessInfo, -): WebDaemonState => ({ +const createDaemonState = (runId: string, pid: number, access: WebAccessInfo): WebDaemonState => ({ version: 1, runId, pid, @@ -587,8 +589,8 @@ const emitDaemonStartResult = ( if (daemon.state?.access) { emitAccessSummary(daemon.state.access) } - process.stdout.write("Status: stash --json web --status\n") - process.stdout.write("Stop: stash --json web --stop\n") + process.stdout.write("Status: stash web --status --json\n") + process.stdout.write("Stop: stash web --stop --json\n") } const stopWebDaemon = async (): Promise<{ @@ -865,9 +867,11 @@ const runSupervisorLoop = async ( process.on("SIGTERM", handleSignal) startRunner() - state.status = "running" - state.lastEvent = "Supervisor started web runner." - persist() + if (!settled) { + state.status = "running" + state.lastEvent = "Supervisor started web runner." + persist() + } }) } @@ -1052,7 +1056,7 @@ const startWebDaemon = async (runtime: ResolvedWebRuntime, jsonMode: boolean): P writeDaemonPid(supervisor.pid) - const state = createDaemonState(runtime, runId, supervisor.pid, access) + const state = createDaemonState(runId, supervisor.pid, access) state.lastEvent = "Daemon supervisor spawned." persistDaemonState(state) @@ -1085,7 +1089,7 @@ export const runWebSupervisorCommand = async ( audioDir: options.audioDir, } const access = resolveWebAccessInfo(runtime.host, runtime.apiPort, runtime.pwaPort) - const state = createDaemonState(runtime, options.runId ?? randomUUID(), process.pid, access) + const state = createDaemonState(options.runId ?? randomUUID(), process.pid, access) state.lastEvent = "Daemon supervisor booting." writeDaemonPid(process.pid) @@ -1210,4 +1214,5 @@ export const __testing__ = { readWebDaemonStatus, buildDaemonPaths, isLoopbackHost, + resetDaemonPathsCache, } diff --git a/apps/cli/test/web.test.ts b/apps/cli/test/web.test.ts index 5ab5ee3..3332d8f 100644 --- a/apps/cli/test/web.test.ts +++ b/apps/cli/test/web.test.ts @@ -338,6 +338,7 @@ describe("web helper behavior", () => { it("cleans up stale daemon pid files when the process is not running", () => { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "stash-web-status-")) const previousDaemonDir = process.env.STASH_WEB_DAEMON_DIR + __testing__.resetDaemonPathsCache() process.env.STASH_WEB_DAEMON_DIR = tempDir try { @@ -394,6 +395,7 @@ describe("web helper behavior", () => { } else { process.env.STASH_WEB_DAEMON_DIR = previousDaemonDir } + __testing__.resetDaemonPathsCache() fs.rmSync(tempDir, { recursive: true, force: true }) } }) From 693e7e754f632653237cda29f77ab8d7dae05b2f Mon Sep 17 00:00:00 2001 From: Serg Dort Date: Mon, 9 Mar 2026 23:16:47 +0000 Subject: [PATCH 3/3] fix(cli): pass daemon db path as global option --- .agents/notes.md | 1 + apps/cli/src/cli.ts | 8 ++----- apps/cli/src/web.ts | 50 +++++++++++++++++---------------------- apps/cli/test/web.test.ts | 20 ++++++++++++++++ 4 files changed, 45 insertions(+), 34 deletions(-) diff --git a/.agents/notes.md b/.agents/notes.md index f671cbe..ee7d28d 100644 --- a/.agents/notes.md +++ b/.agents/notes.md @@ -53,3 +53,4 @@ [0] `stash db doctor` does not create parent directories for a missing DB path; if `STASH_DB_PATH` points to a non-existent directory, command can fail with `unable to open database file`. [0] Prefer explicit named types over `ReturnType` in production code/tests for readability and easier review comments. [0] `tithe web` parity means flag-based daemon controls (`--daemon`, `--status`, `--stop`), not `start`/`stop` subcommands; mirror that CLI shape when porting its web supervisor flow into `stash`. +[0] In Commander, a root/global option like `--db-path` is not reliable as a duplicate command-local option on hidden subcommands. For internal commands, pass the global flag before the subcommand (`stash --db-path ... web-supervisor`) and read it from `program.opts()` inside the action. diff --git a/apps/cli/src/cli.ts b/apps/cli/src/cli.ts index 564f646..6af6b35 100644 --- a/apps/cli/src/cli.ts +++ b/apps/cli/src/cli.ts @@ -1104,7 +1104,6 @@ program .option("--host ", "Host to bind API and PWA servers") .option("--api-port ", "Port to bind API server", parsePort) .option("--pwa-port ", "Port to bind PWA server", parsePort) - .requiredOption("--db-path ", "Path to SQLite database file") .requiredOption("--migrations-dir ", "Path to migrations directory") .requiredOption("--web-dist-dir ", "Path to built web assets") .requiredOption("--audio-dir ", "Path to generated audio directory") @@ -1114,7 +1113,6 @@ program host?: string apiPort?: number pwaPort?: number - dbPath: string migrationsDir: string webDistDir: string audioDir: string @@ -1133,7 +1131,7 @@ program host: options.host, apiPort: options.apiPort, pwaPort: options.pwaPort, - dbPath: options.dbPath, + dbPath: resolveDbPath(program.opts().dbPath as string), migrationsDir: options.migrationsDir, webDistDir: options.webDistDir, audioDir: options.audioDir, @@ -1149,7 +1147,6 @@ program .option("--host ", "Host to bind API and PWA servers") .option("--api-port ", "Port to bind API server", parsePort) .option("--pwa-port ", "Port to bind PWA server", parsePort) - .requiredOption("--db-path ", "Path to SQLite database file") .requiredOption("--migrations-dir ", "Path to migrations directory") .requiredOption("--web-dist-dir ", "Path to built web assets") .requiredOption("--audio-dir ", "Path to generated audio directory") @@ -1158,7 +1155,6 @@ program host?: string apiPort?: number pwaPort?: number - dbPath: string migrationsDir: string webDistDir: string audioDir: string @@ -1177,7 +1173,7 @@ program host: options.host, apiPort: options.apiPort, pwaPort: options.pwaPort, - dbPath: options.dbPath, + dbPath: resolveDbPath(program.opts().dbPath as string), migrationsDir: options.migrationsDir, webDistDir: options.webDistDir, audioDir: options.audioDir, diff --git a/apps/cli/src/web.ts b/apps/cli/src/web.ts index b0c7035..a166891 100644 --- a/apps/cli/src/web.ts +++ b/apps/cli/src/web.ts @@ -656,34 +656,43 @@ const stopWebDaemon = async (): Promise<{ } } -const buildRunnerArgs = (runtime: ResolvedWebRuntime): string[] => [ - "web-runner", +const buildInternalWebCommandArgs = ( + command: "web-runner" | "web-supervisor", + runtime: ResolvedWebRuntime, + extraArgs: string[] = [], +): string[] => [ + "--db-path", + runtime.dbPath, + command, "--host", runtime.host, "--api-port", String(runtime.apiPort), "--pwa-port", String(runtime.pwaPort), - "--db-path", - runtime.dbPath, "--migrations-dir", runtime.migrationsDir, "--web-dist-dir", runtime.webDistDir, "--audio-dir", runtime.audioDir, + ...extraArgs, ] const startRunnerProcess = (runtime: ResolvedWebRuntime): ChildProcess => { const cliEntryPath = resolveCliEntryPath() - return spawn(process.execPath, [...process.execArgv, cliEntryPath, ...buildRunnerArgs(runtime)], { - cwd: workspaceRoot, - env: { - ...process.env, - STASH_WEB_DAEMON_DIR: getDaemonPaths("write").dir, + return spawn( + process.execPath, + [...process.execArgv, cliEntryPath, ...buildInternalWebCommandArgs("web-runner", runtime)], + { + cwd: workspaceRoot, + env: { + ...process.env, + STASH_WEB_DAEMON_DIR: getDaemonPaths("write").dir, + }, + stdio: ["ignore", "inherit", "inherit"], }, - stdio: ["ignore", "inherit", "inherit"], - }) + ) } const runSupervisorLoop = async ( @@ -1020,23 +1029,7 @@ const startWebDaemon = async (runtime: ResolvedWebRuntime, jsonMode: boolean): P [ ...process.execArgv, cliEntryPath, - "web-supervisor", - "--host", - runtime.host, - "--api-port", - String(runtime.apiPort), - "--pwa-port", - String(runtime.pwaPort), - "--db-path", - runtime.dbPath, - "--migrations-dir", - runtime.migrationsDir, - "--web-dist-dir", - runtime.webDistDir, - "--audio-dir", - runtime.audioDir, - "--run-id", - runId, + ...buildInternalWebCommandArgs("web-supervisor", runtime, ["--run-id", runId]), ], { cwd: workspaceRoot, @@ -1213,6 +1206,7 @@ export const __testing__ = { resolveWebAccessInfo, readWebDaemonStatus, buildDaemonPaths, + buildInternalWebCommandArgs, isLoopbackHost, resetDaemonPathsCache, } diff --git a/apps/cli/test/web.test.ts b/apps/cli/test/web.test.ts index 3332d8f..65b349b 100644 --- a/apps/cli/test/web.test.ts +++ b/apps/cli/test/web.test.ts @@ -328,6 +328,26 @@ webSuite("cli web daemon", () => { }) describe("web helper behavior", () => { + it("builds internal daemon command args with the global db-path before the subcommand", () => { + const args = __testing__.buildInternalWebCommandArgs( + "web-supervisor", + { + host: "0.0.0.0", + apiPort: 4173, + pwaPort: 5173, + dbPath: "/tmp/stash.db", + migrationsDir: "/tmp/drizzle", + webDistDir: "/tmp/web-dist", + audioDir: "/tmp/audio", + }, + ["--run-id", "run-123"], + ) + + expect(args.slice(0, 3)).toEqual(["--db-path", "/tmp/stash.db", "web-supervisor"]) + expect(args).toContain("--run-id") + expect(args).toContain("run-123") + }) + it("returns a loopback warning instead of Tailnet URLs when bound to localhost", () => { const access = __testing__.resolveWebAccessInfo("127.0.0.1", 4173, 5173) expect(access.local.pwaUrl).toBe("http://127.0.0.1:5173")