Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: Complete interrupted preview workflows (#6076)
Oleg Isonendd316c53cc70
diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.tsindex b2946005eb..651c6d388b 100644--- a/packages/cli/src/commands/mcp.test.ts+++ b/packages/cli/src/commands/mcp.test.ts@@ -21,6 +21,7 @@ const {getLoadedProjectSessionSnapshot,getMcpOperationInput,reportMcpRunTermination,+ createMcpRunTerminationController,parseMcpRunCalls,parseMcpRunInput,parseMcpSingleOpCallInput,@@ -725,7 +726,7 @@ test("preserves completed calls when a run terminates during an asset query prevconst writeResult = vi.fn();const setExitCode = vi.fn();reportMcpRunTermination({- exitCode: 0,+ termination: { type: "beforeExit", exitCode: 0 },activeCall: { number: 4, tool: "preview-asset-query" },totalCalls: 4,results: completedResults,@@ -756,6 +757,93 @@ test("preserves completed calls when a run terminates during an asset query prevexpect(setExitCode).toHaveBeenCalledWith(1);});+test("identifies a signal that terminates preview.start", () => {+ const writeResult = vi.fn();+ const setExitCode = vi.fn();+ const options = {+ termination: { type: "signal" as const, signal: "SIGTERM" as const },+ activeCall: { number: 1, tool: "preview.start" },+ totalCalls: 4,+ results: [],+ elapsedMs: 123,+ writeStatus: vi.fn(),+ writeResult,+ setExitCode,+ };++ reportMcpRunTermination(options);++ expect(writeResult).toHaveBeenCalledWith({+ ok: false,+ error: {+ code: "MCP_RUN_TERMINATED",+ message:+ "MCP run terminated before call 1/4 preview.start returned a result.",+ },+ data: {+ completedCalls: 0,+ unfinishedCall: { number: 1, tool: "preview.start" },+ totalCalls: 4,+ results: [],+ },+ meta: {+ elapsedMs: 123,+ termination: { type: "signal", signal: "SIGTERM" },+ },+ });+ expect(setExitCode).not.toHaveBeenCalled();+});++test("disposes the preview owner before completing signal termination", async () => {+ const disposeHost = vi.fn(async () => undefined);+ const reportTermination = vi.fn();+ const exitWithSignal = vi.fn();+ const controller = createMcpRunTerminationController({+ getActiveCall: () => ({ number: 1, tool: "preview.start" }),+ totalCalls: 4,+ results: [],+ startedAt: Date.now(),+ disposeHost,+ reportTermination,+ exitWithSignal,+ });++ controller.signal("SIGTERM");+ await vi.waitFor(() => expect(exitWithSignal).toHaveBeenCalledOnce());+ controller.signal("SIGINT");++ expect(reportTermination).toHaveBeenCalledWith(+ expect.objectContaining({+ termination: { type: "signal", signal: "SIGTERM" },+ activeCall: { number: 1, tool: "preview.start" },+ totalCalls: 4,+ results: [],+ })+ );+ expect(disposeHost).toHaveBeenCalledOnce();+ expect(exitWithSignal).toHaveBeenCalledWith("SIGTERM");+});++test("completes signal termination when preview cleanup stalls", async () => {+ const exitWithSignal = vi.fn();+ const controller = createMcpRunTerminationController({+ getActiveCall: () => ({ number: 1, tool: "preview.start" }),+ totalCalls: 4,+ results: [],+ startedAt: Date.now(),+ disposeHost: () => new Promise<never>(() => undefined),+ reportTermination: vi.fn(),+ cleanupTimeout: 1,+ exitWithSignal,+ });++ controller.signal("SIGTERM");++ await vi.waitFor(() =>+ expect(exitWithSignal).toHaveBeenCalledWith("SIGTERM")+ );+});+test("preserves already structured MCP run errors", () => {expect(createMcpRunErrorPayload({diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.tsindex 300758c236..5f3ffe7113 100644--- a/packages/cli/src/commands/mcp.ts+++ b/packages/cli/src/commands/mcp.ts@@ -61,6 +61,7 @@ import {import { readCliDoc } from "../docs";import { printJson } from "../json-output";import { isPlainRecord } from "../type-utils";+import { withTimeout } from "../async-utils";import { LOCAL_DATA_FILE } from "../config";import {assertMcpBatchMutationApproved,@@ -694,8 +695,14 @@ type ActiveMcpRunCall = {tool: string;};+type McpRunTermination =+ | { type: "beforeExit"; exitCode: number }+ | { type: "signal"; signal: NodeJS.Signals };++const mcpRunTerminationCleanupTimeout = 5000;+const reportMcpRunTermination = ({- exitCode,+ termination,activeCall,totalCalls,results,@@ -706,7 +713,7 @@ const reportMcpRunTermination = ({process.exitCode = code;},}: {- exitCode: number;+ termination: McpRunTermination;activeCall: ActiveMcpRunCall;totalCalls: number;results: unknown[];@@ -736,40 +743,114 @@ const reportMcpRunTermination = ({data: { ...payload.data, unfinishedCall: activeCall },meta: {...payload.meta,- termination: { type: "beforeExit", exitCode },+ termination,},});- setExitCode(1);+ if (termination.type === "beforeExit") {+ setExitCode(1);+ }};-const installMcpRunTerminationHandlers = ({+const createMcpRunTerminationController = ({getActiveCall,totalCalls,results,startedAt,+ disposeHost,+ reportTermination = reportMcpRunTermination,+ cleanupTimeout = mcpRunTerminationCleanupTimeout,+ exitWithSignal = (signal) => {+ process.kill(process.pid, signal);+ },}: {getActiveCall: () => ActiveMcpRunCall | undefined;totalCalls: number;results: unknown[];startedAt: number;+ disposeHost: () => Promise<void>;+ reportTermination?: typeof reportMcpRunTermination;+ cleanupTimeout?: number;+ exitWithSignal?: (signal: NodeJS.Signals) => void;}) => {- const beforeExit = (exitCode: number) => {+ let isTerminating = false;+ const beginTermination = (termination: McpRunTermination) => {+ if (isTerminating) {+ return;+ }const activeCall = getActiveCall();- if (activeCall === undefined) {+ if (activeCall === undefined && termination.type === "beforeExit") {return;}- reportMcpRunTermination({- exitCode,- activeCall,- totalCalls,- results,- elapsedMs: Date.now() - startedAt,- });+ isTerminating = true;+ if (activeCall !== undefined) {+ reportTermination({+ termination,+ activeCall,+ totalCalls,+ results,+ elapsedMs: Date.now() - startedAt,+ });+ }+ const cleanup = withTimeout(+ Promise.resolve().then(disposeHost),+ cleanupTimeout,+ () => new Error("MCP run cleanup timed out.")+ ).catch(() => undefined);+ if (termination.type === "signal") {+ void cleanup.finally(() => exitWithSignal(termination.signal));+ }};- process.once("beforeExit", beforeExit);- return () => {+ return {+ beforeExit: (exitCode: number) =>+ beginTermination({ type: "beforeExit", exitCode }),+ signal: (signal: NodeJS.Signals) =>+ beginTermination({ type: "signal", signal }),+ };+};++const installMcpRunTerminationHandlers = ({+ getActiveCall,+ totalCalls,+ results,+ startedAt,+ disposeHost,+}: {+ getActiveCall: () => ActiveMcpRunCall | undefined;+ totalCalls: number;+ results: unknown[];+ startedAt: number;+ disposeHost: () => Promise<void>;+}) => {+ const controller = createMcpRunTerminationController({+ getActiveCall,+ totalCalls,+ results,+ startedAt,+ disposeHost,+ });+ const terminationSignals = ["SIGHUP", "SIGINT", "SIGTERM"] as const;+ const signalHandlers = new Map<NodeJS.Signals, () => void>();+ const beforeExit = (exitCode: number) => {+ dispose();+ controller.beforeExit(exitCode);+ };+ const dispose = () => {process.off("beforeExit", beforeExit);+ for (const [signal, handler] of signalHandlers) {+ process.off(signal, handler);+ }+ signalHandlers.clear();};+ process.once("beforeExit", beforeExit);+ for (const signal of terminationSignals) {+ const handler = () => {+ dispose();+ controller.signal(signal);+ };+ signalHandlers.set(signal, handler);+ process.once(signal, handler);+ }+ return dispose;};const reportMcpRunPreflightFailure = ({@@ -835,9 +916,11 @@ const assertSingleOpCallToolSupported = (tool: string) => {const createCliMcpHost = async ({projectRoot = cwd(),projectId,+ managePreviewProcessSignals = true,}: {projectRoot?: string;projectId?: string;+ managePreviewProcessSignals?: boolean;} = {}) => {const connection = await resolveApiConnection(undefined,@@ -869,7 +952,11 @@ const createCliMcpHost = async ({getCliProjectRestorePointsFile(projectRoot, projectId));await prepareMcpProjectSession(session);- const preview = createPreviewController({ host: "127.0.0.1", port: 5173 });+ const preview = createPreviewController(+ { host: "127.0.0.1", port: 5173 },+ undefined,+ { manageProcessSignals: managePreviewProcessSignals }+ );const previewFreshness = createPreviewFreshness();const previewHandlers = createMcpPreviewHandlers({preview,@@ -1424,6 +1511,7 @@ export const mcpRun = async (options: McpRunOptions) => {try {const mcpHost = await createCliMcpHost({projectId: options.project,+ managePreviewProcessSignals: false,});const { host, apiContract } = mcpHost;disposeHost = mcpHost.dispose;@@ -1447,6 +1535,7 @@ export const mcpRun = async (options: McpRunOptions) => {totalCalls: calls.length,results,startedAt,+ disposeHost: () => disposeHost(),});try {for (const [index, call] of calls.entries()) {@@ -1665,6 +1754,7 @@ export const __testing__ = {}),createMcpRunErrorPayload,reportMcpRunTermination,+ createMcpRunTerminationController,createMcpRunCheckpointStopPayload,getLoadedProjectSessionSnapshot,getMcpOperationInput,diff --git a/packages/cli/src/preview-server.test.ts b/packages/cli/src/preview-server.test.tsindex d359217bb4..6372124e95 100644--- a/packages/cli/src/preview-server.test.ts+++ b/packages/cli/src/preview-server.test.ts@@ -700,6 +700,33 @@ test("preview controller stops its process group before propagating termination"expect(controller.status().running).toBe(false);});+test("lets an outer lifecycle owner manage process signals", async () => {+ const process = createPreviewProcess();+ const parentProcess = {+ pid: 456,+ once: vi.fn(),+ off: vi.fn(),+ kill: vi.fn(() => true),+ };+ const controller = createPreviewController(+ {+ host: "127.0.0.1",+ port: 5173,+ cwd: "/tmp/preview",+ mode: "iterative",+ },+ createDependencies({+ spawn: vi.fn(() => process) as never,+ parentProcess,+ }),+ { manageProcessSignals: false }+ );++ await controller.start();++ expect(parentProcess.once).not.toHaveBeenCalled();+});+test("preview controller reuses custom running options when start has no options", async () => {const process = createPreviewProcess();const buildProcess = createPreviewProcess();diff --git a/packages/cli/src/preview-server.ts b/packages/cli/src/preview-server.tsindex fa5a7a1af7..b1e4f9943a 100644--- a/packages/cli/src/preview-server.ts+++ b/packages/cli/src/preview-server.ts@@ -538,7 +538,8 @@ const formatPreviewServerStartupError = ({export const createPreviewController = (defaults: PreviewServerOptions,- dependencies = defaultPreviewServerDependencies+ dependencies = defaultPreviewServerDependencies,+ { manageProcessSignals = true }: { manageProcessSignals?: boolean } = {}) => {let server: PreviewServerResult | undefined;let currentOptions = defaults;@@ -554,7 +555,7 @@ export const createPreviewController = (terminationHandlers.clear();};const installTerminationHandlers = () => {- if (terminationHandlers.size > 0) {+ if (manageProcessSignals === false || terminationHandlers.size > 0) {return;}for (const signal of terminationSignals) {