mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-22 00:30:19 +02:00
Add manual dev restart action
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
2c0a0f2012
commit
84c85b930b
8 files changed
+324
-11
No files matched your search
+17
-3
@@ -36,6 +36,7 @@ const autoRestartPollIntervalMs = 2500;
|
||||
const gracefulShutdownTimeoutMs = 10_000;
|
||||
const changedPathSampleLimit = 5;
|
||||
const devServerStatusFilePath = path.join(repoRoot, ".paperclip", "dev-server-status.json");
|
||||
const devServerRestartRequestFilePath = path.join(repoRoot, ".paperclip", "dev-server-restart-request.json");
|
||||
const devServerStatusToken = mode === "dev" ? randomUUID() : null;
|
||||
const devServerStatusTokenHeader = "x-paperclip-dev-server-status-token";
|
||||
|
||||
@@ -70,6 +71,7 @@ const ignoredDirectoryNames = new Set([
|
||||
]);
|
||||
|
||||
const ignoredRelativePaths = new Set([
|
||||
".paperclip/dev-server-restart-request.json",
|
||||
".paperclip/dev-server-status.json",
|
||||
]);
|
||||
|
||||
@@ -348,6 +350,13 @@ function writeDevServerStatus() {
|
||||
function clearDevServerStatus() {
|
||||
if (mode !== "dev") return;
|
||||
rmSync(devServerStatusFilePath, { force: true });
|
||||
rmSync(devServerRestartRequestFilePath, { force: true });
|
||||
}
|
||||
|
||||
function consumeDevServerRestartRequest() {
|
||||
if (mode !== "dev" || !existsSync(devServerRestartRequestFilePath)) return false;
|
||||
rmSync(devServerRestartRequestFilePath, { force: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
async function updateDevServiceRecord(extra?: Record<string, unknown>) {
|
||||
@@ -633,7 +642,8 @@ async function startServerChild() {
|
||||
|
||||
async function maybeAutoRestartChild() {
|
||||
if (mode !== "dev" || restartInFlight || !child) return;
|
||||
if (dirtyPaths.size === 0 && pendingMigrations.length === 0) return;
|
||||
const manualRestartRequested = consumeDevServerRestartRequest();
|
||||
if (!manualRestartRequested && dirtyPaths.size === 0 && pendingMigrations.length === 0) return;
|
||||
|
||||
restartInFlight = true;
|
||||
let health: { devServer?: { enabled?: boolean; autoRestartEnabled?: boolean; activeRunCount?: number } } | null = null;
|
||||
@@ -645,11 +655,15 @@ async function maybeAutoRestartChild() {
|
||||
}
|
||||
|
||||
const devServer = health?.devServer;
|
||||
if (!devServer?.enabled || devServer.autoRestartEnabled !== true) {
|
||||
if (!devServer?.enabled) {
|
||||
restartInFlight = false;
|
||||
return;
|
||||
}
|
||||
if ((devServer.activeRunCount ?? 0) > 0) {
|
||||
if (!manualRestartRequested && devServer.autoRestartEnabled !== true) {
|
||||
restartInFlight = false;
|
||||
return;
|
||||
}
|
||||
if (!manualRestartRequested && (devServer.activeRunCount ?? 0) > 0) {
|
||||
restartInFlight = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { readPersistedDevServerStatus, toDevServerHealthStatus } from "../dev-server-status.js";
|
||||
import {
|
||||
getDevServerRestartRequestFilePath,
|
||||
readPersistedDevServerStatus,
|
||||
toDevServerHealthStatus,
|
||||
writeDevServerRestartRequest,
|
||||
} from "../dev-server-status.js";
|
||||
|
||||
const tempDirs = [];
|
||||
|
||||
@@ -73,4 +78,26 @@ describe("dev server status helpers", () => {
|
||||
|
||||
expect(readPersistedDevServerStatus({ PAPERCLIP_DEV_SERVER_STATUS_FILE: filePath })).toBeNull();
|
||||
});
|
||||
|
||||
it("writes restart requests next to the persisted status file", () => {
|
||||
const filePath = createTempStatusFile({
|
||||
dirty: true,
|
||||
changedPathsSample: ["server/src/app.ts"],
|
||||
pendingMigrations: [],
|
||||
});
|
||||
|
||||
const env = { PAPERCLIP_DEV_SERVER_STATUS_FILE: filePath };
|
||||
expect(writeDevServerRestartRequest({
|
||||
requestedAt: "2026-03-20T12:05:00.000Z",
|
||||
reason: "manual_restart_now",
|
||||
}, env)).toBe(true);
|
||||
|
||||
const requestPath = getDevServerRestartRequestFilePath(env);
|
||||
expect(requestPath).toBe(path.join(path.dirname(filePath), "dev-server-restart-request.json"));
|
||||
expect(requestPath && existsSync(requestPath)).toBe(true);
|
||||
expect(JSON.parse(readFileSync(requestPath!, "utf8"))).toEqual({
|
||||
requestedAt: "2026-03-20T12:05:00.000Z",
|
||||
reason: "manual_restart_now",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import express from "express";
|
||||
@@ -126,3 +126,80 @@ describe("GET /health dev-server supervisor access", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /health/dev-server/restart", () => {
|
||||
it("records a manual restart request for the dev runner", async () => {
|
||||
const previousFile = process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
|
||||
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = createDevServerStatusFile({
|
||||
dirty: true,
|
||||
lastChangedAt: "2026-03-20T12:00:00.000Z",
|
||||
changedPathCount: 1,
|
||||
changedPathsSample: ["server/src/routes/health.ts"],
|
||||
pendingMigrations: [],
|
||||
lastRestartAt: "2026-03-20T11:30:00.000Z",
|
||||
});
|
||||
|
||||
try {
|
||||
const app = express();
|
||||
app.use("/health", healthRoutes(undefined));
|
||||
|
||||
const res = await request(app).post("/health/dev-server/restart");
|
||||
|
||||
expect(res.status).toBe(202);
|
||||
expect(res.body).toEqual({ status: "restart_requested" });
|
||||
|
||||
const requestPath = path.join(
|
||||
path.dirname(process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE),
|
||||
"dev-server-restart-request.json",
|
||||
);
|
||||
expect(existsSync(requestPath)).toBe(true);
|
||||
expect(JSON.parse(readFileSync(requestPath, "utf8"))).toMatchObject({
|
||||
reason: "manual_restart_now",
|
||||
});
|
||||
} finally {
|
||||
if (previousFile === undefined) {
|
||||
delete process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
|
||||
} else {
|
||||
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = previousFile;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects unauthenticated manual restarts in authenticated mode", async () => {
|
||||
const previousFile = process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
|
||||
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = createDevServerStatusFile({
|
||||
dirty: true,
|
||||
changedPathCount: 1,
|
||||
changedPathsSample: ["server/src/routes/health.ts"],
|
||||
pendingMigrations: [],
|
||||
});
|
||||
|
||||
try {
|
||||
const app = express();
|
||||
app.use((req, _res, next) => {
|
||||
(req as any).actor = { type: "none", source: "none" };
|
||||
next();
|
||||
});
|
||||
app.use(
|
||||
"/health",
|
||||
healthRoutes(undefined, {
|
||||
deploymentMode: "authenticated",
|
||||
deploymentExposure: "private",
|
||||
authReady: true,
|
||||
companyDeletionEnabled: true,
|
||||
}),
|
||||
);
|
||||
|
||||
const res = await request(app).post("/health/dev-server/restart");
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: "board_access_required" });
|
||||
} finally {
|
||||
if (previousFile === undefined) {
|
||||
delete process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
|
||||
} else {
|
||||
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = previousFile;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { existsSync, readFileSync, statSync } from "node:fs";
|
||||
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
const MAX_PERSISTED_DEV_SERVER_STATUS_BYTES = 64 * 1024;
|
||||
|
||||
@@ -25,6 +26,31 @@ export type DevServerHealthStatus = {
|
||||
lastRestartAt: string | null;
|
||||
};
|
||||
|
||||
export type DevServerRestartRequest = {
|
||||
requestedAt: string;
|
||||
reason: "manual_restart_now";
|
||||
};
|
||||
|
||||
export function getDevServerRestartRequestFilePath(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): string | null {
|
||||
const statusFilePath = env.PAPERCLIP_DEV_SERVER_STATUS_FILE?.trim();
|
||||
if (!statusFilePath) return null;
|
||||
return path.join(path.dirname(statusFilePath), "dev-server-restart-request.json");
|
||||
}
|
||||
|
||||
export function writeDevServerRestartRequest(
|
||||
request: DevServerRestartRequest,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): boolean {
|
||||
const filePath = getDevServerRestartRequestFilePath(env);
|
||||
if (!filePath) return false;
|
||||
|
||||
mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
writeFileSync(filePath, `${JSON.stringify(request, null, 2)}\n`, "utf8");
|
||||
return true;
|
||||
}
|
||||
|
||||
function normalizeStringArray(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { Db } from "@paperclipai/db";
|
||||
import { and, count, eq, gt, inArray, isNull, sql } from "drizzle-orm";
|
||||
import { heartbeatRuns, instanceUserRoles, invites } from "@paperclipai/db";
|
||||
import type { DeploymentExposure, DeploymentMode } from "@paperclipai/shared";
|
||||
import { readPersistedDevServerStatus, toDevServerHealthStatus } from "../dev-server-status.js";
|
||||
import { readPersistedDevServerStatus, toDevServerHealthStatus, writeDevServerRestartRequest } from "../dev-server-status.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
import { serverVersion } from "../version.js";
|
||||
@@ -44,6 +44,40 @@ export function healthRoutes(
|
||||
) {
|
||||
const router = Router();
|
||||
|
||||
router.post("/dev-server/restart", async (req, res) => {
|
||||
const actorType = "actor" in req ? req.actor?.type : null;
|
||||
if (opts.deploymentMode === "authenticated" && actorType !== "board") {
|
||||
res.status(403).json({ error: "board_access_required" });
|
||||
return;
|
||||
}
|
||||
|
||||
const persistedDevServerStatus = readPersistedDevServerStatus();
|
||||
if (!persistedDevServerStatus) {
|
||||
res.status(404).json({ error: "dev_server_supervisor_unavailable" });
|
||||
return;
|
||||
}
|
||||
|
||||
const restartRequired =
|
||||
persistedDevServerStatus.dirty ||
|
||||
persistedDevServerStatus.changedPathCount > 0 ||
|
||||
persistedDevServerStatus.pendingMigrations.length > 0;
|
||||
if (!restartRequired) {
|
||||
res.status(409).json({ error: "restart_not_required" });
|
||||
return;
|
||||
}
|
||||
|
||||
const written = writeDevServerRestartRequest({
|
||||
requestedAt: new Date().toISOString(),
|
||||
reason: "manual_restart_now",
|
||||
});
|
||||
if (!written) {
|
||||
res.status(404).json({ error: "dev_server_supervisor_unavailable" });
|
||||
return;
|
||||
}
|
||||
|
||||
res.status(202).json({ status: "restart_requested" });
|
||||
});
|
||||
|
||||
router.get("/", async (req, res) => {
|
||||
const actorType = "actor" in req ? req.actor?.type : null;
|
||||
const exposeFullDetails = shouldExposeFullHealthDetails(
|
||||
|
||||
@@ -38,4 +38,15 @@ export const healthApi = {
|
||||
}
|
||||
return res.json();
|
||||
},
|
||||
requestDevServerRestart: async (): Promise<void> => {
|
||||
const res = await fetch("/api/health/dev-server/restart", {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
if (!res.ok) {
|
||||
const payload = await res.json().catch(() => null) as { error?: string } | null;
|
||||
throw new Error(payload?.error ?? `Failed to request restart (${res.status})`);
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,91 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { DevRestartBanner } from "./DevRestartBanner";
|
||||
|
||||
const mockHealthApi = vi.hoisted(() => ({
|
||||
requestDevServerRestart: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../api/health", () => ({
|
||||
healthApi: mockHealthApi,
|
||||
}));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
let root: ReturnType<typeof createRoot> | null = null;
|
||||
let container: HTMLDivElement | null = null;
|
||||
|
||||
const devServer = {
|
||||
enabled: true as const,
|
||||
restartRequired: true,
|
||||
reason: "backend_changes" as const,
|
||||
lastChangedAt: "2026-03-20T12:00:00.000Z",
|
||||
changedPathCount: 1,
|
||||
changedPathsSample: ["server/src/routes/health.ts"],
|
||||
pendingMigrations: [],
|
||||
autoRestartEnabled: true,
|
||||
activeRunCount: 1,
|
||||
waitingForIdle: true,
|
||||
lastRestartAt: "2026-03-20T11:30:00.000Z",
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(window, "confirm").mockReturnValue(true);
|
||||
vi.spyOn(window, "alert").mockImplementation(() => undefined);
|
||||
mockHealthApi.requestDevServerRestart.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (root) {
|
||||
act(() => root?.unmount());
|
||||
}
|
||||
root = null;
|
||||
container?.remove();
|
||||
container = null;
|
||||
vi.restoreAllMocks();
|
||||
mockHealthApi.requestDevServerRestart.mockReset();
|
||||
});
|
||||
|
||||
function render() {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() => root?.render(<DevRestartBanner devServer={devServer} />));
|
||||
return container;
|
||||
}
|
||||
|
||||
describe("DevRestartBanner", () => {
|
||||
it("confirms and requests an immediate restart while waiting for live runs", async () => {
|
||||
const node = render();
|
||||
const button = [...node.querySelectorAll("button")]
|
||||
.find((entry) => entry.textContent?.includes("Restart now"));
|
||||
|
||||
expect(node.textContent).toContain("Waiting for 1 live run to finish");
|
||||
expect(button).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(window.confirm).toHaveBeenCalledWith("Restart Paperclip now? This may interrupt 1 live run.");
|
||||
expect(mockHealthApi.requestDevServerRestart).toHaveBeenCalledTimes(1);
|
||||
expect(node.textContent).toContain("Restart requested");
|
||||
});
|
||||
|
||||
it("does not request restart when confirmation is declined", async () => {
|
||||
vi.mocked(window.confirm).mockReturnValue(false);
|
||||
const node = render();
|
||||
const button = [...node.querySelectorAll("button")]
|
||||
.find((entry) => entry.textContent?.includes("Restart now"));
|
||||
|
||||
await act(async () => {
|
||||
button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(mockHealthApi.requestDevServerRestart).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState } from "react";
|
||||
import { AlertTriangle, RotateCcw, TimerReset } from "lucide-react";
|
||||
import type { DevServerHealthStatus } from "../api/health";
|
||||
import { healthApi, type DevServerHealthStatus } from "../api/health";
|
||||
|
||||
function formatRelativeTimestamp(value: string | null): string | null {
|
||||
if (!value) return null;
|
||||
@@ -27,10 +28,31 @@ function describeReason(devServer: DevServerHealthStatus): string {
|
||||
}
|
||||
|
||||
export function DevRestartBanner({ devServer }: { devServer?: DevServerHealthStatus }) {
|
||||
const [restartPending, setRestartPending] = useState(false);
|
||||
if (!devServer?.enabled || !devServer.restartRequired) return null;
|
||||
|
||||
const currentDevServer = devServer;
|
||||
const changedAt = formatRelativeTimestamp(devServer.lastChangedAt);
|
||||
const sample = devServer.changedPathsSample.slice(0, 3);
|
||||
const activeRunLabel = `${devServer.activeRunCount} live run${
|
||||
devServer.activeRunCount === 1 ? "" : "s"
|
||||
}`;
|
||||
|
||||
async function requestRestartNow() {
|
||||
const warning =
|
||||
currentDevServer.activeRunCount > 0
|
||||
? `Restart Paperclip now? This may interrupt ${activeRunLabel}.`
|
||||
: "Restart Paperclip now?";
|
||||
if (!window.confirm(warning)) return;
|
||||
|
||||
setRestartPending(true);
|
||||
try {
|
||||
await healthApi.requestDevServerRestart();
|
||||
} catch (error) {
|
||||
setRestartPending(false);
|
||||
window.alert(error instanceof Error ? error.message : "Failed to request restart");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="border-b border-amber-300/60 bg-amber-50 text-amber-950 dark:border-amber-500/25 dark:bg-amber-500/10 dark:text-amber-100">
|
||||
@@ -65,11 +87,11 @@ export function DevRestartBanner({ devServer }: { devServer?: DevServerHealthSta
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 items-center gap-2 text-xs font-medium">
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs font-medium md:justify-end">
|
||||
{devServer.waitingForIdle ? (
|
||||
<div className="inline-flex items-center gap-2 rounded-full bg-amber-900/10 px-3 py-1.5 dark:bg-amber-100/10">
|
||||
<TimerReset className="h-3.5 w-3.5" />
|
||||
<span>Waiting for {devServer.activeRunCount} live run{devServer.activeRunCount === 1 ? "" : "s"} to finish</span>
|
||||
<span>Waiting for {activeRunLabel} to finish</span>
|
||||
</div>
|
||||
) : devServer.autoRestartEnabled ? (
|
||||
<div className="inline-flex items-center gap-2 rounded-full bg-amber-900/10 px-3 py-1.5 dark:bg-amber-100/10">
|
||||
@@ -82,6 +104,17 @@ export function DevRestartBanner({ devServer }: { devServer?: DevServerHealthSta
|
||||
<span>Restart <code>pnpm dev:once</code> after the active work is safe to interrupt</span>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex items-center gap-2 rounded-md bg-amber-950 px-3 py-1.5 text-xs font-semibold text-amber-50 transition-colors hover:bg-amber-900 disabled:cursor-not-allowed disabled:opacity-60 dark:bg-amber-200 dark:text-amber-950 dark:hover:bg-amber-100"
|
||||
onClick={() => {
|
||||
void requestRestartNow();
|
||||
}}
|
||||
disabled={restartPending}
|
||||
>
|
||||
<RotateCcw className="h-3.5 w-3.5" />
|
||||
<span>{restartPending ? "Restart requested" : "Restart now"}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user