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 <noreply@anthropic.com>
This commit is contained in:
Michael Wang
2026-11-07 17:24:14 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 7b1d9ccebf
commit 896a77c307
10 changed files with 274 additions and 15 deletions
+7
View File
@@ -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
+137
View File
@@ -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();
});
});
+69 -4
View File
@@ -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<Extract<DesktopOpenResult, { opened: false }>["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<typeof readBackgroundPreviewStatus>;
stop?: (dir: string, startPort: number) => Promise<boolean>;
appInstalled?: () => boolean;
} = {},
): Promise<PreviewBeforeOpen> {
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);
}
},
});
+6 -2
View File
@@ -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.",
+3 -1
View File
@@ -53,7 +53,9 @@ npx hyperframes docs <topic> # 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.
+3 -1
View File
@@ -53,7 +53,9 @@ npx hyperframes docs <topic> # 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.
+24
View File
@@ -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,
+23 -5
View File
@@ -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;
}
+1 -1
View File
@@ -10,7 +10,7 @@
"files": 78
},
"hyperframes-cli": {
"hash": "af4aa1c5232591dd",
"hash": "adcd30f21c700eba",
"files": 13
},
"hyperframes-registry": {
@@ -23,7 +23,7 @@ http://localhost:<port>/#project/<project-name>
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/<project-name>` 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/<project-name>` 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