From 896a77c3076e5a6360cc3557cac576625786906f Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 7 Nov 2026 17:24:14 +0000 Subject: [PATCH] fix(cli): open stops the project's background preview first (#7297) The desktop app can't run an edit while a preview of the project is running, because the preview holds the project's history lock. Following the hint that `preview --background` prints therefore left the app's edit waiting until someone stopped the preview by hand. `hyperframes open` now stops a background preview of the same project before handing it to the app, and prints one line saying so. It only stops a preview it can prove it started (a saved session whose wrapper process still owns the server). Any other preview is left running, and `open` prints the exact `preview --stop --port N` command instead. With --json the result carries a `preview` field. The hint that `preview` prints now says that `open` stops a background preview, or that a foreground one must be stopped first. The project template and the CLI skill's preview reference say the same. Co-authored-by: Claude Opus 5.5 --- docs/packages/cli.mdx | 7 + packages/cli/src/commands/open.test.ts | 137 ++++++++++++++++++ packages/cli/src/commands/open.ts | 73 +++++++++- packages/cli/src/commands/preview.ts | 8 +- packages/cli/src/templates/_shared/AGENTS.md | 4 +- packages/cli/src/templates/_shared/CLAUDE.md | 4 +- packages/cli/src/utils/desktopApp.test.ts | 24 +++ packages/cli/src/utils/desktopApp.ts | 28 +++- skills-manifest.json | 2 +- .../references/preview-render.md | 2 +- 10 files changed, 274 insertions(+), 15 deletions(-) create mode 100644 packages/cli/src/commands/open.test.ts diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index bf46e6174e..cef110d4cc 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -1155,6 +1155,13 @@ installed, `open` exits 1 and prints a download link. With `--json`, the result names the `reason` and the `downloadUrl`. The hand-off works on macOS, Windows and Linux. +The app can't edit a project while a preview of it is running, because the +preview holds the project's edit history. So `open` first stops the project's +`preview --background` server and says so. It leaves any other preview running, +such as one started in a terminal, and prints the `preview --stop` command +instead. With `--json`, the `preview` field reports `none`, `stopped` or +`left-running`. + `catch-up` is the other half of that hand-off. Run it when the person is back from the desktop app, before you change anything: it lists what they asked and what changed in the app since you last looked, and the files changed since diff --git a/packages/cli/src/commands/open.test.ts b/packages/cli/src/commands/open.test.ts new file mode 100644 index 0000000000..fc45cb7473 --- /dev/null +++ b/packages/cli/src/commands/open.test.ts @@ -0,0 +1,137 @@ +import { existsSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { describe, expect, it, onTestFinished, vi } from "vitest"; +import type { ActiveServer } from "../server/portUtils.js"; +import { endPreviewBeforeOpening } from "./open.js"; +import { + previewSessionPath, + readBackgroundPreviewStatus, + stopBackgroundPreview, + writePreviewSession, +} from "./previewLifecycle.js"; + +const projectDir = resolve("/tmp/hyperframes-open-project"); +const background = { pid: 4321, port: 3210, projectDir, logPath: "/tmp/preview.log" }; +const never = () => { + throw new Error("must not run"); +}; + +describe("endPreviewBeforeOpening", () => { + it("does nothing when no preview of the project runs", async () => { + const result = await endPreviewBeforeOpening(projectDir, { + status: async () => null, + stop: never, + appInstalled: never, + }); + + expect(result).toEqual({ state: "none" }); + }); + + it("stops the background preview so the app can take the history lock", async () => { + const stop = vi.fn(async () => true); + + const result = await endPreviewBeforeOpening(projectDir, { + status: async () => background, + stop, + appInstalled: () => true, + }); + + expect(result).toEqual({ state: "stopped", port: 3210 }); + expect(stop).toHaveBeenCalledWith(projectDir, 3210); + }); + + it("leaves a preview it did not start in the background to its owner, naming the stop command", async () => { + const result = await endPreviewBeforeOpening(projectDir, { + status: async () => ({ pid: 999, port: 3002, projectDir }), + stop: never, + appInstalled: () => true, + }); + + expect(result).toMatchObject({ state: "left-running", port: 3002 }); + expect(result).toHaveProperty( + "stopCommand", + expect.stringMatching(/^hyperframes preview .+ --stop --port 3002$/), + ); + }); + + it("keeps the preview when the app isn't installed, since nothing will open", async () => { + const result = await endPreviewBeforeOpening(projectDir, { + status: async () => background, + stop: never, + appInstalled: () => false, + }); + + expect(result).toMatchObject({ state: "left-running", port: 3210 }); + }); + + it("reports a stop that fails instead of throwing, with the command to retry", async () => { + const result = await endPreviewBeforeOpening(projectDir, { + status: async () => background, + stop: async () => { + throw new Error("background preview did not stop"); + }, + appInstalled: () => true, + }); + + expect(result).toMatchObject({ + state: "left-running", + port: 3210, + error: "background preview did not stop", + }); + }); + + function liveLifecycle(saveSession: boolean) { + const stateHome = mkdtempSync(join(tmpdir(), "hf-open-preview-")); + onTestFinished(() => rmSync(stateHome, { recursive: true, force: true })); + if (saveSession) + writePreviewSession({ ...background, wrapperIdentity: "wrapper-birth" }, stateHome); + let running = true; + const server: ActiveServer = { + port: background.port, + projectName: "hyperframes-open-project", + projectDir, + version: "test", + pid: String(background.pid), + pidSource: "os", + }; + const lifecycle = { + stateHome, + scan: async () => (running ? [server] : []), + probe: async (port: number) => (running && port === server.port ? server : null), + kill: vi.fn(() => { + running = false; + }), + sleep: async () => {}, + identity: () => "wrapper-birth", + }; + return { + lifecycle, + deps: { + status: (dir: string, port: number) => readBackgroundPreviewStatus(dir, port, lifecycle), + stop: (dir: string, port: number) => stopBackgroundPreview(dir, port, lifecycle), + appInstalled: () => true, + }, + }; + } + + it("stops a saved background preview end to end and retires its session record", async () => { + const { lifecycle, deps } = liveLifecycle(true); + + const result = await endPreviewBeforeOpening(projectDir, deps); + + expect(result).toEqual({ state: "stopped", port: background.port }); + expect(lifecycle.kill).toHaveBeenCalledWith(background.pid); + expect(existsSync(previewSessionPath(projectDir, lifecycle.stateHome))).toBe(false); + expect(await readBackgroundPreviewStatus(projectDir, 3002, lifecycle)).toBeNull(); + }); + + it("never kills a matching server that has no saved background session", async () => { + const { lifecycle, deps } = liveLifecycle(false); + + const result = await endPreviewBeforeOpening(projectDir, deps); + + expect(result).toMatchObject({ state: "left-running", port: background.port }); + expect(lifecycle.kill).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/cli/src/commands/open.ts b/packages/cli/src/commands/open.ts index 3533c0aa8b..4dfb3106c0 100644 --- a/packages/cli/src/commands/open.ts +++ b/packages/cli/src/commands/open.ts @@ -2,8 +2,15 @@ import { defineCommand } from "../utils/defineCommand.js"; import type { Example } from "./_examples.js"; import { c } from "../ui/colors.js"; import { setCommandExitCode } from "../utils/commandResult.js"; -import { downloadHint, openInDesktop, type DesktopOpenResult } from "../utils/desktopApp.js"; +import { + desktopInstalled, + downloadHint, + openInDesktop, + previewStopCommandFor, + type DesktopOpenResult, +} from "../utils/desktopApp.js"; import { resolveProject, resolveProjectOrThrow, type ProjectDir } from "../utils/project.js"; +import { readBackgroundPreviewStatus, stopBackgroundPreview } from "./previewLifecycle.js"; export const examples: Example[] = [ ["Open this project in the HyperFrames desktop app", "hyperframes ."], @@ -19,6 +26,58 @@ const WHY_NOT: Record["reason"], s "open-failed": "The HyperFrames desktop app couldn't be started.", }; +type PreviewBeforeOpen = + | { state: "none" } + | { state: "stopped"; port: number } + | { state: "left-running"; port: number; stopCommand: string; error?: string }; + +const PREVIEW_SCAN_START_PORT = 3002; + +export async function endPreviewBeforeOpening( + dir: string, + { + status = readBackgroundPreviewStatus, + stop = stopBackgroundPreview, + appInstalled = () => desktopInstalled(), + }: { + status?: (dir: string, startPort: number) => ReturnType; + stop?: (dir: string, startPort: number) => Promise; + appInstalled?: () => boolean; + } = {}, +): Promise { + const running = await status(dir, PREVIEW_SCAN_START_PORT); + if (!running) return { state: "none" }; + const leftRunning = (error?: string): PreviewBeforeOpen => ({ + state: "left-running", + port: running.port, + stopCommand: previewStopCommandFor(dir, running.port), + ...(error ? { error } : {}), + }); + const startedInBackground = Boolean(running.logPath); + if (!startedInBackground || !appInstalled()) return leftRunning(); + try { + return (await stop(dir, running.port)) + ? { state: "stopped", port: running.port } + : { state: "none" }; + } catch (error) { + return leftRunning(error instanceof Error ? error.message : String(error)); + } +} + +function printPreview(preview: PreviewBeforeOpen, opened: boolean): void { + if (preview.state === "stopped") + return console.log( + `${c.success("◇")} Stopped this project's background preview (port ${preview.port}) so the app can edit it.`, + ); + if (preview.state !== "left-running" || !opened) return; + console.log( + preview.error + ? `${c.warn("◇")} Couldn't stop this project's preview (port ${preview.port}): ${preview.error}` + : `${c.warn("◇")} A preview of this project is running (port ${preview.port}), and the app's edits wait until it stops.`, + ); + console.log(` Stop it with: ${c.accent(preview.stopCommand)}`); +} + function printResult(project: ProjectDir, result: DesktopOpenResult): void { if (result.opened) { console.log(`${c.success("◇")} Opening ${c.accent(project.name)} in ${result.app}`); @@ -61,15 +120,21 @@ export default defineCommand({ }, json: { type: "boolean", description: "Output as JSON", default: false }, }, - run({ args }) { + async run({ args }) { const project = args.json ? projectForJson(args.dir) : resolveProject(args.dir); if (!project) return; + const preview = await endPreviewBeforeOpening(project.dir); const result = openInDesktop(project.dir); if (!result.opened) setCommandExitCode(1); const catchUp = result.opened && result.handedOver ? { catchUp: "npx hyperframes catch-up" } : {}; if (args.json) - console.log(JSON.stringify({ project: project.dir, ...result, ...catchUp }, null, 2)); - else printResult(project, result); + console.log( + JSON.stringify({ project: project.dir, ...result, ...catchUp, preview }, null, 2), + ); + else { + printPreview(preview, result.opened); + printResult(project, result); + } }, }); diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.ts index 34cd386a8d..4b909468a8 100644 --- a/packages/cli/src/commands/preview.ts +++ b/packages/cli/src/commands/preview.ts @@ -373,6 +373,7 @@ export default defineCommand({ return; } printStudioSummary(project.name, previewBaseUrl(status.port), project.dir, { + preview: status.logPath ? "background" : "foreground", details: [ `${status.logPath ? "Background preview" : "Preview"} running${status.pid === null ? "" : ` (PID ${status.pid})`}.`, ...(status.logPath ? [`Log: ${status.logPath}`] : []), @@ -556,6 +557,7 @@ export default defineCommand({ } else { clack.intro(c.bold("hyperframes preview")); printStudioSummary(projectName, url, dir, { + preview: "background", details: [ background.type === "reused" ? "Reusing the background server already running for this project." @@ -1323,14 +1325,14 @@ function printStudioSummary( projectName: string, serverUrl: string, projectDir: string, - opts: { details?: string[]; footer?: string } = {}, + opts: { details?: string[]; footer?: string; preview?: "background" | "foreground" } = {}, ): void { const urls = studioSummaryUrls(projectName, serverUrl); console.log(); console.log(` ${c.dim("Project")} ${c.accent(projectName)}`); console.log(` ${c.dim("Studio")} ${c.accent(urls.studioUrl)}`); console.log(` ${c.dim("Server")} ${c.accent(urls.serverUrl)}`); - const hint = desktopHint(projectDir); + const hint = desktopHint(projectDir, { preview: opts.preview }); if (hint) console.log(` ${c.dim("Desktop")} ${hint}`); console.log(); for (const detail of opts.details ?? []) { @@ -1439,6 +1441,7 @@ function attachStudioReadyHandler( } else { spinner.stop(c.success("Studio running")); printStudioSummary(projectName, url, projectDir, { + preview: "foreground", footer: "Press Ctrl+C to stop", }); } @@ -1695,6 +1698,7 @@ export async function runEmbeddedMode( console.log(); } printStudioSummary(pName, url, dir, { + preview: "foreground", details: [ "Edit with your AI agent — it has HyperFrames skills installed.", "Changes reload automatically in the studio.", diff --git a/packages/cli/src/templates/_shared/AGENTS.md b/packages/cli/src/templates/_shared/AGENTS.md index 45ab10842b..6a8302b267 100644 --- a/packages/cli/src/templates/_shared/AGENTS.md +++ b/packages/cli/src/templates/_shared/AGENTS.md @@ -53,7 +53,9 @@ npx hyperframes docs # reference docs in terminal > **Agents must use `npx hyperframes preview --background` for Studio handoff.** Do not rely > on a shell/tool `run_in_background` wrapper around `npm run dev`: that foreground process > remains owned by the invoking session and can disappear while the browser stays open, -> leaving refreshes at `ERR_CONNECTION_TIMED_OUT`. Verify with `preview --status`, keep it +> leaving refreshes at `ERR_CONNECTION_TIMED_OUT`. Verify with `preview --status`. The desktop +> app can't edit the project while this preview runs, so `npx hyperframes open` stops it first. +> If you hand the project to the app another way, run `preview --stop` before you do. Otherwise keep it > alive through review, and stop it explicitly with `preview --stop` afterward. > **Back from the desktop app.** Once this project was opened in the HyperFrames desktop app, run `npx hyperframes catch-up` before your next change here: it lists what the person asked Framey in the app and which files changed since. diff --git a/packages/cli/src/templates/_shared/CLAUDE.md b/packages/cli/src/templates/_shared/CLAUDE.md index 45ab10842b..6a8302b267 100644 --- a/packages/cli/src/templates/_shared/CLAUDE.md +++ b/packages/cli/src/templates/_shared/CLAUDE.md @@ -53,7 +53,9 @@ npx hyperframes docs # reference docs in terminal > **Agents must use `npx hyperframes preview --background` for Studio handoff.** Do not rely > on a shell/tool `run_in_background` wrapper around `npm run dev`: that foreground process > remains owned by the invoking session and can disappear while the browser stays open, -> leaving refreshes at `ERR_CONNECTION_TIMED_OUT`. Verify with `preview --status`, keep it +> leaving refreshes at `ERR_CONNECTION_TIMED_OUT`. Verify with `preview --status`. The desktop +> app can't edit the project while this preview runs, so `npx hyperframes open` stops it first. +> If you hand the project to the app another way, run `preview --stop` before you do. Otherwise keep it > alive through review, and stop it explicitly with `preview --stop` afterward. > **Back from the desktop app.** Once this project was opened in the HyperFrames desktop app, run `npx hyperframes catch-up` before your next change here: it lists what the person asked Framey in the app and which files changed since. diff --git a/packages/cli/src/utils/desktopApp.test.ts b/packages/cli/src/utils/desktopApp.test.ts index 0ea014e124..0484b4bb02 100644 --- a/packages/cli/src/utils/desktopApp.test.ts +++ b/packages/cli/src/utils/desktopApp.test.ts @@ -19,6 +19,7 @@ import { desktopInstalled, openCommandFor, openInDesktop, + previewStopCommandFor, } from "./desktopApp.js"; const LIVE = { ready: true, platform: "darwin" as const, env: {}, installed: () => true }; @@ -398,6 +399,16 @@ describe("openCommandFor", () => { ); expect(openCommandFor(join(work, "my film"), work)).toBe('hyperframes open "my film"'); }); + + it("names the matching `preview --stop` the same way", () => { + const work = resolve("work"); + expect(previewStopCommandFor(work, 3002, work)).toBe( + "hyperframes preview . --stop --port 3002", + ); + expect(previewStopCommandFor(join(work, "my film"), 4567, work)).toBe( + 'hyperframes preview "my film" --stop --port 4567', + ); + }); }); describe("desktopInstalled", () => { @@ -483,6 +494,19 @@ describe("desktopHint", () => { ); }); + it("tells a preview's reader that the app can't edit while the preview runs", () => { + const installed = { ...mac, ready: true, installed: true }; + expect(desktopHint(process.cwd(), { ...installed, preview: "background" })).toBe( + "Keep editing by chatting with Framey in the desktop app: hyperframes open . (this stops the background preview)", + ); + expect(desktopHint(process.cwd(), { ...installed, preview: "foreground" })).toBe( + "Keep editing by chatting with Framey in the desktop app: stop this preview, then run hyperframes open .", + ); + expect(desktopHint(process.cwd(), { ...mac, installed: false, preview: "background" })).toBe( + MAC_HINT, + ); + }); + it("says nothing inside the app, whose runs carry HYPERFRAMES_DESKTOP_PROJECT", () => { const inApp = { ...mac, diff --git a/packages/cli/src/utils/desktopApp.ts b/packages/cli/src/utils/desktopApp.ts index c26d71d664..f0c9f7f845 100644 --- a/packages/cli/src/utils/desktopApp.ts +++ b/packages/cli/src/utils/desktopApp.ts @@ -246,10 +246,18 @@ function leaveIntent(dir: string, cta?: string, doc?: "storyboard"): () => void }; } +function shownDir(dir: string, cwd: string): string { + const shown = relative(cwd, dir) || "."; + return /\s/.test(shown) ? JSON.stringify(shown) : shown; +} + /** The `hyperframes open` line for a project, relative to where the person is. */ export function openCommandFor(dir: string, cwd = process.cwd()): string { - const shown = relative(cwd, dir) || "."; - return `hyperframes open ${/\s/.test(shown) ? JSON.stringify(shown) : shown}`; + return `hyperframes open ${shownDir(dir, cwd)}`; +} + +export function previewStopCommandFor(dir: string, port: number, cwd = process.cwd()): string { + return `hyperframes preview ${shownDir(dir, cwd)} --stop --port ${port}`; } /** Spotlight's copies of an app with this bundle id; an updater's hidden leftover (`.X.app.installing-…`) is none. */ @@ -280,7 +288,7 @@ function someoneToTell(env: NodeJS.ProcessEnv, tty: boolean): boolean { return tty || env["HYPERFRAMES_AGENT"] === "1" || isAgentDriven(env); } -/** The app line render and preview print for a person or the agent relaying it (skills/hyperframes/SKILL.md); null inside the app, under CI or a pipe, or with nothing to open or download. */ +/** The app line render and preview print (skills/hyperframes/SKILL.md), saying how a preview stops; null inside the app, under CI or a pipe, or with nothing to open or download. */ export function desktopHint( dir: string, { @@ -289,17 +297,27 @@ export function desktopHint( installed, platform = process.platform, tty = process.stdout.isTTY === true, + preview, }: { env?: NodeJS.ProcessEnv; ready?: boolean; installed?: boolean; platform?: NodeJS.Platform; tty?: boolean; + preview?: "background" | "foreground"; } = {}, ): string | null { if (insideHostApp(env) || !someoneToTell(env, tty)) return null; - if (ready && (installed ?? desktopInstalled({ platform, env }))) - return `Keep editing by chatting with Framey in the desktop app: ${openCommandFor(dir)}`; + if (ready && (installed ?? desktopInstalled({ platform, env }))) { + const open = openCommandFor(dir); + const how = + preview === "background" + ? `${open} (this stops the background preview)` + : preview === "foreground" + ? `stop this preview, then run ${open}` + : open; + return `Keep editing by chatting with Framey in the desktop app: ${how}`; + } const url = desktopDownloadUrl(platform); return url ? downloadHint(url) : null; } diff --git a/skills-manifest.json b/skills-manifest.json index 1e0f78fac5..03e91da346 100644 --- a/skills-manifest.json +++ b/skills-manifest.json @@ -10,7 +10,7 @@ "files": 78 }, "hyperframes-cli": { - "hash": "af4aa1c5232591dd", + "hash": "adcd30f21c700eba", "files": 13 }, "hyperframes-registry": { diff --git a/skills/hyperframes-cli/references/preview-render.md b/skills/hyperframes-cli/references/preview-render.md index 31d1255cbf..19de7a6770 100644 --- a/skills/hyperframes-cli/references/preview-render.md +++ b/skills/hyperframes-cli/references/preview-render.md @@ -23,7 +23,7 @@ http://localhost:/#project/ Use the actual port and project directory name; treat `index.html` as source-code context, not the preview surface. For example, after `npx hyperframes preview --background --port 3017` in `codex-openai-video`, report `http://localhost:3017/#project/codex-openai-video`. -Two ways a handed URL turns out dead — check both before handing it back: the URL is missing its `#project/` hash (Studio loads but has no project to open), or the server is not actually running. Bare `preview` automatically creates a managed persistent session in a non-TTY agent shell; `--background` remains the clearest explicit form. Verify the printed URL returns HTTP 200, keep it alive for the whole review, and stop it explicitly with `npx hyperframes preview --stop` afterward. Use the printed URL as-is: HyperFrames URL-encodes project names that contain route metacharacters. +Two ways a handed URL turns out dead — check both before handing it back: the URL is missing its `#project/` hash (Studio loads but has no project to open), or the server is not actually running. Bare `preview` automatically creates a managed persistent session in a non-TTY agent shell; `--background` remains the clearest explicit form. Verify the printed URL returns HTTP 200, keep it alive for the whole review, and stop it explicitly with `npx hyperframes preview --stop` afterward. The desktop app can't edit a project while its preview runs; `npx hyperframes open` stops the background preview before handing the project over. Use the printed URL as-is: HyperFrames URL-encodes project names that contain route metacharacters. ### Agent context from Studio selection