Add remote server updates and standalone service management #4286
Mergedjuliusmarmingemerged 14 commits into
main fromrefs/pull/4286/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/cloud/selfUpdate.ts line 268OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +248,21 @@248+ yield* Effect.logInfo("Server self-update installed; respawning.", { targetVersion });249+ // The shim sleeps so this process has released its listeners before250+ // the replacement binds them, then execs the new version with the251+ // original CLI arguments.252+ yield* scheduleRestart(253+ Effect.sync(() => {254+ host.spawnDetached("/bin/sh", [255+ "-c",256+ 'sleep 1; exec "$@"',257+ "t3-self-update",258+ host.execPath,259+ runtimePaths.entryPath,260+ ...host.cliArgs,261+ ]);262+ host.exitProcess();263+ }),264+ );265+ }266+267+ return { targetVersion, method: activeMethod };268+ }).pipe(Effect.ensuring(Ref.set(inFlight, false)));apps/server/src/cloud/selfUpdate.ts line 236OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +216,21 @@216+ const homeDir = env.HOME ?? "";217+ const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);218+ // Same shape bootService.install writes, so the next `t3 connect`219+ // still recognizes the unit as current.220+ const unit = renderBootServiceUnit({221+ nodePath: host.execPath,222+ t3EntryPath: runtimePaths.entryPath,223+ baseDir: serverConfig.baseDir,224+ logPath: path.join(serverConfig.logsDir, "boot-service.log"),225+ unitPath,226+ });227+ yield* fs228+ .writeFileString(unitPath, unit)229+ .pipe(Effect.mapError((cause) => failWith("Could not update the systemd unit.", cause)));230+ const reload = yield* runner231+ .run({ command: "systemctl", args: ["--user", "daemon-reload"] })232+ .pipe(Effect.mapError((cause) => failWith("Could not reload systemd units.", cause)));233+ if (reload.code !== 0) {234+ return yield* failWith(235+ `Reloading systemd units failed (exit code ${String(reload.code)}).`,236+ );apps/server/src/cloud/pinnedRuntime.ts line 126OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +106,21 @@106+ ],107+ // Native deps (node-pty) can compile from source on slow boxes; the108+ // ProcessRunner default of 60s would kill a healthy install.109+ timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,110+ })111+ .pipe(112+ Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: installStep, cause })),113+ Effect.filterOrFail(114+ (result) => result.code === 0,115+ (result) =>116+ new PinnedRuntimeInstallError({117+ step: installStep,118+ exitCode: Number(result.code),119+ stdoutLength: result.stdout.length,120+ stderrLength: result.stderr.length,121+ }),122+ ),123+ Effect.tapError(() =>124+ fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(Effect.ignore),125+ ),126+ );apps/server/src/cloud/selfUpdate.ts line 268OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +248,21 @@248+ yield* Effect.logInfo("Server self-update installed; respawning.", { targetVersion });249+ // The shim sleeps so this process has released its listeners before250+ // the replacement binds them, then execs the new version with the251+ // original CLI arguments.252+ yield* scheduleRestart(253+ Effect.sync(() => {254+ host.spawnDetached("/bin/sh", [255+ "-c",256+ 'sleep 1; exec "$@"',257+ "t3-self-update",258+ host.execPath,259+ runtimePaths.entryPath,260+ ...host.cliArgs,261+ ]);262+ host.exitProcess();263+ }),264+ );265+ }266+267+ return { targetVersion, method: activeMethod };268+ }).pipe(Effect.ensuring(Ref.set(inFlight, false)));
- apps/server/src/ws.ts lines 2111 to 2111OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2101,3 +2108,4 @@21012108 makeWsRpcLayer(session, previewAutomationBroker).pipe(21022109 Layer.provideMerge(RpcSerialization.layerJson),21032110 Layer.provide(ProviderMaintenanceRunner.layer),2111+ Layer.provide(ServerSelfUpdate.layer),apps/server/src/cloud/selfUpdate.ts lines 227 to 229OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +209,21 @@209+ if (preflight.code !== 0) {210+ return yield* failWith(211+ `The installed t3@${targetVersion} failed its version check (exit code ${String(preflight.code)}).`,212+ );213+ }214+215+ if (activeMethod === "boot-service") {216+ const homeDir = env.HOME ?? "";217+ const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);218+ // Same shape bootService.install writes, so the next `t3 connect`219+ // still recognizes the unit as current.220+ const unit = renderBootServiceUnit({221+ nodePath: host.execPath,222+ t3EntryPath: runtimePaths.entryPath,223+ baseDir: serverConfig.baseDir,224+ logPath: path.join(serverConfig.logsDir, "boot-service.log"),225+ unitPath,226+ });227+ yield* fs228+ .writeFileString(unitPath, unit)229+ .pipe(Effect.mapError((cause) => failWith("Could not update the systemd unit.", cause)));apps/server/src/cloud/selfUpdate.ts line 107OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +87,21 @@87+ const hostArguments = yield* HostProcessArguments;88+ const fs = yield* FileSystem.FileSystem;89+ const path = yield* Path.Path;90+91+ const entryPath = hostArguments[1] ?? "";92+ if (entryPath === "") {93+ return null;94+ }95+96+ const homeDir = env.HOME ?? "";97+ if (platform === "linux" && homeDir !== "") {98+ const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);99+ const unitReferencesEntry = yield* fs.readFileString(unitPath).pipe(100+ Effect.map((unit) => unit.includes(quoteSystemdValue(entryPath))),101+ Effect.orElseSucceed(() => false),102+ );103+ // INVOCATION_ID is set by systemd for the processes it spawns; requiring104+ // it distinguishes the unit's own process (restarting the unit replaces105+ // us) from a manual foreground run of the same pinned artifact (it would106+ // not).107+ if (unitReferencesEntry && (env.INVOCATION_ID ?? "") !== "") {
- apps/server/src/vcs/GitVcsDriverCore.ts lines 248 to 251OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -236,8 +236,16 @@236236 }237237238238 function normalizeRemoteUrl(value: string): string {239- return value239+ const normalized = value240240 .trim()241241 .replace(/\/+$/g, "")242242 .replace(/\.git$/i, "")243243 .toLowerCase();244+ // Reduce transport variants of the same repository to `host/path` so245+ // ensureRemote reuses an existing remote instead of adding an ssh/https246+ // duplicate (git@host:owner/repo, ssh://git@host/owner/repo,247+ // https://host/owner/repo all compare equal).248+ const scpLike = /^(?:ssh:\/\/)?(?:[^@/:]+@)([^:/]+)[:/](.+)$/.exec(normalized);249+ if (scpLike) {250+ return `${scpLike[1]}/${scpLike[2]}`;251+ }
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/cloud/selfUpdate.ts lines 244 to 248OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +228,21 @@228+ runner,229+ }).pipe(Effect.mapError((error) => failWith(error.message, error)));230+231+ // A broken artifact (failed native build, incompatible node) must be232+ // caught while the current server is still alive to report it.233+ const preflight = yield* runner234+ .run({235+ command: host.execPath,236+ args: [runtimePaths.entryPath, "--version"],237+ timeout: PREFLIGHT_TIMEOUT,238+ })239+ .pipe(240+ Effect.mapError((cause) =>241+ failWith(`Could not verify the installed t3@${targetVersion}.`, cause),242+ ),243+ );244+ if (preflight.code !== 0) {245+ return yield* failWith(246+ `The installed t3@${targetVersion} failed its version check (exit code ${String(preflight.code)}).`,247+ );248+ }
- apps/server/src/cloud/selfUpdate.ts line 229OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +209,21 @@209+ );210+ }211+ const activeMethod = capability;212+ const targetVersion = input.targetVersion.trim();213+ if (!EXACT_VERSION_PATTERN.test(targetVersion)) {214+ return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);215+ }216+217+ const alreadyRunning = yield* Ref.getAndSet(inFlight, true);218+ if (alreadyRunning) {219+ return yield* failWith("A server update is already in progress.");220+ }221+222+ return yield* Effect.gen(function* () {223+ const runtimePaths = yield* ensurePinnedRuntimeInstalled({224+ baseDir: serverConfig.baseDir,225+ version: targetVersion,226+ fs,227+ path,228+ runner,229+ }).pipe(Effect.mapError((error) => failWith(error.message, error)));
- @@ -0,0 +100,21 @@100+ });101+ }102+ return;103+ }104+ toastManager.add({105+ type: "success",106+ title: `Updating ${serverLabel}`,107+ description: `t3@${result.value.targetVersion} is installed — the server is restarting and will reconnect shortly.`,108+ });109+ })110+ .catch((error: unknown) => {111+ toastManager.add({112+ type: "error",113+ title: "Server update failed",114+ description: updateFailureMessage(error),115+ });116+ })117+ .finally(() => {118+ clearTimeout(expiry);119+ inFlightRef.current = false;120+ setPending(false);
- @@ -0,0 +234,21 @@234+ .run({235+ command: host.execPath,236+ args: [runtimePaths.entryPath, "--version"],237+ timeout: PREFLIGHT_TIMEOUT,238+ })239+ .pipe(240+ Effect.mapError((cause) =>241+ failWith(`Could not verify the installed t3@${targetVersion}.`, cause),242+ ),243+ );244+ if (preflight.code !== 0) {245+ // A completed npm install can still be unusable under this Node or on246+ // this machine. Remove its sentinel and tree so a retry of the same247+ // version performs a clean install instead of reusing a known-bad one.248+ yield* fs249+ .remove(runtimePaths.versionDir, { recursive: true, force: true })250+ .pipe(251+ Effect.mapError((cause) =>252+ failWith(`Could not remove the failed t3@${targetVersion} installation.`, cause),253+ ),254+ );
- apps/server/src/cloud/selfUpdate.ts line 420Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +324,21 @@324+ yield* Effect.logInfo("Server self-update installed; respawning.", { targetVersion });325+ // The shim sleeps so this process has released its listeners before326+ // the replacement binds them, then execs the new version with the327+ // original CLI arguments.328+ yield* scheduleRestart(329+ Effect.sync(() => {330+ host.spawnDetached("/bin/sh", [331+ "-c",332+ 'sleep 1; exec "$@"',333+ "t3-self-update",334+ host.execPath,335+ runtimePaths.entryPath,336+ ...host.cliArgs,337+ ]);338+ host.exitProcess();339+ }),340+ );341+ }342+343+ return { targetVersion, method: activeMethod };344+ }).pipe(Effect.onError(() => Ref.set(inFlight, false)));
- @@ -0,0 +119,21 @@119+ toastManager.add({120+ type: "success",121+ title: `Updating ${serverLabel}`,122+ description: `t3@${result.value.targetVersion} is installed — the server is restarting and will reconnect shortly.`,123+ });124+ })125+ .catch((error: unknown) => {126+ toastManager.add({127+ type: "error",128+ title: "Server update failed",129+ description: updateFailureMessage(error),130+ });131+ })132+ .finally(() => {133+ // A successful RPC only acknowledges that restart is scheduled. Keep134+ // the action disabled until version sync unmounts it, or until the135+ // safety expiry reports that reconnection never arrived.136+ if (restartAccepted) return;137+ if (expiryRef.current === expiry) {138+ expiryRef.current = null;139+ }
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/cloud/selfUpdate.ts lines 171 to 173OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +153,21 @@153+}) {154+ const serverConfig = yield* ServerConfig.ServerConfig;155+ const fs = yield* FileSystem.FileSystem;156+ const path = yield* Path.Path;157+ const runner = yield* ProcessRunner.ProcessRunner;158+ const env = yield* HostProcessEnvironment;159+ const hostExecPath = yield* HostProcessExecutablePath;160+ const hostArguments = yield* HostProcessArguments;161+ const capability: ServerSelfUpdateCapability | null = yield* resolveServerSelfUpdateCapability({162+ desktopManaged: serverConfig.mode === "desktop",163+ });164+165+ const host: ServerSelfUpdateHost = {166+ execPath: options?.host?.execPath ?? hostExecPath,167+ cliEntryPath: options?.host?.cliEntryPath ?? hostArguments[1] ?? "",168+ cliArgs: options?.host?.cliArgs ?? hostArguments.slice(2),169+ spawnDetached:170+ options?.host?.spawnDetached ??171+ ((command, args) => {172+ NodeChildProcess.spawn(command, [...args], { detached: true, stdio: "ignore" }).unref();173+ }),apps/web/src/components/ServerUpdateAction.tsx line 161Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +123,21 @@123+ // Installation can legitimately consume most of the request window.124+ // Give restart/reconnect a fresh full window after the server accepts125+ // the handoff instead of expiring based on the original click time.126+ if (expiryRef.current === expiry) {127+ clearTimeout(expiry);128+ expiry = armExpiry();129+ }130+ toastManager.add({131+ type: "success",132+ title: `Updating ${serverLabel}`,133+ description: `t3@${result.value.targetVersion} is installed — the server is restarting and will reconnect shortly.`,134+ });135+ })136+ .catch((error: unknown) => {137+ toastManager.add({138+ type: "error",139+ title: "Server update failed",140+ description: updateFailureMessage(error),141+ });142+ })143+ .finally(() => {
- @@ -0,0 +372,21 @@372+ yield* Effect.logInfo("Server self-update installed; respawning.", { targetVersion });373+ // The shim sleeps so this process has released its listeners before374+ // the replacement binds them, then execs the new version with the375+ // original CLI arguments.376+ yield* scheduleRestart(377+ Effect.sync(() => {378+ host.spawnDetached("/bin/sh", [379+ "-c",380+ 'sleep 1; exec "$@"',381+ "t3-self-update",382+ host.execPath,383+ runtimePaths.entryPath,384+ ...host.cliArgs,385+ ]);386+ host.exitProcess();387+ }),388+ );389+ }390+391+ return { targetVersion, method: activeMethod };392+ }).pipe(Effect.onError(() => Ref.set(inFlight, false)));@@ -0,0 +242,21 @@242+ Effect.mapError((cause) =>243+ failWith(`Could not verify the installed t3@${targetVersion}.`, cause),244+ ),245+ );246+ if (preflight.code !== 0) {247+ // A completed npm install can still be unusable under this Node or on248+ // this machine. Remove its sentinel and tree so a retry of the same249+ // version performs a clean install instead of reusing a known-bad one.250+ yield* removePinnedRuntimeInstallation({251+ baseDir: serverConfig.baseDir,252+ version: targetVersion,253+ fs,254+ path,255+ }).pipe(256+ Effect.mapError((error) =>257+ failWith(`Could not remove the failed t3@${targetVersion} installation.`, error),258+ ),259+ );260+ return yield* failWith(261+ `The installed t3@${targetVersion} failed its version check (exit code ${String(preflight.code)}).`,262+ );@@ -0,0 +371,21 @@371+ } else {372+ yield* Effect.logInfo("Server self-update installed; respawning.", { targetVersion });373+ // The shim sleeps so this process has released its listeners before374+ // the replacement binds them, then execs the new version with the375+ // original CLI arguments.376+ yield* scheduleRestart(377+ Effect.sync(() => {378+ host.spawnDetached("/bin/sh", [379+ "-c",380+ 'sleep 1; exec "$@"',381+ "t3-self-update",382+ host.execPath,383+ runtimePaths.entryPath,384+ ...host.cliArgs,385+ ]);386+ host.exitProcess();387+ }),388+ );389+ }390+391+ return { targetVersion, method: activeMethod };
- @@ -0,0 +114,21 @@114+ if (expiryRef.current === expiry) {115+ clearTimeout(expiry);116+ expiry = armExpiry();117+ }118+ };119+ void Promise.resolve()120+ .then(() =>121+ updateServer({122+ environmentId,123+ input: { targetVersion },124+ }),125+ )126+ .then((result) => {127+ if (!ownsAttempt()) return;128+ if (result._tag === "Failure") {129+ // A successful boot-service restart kills the process serving this130+ // RPC, so interruption is the expected acknowledgement. Keep the UI131+ // pending until the new server version reconnects (or expiry).132+ if (isAtomCommandInterrupted(result)) {133+ keepPendingForRestart();134+ return;
- apps/web/src/components/ServerUpdateAction.tsx line 131OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +111,21 @@111+ let restartAccepted = false;112+ const keepPendingForRestart = () => {113+ restartAccepted = true;114+ if (expiryRef.current === expiry) {115+ clearTimeout(expiry);116+ expiry = armExpiry();117+ }118+ };119+ void Promise.resolve()120+ .then(() =>121+ updateServer({122+ environmentId,123+ input: { targetVersion },124+ }),125+ )126+ .then((result) => {127+ if (!ownsAttempt()) return;128+ if (result._tag === "Failure") {129+ // A successful boot-service restart kills the process serving this130+ // RPC, so interruption is the expected acknowledgement. Keep the UI131+ // pending until the new server version reconnects (or expiry).
- apps/web/src/components/ServerUpdateAction.tsx line 137OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +117,21 @@117+ restartAccepted = true;118+ if (expiryRef.current === expiry) {119+ clearTimeout(expiry);120+ expiry = armExpiry(expiryMs);121+ }122+ };123+ void Promise.resolve()124+ .then(() =>125+ updateServer({126+ environmentId,127+ input: { targetVersion },128+ }),129+ )130+ .then((result) => {131+ if (!ownsAttempt()) return;132+ if (result._tag === "Failure") {133+ // A successful boot-service restart kills the process serving this134+ // RPC, so interruption is the expected acknowledgement. Keep the UI135+ // pending until the new server version reconnects (or expiry).136+ if (isAtomCommandInterrupted(result)) {137+ keepPendingForRestart(INTERRUPTED_RESTART_GRACE_MS);
juliusmarminge changed the title
juliusmarminge merged thisab4a883
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
e726e751-bde8-459b-95a5-87502b791317You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.