feat(server): background services update themselves #17586
t3/background-provider-updates fromt3/background-server-updatesopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge added labelsmacroscope-review
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- @@ -0,0 +81,21 @@81+ });82+ return;83+ }84+ yield* updateWindow.runWhenOpen(85+ { closesWindows: false },86+ Effect.gen(function* () {87+ // The setting may have been turned off while waiting.88+ if (!(yield* automaticUpdatesEnabled)) return;89+ skippedTargets.add(targetVersion);90+ yield* Effect.logInfo("Installing a background server update", { targetVersion });91+ yield* selfUpdate.update({ targetVersion });92+ }),93+ );94+ }).pipe(95+ Effect.catchCause((cause) => Effect.logWarning("Background server update failed", { cause })),96+ Effect.withSpan("updates.ServerAutoUpdater.bootService"),97+ );98+99+ const updateDesktopApp = (downloadedVersion: string) =>100+ Effect.gen(function* () {101+ if (!(yield* automaticUpdatesEnabled) || skippedTargets.has(downloadedVersion)) return;
- apps/server/src/updates/ServerAutoUpdater.ts lines 69 to 83OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +63,21 @@63+ releaseBaseUrl,64+ ).pipe(Effect.provideService(HttpClient.HttpClient, httpClient));65+ if (66+ compareExactServiceVersions(targetVersion, currentVersion) <= 0 ||67+ skippedTargets.has(targetVersion)68+ ) {69+ return;70+ }71+ yield* Effect.logInfo("Staging a background server update", { targetVersion });72+ const staged = yield* selfUpdate.stage(targetVersion);73+ if (74+ staged.orchestrationProtocol !== undefined &&75+ staged.orchestrationProtocol !== ORCHESTRATION_PROTOCOL_VERSION76+ ) {77+ // Connected clients would be refused until they update; leave this one to a person.78+ skippedTargets.add(targetVersion);79+ yield* Effect.logInfo("Skipping a background update that changes the client protocol", {80+ targetVersion,81+ });82+ return;83+ }apps/server/src/updates/ServerAutoUpdater.ts lines 84 to 93OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +73,21 @@73+ if (74+ staged.orchestrationProtocol !== undefined &&75+ staged.orchestrationProtocol !== ORCHESTRATION_PROTOCOL_VERSION76+ ) {77+ // Connected clients would be refused until they update; leave this one to a person.78+ skippedTargets.add(targetVersion);79+ yield* Effect.logInfo("Skipping a background update that changes the client protocol", {80+ targetVersion,81+ });82+ return;83+ }84+ yield* updateWindow.runWhenOpen(85+ { closesWindows: false },86+ Effect.gen(function* () {87+ // The setting may have been turned off while waiting.88+ if (!(yield* automaticUpdatesEnabled)) return;89+ skippedTargets.add(targetVersion);90+ yield* Effect.logInfo("Installing a background server update", { targetVersion });91+ yield* selfUpdate.update({ targetVersion });92+ }),93+ );
- apps/server/src/terminal/Manager.ts lines 2985 to 3012OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -2974,3 +2995,18 @@2974- }),2975- });2976- });2995+ });2996+ }2997+ session.inputCount += 1;2998+ yield* Effect.try({2999+ try: () => process.write(input.data),3000+ catch: (cause) =>3001+ new TerminalWriteError({3002+ threadId: input.threadId,3003+ terminalId,3004+ terminalPid: process.pid,3005+ cause,3006+ }),3007+ });3008+ },3009+ );3010+3011+ const write: TerminalManager["Service"]["write"] = (input) =>3012+ withRestartPermit(writeUnlocked(input));docs/user/updating.md lines 88 to 89OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -74,8 +74,16 @@747475-## Update providers75+## Automatic updates76767777 **Settings → General → Update automatically** is on by default. Each environment78-installs provider CLI updates in the background once no thread is running or79-waiting for you, no client has been used for 15 minutes, and no scheduled task80-or usage-limit resume is due within 5 minutes. A failed update is retried81-after 6 hours or when a newer version is published.78+waits until no thread is running or waiting for you, no client has been used for79+15 minutes, and no scheduled task or usage-limit resume is due within 5 minutes.80+Then it installs:81+82+provider CLI updates that have a one-click update;83+the newest T3 Code release on its channel, when it runs as a background service84+ (`t3 service install`). It downloads first and restarts only inside that window.85+86+Background services also wait for integrated terminal commands to finish.87+88+Desktop updates download in the background and install when you quit the app.89+The app stays open while you work, including when it hosts multiple backends.
- docs/user/updating.md lines 78 to 79OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -72,10 +72,8 @@7272 Check that you updated the server's machine, not only the device you are using.7373 For a command-line server, stop it and relaunch the exact version shown in the notice.747475-## Update providers75+## Automatic updates76767777 **Settings → General → Update automatically** is on by default. Each environment78-installs provider CLI updates in the background once no thread is running or79-waiting for you, no client has been used for 15 minutes, and no scheduled task80-or usage-limit resume is due within 5 minutes. A failed update is retried81-after 6 hours or when a newer version is published.78+waits until no thread is running or waiting for you, no client has been used for79+15 minutes, and no scheduled task or usage-limit resume is due within 5 minutes.
- @@ -72,10 +72,16 @@7272 Check that you updated the server's machine, not only the device you are using.7373 For a command-line server, stop it and relaunch the exact version shown in the notice.747475-## Update providers75+## Automatic updates76767777 **Settings → General → Update automatically** is on by default. Each environment78-installs provider CLI updates in the background once no thread is running or79-waiting for you, no client has been used for 15 minutes, and no scheduled task80-or usage-limit resume is due within 5 minutes. A failed update is retried81-after 6 hours or when a newer version is published.78+waits until no thread is running or waiting for you, no background work is pending,79+no client has been used for 15 minutes, and no scheduled task or usage-limit resume80+is due within 5 minutes.81+Then it installs:82+83+provider CLI updates that have a one-click update;84+the newest T3 Code release on its channel, when it runs as a background service85+ (`t3 service install`). It downloads first and restarts only inside that window.86+87+Background services also wait for integrated terminal commands to finish.
- apps/server/src/updates/UpdateWindow.ts line 80OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -73,3 +77,4 @@7377 provider.updateState?.status === "queued" || provider.updateState?.status === "running",7478 );7579 if (providerUpdating) found.push("provider-update");80+ if (restartsServer && (yield* terminals.hasBusyTerminals)) found.push("terminal-work");apps/server/src/terminal/Manager.ts line 3186OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3175,3 +3178,9 @@31753178 ),31763179 );317731803181+ const hasBusyTerminals: TerminalManager["Service"]["hasBusyTerminals"] = readManagerState.pipe(3182+ Effect.map((state) =>3183+ [...state.sessions.values()].some(3184+ (session) =>3185+ session.status === "starting" ||3186+ (session.status === "running" && session.hasRunningSubprocess),
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/process/ownedProcesses.ts line 362OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +342,21 @@342+ }343+ let next = withoutInstaller(discover(entry, table), table);344+ if (platform !== "win32") {345+ // Freeze to a fixed point. A child may fork while its parent is being stopped.346+ const stopped = new Set<string>();347+ for (let attempt = 0; attempt < 100; attempt++) {348+ const pending = survivors(next, table).filter(349+ (p) => !stopped.has(`${p.pid}:${p.startTime}`),350+ );351+ if (pending.length === 0) break;352+ for (const p of pending) {353+ await signal(p, "SIGSTOP");354+ stopped.add(`${p.pid}:${p.startTime}`);355+ }356+ table = await controller.snapshot();357+ next = withoutInstaller(discover(next, table), table);358+ if (attempt === 99) throw new Error("Provider process tree did not stop for cleanup");359+ }360+ }361+ // Persist newly discovered children before signalling: recovery can itself be killed.362+ write(file, next);
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:L
- apps/server/src/serviceLauncher.ts line 606OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -561,3 +596,11 @@561596 child.role = "active";562597 await discardDatabaseBackup(this.#baseDir, committed.id).catch(() => undefined);563598 await sendMessage(child.process, { type: "committed", updateId: committed.id });599+ await this.#pruneRuntimes();600+ }601+602+ async #pruneRuntimes(): Promise<void> {603+ try {604+ // The unit's ExecStart names a specific runtime/versions/<v>/t3.605+ const executableDir = NodePath.dirname(await NodeFSP.realpath(process.execPath));606+ const versionsDir = NodePath.join(this.#baseDir, "runtime", "versions");apps/server/src/updates/ServerAutoUpdater.ts line 107OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +87,21 @@87+ Effect.gen(function* () {88+ // The setting may have been turned off while waiting for the window.89+ if (!(yield* enabled)) return;90+ staged = undefined;91+ skipped.add(targetVersion);92+ yield* Effect.logInfo("Installing a background server update", { targetVersion });93+ yield* selfUpdate.update({ targetVersion }).pipe(94+ // Refused before the handoff (say, a manual update in progress): stage again next check.95+ Effect.tapError(() => Effect.sync(() => skipped.delete(targetVersion))),96+ );97+ // The launcher stops this server after accepting. Held until then, a turn98+ // cannot start in the gap, but not forever if the launcher never does.99+ yield* Effect.sleep(HANDOFF_TIMEOUT);100+ yield* Effect.logWarning("The service launcher did not stop this server after an update", {101+ targetVersion,102+ });103+ });104+105+ const pass = Effect.gen(function* () {106+ if (!(yield* enabled)) return;107+ if (staged === undefined && (yield* Clock.currentTimeMillis) >= nextReleaseCheckAt) {
maria-rcks changed the title
- apps/server/src/serviceLauncher.ts line 880OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -772,4 +826,11 @@772826 await this.#startTrial(pending);773827 return;774828 }775- throw new Error(`Active child exited unexpectedly (${String(code ?? signal ?? "unknown")}).`);829+ // Restart in-process so systemd's start limit cannot strand an unattended830+ // service behind a crashing release.831+ if (performance.now() - child.startedAt >= STABLE_RUN_MS) {832+ this.#crashDelayMs = CRASH_RESTART_BASE_MS;833+ }834+ const delay = this.#crashDelayMs;835+ this.#crashDelayMs = Math.min(delay * 2, CRASH_RESTART_MAX_MS);836+ this.#timer = setTimeout(() => {apps/server/src/serviceLauncher.ts line 412OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -382,0 +392,21 @@392+ * and a pending target stay because recovery may start them.393+ */394+export async function pruneServiceRuntimes(395+ baseDir: string,396+ state: ServiceState,397+ launcherVersion: string | undefined,398+): Promise<void> {399+ const keep = new Set([state.activeVersion]);400+ if (launcherVersion !== undefined) keep.add(launcherVersion);401+ if (state.update !== undefined) {402+ keep.add(state.update.fromVersion);403+ if (state.update.status === "pending") keep.add(state.update.targetVersion);404+ }405+ const versionsDir = NodePath.join(baseDir, "runtime", "versions");406+ for (const entry of await NodeFSP.readdir(versionsDir, { withFileTypes: true })) {407+ if (!entry.isDirectory() || !isExactServiceVersion(entry.name) || keep.has(entry.name)) {408+ continue;409+ }410+ // An incomplete directory is a staging in progress, not an old runtime.411+ if (!(await runtimeExists(baseDir, entry.name))) continue;412+ await NodeFSP.rm(NodePath.join(versionsDir, entry.name), { recursive: true, force: true });
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/serviceLauncher.ts line 419OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -382,0 +399,21 @@399+ const keep = new Set([state.activeVersion]);400+ if (launcherVersion !== undefined) keep.add(launcherVersion);401+ const installedVersion = await NodeFSP.readFile(restartPendingPath(baseDir), "utf8").catch(402+ (error: unknown) => {403+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;404+ throw error;405+ },406+ );407+ if (installedVersion !== undefined) keep.add(installedVersion.trim());408+ if (state.update !== undefined) {409+ keep.add(state.update.fromVersion);410+ if (state.update.status === "pending") keep.add(state.update.targetVersion);411+ }412+ const versionsDir = NodePath.join(baseDir, "runtime", "versions");413+ for (const entry of await NodeFSP.readdir(versionsDir, { withFileTypes: true })) {414+ if (!entry.isDirectory() || !isExactServiceVersion(entry.name) || keep.has(entry.name)) {415+ continue;416+ }417+ // An incomplete directory is a staging in progress, not an old runtime.418+ if (!(await runtimeExists(baseDir, entry.name))) continue;419+ await NodeFSP.rm(NodePath.join(versionsDir, entry.name), { recursive: true, force: true });
juliusmarminge assignedjuliusmarminge
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
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
- @@ -385,0 +402,21 @@402+ baseDir: string,403+ state: ServiceState,404+ launcherVersion: string | undefined,405+): Promise<void> {406+ const keep = new Set([state.activeVersion]);407+ if (launcherVersion !== undefined) keep.add(launcherVersion);408+ const readOptionalText = (filePath: string) =>409+ NodeFSP.readFile(filePath, "utf8").catch((error: unknown) => {410+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;411+ throw error;412+ });413+ const installedVersion = await readOptionalText(restartPendingPath(baseDir));414+ if (installedVersion !== undefined) keep.add(installedVersion.trim());415+ const versionsDir = NodePath.join(baseDir, "runtime", "versions");416+ const cliLaunchers = await readOptionalText(NodePath.join(baseDir, "runtime", "launchers"));417+ for (const cliPath of (cliLaunchers ?? "").split(/\r?\n/).filter(Boolean)) {418+ const cliEntry =419+ // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime.420+ process.platform === "win32"421+ ? /^"([^"]+)"/m.exec((await readOptionalText(cliPath)) ?? "")?.[1]422+ : await NodeFSP.readlink(cliPath)
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
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
- apps/server/src/updates/RestartWork.ts line 30OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +10,21 @@10+ */11+export class RestartWork extends Context.Service<12+ RestartWork,13+ {14+ /** Counts `effect` as restart-sensitive from now until it ends, however it ends. */15+ readonly track: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;16+ readonly count: Effect.Effect<number>;17+ /** Holds new work outside the final restart check and launcher handoff. */18+ readonly withRestartGate: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;19+ }20+>()("t3/updates/RestartWork") {}21+22+export const layer = Layer.effect(23+ RestartWork,24+ Effect.gen(function* () {25+ const active = yield* Ref.make(0);26+ const gate = yield* Semaphore.make(1);27+ return RestartWork.of({28+ track: Effect.fn("RestartWork.track")(<A, E, R>(effect: Effect.Effect<A, E, R>) =>29+ Effect.acquireUseRelease(30+ gate.withPermits(1)(Ref.update(active, (n) => n + 1)),
Wladefant(GitHub profile, opens in a new tab) requested changes
tanstack-source added labelsfeature
Sign in to join this conversation.



macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed