Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 35 additions & 11 deletions backend/src/development/developmentStack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ export interface DevelopmentStackConfig {
frontendPort: number;
gatewayTokenFile?: string;
gatewayUrl: string;
hotReload: boolean;
openClawClientHome: string;
openClawConfigSource?: string;
openClawHome: string;
Expand Down Expand Up @@ -269,6 +270,18 @@ function configuredStateOwner(value: string | undefined, fallback: string): stri
return owner;
}

function isEnvironmentFlagEnabled(
name: string,
value: string | undefined,
isEnabledByDefault: boolean
): boolean {
const configured = value?.trim();
if (!configured) return isEnabledByDefault;
if (configured === "1") return true;
if (configured === "0") return false;
throw new TypeError(`${name} must be 0 or 1`);
}

function absoluteNonRootPath(
name: string,
value: string | undefined,
Expand Down Expand Up @@ -425,6 +438,11 @@ export function resolveDevelopmentStackConfig(
frontendPort,
gatewayTokenFile,
gatewayUrl: gatewayUrl || DEFAULT_GATEWAY_URL,
hotReload: isEnvironmentFlagEnabled(
"MIRA_DASHBOARD_DEV_HOT_RELOAD",
environment.MIRA_DASHBOARD_DEV_HOT_RELOAD,
true
),
openClawClientHome: path.join(stateRoot, "openclaw-client"),
openClawConfigSource: absoluteNonRootPath(
"MIRA_DASHBOARD_DEV_OPENCLAW_CONFIG_SOURCE",
Expand Down Expand Up @@ -993,6 +1011,7 @@ function frontendEnvironment(config: DevelopmentStackConfig): Record<string, str
DASHBOARD_API_TARGET: config.apiTarget,
HOST: config.frontendHost,
MIRA_DASHBOARD_DEV_COOKIE_NAMESPACE: `mira_dashboard_dev_${config.frontendPort}`,
MIRA_DASHBOARD_DEV_HOT_RELOAD: config.hotReload ? "1" : "0",
MIRA_DASHBOARD_DEV_PUBLIC_ORIGIN: config.publicOrigin,
PORT: String(config.frontendPort),
};
Expand All @@ -1013,27 +1032,31 @@ function stopChild(child: DevelopmentChild): void {
}
}

/** Starts watched frontend/backend children and keeps their lifecycle coupled. */
/** Starts frontend/backend children and keeps their lifecycle coupled. */
export async function runDevelopmentStack(
config: DevelopmentStackConfig
): Promise<number> {
const state = prepareDevelopmentState(config);
prepareDevelopmentLog(config);
const bun = Bun.which("bun") || process.execPath;
const backend = Bun.spawn([bun, "--watch", "src/serverStart.ts"], {
const watchArguments = config.hotReload ? ["--watch"] : [];
const backend = Bun.spawn([bun, ...watchArguments, "src/serverStart.ts"], {
cwd: path.join(config.repositoryRoot, "backend"),
env: developmentBackendEnvironment(config),
stderr: "inherit",
stdin: "inherit",
stdout: "inherit",
});
const frontend = Bun.spawn([bun, "--watch", "scripts/developmentFrontend.ts"], {
cwd: config.repositoryRoot,
env: frontendEnvironment(config),
stderr: "inherit",
stdin: "inherit",
stdout: "inherit",
});
const frontend = Bun.spawn(
[bun, ...watchArguments, "scripts/developmentFrontend.ts"],
{
cwd: config.repositoryRoot,
env: frontendEnvironment(config),
stderr: "inherit",
stdin: "inherit",
stdout: "inherit",
}
);
let developmentLogFixtureIndex = 0;
const developmentLogFixtureTimer = setInterval(() => {
try {
Expand Down Expand Up @@ -1065,8 +1088,9 @@ export async function runDevelopmentStack(
console.log(
[
`Mira Dashboard development stack: ${config.publicOrigin}`,
`Frontend HMR: ${config.frontendHost}:${config.frontendPort}`,
`Backend HMR: ${config.backendHost}:${config.backendPort}`,
`Frontend${config.hotReload ? " HMR" : ""}: ${config.frontendHost}:${config.frontendPort}`,
`Backend${config.hotReload ? " HMR" : ""}: ${config.backendHost}:${config.backendPort}`,
`Hot reload: ${config.hotReload ? "enabled" : "disabled"}.`,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
`State: ${config.stateRoot} (database ${state.database}, workspace ${state.workspace}, releases ${state.releases})`,
`Gateway: ${config.gatewayUrl}`,
"Isolated scheduler/worker enabled.",
Expand Down
5 changes: 4 additions & 1 deletion backend/src/routes/pullRequestRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
getPullRequestPreviewStatus,
prepareAndStartPullRequestPreview,
prepareAndStopPullRequestPreview,
reconcileClosedPullRequestPreview,
} from "../services/pullRequestPreviews.ts";
import {
getDashboardReleaseStatus,
Expand Down Expand Up @@ -43,7 +44,9 @@ export const pullRequestRoutes = {
"/api/pull-requests": {
GET: async () => {
try {
return json({ pullRequests: await listDashboardPullRequests() });
const pullRequests = await listDashboardPullRequests();
await reconcileClosedPullRequestPreview(pullRequests);
return json({ pullRequests });
} catch (error) {
return routeError(error);
}
Expand Down
159 changes: 140 additions & 19 deletions backend/src/services/pullRequestPreviewHost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ const COMMIT_PATTERN = /^[\da-f]{40}$/u;
const UNIT_NAME_PATTERN = /^[A-Za-z0-9_.@-]+\.service$/u;
const DEFAULT_GATEWAY_URL = "ws://127.0.0.1:18789";
const DEFAULT_GATEWAY_PROXY_PORT = 18_790;
const DEFAULT_PREVIEW_WORKTREE_PATH = "/home/ubuntu/projects/mira-dashboard-preview";
const PREVIEW_REFERENCE = "refs/mira-dashboard/previews/active";
const PREVIEW_GATEWAY_PROXY_ENTRYPOINT = "pullRequestPreviewGatewayProxy.js";
const PREVIEW_GATEWAY_PROXY_READY_TIMEOUT_MS = 45_000;
const PREVIEW_GATEWAY_PROXY_READY_POLL_MS = 250;
Expand Down Expand Up @@ -81,6 +83,12 @@ export interface PullRequestPreviewCandidate {
title: string;
}

export interface PullRequestPreviewCleanupResult {
message: string;
number: number;
status: "removed" | "skipped" | "warning";
}

export interface PullRequestPreviewConfig {
allowedAuthors: ReadonlySet<string>;
backendPort: number;
Expand All @@ -96,6 +104,7 @@ export interface PullRequestPreviewConfig {
gatewayUpstreamTokenFile: string;
gatewayUrl: string;
gitCommonDirectory: string;
managedWorktreePath: string;
openClawConfigSource?: string;
previewRoot: string;
recentAuthMinutes?: string;
Expand All @@ -105,7 +114,6 @@ export interface PullRequestPreviewConfig {
stateFile: string;
unitName: string;
workspaceSource?: string;
worktreeRoot: string;
}

interface PullRequestPreviewRecord {
Expand Down Expand Up @@ -277,16 +285,28 @@ export function resolvePullRequestPreviewConfig(
"MIRA_DASHBOARD_ROOT",
environment.MIRA_DASHBOARD_ROOT?.trim() || "/home/ubuntu/projects/mira-dashboard"
);
const worktreeRoot = absoluteNonRootPath(
"MIRA_DASHBOARD_WORKTREE_ROOT",
environment.MIRA_DASHBOARD_WORKTREE_ROOT?.trim() ||
"/home/ubuntu/projects/mira-dashboard-worktrees"
);
const previewRoot = absoluteNonRootPath(
"MIRA_DASHBOARD_PREVIEW_ROOT",
environment.MIRA_DASHBOARD_PREVIEW_ROOT?.trim() ||
"/home/ubuntu/projects/mira-dashboard-preview-state/managed"
);
const managedWorktreePath = absoluteNonRootPath(
"MIRA_DASHBOARD_PREVIEW_WORKTREE_PATH",
environment.MIRA_DASHBOARD_PREVIEW_WORKTREE_PATH?.trim() ||
DEFAULT_PREVIEW_WORKTREE_PATH
);
if (
[dashboardRoot, previewRoot].some(
(protectedRoot) =>
managedWorktreePath === protectedRoot ||
isPathStrictlyWithin(managedWorktreePath, protectedRoot) ||
isPathStrictlyWithin(protectedRoot, managedWorktreePath)
)
) {
throw new TypeError(
"MIRA_DASHBOARD_PREVIEW_WORKTREE_PATH must not overlap Dashboard source or preview state"
);
}
const frontendPort = configuredPort(
"MIRA_DASHBOARD_PREVIEW_FRONTEND_PORT",
environment.MIRA_DASHBOARD_PREVIEW_FRONTEND_PORT,
Expand Down Expand Up @@ -368,6 +388,7 @@ export function resolvePullRequestPreviewConfig(
dashboardRoot,
environment.MIRA_DASHBOARD_PREVIEW_GIT_COMMON_DIR
),
managedWorktreePath,
openClawConfigSource: openClawSourceRoot
? path.join(openClawSourceRoot, "openclaw.json")
: undefined,
Expand All @@ -394,7 +415,6 @@ export function resolvePullRequestPreviewConfig(
workspaceSource: openClawSourceRoot
? path.join(openClawSourceRoot, "workspace")
: undefined,
worktreeRoot,
};
}

Expand Down Expand Up @@ -696,8 +716,47 @@ function githubCommandEnvironment(): Record<string, string | undefined> {
return environment;
}

function previewWorktreePath(config: PullRequestPreviewConfig, number: number): string {
return path.join(config.worktreeRoot, `preview-pr-${number}`);
function previewWorktreePath(config: PullRequestPreviewConfig): string {
return config.managedWorktreePath;
}

async function removePreviewWorktree(
config: PullRequestPreviewConfig,
worktreePath: string,
signal?: AbortSignal
): Promise<boolean> {
const resolvedWorktreePath = path.resolve(worktreePath);
if (resolvedWorktreePath !== path.resolve(config.managedWorktreePath)) {
throw new Error("Refusing to remove an unmanaged preview worktree");
}
if (!existsSync(resolvedWorktreePath)) return false;
Comment thread
mira-2026 marked this conversation as resolved.
Outdated
if (!isRealDirectory(resolvedWorktreePath)) {
throw new Error("Preview worktree path must be a real directory");
}
const { stdout: registeredRoot } = await runCommand(
"git",
["-C", resolvedWorktreePath, "rev-parse", "--show-toplevel"],
{ signal }
);
if (realpathSync(registeredRoot.trim()) !== realpathSync(resolvedWorktreePath)) {
throw new Error("Preview path is not the expected registered worktree");
}
await runCommand(
"git",
[
"-C",
config.dashboardRoot,
"worktree",
"remove",
"--force",
resolvedWorktreePath,
],
{ signal, timeoutMs: 120_000 }
);
if (existsSync(resolvedWorktreePath)) {
throw new Error("Git did not remove the managed preview worktree");
}
return true;
}

async function ensurePreviewWorktree(
Expand All @@ -706,12 +765,8 @@ async function ensurePreviewWorktree(
commitSha: string,
signal?: AbortSignal
): Promise<string> {
ensureRealDirectory(config.worktreeRoot);
const worktreePath = previewWorktreePath(config, number);
if (!isPathStrictlyWithin(worktreePath, config.worktreeRoot)) {
throw new Error("Preview worktree escaped the configured worktree root");
}
const previewReference = `refs/mira-dashboard/previews/pr-${number}`;
ensureRealDirectory(path.dirname(config.managedWorktreePath));
Comment thread
mira-2026 marked this conversation as resolved.
Outdated
const worktreePath = previewWorktreePath(config);
await runCommand(
"git",
[
Expand All @@ -721,7 +776,7 @@ async function ensurePreviewWorktree(
"--force",
"--no-tags",
"origin",
`pull/${number}/head:${previewReference}`,
`pull/${number}/head:${PREVIEW_REFERENCE}`,
],
{
env: githubCommandEnvironment(),
Expand All @@ -731,7 +786,7 @@ async function ensurePreviewWorktree(
);
const { stdout: fetchedCommit } = await runCommand(
"git",
["-C", config.dashboardRoot, "rev-parse", previewReference],
["-C", config.dashboardRoot, "rev-parse", PREVIEW_REFERENCE],
{ env: githubCommandEnvironment(), signal }
);
if (fetchedCommit.trim() !== commitSha) {
Expand Down Expand Up @@ -961,6 +1016,28 @@ function managedStateRoot(config: PullRequestPreviewConfig, number: number): str
return stateRoot;
}

function didRemoveManagedPreviewState(
config: PullRequestPreviewConfig,
number: number
): boolean {
const stateRoot = managedStateRoot(config, number);
if (!existsSync(stateRoot)) return false;
if (!isRealDirectory(stateRoot)) {
throw new Error("PR dev state path must be a real directory");
}
rmSync(stateRoot, { force: true, recursive: true });
return true;
}

function didRemovePreviewRecord(config: PullRequestPreviewConfig): boolean {
if (!existsSync(config.stateFile)) return false;
if (!isRealRegularFile(config.stateFile)) {
throw new Error("PR dev record path must be a real regular file");
}
rmSync(config.stateFile, { force: true });
return true;
}

function previewGatewayProxyUrl(config: PullRequestPreviewConfig): string {
return `ws://127.0.0.1:${config.gatewayProxyPort}/gateway`;
}
Expand Down Expand Up @@ -1122,6 +1199,9 @@ export function buildPullRequestPreviewSandboxCommand(input: {
"MIRA_DASHBOARD_DEV_GATEWAY_URL",
previewGatewayProxyUrl(config),
"--setenv",
"MIRA_DASHBOARD_DEV_HOT_RELOAD",
"0",
"--setenv",
"MIRA_DASHBOARD_DEV_PUBLIC_ORIGIN",
publicOrigin,
"--setenv",
Expand Down Expand Up @@ -1515,7 +1595,7 @@ async function waitForPreviewReady(
});
if (response.ok && state?.activeState === "active") return;
} catch {
// The watched frontend/backend pair is still starting.
// The managed frontend/backend pair is still starting.
}
await Bun.sleep(PREVIEW_READY_POLL_MS);
}
Expand Down Expand Up @@ -1617,7 +1697,7 @@ export async function startPullRequestPreview(
isTailscaleServeOwned = false;
}
const publicOrigin = tailscaleRoute.url;
const worktreePath = previewWorktreePath(config, number);
const worktreePath = previewWorktreePath(config);
const startingRecord: PullRequestPreviewRecord = {
backendPort: config.backendPort,
commitSha: pullRequest.commitSha,
Expand Down Expand Up @@ -1759,3 +1839,44 @@ export async function stopPullRequestPreview(
writePreviewRecord(config, stoppedRecord);
return publicPreviewStatus(stoppedRecord);
}

/** Removes the shared checkout and isolated state after its owning PR closes. */
export async function cleanupClosedPullRequestPreview(
number: number,
options: { config?: PullRequestPreviewConfig } = {}
): Promise<PullRequestPreviewCleanupResult> {
const config = options.config ?? resolvePullRequestPreviewConfig();
const record = readPreviewRecord(config);
Comment thread
mira-2026 marked this conversation as resolved.
Outdated
const hasManagedSlotOwnership = record?.number === number;
let didRemove = false;
try {
if (hasManagedSlotOwnership) {
await stopPullRequestPreview(number, { config });
didRemove =
(await removePreviewWorktree(config, previewWorktreePath(config))) ||
Comment thread
mira-2026 marked this conversation as resolved.
didRemove;
await runCommand("git", [
"-C",
config.dashboardRoot,
"update-ref",
"-d",
PREVIEW_REFERENCE,
]);
didRemove = didRemovePreviewRecord(config) || didRemove;
}
didRemove = didRemoveManagedPreviewState(config, number) || didRemove;
return {
message: didRemove
? `Removed managed PR dev data for #${number}`
: `No managed PR dev data found for #${number}`,
number,
status: didRemove ? "removed" : "skipped",
};
} catch (error) {
return {
message: `PR dev cleanup warning for #${number}: ${errorMessage(error, "cleanup failed")}`,
number,
status: "warning",
};
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Loading