From 02166dad9f468d4e7bc3d228ed84ec2d0061a806 Mon Sep 17 00:00:00 2001 From: Miao Yang Date: Tue, 14 Jul 2026 16:55:11 +0800 Subject: [PATCH] =?UTF-8?q?feat(cli):=20preview=20lifecycle=20=E2=80=94=20?= =?UTF-8?q?idle=20timeout=20and=20owner-pid=20for=20background=20servers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rework of the original `preview --detach` PR on top of the `--background/--status/--stop` lifecycle that landed in #2384: instead of a parallel detached-server implementation (state files, launch nonces, a --detached-child internal mode), the two capabilities main lacks become first-class preview flags that ride the existing argv forwarding into the background child. - `--idle-timeout `: the server shuts itself down after this long with no requests. An open Studio tab counts as activity (it polls the project signature), so "idle" means nobody — human or agent — is looking. `--background` children default to 60 minutes (injected by buildBackgroundPreviewArgs unless the caller pinned a value; `--idle-timeout 0` opts out), so background servers no longer outlive their usefulness. Foreground default stays disabled. - `--owner-pid `: the server exits when that process does — an agent session can tie the preview to its own lifetime instead of leaking servers when it is killed. The watcher checks both conditions every 30s and SIGTERMs itself, reusing the exact Ctrl+C shutdown path (browser-pool drain, ffmpeg kill, hard deadline). Flags parse and fail loudly in the launching process, not inside a detached child's log file. Vite dev/local-studio modes warn that lifecycle flags apply to the embedded server only. Co-Authored-By: Claude Fable 5 --- packages/cli/src/commands/preview.ts | 88 ++++++++++++++++++- .../cli/src/commands/previewLifecycle.test.ts | 82 ++++++++++++++++- packages/cli/src/commands/previewLifecycle.ts | 45 +++++++++- skills-manifest.json | 2 +- .../references/preview-render.md | 5 ++ 5 files changed, 218 insertions(+), 4 deletions(-) diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.ts index 9e1ad75598..955918f0f9 100644 --- a/packages/cli/src/commands/preview.ts +++ b/packages/cli/src/commands/preview.ts @@ -11,6 +11,11 @@ export const examples: Example[] = [ ["Use a custom port", "hyperframes preview --port 8080"], ["Force a new server even if one is already running", "hyperframes preview --force-new"], ["Keep preview running after this command exits", "hyperframes preview --background"], + [ + "Background server that dies with your agent session", + "hyperframes preview --background --owner-pid $$", + ], + ["Background server that never idles out", "hyperframes preview --background --idle-timeout 0"], ["Show the background preview for this project", "hyperframes preview --status"], ["Stop the background preview for this project", "hyperframes preview --stop"], ["Start without opening the browser", "hyperframes preview --no-open"], @@ -48,6 +53,8 @@ import { import { killOrphanedProcesses, killProcessTree } from "../utils/orphanCleanup.js"; import { resolveProject } from "../utils/project.js"; import { + lifecycleShutdownReason, + processAlive, readBackgroundPreviewStatus, startBackgroundPreview, stopBackgroundPreview, @@ -67,6 +74,8 @@ interface StudioLaunchOptions extends BrowserLaunchOptions { interface EmbeddedStudioOptions extends StudioLaunchOptions { forceNew?: boolean; + /** Self-shutdown conditions for the server process (idle / owner exit). */ + lifecycle?: { ownerPid: number | null; idleLimitMs: number }; } type StudioChildProcess = ChildProcessByStdio; @@ -113,6 +122,16 @@ export default defineCommand({ description: "Stop the background preview for this project and exit", default: false, }, + "idle-timeout": { + type: "string", + description: + "Shut the server down after this many minutes without a request; 0 disables (--background defaults to 60)", + }, + "owner-pid": { + type: "string", + description: + "Shut the server down when this process exits — with --background, ties the server to your agent session", + }, list: { type: "boolean", description: "List all active preview servers and exit", @@ -313,12 +332,42 @@ export default defineCommand({ return; } + // Lifecycle flags parse up front: a `--background` parent forwards them to + // its child through argv (see buildBackgroundPreviewArgs), so bad values + // must fail loudly here, not inside a detached process's log file. + const rawOwnerPid = args["owner-pid"] as string | undefined; + const ownerPid = rawOwnerPid === undefined ? null : Number.parseInt(rawOwnerPid, 10); + if ( + rawOwnerPid !== undefined && + (ownerPid === null || !Number.isInteger(ownerPid) || ownerPid <= 1) + ) { + clack.log.error("--owner-pid must be an integer greater than 1"); + process.exitCode = 1; + return; + } + const rawIdleTimeout = args["idle-timeout"] as string | undefined; + const idleTimeoutMinutes = rawIdleTimeout === undefined ? 0 : Number(rawIdleTimeout); + if ( + rawIdleTimeout !== undefined && + (!Number.isFinite(idleTimeoutMinutes) || idleTimeoutMinutes < 0) + ) { + clack.log.error("--idle-timeout must be a number of minutes ≥ 0 (0 disables)"); + process.exitCode = 1; + return; + } + const lifecycle = { ownerPid, idleLimitMs: Math.round(idleTimeoutMinutes * 60_000) }; + if (isDevMode()) { if (args.background) { clack.log.error("--background currently supports the embedded preview server only"); process.exitCode = 1; return; } + if (rawOwnerPid !== undefined || rawIdleTimeout !== undefined) { + clack.log.warn( + "--idle-timeout/--owner-pid apply to the embedded preview server only — ignored here.", + ); + } return runDevMode(dir, { projectName, noOpen, @@ -336,6 +385,11 @@ export default defineCommand({ process.exitCode = 1; return; } + if (rawOwnerPid !== undefined || rawIdleTimeout !== undefined) { + clack.log.warn( + "--idle-timeout/--owner-pid apply to the embedded preview server only — ignored here.", + ); + } return runLocalStudioMode(dir, { projectName, noOpen, @@ -387,6 +441,7 @@ export default defineCommand({ userDataDir, remoteDebuggingPort, browserNoGpu, + lifecycle, }); }, }); @@ -974,10 +1029,23 @@ async function runEmbeddedMode( const { app } = createStudioServer({ projectDir: dir, projectName: pName }); const serverBuildSignature = await loadPreviewServerBuildSignature(); + // Lifecycle-managed servers track request activity: an open Studio tab polls + // the project signature, so "idle" only starts once nobody is looking. + const lifecycle = options?.lifecycle; + const watchLifecycle = + lifecycle !== undefined && (lifecycle.idleLimitMs > 0 || lifecycle.ownerPid !== null); + let lastActivityMs = Date.now(); + const fetchHandler: typeof app.fetch = watchLifecycle + ? (...fetchArgs: Parameters) => { + lastActivityMs = Date.now(); + return app.fetch(...fetchArgs); + } + : app.fetch; + let result: FindPortResult; try { result = await findPortAndServe( - app.fetch, + fetchHandler, startPort, dir, !!options?.forceNew, @@ -1018,6 +1086,24 @@ async function runEmbeddedMode( }); openStudioBrowser(url, pName, options); + if (watchLifecycle && lifecycle) { + // Self-shutdown watcher: SIGTERM to self reuses the exact shutdown path + // Ctrl+C takes below, so cleanup and the hard deadline stay in one place. + const watcher = setInterval(() => { + const reason = lifecycleShutdownReason({ + ownerPid: lifecycle.ownerPid, + ownerAlive: processAlive, + idleMs: Date.now() - lastActivityMs, + idleLimitMs: lifecycle.idleLimitMs, + }); + if (!reason) return; + clearInterval(watcher); + console.log(` Preview server shutting down: ${reason}.`); + process.kill(process.pid, "SIGTERM"); + }, 30_000); + watcher.unref(); + } + // Block until Ctrl+C. Node would normally exit on SIGINT, but the listening // HTTP server keeps handles open, so the event loop stays alive after the // signal handler fires. Close the server explicitly and resolve the promise diff --git a/packages/cli/src/commands/previewLifecycle.test.ts b/packages/cli/src/commands/previewLifecycle.test.ts index 86ba10e89c..e4d7c5d990 100644 --- a/packages/cli/src/commands/previewLifecycle.test.ts +++ b/packages/cli/src/commands/previewLifecycle.test.ts @@ -4,8 +4,11 @@ import { join, resolve } from "node:path"; import { describe, expect, it, vi } from "vitest"; import type { ActiveServer } from "../server/portUtils.js"; import { + BACKGROUND_IDLE_TIMEOUT_DEFAULT_MINUTES, buildBackgroundPreviewArgs, + lifecycleShutdownReason, previewSessionPath, + processAlive, readBackgroundPreviewStatus, startBackgroundPreview, stopBackgroundPreview, @@ -57,7 +60,42 @@ describe("background preview lifecycle", () => { "--background", "--open", ]), - ).toEqual(["/opt/hyperframes/cli.js", "preview", projectDir, "--no-open"]); + ).toEqual([ + "/opt/hyperframes/cli.js", + "preview", + projectDir, + "--no-open", + "--idle-timeout", + String(BACKGROUND_IDLE_TIMEOUT_DEFAULT_MINUTES), + ]); + }); + + it("keeps an explicit --idle-timeout instead of stacking the default", () => { + const explicit = buildBackgroundPreviewArgs([ + "/opt/hyperframes/cli.js", + "preview", + projectDir, + "--background", + "--idle-timeout", + "0", + ]); + expect(explicit).toEqual([ + "/opt/hyperframes/cli.js", + "preview", + projectDir, + "--idle-timeout", + "0", + "--no-open", + ]); + + const equalsForm = buildBackgroundPreviewArgs(["preview", projectDir, "--idle-timeout=15"]); + expect(equalsForm.filter((arg) => arg.includes("idle-timeout"))).toEqual(["--idle-timeout=15"]); + }); + + it("forwards --owner-pid to the detached child untouched", () => { + expect( + buildBackgroundPreviewArgs(["preview", projectDir, "--background", "--owner-pid", "812"]), + ).toContain("--owner-pid"); }); it("reuses an already-running server for the same project", async () => { @@ -219,3 +257,45 @@ describe("background preview lifecycle", () => { expect(existsSync(previewSessionPath(projectDir, stateHome))).toBe(true); }); }); + +describe("lifecycleShutdownReason", () => { + const HOUR = 60 * 60 * 1000; + + it("keeps serving while active and owned", () => { + expect( + lifecycleShutdownReason({ + ownerPid: 42, + ownerAlive: () => true, + idleMs: 5 * 60 * 1000, + idleLimitMs: HOUR, + }), + ).toBeNull(); + }); + + it("shuts down when the owner is gone", () => { + expect( + lifecycleShutdownReason({ + ownerPid: 42, + ownerAlive: () => false, + idleMs: 0, + idleLimitMs: HOUR, + }), + ).toContain("owner process 42"); + }); + + it("shuts down past the idle limit, but never with the limit disabled", () => { + const base = { ownerPid: null, ownerAlive: () => true }; + expect(lifecycleShutdownReason({ ...base, idleMs: HOUR, idleLimitMs: HOUR })).toContain("idle"); + expect(lifecycleShutdownReason({ ...base, idleMs: 10 * HOUR, idleLimitMs: 0 })).toBeNull(); + }); +}); + +describe("processAlive", () => { + it("sees this process, rejects sentinels and absent pids", () => { + expect(processAlive(process.pid)).toBe(true); + expect(processAlive(0)).toBe(false); + expect(processAlive(1)).toBe(false); + expect(processAlive(-5)).toBe(false); + expect(processAlive(2 ** 30)).toBe(false); + }); +}); diff --git a/packages/cli/src/commands/previewLifecycle.ts b/packages/cli/src/commands/previewLifecycle.ts index 4082370d28..8c6a16491a 100644 --- a/packages/cli/src/commands/previewLifecycle.ts +++ b/packages/cli/src/commands/previewLifecycle.ts @@ -153,6 +153,9 @@ function startedServer( return matchingServer(candidates, projectDir); } +/** Idle default for `--background` children: an hour with no requests. */ +export const BACKGROUND_IDLE_TIMEOUT_DEFAULT_MINUTES = 60; + export function buildBackgroundPreviewArgs(argv: string[]): string[] { const filtered = argv.filter( (arg) => @@ -161,7 +164,47 @@ export function buildBackgroundPreviewArgs(argv: string[]): string[] { arg !== "--open" && arg !== "--no-open", ); - return [...filtered, "--no-open"]; + // Background servers must not outlive their usefulness: default the child to + // the idle timeout unless the caller pinned one (`--idle-timeout 0` opts out). + const hasIdleTimeout = filtered.some( + (arg) => arg === "--idle-timeout" || arg.startsWith("--idle-timeout="), + ); + const idleDefault = hasIdleTimeout + ? [] + : ["--idle-timeout", String(BACKGROUND_IDLE_TIMEOUT_DEFAULT_MINUTES)]; + return [...filtered, "--no-open", ...idleDefault]; +} + +export function processAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 1) return false; + try { + process.kill(pid, 0); + return true; + } catch (err) { + // EPERM means the process exists but belongs to someone else. + return (err as NodeJS.ErrnoException).code === "EPERM"; + } +} + +/** + * Decide whether a preview server should shut itself down. Returns the + * human-readable reason, or null to keep serving. An open Studio tab counts as + * activity (the storyboard polls the signature endpoint), so "idle" really + * means nobody — human or agent — is looking. + */ +export function lifecycleShutdownReason(opts: { + ownerPid: number | null; + ownerAlive: (pid: number) => boolean; + idleMs: number; + idleLimitMs: number; +}): string | null { + if (opts.ownerPid !== null && !opts.ownerAlive(opts.ownerPid)) { + return `owner process ${opts.ownerPid} exited`; + } + if (opts.idleLimitMs > 0 && opts.idleMs >= opts.idleLimitMs) { + return `idle for ${Math.round(opts.idleMs / 60_000)} minutes`; + } + return null; } export async function readBackgroundPreviewStatus( diff --git a/skills-manifest.json b/skills-manifest.json index 868882e205..76e3a57818 100644 --- a/skills-manifest.json +++ b/skills-manifest.json @@ -26,7 +26,7 @@ "files": 99 }, "hyperframes-cli": { - "hash": "5e1e197baf9b6653", + "hash": "2bc78510660af5dd", "files": 8 }, "hyperframes-core": { diff --git a/skills/hyperframes-cli/references/preview-render.md b/skills/hyperframes-cli/references/preview-render.md index 611a914d03..287f8581c0 100644 --- a/skills/hyperframes-cli/references/preview-render.md +++ b/skills/hyperframes-cli/references/preview-render.md @@ -9,8 +9,13 @@ npx hyperframes preview # serve current directory npx hyperframes preview --port 4567 # custom port (default 3002) npx hyperframes preview --selection --json # print the current Studio selection and exit npx hyperframes preview --context --json # print compact agent context from Studio +npx hyperframes preview --background # keep the server running after the command exits +npx hyperframes preview --status # show the background server for this project +npx hyperframes preview --stop # stop the background server for this project ``` +Background servers shut themselves down after 60 minutes without a request — an open Studio tab counts as activity (it polls the project signature), so "idle" means nobody is looking. Tune with `--idle-timeout ` (`0` disables), or pass `--owner-pid ` to tie the server to your session so it exits when your process does. + Hot-reloads on file changes. Opens Studio in the browser automatically — the full timeline editor, where the user can play the video and edit anything by hand before rendering. This is the review surface, not just a viewer. When handing a project back to the user, use the Studio project URL, not the source `index.html` path: