From 8bfc70e4cb2eaa6cb0237de5e80bb58cb837e4ba Mon Sep 17 00:00:00 2001 From: Vance Ingalls Date: Wed, 15 Jul 2026 02:17:58 -0700 Subject: [PATCH] feat(cli): spawn VST sidecar with ready handshake and shutdown Adds packages/cli/src/vst/sidecar.ts: resolves the vst-host sidecar command (HF_VST_HOST_CMD override -> monorepo uv run -> bare command on PATH), spawns ` serve --port 0`, and resolves once stdout announces VST-HOST-LISTENING port= (30s timeout with an `uv tool install` hint). startVstSidecar()/getVstSidecar() are a per-process singleton. Wires sidecar teardown into all three `hyperframes preview` launch paths: registerChildTreeShutdown's signal handler (dev + local studio modes) and embedded mode's own SIGINT/SIGTERM cleanup + last-resort exit handler, since embedded mode has no child process to register with registerChildTreeShutdown. stopVstSidecar() is a safe no-op when no sidecar is running, so this holds even though the sidecar itself is started lazily by a later API route (Task 10), not by preview.ts. --- packages/cli/src/commands/preview.ts | 16 ++- packages/cli/src/vst/sidecar.test.ts | 42 ++++++++ packages/cli/src/vst/sidecar.ts | 149 +++++++++++++++++++++++++++ 3 files changed, 206 insertions(+), 1 deletion(-) create mode 100644 packages/cli/src/vst/sidecar.test.ts create mode 100644 packages/cli/src/vst/sidecar.ts diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.ts index 9879f0c519..4c8b41e9b9 100644 --- a/packages/cli/src/commands/preview.ts +++ b/packages/cli/src/commands/preview.ts @@ -61,6 +61,7 @@ import { startBackgroundPreview, stopBackgroundPreview, } from "./previewLifecycle.js"; +import { stopVstSidecar } from "../vst/sidecar.js"; interface BrowserLaunchOptions { noOpen?: boolean; @@ -861,6 +862,11 @@ function removeSymlinkOnExit(createdSymlink: boolean, symlinkPath: string): void function registerChildTreeShutdown(child: StudioChildProcess): void { const shutdown = (): void => { if (child.pid) killProcessTree(child.pid); + // The VST sidecar (packages/cli/src/vst/sidecar.ts) is started lazily by + // the studio's API route, not spawned here — but whichever mode ends up + // starting it, Ctrl-C during this preview session must still tear it + // down. Safe no-op if no sidecar is running. + stopVstSidecar(); }; process.once("SIGINT", shutdown); process.once("SIGTERM", shutdown); @@ -1106,6 +1112,11 @@ async function runEmbeddedMode( const { closeThumbnailBrowser } = await import("../server/studioServer.js"); const { drainBrowserPool, killTrackedProcesses } = await import("@hyperframes/engine"); killTrackedProcesses(); + // Embedded mode has no StudioChildProcess to hand to + // registerChildTreeShutdown (it runs an in-process Hono server, not + // a spawned child) — so the VST sidecar, if the API route started + // one during this session, is torn down directly here instead. + stopVstSidecar(); await closeThumbnailBrowser().catch(() => {}); await drainBrowserPool().catch(() => {}); }; @@ -1125,7 +1136,10 @@ async function runEmbeddedMode( import("@hyperframes/engine") .then(({ killTrackedProcesses }) => { process.once("exit", () => { - if (!shuttingDown) killTrackedProcesses(); + if (!shuttingDown) { + killTrackedProcesses(); + stopVstSidecar(); + } }); }) .catch(() => {}); diff --git a/packages/cli/src/vst/sidecar.test.ts b/packages/cli/src/vst/sidecar.test.ts new file mode 100644 index 0000000000..d08d0e3167 --- /dev/null +++ b/packages/cli/src/vst/sidecar.test.ts @@ -0,0 +1,42 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { chmodSync, mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { getVstSidecar, startVstSidecar, __resetForTests } from "./sidecar"; + +afterEach(() => { + __resetForTests(); + delete process.env.HF_VST_HOST_CMD; +}); + +function fakeServe(dir: string, lines: string): string { + const script = join(dir, "fake-serve.sh"); + writeFileSync(script, `#!/bin/sh\n${lines}\n`); + chmodSync(script, 0o755); + return script; +} + +describe("startVstSidecar", () => { + it("resolves the announced port", async () => { + const dir = mkdtempSync(join(tmpdir(), "vst-cli-")); + process.env.HF_VST_HOST_CMD = fakeServe(dir, `echo "VST-HOST-LISTENING port=9555"; sleep 60`); + const { port, stop } = await startVstSidecar(); + expect(port).toBe(9555); + expect(getVstSidecar()?.port).toBe(9555); + stop(); + }); + + it("is a singleton while running", async () => { + const dir = mkdtempSync(join(tmpdir(), "vst-cli-")); + process.env.HF_VST_HOST_CMD = fakeServe(dir, `echo "VST-HOST-LISTENING port=9556"; sleep 60`); + const a = await startVstSidecar(); + const b = await startVstSidecar(); + expect(b.port).toBe(a.port); + a.stop(); + }); + + it("rejects with install hint when command is missing", async () => { + process.env.HF_VST_HOST_CMD = "/definitely/not/here"; + await expect(startVstSidecar()).rejects.toThrow(/uv tool install hyperframes-vst-host/); + }); +}); diff --git a/packages/cli/src/vst/sidecar.ts b/packages/cli/src/vst/sidecar.ts new file mode 100644 index 0000000000..e5229a49d6 --- /dev/null +++ b/packages/cli/src/vst/sidecar.ts @@ -0,0 +1,149 @@ +/** + * CLI-side lifecycle for the VST host sidecar (`packages/vst-host`). + * + * Spawns the sidecar's `serve` subcommand, waits for its ready handshake on + * stdout, and tracks the single running instance for the lifetime of this + * CLI process. `hyperframes preview` registers the running child with the + * same signal-driven shutdown paths it uses for its own studio child + * processes so Ctrl-C during a preview session also tears the sidecar down. + */ + +import { spawn, type ChildProcess } from "node:child_process"; +import { existsSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { join, resolve } from "node:path"; + +const READY_RE = /VST-HOST-LISTENING port=(\d+)/; +const READY_TIMEOUT_MS = 30_000; +const INSTALL_HINT = "Install the VST host: uv tool install hyperframes-vst-host (requires uv)"; + +interface RunningSidecar { + port: number; + child: ChildProcess; +} + +let running: RunningSidecar | null = null; + +/** + * Resolves the command used to invoke the VST host sidecar. + * + * Precedence: + * 1. `HF_VST_HOST_CMD` env var (space-split) — lets CI/dev machines point at + * an arbitrary executable (or, in tests, a fake shell script). + * 2. `uv run --project hyperframes-vst` when the + * monorepo's `packages/vst-host` directory is present relative to this + * package (the common case: a source checkout of hyperframes). + * 3. Bare `hyperframes-vst` on PATH (an installed/published sidecar). + * + * Duplicated from `@hyperframes/engine`'s `resolveVstHostCommand` + * (packages/engine/src/services/vstBounce.ts) — that package doesn't export + * it from its public entry point or a subpath, so the CLI carries its own + * copy with a CLI-relative monorepo path. Not exported: nothing outside this + * module needs it directly — `HF_VST_HOST_CMD` is the test seam (see + * sidecar.test.ts), exercised indirectly through `startVstSidecar`. + */ +function resolveVstHostCommand(): string[] { + const override = process.env.HF_VST_HOST_CMD; + if (override && override.trim().length > 0) { + return override.trim().split(/\s+/); + } + + const thisDir = fileURLToPath(new URL(".", import.meta.url)); + const monorepoVstHostDir = resolve(thisDir, "../../../vst-host"); + if (existsSync(join(monorepoVstHostDir, "pyproject.toml"))) { + return ["uv", "run", "--project", monorepoVstHostDir, "hyperframes-vst"]; + } + + return ["hyperframes-vst"]; +} + +/** Returns the running sidecar's port, or `null` if none is running. */ +export function getVstSidecar(): { port: number } | null { + return running ? { port: running.port } : null; +} + +/** + * Kills the running sidecar, if any. Safe to call whether or not a sidecar + * is currently running — used by `hyperframes preview`'s shutdown paths so + * every launch mode tears the sidecar down without needing to know whether + * one was ever started. + */ +export function stopVstSidecar(): void { + if (running) stopSidecar(running.child); +} + +/** Test-only: force-resets singleton state between test cases. */ +export function __resetForTests(): void { + if (running) { + running.child.kill(); + } + running = null; +} + +/** + * Starts the VST host sidecar (` serve --port 0`) and resolves + * once it announces its bound port on stdout. Only one sidecar runs per CLI + * process — a second call while one is already running returns the same + * instance. + */ +export function startVstSidecar(): Promise<{ port: number; stop: () => void }> { + if (running) { + const current = running; + return Promise.resolve({ port: current.port, stop: () => stopSidecar(current.child) }); + } + + const [cmd, ...baseArgs] = resolveVstHostCommand(); + if (!cmd) { + return Promise.reject(new Error(`VST sidecar could not be started. ${INSTALL_HINT}`)); + } + + return new Promise((resolvePromise, reject) => { + const child = spawn(cmd, [...baseArgs, "serve", "--port", "0"], { + stdio: ["ignore", "pipe", "pipe"], + }); + let settled = false; + + const timer = setTimeout(() => { + if (settled) return; + settled = true; + child.kill(); + reject(new Error(`VST sidecar did not become ready in 30s. ${INSTALL_HINT}`)); + }, READY_TIMEOUT_MS); + + child.stdout?.on("data", (buf: Buffer) => { + if (settled) return; + const match = buf.toString().match(READY_RE); + const portGroup = match?.[1]; + if (!portGroup) return; + settled = true; + clearTimeout(timer); + const port = Number(portGroup); + running = { port, child }; + resolvePromise({ port, stop: () => stopSidecar(child) }); + }); + + child.on("error", () => { + if (settled) return; + settled = true; + clearTimeout(timer); + reject(new Error(`VST sidecar could not be started. ${INSTALL_HINT}`)); + }); + + child.on("exit", () => { + if (running && running.child === child) { + running = null; + } + if (settled) return; + settled = true; + clearTimeout(timer); + reject(new Error(`VST sidecar exited before becoming ready. ${INSTALL_HINT}`)); + }); + }); +} + +function stopSidecar(child: ChildProcess): void { + child.kill(); + if (running && running.child === child) { + running = null; + } +}