Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
5 changes: 3 additions & 2 deletions packages/host-service/src/daemon/singleton.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ export function getSupervisor(scriptPath?: string): DaemonSupervisor {
* migration plan, decision D3 — fire-and-track). Stash the promise so
* callers that need the daemon up can await it via `waitForDaemonReady`.
*/
export function startDaemonBootstrap(organizationId: string): void {
if (bootstrapPromise) return;
export function startDaemonBootstrap(organizationId: string): Promise<unknown> {
if (bootstrapPromise) return bootstrapPromise;
const sup = getSupervisor();
console.log("[supervisor] kicking off bootstrap (org):", organizationId);
bootstrapPromise = sup
Expand All @@ -87,6 +87,7 @@ export function startDaemonBootstrap(organizationId: string): void {
bootstrapPromise = null;
throw err;
});
return bootstrapPromise;
}

/**
Expand Down
258 changes: 137 additions & 121 deletions packages/host-service/src/serve.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { serve } from "@hono/node-server";
import { createAdaptorServer } from "@hono/node-server";
import { moveLegacyAppHome } from "@superset/agent-setup/legacy-home-move";
import { SANDBOX_PATHS } from "@superset/shared/sandbox/contract";
import { createApp } from "./app";
Expand Down Expand Up @@ -31,10 +31,28 @@ import { detachFromLaunchDirectory } from "./runtime/working-directory";
import { installProcessSafetyNet, installUpgradeSocketGuard } from "./safety";
import { configureSelfUpdater } from "./self-update";
import { boxLogsEnabled, captureFatalStartupError, initSentry } from "./sentry";
import { createStandaloneShutdown } from "./standalone-shutdown";
import { startTerminalBaseEnvResolution } from "./terminal/env";
import { startTerminalReaper } from "./terminal/reaper";
import { connectRelay, type TunnelClient } from "./tunnel";

const stopping = new AbortController();
const cleanup: {
stopServing?: () => Promise<void>;
stopDaemon?: () => Promise<void>;
dispose?: () => Promise<void>;
} = {};
const shutdown = createStandaloneShutdown({
stopServing: async () => cleanup.stopServing?.(),
stopDaemon: async () => cleanup.stopDaemon?.(),
dispose: async () => cleanup.dispose?.(),
});

function stopOnSignal(signal: NodeJS.Signals): void {
stopping.abort();
void shutdown(signal);
}

async function main(): Promise<void> {
installConsoleTimestamps();
recordBootStamp("host.process.start", processStartedAt());
Expand Down Expand Up @@ -78,12 +96,24 @@ async function main(): Promise<void> {
// so an in-flight bootstrap doesn't race with the first terminal launch.
// Non-terminal requests (workspaces, git, chat) are unaffected if the
// daemon takes time to come up or fails entirely.
startDaemonBootstrap(env.ORGANIZATION_ID);
const daemonBootstrap = startDaemonBootstrap(env.ORGANIZATION_ID);
// Bootstrap already logs its errors. The host can serve non-terminal requests without it.
void daemonBootstrap.catch(() => {});
if (process.env.NODE_ENV === "development") {
cleanup.stopDaemon = async () => {
try {
await daemonBootstrap;
} finally {
await getSupervisor().stop(env.ORGANIZATION_ID);
}
};
}

// Standalone entry only: the desktop provisions these itself for hosts it
// spawns (with its per-agent disable settings); this covers CLI/systemd
// launches, which previously had no notify hooks or shell wrappers (#6254).
await provisionAgentIntegrations();
if (stopping.signal.aborted) return;

const configTokenSource = env.SUPERSET_AUTH_CONFIG_PATH
? new ConfigFileSessionTokenSource({
Expand Down Expand Up @@ -115,6 +145,7 @@ async function main(): Promise<void> {
readLinkedPullRequests,
onPullRequestLinked,
terminalAgentStore,
dispose,
} = createApp({
config: {
organizationId: env.ORGANIZATION_ID,
Expand All @@ -133,135 +164,117 @@ async function main(): Promise<void> {
credentials: new LocalGitCredentialProvider(),
},
});

// Dev-mode shutdown: kill the daemon on host-service exit so dev
// iteration on daemon code resets cleanly. Production keeps the
// daemon detached so PTYs survive host-service restarts.
// Per the migration plan's D5 decision.
const isDev = process.env.NODE_ENV === "development";
if (isDev) {
let shuttingDown = false;
const devShutdown = async (signal: NodeJS.Signals) => {
if (shuttingDown) return;
shuttingDown = true;
console.log(
"[host-service] dev-mode signal, stopping pty-daemon for clean iteration:",
signal,
);
try {
await getSupervisor().stop(env.ORGANIZATION_ID);
} catch (err) {
console.error(
"[host-service] dev shutdown: supervisor.stop failed:",
caught(err),
);
} finally {
process.exit(0);
}
};
process.on("SIGINT", () => void devShutdown("SIGINT"));
process.on("SIGTERM", () => void devShutdown("SIGTERM"));
}
cleanup.dispose = dispose;

const relayAbort = new AbortController();
let tunnelPromise: Promise<TunnelClient | null> = Promise.resolve(null);
const hostname =
env.SUPERSET_HOST_RUN_MODE === "sandbox" ? undefined : "127.0.0.1";
const listen = { fetch: app.fetch, port: env.PORT, hostname };
const server = serve(listen, (info) => {
// Install only after the server is listening so startup throws still
// reach `main().catch(...)` and exit with a non-zero code.
installProcessSafetyNet();
const address = info.address.includes(":")
? `[${info.address}]`
: info.address;
console.log(
"[host-service] listening (address, port):",
address,
info.port,
);
recordBootStamp("host.listening");

startTerminalReaper(db);
startVitalsLog();
// A cloud workspace created with an agent starts it now: the pty daemon
// and event bus are up, and a person opening the workspace sees the
// agent's terminal the way they would on their own machine.
void launchSandboxAgent();
// A stop keeps the disk and drops every process, so nothing else on the
// box will notice that its agents are gone.
if (env.SUPERSET_HOST_RUN_MODE === "sandbox") void resumeCrashedAgents();
const sandboxWorkspaceId = process.env.SUPERSET_SANDBOX_WORKSPACE_ID;
if (env.SUPERSET_HOST_RUN_MODE === "sandbox" && sandboxWorkspaceId) {
startSandboxAgentStatusReporter({
apiUrl: env.SUPERSET_API_URL,
workspaceId: sandboxWorkspaceId,
hostSecret: env.HOST_SERVICE_SECRET,
store: terminalAgentStore,
});
startSandboxBoxPressureReporter({
apiUrl: env.SUPERSET_API_URL,
workspaceId: sandboxWorkspaceId,
hostSecret: env.HOST_SERVICE_SECRET,
read: readSandboxBoxResources,
});
if (boxLogsEnabled()) {
startSandboxBootPhaseLog({ path: SANDBOX_PATHS.bootLog });
}
startSandboxKeepalive({
keepalive: (pingsEveryMs) =>
api.sandbox.keepalive.mutate({ pingsEveryMs }),
store: terminalAgentStore,
});
startSandboxPullRequestReporter({
read: readLinkedPullRequests,
report: (pullRequests) =>
api.cloudWorkspace.reportPullRequests.mutate({
id: sandboxWorkspaceId,
pullRequests,
}),
onLinked: onPullRequestLinked,
});
}

if (env.RELAY_URL && env.SUPERSET_HOST_RUN_MODE !== "sandbox") {
tunnelPromise = connectRelay({
signal: relayAbort.signal,
api,
relayUrl: env.RELAY_URL,
localPort: info.port,
organizationId: env.ORGANIZATION_ID,
authProvider,
hostServiceSecret: env.HOST_SERVICE_SECRET,
});
}
const server = createAdaptorServer({
fetch: app.fetch,
port: env.PORT,
hostname,
});
const stopServing = async () => {
// Cancel registration retries before replacing this process.
relayAbort.abort();
const tunnel = await Promise.race([
tunnelPromise,
new Promise<null>((resolve) => setTimeout(() => resolve(null), 1_000)),
]);
tunnel?.close();
const httpServer = server as unknown as {
closeAllConnections?: () => void;
close: (callback: () => void) => void;
};
httpServer.closeAllConnections?.();
await Promise.race([
new Promise<void>((resolve) => httpServer.close(() => resolve())),
new Promise<void>((resolve) => setTimeout(resolve, 3_000)),
]);
};
cleanup.stopServing = stopServing;
installUpgradeSocketGuard(server);
injectWebSocket(server);
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen({ port: env.PORT, host: hostname }, () => {
server.off("error", reject);
resolve();
});
});
if (stopping.signal.aborted) return;
const info = server.address();
if (!info || typeof info === "string") {
throw new Error("The host server did not start a TCP listener");
}
// Install only after the server is listening so startup throws still
// reach `main().catch(...)` and exit with a non-zero code.
installProcessSafetyNet();
const address = info.address.includes(":")
? `[${info.address}]`
: info.address;
console.log("[host-service] listening (address, port):", address, info.port);
recordBootStamp("host.listening");

startTerminalReaper(db);
startVitalsLog();
// A cloud workspace created with an agent starts it now: the pty daemon
// and event bus are up, and a person opening the workspace sees the
// agent's terminal the way they would on their own machine.
void launchSandboxAgent();
// A stop keeps the disk and drops every process, so nothing else on the
// box will notice that its agents are gone.
if (env.SUPERSET_HOST_RUN_MODE === "sandbox") void resumeCrashedAgents();
const sandboxWorkspaceId = process.env.SUPERSET_SANDBOX_WORKSPACE_ID;
if (env.SUPERSET_HOST_RUN_MODE === "sandbox" && sandboxWorkspaceId) {
startSandboxAgentStatusReporter({
apiUrl: env.SUPERSET_API_URL,
workspaceId: sandboxWorkspaceId,
hostSecret: env.HOST_SERVICE_SECRET,
store: terminalAgentStore,
});
startSandboxBoxPressureReporter({
apiUrl: env.SUPERSET_API_URL,
workspaceId: sandboxWorkspaceId,
hostSecret: env.HOST_SERVICE_SECRET,
read: readSandboxBoxResources,
});
if (boxLogsEnabled()) {
startSandboxBootPhaseLog({ path: SANDBOX_PATHS.bootLog });
}
startSandboxKeepalive({
keepalive: (pingsEveryMs) =>
api.sandbox.keepalive.mutate({ pingsEveryMs }),
store: terminalAgentStore,
});
startSandboxPullRequestReporter({
read: readLinkedPullRequests,
report: (pullRequests) =>
api.cloudWorkspace.reportPullRequests.mutate({
id: sandboxWorkspaceId,
pullRequests,
}),
onLinked: onPullRequestLinked,
});
}

if (env.RELAY_URL && env.SUPERSET_HOST_RUN_MODE !== "sandbox") {
tunnelPromise = connectRelay({
signal: relayAbort.signal,
api,
relayUrl: env.RELAY_URL,
localPort: info.port,
organizationId: env.ORGANIZATION_ID,
authProvider,
hostServiceSecret: env.HOST_SERVICE_SECRET,
});
}

// Standalone only: this process owns its listener and relay socket, so it
// can hand the port to a successor build (system.update). The desktop
// entry never registers this and its host-service stays non-updatable.
const selfUpdater = configureSelfUpdater({
stopServing: async () => {
// Cancel registration retries before replacing this process.
relayAbort.abort();
const tunnel = await Promise.race([
tunnelPromise,
new Promise<null>((resolve) => setTimeout(() => resolve(null), 1_000)),
]);
tunnel?.close();
const httpServer = server as unknown as {
closeAllConnections?: () => void;
close: (callback: () => void) => void;
};
httpServer.closeAllConnections?.();
await Promise.race([
new Promise<void>((resolve) => httpServer.close(() => resolve())),
new Promise<void>((resolve) => setTimeout(resolve, 3_000)),
]);
},
});
const selfUpdater = configureSelfUpdater({ stopServing });
if (env.SUPERSET_HOST_AUTO_UPDATE && selfUpdater.status().updatable) {
const timer = setInterval(
() => void selfUpdater.checkForUpdates(),
Expand All @@ -271,8 +284,11 @@ async function main(): Promise<void> {
}
}

process.on("SIGINT", () => stopOnSignal("SIGINT"));
process.on("SIGTERM", () => stopOnSignal("SIGTERM"));
void main().catch(async (error) => {
if (stopping.signal.aborted) return;
stopping.abort();
console.error("[host-service] Failed to start:", caught(error));
await captureFatalStartupError(error);
process.exit(1);
await shutdown("startup failure", () => captureFatalStartupError(error));
});
Loading
Loading