Skip to content
TypeScript

feat(updates): switch your whole fleet between Stable and Nightly in one step (#26288)

Theo Brownef2943ee90ef7
diff --git a/apps/desktop/src/ipc/methods/updates.ts b/apps/desktop/src/ipc/methods/updates.ts
index b2212609030..ca85ee8b0c4 100644
--- a/apps/desktop/src/ipc/methods/updates.ts
+++ b/apps/desktop/src/ipc/methods/updates.ts
@@ -23,11 +23,14 @@ export const getUpdateState = DesktopIpc.makeIpcMethod({
export const setUpdateChannel = DesktopIpc.makeIpcMethod({
channel: IpcChannels.UPDATE_SET_CHANNEL_CHANNEL,
- payload: DesktopUpdateChannelSchema,
+ payload: Schema.Struct({
+ channel: DesktopUpdateChannelSchema,
+ minimumVersion: Schema.optional(Schema.String),
+ }),
result: DesktopUpdateStateSchema,
- handler: Effect.fn("desktop.ipc.updates.setChannel")(function* (channel) {
+ handler: Effect.fn("desktop.ipc.updates.setChannel")(function* ({ channel, minimumVersion }) {
const updates = yield* DesktopUpdates.DesktopUpdates;
- return yield* updates.setChannel(channel);
+ return yield* updates.setChannel(channel, { minimumVersion });
}),
});
@@ -43,11 +46,14 @@ export const downloadUpdate = DesktopIpc.makeIpcMethod({
export const installUpdate = DesktopIpc.makeIpcMethod({
channel: IpcChannels.UPDATE_INSTALL_CHANNEL,
- payload: Schema.Void,
+ /** A version installs only that downloaded build, never one that replaced it. */
+ payload: Schema.UndefinedOr(Schema.String),
result: DesktopUpdateActionResultSchema,
- handler: Effect.fn("desktop.ipc.updates.install")(function* () {
+ handler: Effect.fn("desktop.ipc.updates.install")(function* (expectedVersion) {
const updates = yield* DesktopUpdates.DesktopUpdates;
- return yield* updates.install;
+ if (expectedVersion === undefined) return yield* updates.install;
+ const { accepted, completed, state } = yield* updates.installPrepared(expectedVersion);
+ return { accepted, completed, state };
}),
});
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index a3e1e711cb2..965b7db5d6d 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -261,11 +261,12 @@ contextBridge.exposeInMainWorld("desktopBridge", {
};
},
getUpdateState: () => ipcRenderer.invoke(IpcChannels.UPDATE_GET_STATE_CHANNEL),
- setUpdateChannel: (channel) =>
- ipcRenderer.invoke(IpcChannels.UPDATE_SET_CHANNEL_CHANNEL, channel),
+ setUpdateChannel: (channel, minimumVersion) =>
+ ipcRenderer.invoke(IpcChannels.UPDATE_SET_CHANNEL_CHANNEL, { channel, minimumVersion }),
checkForUpdate: () => ipcRenderer.invoke(IpcChannels.UPDATE_CHECK_CHANNEL),
downloadUpdate: () => ipcRenderer.invoke(IpcChannels.UPDATE_DOWNLOAD_CHANNEL),
- installUpdate: () => ipcRenderer.invoke(IpcChannels.UPDATE_INSTALL_CHANNEL),
+ installUpdate: (expectedVersion) =>
+ ipcRenderer.invoke(IpcChannels.UPDATE_INSTALL_CHANNEL, expectedVersion),
cliCommand: {
getState: () => ipcRenderer.invoke(IpcChannels.CLI_COMMAND_GET_STATE_CHANNEL),
install: () => ipcRenderer.invoke(IpcChannels.CLI_COMMAND_INSTALL_CHANNEL),
diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.ts
index 5767057b4a3..a0624ced669 100644
--- a/apps/desktop/src/settings/DesktopAppSettings.ts
+++ b/apps/desktop/src/settings/DesktopAppSettings.ts
@@ -22,7 +22,7 @@ import {
normalizeLinuxPasswordStorePreference,
type LinuxPasswordStorePreference,
} from "../linuxSecretStorage.ts";
-import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
+import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
export interface DesktopSettings {
@@ -180,7 +180,7 @@ export class DesktopAppSettings extends Context.Service<
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
return {
...DEFAULT_DESKTOP_SETTINGS,
- updateChannel: resolveDefaultDesktopUpdateChannel(appVersion),
+ updateChannel: desktopUpdateChannelOf(appVersion),
};
}
diff --git a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts
index 253a015d8ec..1f5321148b7 100644
--- a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts
+++ b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts
@@ -119,6 +119,239 @@ describe("DesktopRemoteUpdates", () => {
);
});
+ it.effect("switches to the requested track before preparing its release", () => {
+ // In-memory settings keep the channel write off real disk I/O.
+ const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });
+
+ return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* Queue.offer(requests, {
+ ...request("req-switch"),
+ channel: "nightly",
+ targetVersion: "1.2.4-nightly.20261027.1",
+ });
+ yield* settle;
+ assert.equal((yield* updates.getState).channel, "nightly");
+
+ harness.emit("update-available", { version: "1.2.4-nightly.20261027.1" });
+ yield* settle;
+ harness.emit("update-downloaded", { version: "1.2.4-nightly.20261027.1" });
+ yield* settle;
+
+ const terminals = terminalReports(reports);
+ assert.deepEqual(
+ terminals.map((report) => [report.requestId, report.outcome]),
+ [["req-switch", "ready-to-install"]],
+ );
+ assert.equal(terminals[0]?.state.downloadedVersion, "1.2.4-nightly.20261027.1");
+ }),
+ );
+ });
+
+ it.effect(
+ "refuses a crossing whose feed has only an older build, and never offers it later",
+ () => {
+ const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });
+
+ return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ const older = "1.2.4-nightly.20261020.1";
+ yield* Queue.offer(requests, {
+ ...request("req-older"),
+ channel: "nightly",
+ targetVersion: "1.2.4-nightly.20261027.1",
+ });
+ yield* settle;
+ // Answers the track change's check, then the request's own check.
+ harness.emit("update-available", { version: older });
+ yield* settle;
+ harness.emit("update-available", { version: older });
+ yield* settle;
+
+ assert.deepEqual(
+ terminalReports(reports).map((report) => [report.outcome, report.reason]),
+ [["failed", "The desktop app found no build of 1.2.4-nightly.20261027.1."]],
+ );
+ // The saved track is the user's intent; a retry picks it up from here.
+ assert.equal((yield* updates.getState).channel, "nightly");
+
+ // A plain update afterwards cannot reach the build the switch refused.
+ yield* Queue.offer(requests, request("req-plain"));
+ yield* settle;
+ harness.emit("update-available", { version: older });
+ yield* settle;
+ assert.isNull((yield* updates.getState).availableVersion);
+ assert.equal(harness.downloadCount(), 0);
+ }),
+ );
+ },
+ );
+
+ it.effect("only saves the track on a host already running the release", () => {
+ const harness = makeHarness({ savedChannel: "nightly" });
+
+ return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* Queue.offer(requests, {
+ ...request("req-track-only"),
+ channel: "latest",
+ targetVersion: "1.2.3",
+ });
+ yield* settle;
+ // Even with a newer build on the feed, the host only saves its track.
+ harness.emit("update-available", { version: "1.2.4" });
+ yield* settle;
+
+ assert.deepEqual(
+ terminalReports(reports).map((report) => report.outcome),
+ ["up-to-date"],
+ );
+ assert.equal((yield* updates.getState).channel, "latest");
+ assert.equal(harness.downloadCount(), 0);
+ }),
+ );
+ });
+
+ it.effect("drops a retained download below the switch's checked release", () => {
+ const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });
+
+ return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ // Downloaded earlier on this Stable host, before the switch checked 1.2.5.
+ harness.emit("update-downloaded", { version: "1.2.4" });
+ yield* settle;
+ assert.equal((yield* updates.getState).downloadedVersion, "1.2.4");
+
+ yield* Queue.offer(requests, {
+ ...request("req-floor"),
+ channel: "latest",
+ targetVersion: "1.2.5",
+ });
+ yield* settle;
+ harness.emit("update-available", { version: "1.2.5" });
+ yield* settle;
+ harness.emit("update-downloaded", { version: "1.2.5" });
+ yield* settle;
+
+ assert.deepEqual(
+ terminalReports(reports).map((report) => [
+ report.outcome,
+ report.state.downloadedVersion,
+ ]),
+ [["ready-to-install", "1.2.5"]],
+ );
+ }),
+ );
+ });
+
+ it.effect("refuses to cross tracks remotely while WSL backends need their own checks", () => {
+ const harness = makeHarness({ beforeSetUpdateChannel: Effect.void, wslBackend: true });
+
+ return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* Queue.offer(requests, {
+ ...request("req-wsl"),
+ channel: "nightly",
+ targetVersion: "1.2.4-nightly.20261027.1",
+ });
+ yield* settle;
+
+ assert.deepEqual(
+ terminalReports(reports).map((report) => report.outcome),
+ ["failed"],
+ );
+ assert.include(terminalReports(reports)[0]?.reason ?? "", "Switch it on that machine");
+ assert.equal((yield* updates.getState).channel, "latest");
+ }),
+ );
+ });
+
+ it.effect("fails a switch that leaves a same-track host below the checked release", () => {
+ const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });
+
+ return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
+ Effect.gen(function* () {
+ yield* Queue.offer(requests, {
+ ...request("req-behind"),
+ channel: "latest",
+ targetVersion: "1.2.5",
+ });
+ yield* settle;
+ // The feed lags npm and has nothing newer than this host's 1.2.3.
+ harness.emit("update-not-available");
+ yield* settle;
+ harness.emit("update-not-available");
+ yield* settle;
+
+ assert.deepEqual(
+ terminalReports(reports).map((report) => [report.outcome, report.reason]),
+ [["failed", "The desktop app found no build of 1.2.5."]],
+ );
+ }),
+ );
+ });
+
+ it.effect("fails a crossing to an older-numbered Stable that the feed does not offer", () => {
+ const harness = makeHarness({
+ appVersion: "1.2.4-nightly.20261027.1",
+ beforeSetUpdateChannel: Effect.void,
+ });
+
+ return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
+ Effect.gen(function* () {
+ yield* Queue.offer(requests, {
+ ...request("req-to-stable"),
+ channel: "latest",
+ targetVersion: "1.2.3",
+ });
+ yield* settle;
+ harness.emit("update-not-available");
+ yield* settle;
+ harness.emit("update-not-available");
+ yield* settle;
+
+ // Still on Nightly, though the target is numbered below this build.
+ assert.deepEqual(
+ terminalReports(reports).map((report) => [report.outcome, report.reason]),
+ [["failed", "The desktop app found no build of 1.2.3."]],
+ );
+ }),
+ );
+ });
+
+ it.effect("accepts a newer build than the checked release on the requested track", () => {
+ const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });
+
+ return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
+ Effect.gen(function* () {
+ const newer = "1.2.4-nightly.20261028.2";
+ yield* Queue.offer(requests, {
+ ...request("req-newer"),
+ channel: "nightly",
+ targetVersion: "1.2.4-nightly.20261027.1",
+ });
+ yield* settle;
+ harness.emit("update-available", { version: newer });
+ yield* settle;
+ harness.emit("update-downloaded", { version: newer });
+ yield* settle;
+
+ assert.deepEqual(
+ terminalReports(reports).map((report) => [
+ report.outcome,
+ report.state.downloadedVersion,
+ ]),
+ [["ready-to-install", newer]],
+ );
+ }),
+ );
+ });
+
it.effect("reports a failed outcome when quitAndInstall fails", () => {
const harness = makeHarness({
quitAndInstall: Effect.fail(
@@ -525,6 +758,42 @@ describe("DesktopRemoteUpdates", () => {
);
});
+ it.effect("cancels a track switch while its own feed check is still running", () => {
+ const releaseCheck = Deferred.makeUnsafe<void>();
+ const harness = makeHarness({
+ beforeSetUpdateChannel: Effect.void,
+ checkForUpdates: Deferred.await(releaseCheck),
+ });
+
+ return runRemoteUpdatesTest(harness, ({ requests, cancellations }) =>
+ Effect.gen(function* () {
+ yield* Queue.offer(requests, {
+ ...request("req-switch-cancel"),
+ channel: "nightly",
+ targetVersion: "1.2.4-nightly.20261027.1",
+ });
+ yield* settle;
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* Queue.offer(cancellations, {
+ version: 1,
+ type: "cancelDesktopUpdate",
+ requestId: "req-switch-cancel",
+ });
+ yield* settle;
+ // The next request starts without waiting for the cancelled switch's feed check.
+ yield* Queue.offer(requests, {
+ ...request("req-switch-back"),
+ channel: "latest",
+ targetVersion: "1.2.3",
+ });
+ yield* settle;
+
+ assert.equal((yield* updates.getState).channel, "latest");
+ yield* Deferred.succeed(releaseCheck, undefined);
+ }),
+ );
+ });
+
it.effect("cancels an active preparation so the next request can run", () => {
const releaseCheck = Deferred.makeUnsafe<void>();
const harness = makeHarness({ checkForUpdates: Deferred.await(releaseCheck) });
diff --git a/apps/desktop/src/updates/DesktopRemoteUpdates.ts b/apps/desktop/src/updates/DesktopRemoteUpdates.ts
index cb606d8fbd2..560e2e78d4b 100644
--- a/apps/desktop/src/updates/DesktopRemoteUpdates.ts
+++ b/apps/desktop/src/updates/DesktopRemoteUpdates.ts
@@ -10,10 +10,13 @@ import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
+import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
+import { compareSemverVersions } from "@t3tools/shared/semver";
import type * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as DesktopObservability from "../app/DesktopObservability.ts";
+import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
import * as DesktopUpdates from "./DesktopUpdates.ts";
import {
@@ -44,9 +47,13 @@ type CommitClaim =
export const listen: Effect.Effect<
void,
never,
- DesktopUpdates.DesktopUpdates | DesktopTelemetryPublisher.DesktopTelemetryPublisher | Scope.Scope
+ | DesktopUpdates.DesktopUpdates
+ | DesktopTelemetryPublisher.DesktopTelemetryPublisher
+ | DesktopBackendPool.DesktopBackendPool
+ | Scope.Scope
> = Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
+ const backends = yield* DesktopBackendPool.DesktopBackendPool;
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
const activeRequestIdRef = yield* Ref.make(Option.none<string>());
const requestControlRef = yield* Ref.make<{
@@ -171,7 +178,59 @@ export const listen: Effect.Effect<
return;
}
yield* Ref.set(activeRequestIdRef, Option.some(request.requestId));
- yield* logInfo("remote update requested", { requestId: request.requestId });
+ yield* logInfo("remote update requested", {
+ requestId: request.requestId,
+ channel: request.channel,
+ });
+ // A switch saves its track first, so the step machine never sees the old track's offer.
+ // The saved track is the user's intent and stays even if this request fails: a track saved
+ // toward Stable never offers an older build outside a guarded switch.
+ if (request.channel !== undefined) {
+ // A reinstall restarts every backend, but the requesting server checked only its own
+ // database. A WSL backend keeps its own, so cross tracks only where all can be checked.
+ const current = yield* updates.getState;
+ if (
+ desktopUpdateChannelOf(current.currentVersion) !== request.channel &&
+ (yield* backends.list).length > 1
+ ) {
+ yield* publishReport(
+ current,
+ {
+ outcome: "failed",
+ reason:
+ "This desktop app also runs WSL backends, whose databases a remote switch cannot check. Switch it on that machine.",
+ },
+ request.requestId,
+ );
+ return;
+ }
+ const switched = yield* Effect.raceFirst(
+ updates.setChannel(request.channel, { minimumVersion: request.targetVersion }).pipe(
+ Effect.as(true),
+ Effect.catch((error) =>
+ updates.getState.pipe(
+ Effect.flatMap((state) =>
+ publishReport(
+ state,
+ { outcome: "failed", reason: error.message },
+ request.requestId,
+ ),
+ ),
+ Effect.as(false),
+ ),
+ ),
+ ),
+ Deferred.await(cancellation).pipe(Effect.as(false)),
+ );
+ if (!switched) return;
+ // A host already running the target only needed its track saved; installing a newer
+ // build here would restart it without the dialog having said so.
+ const state = yield* updates.getState;
+ if (request.targetVersion === state.currentVersion) {
+ yield* publishReport(state, { outcome: "up-to-date" }, request.requestId);
+ return;
+ }
+ }
const { latest, changes } = yield* updates.subscribe;
const disabledReason = Option.getOrNull(yield* updates.disabledReason);
let attempts: RemoteDesktopUpdateAttempts = { checks: 0, downloads: 0 };
@@ -184,6 +243,12 @@ export const listen: Effect.Effect<
Effect.forkScoped,
);
+ // A host leaving its build's track may need an older build, down to the checked release;
+ // the updater offers nothing below it.
+ const crossing = (state: DesktopUpdateState) =>
+ request.channel !== undefined &&
+ request.targetVersion !== undefined &&
+ desktopUpdateChannelOf(state.currentVersion) !== request.channel;
const step = Effect.fn("DesktopRemoteUpdates.step")(function* (
state: DesktopUpdateState,
): Effect.fn.Return<boolean, never, Scope.Scope> {
@@ -193,7 +258,7 @@ export const listen: Effect.Effect<
return false;
case "check":
attempts = { ...attempts, checks: attempts.checks + 1 };
- yield* updates.check("remote-update").pipe(
+ yield* updates.check("remote-update", { allowDowngrade: crossing(state) }).pipe(
Effect.flatMap((result) => {
if (result.checked) return Effect.void;
attempts = { ...attempts, checks: attempts.checks - 1 };
@@ -246,21 +311,34 @@ export const listen: Effect.Effect<
yield* logInfo("remote update prepared", { requestId: request.requestId });
return true;
}
- case "done":
+ case "done": {
+ // A switch that leaves the host on its old track, or below its checked release, did
+ // not reach it; a track-only host already at the release is done.
+ const done =
+ request.targetVersion !== undefined &&
+ next.outcome === "up-to-date" &&
+ (crossing(state) ||
+ compareSemverVersions(state.currentVersion, request.targetVersion) < 0)
+ ? {
+ outcome: "failed" as const,
+ reason: `The desktop app found no build of ${request.targetVersion}.`,
+ }
+ : next;
yield* publishReport(
state,
{
- outcome: next.outcome,
- ...(next.reason === undefined ? {} : { reason: next.reason }),
+ outcome: done.outcome,
+ ...(done.reason === undefined ? {} : { reason: done.reason }),
},
request.requestId,
);
yield* logInfo("remote update finished", {
requestId: request.requestId,
- outcome: next.outcome,
- reason: next.reason ?? null,
+ outcome: done.outcome,
+ reason: done.reason ?? null,
});
return true;
+ }
}
});
diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts
index d2f24143fc2..c6bcd46b8c2 100644
--- a/apps/desktop/src/updates/DesktopUpdates.test.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.test.ts
@@ -2,6 +2,7 @@ import { assert, describe, it } from "@effect/vitest";
import { DESKTOP_UPDATE_RESTART_MARKER_FILE } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
+import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
@@ -694,6 +695,65 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
+ it.effect("ignores a finished download from a track it no longer follows", () => {
+ const harness = makeHarness();
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ // A backed-out switch's download keeps reporting progress until it finishes.
+ harness.emit("download-progress", { percent: 40 });
+ yield* flushCallbacks;
+ harness.emit("update-downloaded", { version: "1.2.4-nightly.20261027.1" });
+ yield* flushCallbacks;
+
+ const state = yield* updates.getState;
+ assert.equal(state.downloadedVersion, null);
+ assert.notEqual(state.status, "downloading");
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ });
+
+ it.effect("offers older releases only to checks that leave the running build's track", () => {
+ const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ const before = harness.checkAllowedDowngrade.length;
+ yield* updates.setChannel("nightly");
+ yield* updates.setChannel("latest");
+ yield* updates.check("remote-update", { allowDowngrade: true });
+
+ // Back on its own Stable track the build never needs an older release.
+ assert.deepEqual(harness.checkAllowedDowngrade.slice(before), [true, false, true]);
+ assert.isFalse(harness.allowDowngrade());
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ });
+
+ it.effect("re-checks a saved track that differs from the running build's track", () => {
+ const harness = makeHarness({
+ appVersion: "1.2.4-nightly.20261027.1",
+ beforeSetUpdateChannel: Effect.void,
+ });
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ yield* updates.setChannel("latest");
+ const checks = harness.checkCount();
+
+ yield* updates.setChannel("latest");
+
+ assert.equal(harness.checkCount(), checks + 1);
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ });
+
it.effect("does not persist an unchanged update channel as a user preference", () => {
const harness = makeHarness();
@@ -713,6 +773,116 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
+ it.effect("offers nothing below a track switch's checked release", () => {
+ const harness = makeHarness({
+ appVersion: "1.2.4-nightly.20261027.1",
+ beforeSetUpdateChannel: Effect.void,
+ });
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ yield* updates.setChannel("latest", { minimumVersion: "1.2.3" });
+
+ harness.emit("update-available", { version: "1.2.2" });
+ yield* flushCallbacks;
+ assert.isNull((yield* updates.getState).availableVersion);
+ harness.emit("update-downloaded", { version: "1.2.2" });
+ yield* flushCallbacks;
+ assert.isNull((yield* updates.getState).downloadedVersion);
+
+ harness.emit("update-available", { version: "1.2.3" });
+ yield* flushCallbacks;
+ assert.equal((yield* updates.getState).availableVersion, "1.2.3");
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ });
+
+ it.effect("keeps a saved Stable track across a restart without offering an older release", () => {
+ // A Nightly build whose switch to Stable did not finish before the app quit.
+ const harness = makeHarness({ appVersion: "1.2.4-nightly.20261027.1", savedChannel: "latest" });
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ yield* updates.check("startup");
+
+ assert.equal((yield* updates.getState).channel, "latest");
+ assert.deepEqual(harness.checkAllowedDowngrade, [false]);
+ // Semver ranks Stable 1.2.4 above this Nightly, but a Nightly built before the release's
+ // version bump can hold migrations 1.2.4 lacks. Crossing needs a guarded switch.
+ harness.emit("update-available", { version: "1.2.4" });
+ yield* flushCallbacks;
+ assert.isNull((yield* updates.getState).availableVersion);
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ });
+
+ it.effect("keeps a saved Nightly track across a restart without crossing on its own", () => {
+ // A Stable build whose switch to Nightly was refused before the app quit; its floor is gone.
+ const harness = makeHarness({ savedChannel: "nightly" });
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ yield* updates.check("startup");
+ harness.emit("update-available", { version: "1.2.4-nightly.20261027.1" });
+ yield* flushCallbacks;
+
+ assert.equal((yield* updates.getState).channel, "nightly");
+ assert.isNull((yield* updates.getState).availableVersion);
+ assert.deepEqual(harness.checkAllowedDowngrade, [false]);
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ });
+
+ it.effect("never offers an older Nightly to a Nightly build's own checks", () => {
+ const harness = makeHarness({ appVersion: "1.2.4-nightly.20261027.1" });
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ yield* updates.check("poll");
+
+ assert.equal((yield* updates.getState).channel, "nightly");
+ assert.deepEqual(harness.checkAllowedDowngrade, [false]);
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ });
+
+ it.effect("waits out a background check instead of refusing a track change", () =>
+ Effect.gen(function* () {
+ const checkStarted = yield* Deferred.make<void>();
+ const releaseCheck = yield* Deferred.make<void>();
+ const harness = makeHarness({
+ beforeSetUpdateChannel: Effect.void,
+ checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe(
+ Effect.andThen(Deferred.await(releaseCheck)),
+ ),
+ });
+
+ yield* Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ yield* updates.check("poll").pipe(Effect.forkScoped);
+ yield* Deferred.await(checkStarted);
+
+ const channelFiber = yield* updates.setChannel("nightly").pipe(Effect.forkScoped);
+ yield* Deferred.succeed(releaseCheck, undefined);
+ yield* TestClock.adjust(Duration.seconds(2));
+ const state = yield* Fiber.join(channelFiber);
+
+ assert.equal(state.channel, "nightly");
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ }),
+ );
+
it.effect("rejects checks while an update channel change is being persisted", () =>
Effect.gen(function* () {
const channelChangeStarted = yield* Deferred.make<void>();
diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts
index aeda73f2bfa..4da742f453a 100644
--- a/apps/desktop/src/updates/DesktopUpdates.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.ts
@@ -19,6 +19,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
+import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
@@ -34,7 +35,8 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
-import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
+import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
+import { compareSemverVersions } from "@t3tools/shared/semver";
import {
createInitialDesktopUpdateState,
reduceDesktopUpdateStateOnCheckFailure,
@@ -49,6 +51,8 @@ import {
resolveNotAppliedInstallVersion,
} from "./updateMachine.ts";
+const CHANNEL_CHANGE_RETRY_DELAY = Duration.seconds(1);
+const CHANNEL_CHANGE_RETRIES = 30;
const AUTO_UPDATE_STARTUP_DELAY = "15 seconds";
const AUTO_UPDATE_POLL_INTERVAL = "4 minutes";
const PREPARED_INSTALL_CHECK_WAIT = Duration.seconds(90);
@@ -179,10 +183,16 @@ export class DesktopUpdates extends Context.Service<
readonly emitState: Effect.Effect<void>;
readonly disabledReason: Effect.Effect<Option.Option<string>>;
readonly configure: Effect.Effect<void, never, Scope.Scope>;
+ /** `minimumVersion` is a track switch's checked release; nothing older is offered after. */
readonly setChannel: (
channel: DesktopUpdateChannel,
+ options?: { readonly minimumVersion?: string | undefined },
) => Effect.Effect<DesktopUpdateState, DesktopUpdateSetChannelError>;
- readonly check: (reason: string) => Effect.Effect<DesktopUpdateCheckResult>;
+ /** `allowDowngrade` is for a guarded track switch, which checked that older release. */
+ readonly check: (
+ reason: string,
+ options?: { readonly allowDowngrade?: boolean },
+ ) => Effect.Effect<DesktopUpdateCheckResult>;
readonly download: Effect.Effect<DesktopUpdateActionResult>;
readonly install: Effect.Effect<DesktopUpdateActionResult>;
readonly installPrepared: (
@@ -351,6 +361,20 @@ export const make = Effect.gen(function* () {
const updaterConfiguredRef = yield* Ref.make(false);
const lastLoggedDownloadMilestoneRef = yield* Ref.make(-1);
const notAppliedVersionRef = yield* Ref.make(Option.none<string>());
+ // The release a track switch's database check cleared. A build crosses to another track only
+ // through such a switch, and never below that release: version order alone cannot tell whether
+ // a Stable knows a Nightly's migrations.
+ const releaseFloorRef = yield* Ref.make(Option.none<string>());
+ const offerable = (version: string, state: DesktopUpdateState) =>
+ Ref.get(releaseFloorRef).pipe(
+ Effect.map(
+ (floor) =>
+ desktopUpdateChannelOf(version) === state.channel &&
+ (Option.isSome(floor)
+ ? compareSemverVersions(version, floor.value) >= 0
+ : desktopUpdateChannelOf(environment.appVersion) === state.channel),
+ ),
+ );
const updateStateRef = yield* Ref.make<DesktopUpdateState>(
createInitialDesktopUpdateState(
environment.appVersion,
@@ -454,12 +478,13 @@ export const make = Effect.gen(function* () {
const allowsPrerelease = channel === "nightly";
yield* electronUpdater.setChannel(channel);
yield* electronUpdater.setAllowPrerelease(allowsPrerelease);
- yield* electronUpdater.setAllowDowngrade(allowsPrerelease);
+ // An older build can lack migrations this one ran. Only a guarded track switch's own check
+ // may offer one.
+ yield* electronUpdater.setAllowDowngrade(false);
yield* electronUpdater.setFullChangelog(allowsPrerelease);
yield* logUpdaterInfo("using update channel", {
channel,
allowPrerelease: allowsPrerelease,
- allowDowngrade: allowsPrerelease,
fullChangelog: allowsPrerelease,
});
});
@@ -467,6 +492,7 @@ export const make = Effect.gen(function* () {
const checkForUpdates = Effect.fn("desktop.updates.checkForUpdates")(function* (
reason: string,
actionReservation: "acquire" | "held" = "acquire",
+ allowDowngrade = false,
) {
yield* Effect.annotateCurrentSpan({ reason });
if (yield* Ref.get(desktopState.quitting)) return false;
@@ -488,7 +514,11 @@ export const make = Effect.gen(function* () {
yield* setState(reduceDesktopUpdateStateOnCheckStart(state, checkedAt));
yield* logUpdaterInfo("checking for updates", { reason });
+ // The flag is shared updater state, so it flips only while this check holds the reservation.
+ const restoreDowngrade = yield* electronUpdater.allowDowngrade;
+ if (allowDowngrade) yield* electronUpdater.setAllowDowngrade(true);
return yield* electronUpdater.checkForUpdates.pipe(
+ Effect.ensuring(electronUpdater.setAllowDowngrade(restoreDowngrade).pipe(Effect.ignore)),
Effect.as(true),
Effect.catchTags({
ElectronUpdaterCheckForUpdatesError: Effect.fn(
@@ -849,8 +879,8 @@ export const make = Effect.gen(function* () {
Effect.flatMap(
Effect.fn("desktop.updates.applyUpdateAvailable")(function* (info) {
const state = yield* Ref.get(updateStateRef);
- if (resolveDefaultDesktopUpdateChannel(info.version) !== state.channel) {
- yield* logUpdaterInfo("ignoring update that does not match selected channel", {
+ if (!(yield* offerable(info.version, state))) {
+ yield* logUpdaterInfo("ignoring update outside the selected channel or its floor", {
version: info.version,
channel: state.channel,
});
@@ -986,6 +1016,20 @@ export const make = Effect.gen(function* () {
Effect.flatMap(
Effect.fn("desktop.updates.applyUpdateDownloaded")(function* (info) {
const state = yield* Ref.get(updateStateRef);
+ // A download can finish after its track switch moved on; never offer that build.
+ if (!(yield* offerable(info.version, state))) {
+ yield* logUpdaterInfo("ignoring download outside the selected channel or its floor", {
+ version: info.version,
+ channel: state.channel,
+ });
+ // Its progress events left the updater "downloading", which would block every check.
+ if (state.status === "downloading") {
+ yield* setState(
+ reduceDesktopUpdateStateOnNoUpdate(state, yield* currentIsoTimestamp),
+ );
+ }
+ return;
+ }
yield* setState(reduceDesktopUpdateStateOnDownloadComplete(state, info.version));
yield* logUpdaterInfo("update downloaded", { version: info.version });
}),
@@ -1092,9 +1136,17 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.updates.configure")),
setChannel: Effect.fn("desktop.updates.setChannel")(function* (
nextChannel: DesktopUpdateChannel,
+ options?: { readonly minimumVersion?: string | undefined },
) {
yield* Effect.annotateCurrentSpan({ channel: nextChannel });
- const activeAction = yield* tryStartChannelChange;
+ // A background check holds the updater only briefly, so wait it out instead of refusing.
+ const activeAction = yield* tryStartChannelChange.pipe(
+ Effect.repeat({
+ while: (active) => Option.isSome(active) && active.value === "check",
+ schedule: Schedule.spaced(CHANNEL_CHANGE_RETRY_DELAY),
+ times: CHANNEL_CHANGE_RETRIES,
+ }),
+ );
if (Option.isSome(activeAction)) {
return yield* new DesktopUpdateActionInProgressError({
action: activeAction.value === "install-recovery" ? "install" : activeAction.value,
@@ -1103,8 +1155,16 @@ export const make = Effect.gen(function* () {
}
return yield* Effect.gen(function* () {
+ yield* Ref.set(releaseFloorRef, Option.fromNullishOr(options?.minimumVersion));
const state = yield* Ref.get(updateStateRef);
- if (nextChannel === state.channel) {
+ const retained = state.downloadedVersion ?? state.availableVersion;
+ // A build from another track re-checks, so retrying a track switch finds an older release.
+ // So does a retained offer below the new floor, which must not install.
+ if (
+ nextChannel === state.channel &&
+ nextChannel === desktopUpdateChannelOf(environment.appVersion) &&
+ (retained === null || (yield* offerable(retained, state)))
+ ) {
return state;
}
@@ -1124,15 +1184,19 @@ export const make = Effect.gen(function* () {
}
yield* applyAutoUpdaterChannel(nextChannel);
- const allowDowngrade = yield* electronUpdater.allowDowngrade;
- yield* electronUpdater.setAllowDowngrade(true);
- yield* checkForUpdates("channel-change", "held").pipe(
- Effect.ensuring(electronUpdater.setAllowDowngrade(allowDowngrade).pipe(Effect.ignore)),
+ // Only leaving the running build's track can need an older release.
+ yield* checkForUpdates(
+ "channel-change",
+ "held",
+ nextChannel !== desktopUpdateChannelOf(environment.appVersion),
);
return yield* Ref.get(updateStateRef);
}).pipe(Effect.ensuring(finishUpdateAction("channel")));
}),
- check: Effect.fn("desktop.updates.check")(function* (reason: string) {
+ check: Effect.fn("desktop.updates.check")(function* (
+ reason: string,
+ options?: { readonly allowDowngrade?: boolean },
+ ) {
yield* Effect.annotateCurrentSpan({ reason });
if (!(yield* Ref.get(updaterConfiguredRef))) {
return {
@@ -1140,7 +1204,7 @@ export const make = Effect.gen(function* () {
state: yield* Ref.get(updateStateRef),
};
}
- const checked = yield* checkForUpdates(reason);
+ const checked = yield* checkForUpdates(reason, "acquire", options?.allowDowngrade === true);
return {
checked,
state: yield* Ref.get(updateStateRef),
diff --git a/apps/desktop/src/updates/releaseNotes.ts b/apps/desktop/src/updates/releaseNotes.ts
index 69d710ff7b2..8698d8d4991 100644
--- a/apps/desktop/src/updates/releaseNotes.ts
+++ b/apps/desktop/src/updates/releaseNotes.ts
@@ -1,6 +1,6 @@
import type { DesktopUpdateChannel, DesktopUpdateReleaseNote } from "@t3tools/contracts";
-import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
+import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
interface ElectronReleaseNoteInfo {
readonly version: string;
@@ -134,7 +134,7 @@ export function normalizeDesktopUpdateReleaseNotes(
: Array.isArray(releaseNotes)
? releaseNotes.filter(isElectronReleaseNoteInfo)
: []
- ).filter((entry) => resolveDefaultDesktopUpdateChannel(entry.version) === channel);
+ ).filter((entry) => desktopUpdateChannelOf(entry.version) === channel);
const normalizedNotes = rawNotes.flatMap((entry) => {
const { items, totalItems } = extractReleaseNoteItems(entry.note);
diff --git a/apps/desktop/src/updates/updateChannels.ts b/apps/desktop/src/updates/updateChannels.ts
index d79a374a668..b07735ceb7a 100644
--- a/apps/desktop/src/updates/updateChannels.ts
+++ b/apps/desktop/src/updates/updateChannels.ts
@@ -1,13 +1,6 @@
-import type { DesktopUpdateChannel } from "@t3tools/contracts";
-
-const NIGHTLY_VERSION_PATTERN = /^[^-+]+-nightly\.\d{8}\.\d+$/;
// Preview builds share nightly branding but ship without an update feed.
const PRERELEASE_VERSION_PATTERN = /^[^-+]+-(?:nightly|preview)\.\d{8}\.\d+$/;
export function isNightlyDesktopVersion(version: string): boolean {
return PRERELEASE_VERSION_PATTERN.test(version);
}
-
-export function resolveDefaultDesktopUpdateChannel(appVersion: string): DesktopUpdateChannel {
- return NIGHTLY_VERSION_PATTERN.test(appVersion) ? "nightly" : "latest";
-}
diff --git a/apps/desktop/src/updates/updatesTestHarness.ts b/apps/desktop/src/updates/updatesTestHarness.ts
index 1d8c21a42df..d8d16b7dbfd 100644
--- a/apps/desktop/src/updates/updatesTestHarness.ts
+++ b/apps/desktop/src/updates/updatesTestHarness.ts
@@ -35,6 +35,11 @@ export interface UpdatesHarnessOptions {
readonly platform?: NodeJS.Platform;
readonly packageType?: string | undefined;
readonly installRecord?: string | undefined;
+ readonly appVersion?: string;
+ /** Starts from in-memory settings with this track saved, as after a restart. */
+ readonly savedChannel?: DesktopAppSettings.DesktopSettings["updateChannel"];
+ /** Adds a WSL backend beside the primary, as on a Windows host with WSL enabled. */
+ readonly wslBackend?: boolean;
}
export function makeHarness(options: UpdatesHarnessOptions = {}) {
@@ -42,6 +47,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
let quitAndInstallCount = 0;
let downloadCount = 0;
let allowDowngrade = false;
+ const checkAllowedDowngrade: boolean[] = [];
let fullChangelog = false;
const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
@@ -86,6 +92,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
checkForUpdates: Effect.sync(() => {
checkCount += 1;
+ checkAllowedDowngrade.push(allowDowngrade);
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
downloadUpdate: Effect.sync(() => {
downloadCount += 1;
@@ -149,7 +156,17 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
waitForReady: () => Effect.succeed(true),
};
const layerBackend = DesktopBackendPool.layerTest(
- options.backendInstances ?? [stubBackendInstance],
+ options.backendInstances ??
+ (options.wslBackend
+ ? [
+ stubBackendInstance,
+ {
+ ...stubBackendInstance,
+ id: DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"),
+ label: Effect.succeed("Ubuntu"),
+ },
+ ]
+ : [stubBackendInstance]),
);
const layerEnvironment = DesktopEnvironment.layer({
@@ -157,7 +174,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
platform: options.platform ?? "darwin",
processArch: "x64",
- appVersion: "1.2.3",
+ appVersion: options.appVersion ?? "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
@@ -178,10 +195,13 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
let testSettings: DesktopAppSettings.DesktopSettings = {
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ ...(options.savedChannel === undefined
+ ? {}
+ : { updateChannel: options.savedChannel, updateChannelConfiguredByUser: true }),
};
const setUpdateChannelError = options.setUpdateChannelError;
const layerSettings =
- setUpdateChannelError || options.beforeSetUpdateChannel
+ setUpdateChannelError || options.beforeSetUpdateChannel || options.savedChannel
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
get: Effect.sync(() => testSettings),
load: Effect.sync(() => testSettings),
@@ -279,6 +299,9 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
downloadCount: () => downloadCount,
feedUrls: (): ElectronUpdater.ElectronUpdaterFeedUrl[] => feedUrls,
fullChangelog: () => fullChangelog,
+ /** Whether each feed check could offer an older release, and the flag now. */
+ checkAllowedDowngrade,
+ allowDowngrade: () => allowDowngrade,
listenerCount: () =>
Array.from(listeners.values()).reduce(
(total, eventListeners) => total + eventListeners.size,
diff --git a/apps/server/src/cloud/selfUpdate.test.ts b/apps/server/src/cloud/selfUpdate.test.ts
index 84877d41a70..1e3157adfff 100644
--- a/apps/server/src/cloud/selfUpdate.test.ts
+++ b/apps/server/src/cloud/selfUpdate.test.ts
@@ -313,3 +313,36 @@ it.layer(NodeServices.layer)("pruning runtimes on start", (it) => {
}),
);
});
+
+it("a host crosses tracks only to a release that knows its whole database", () => {
+ const cross = (
+ serverVersion: string,
+ targetVersion: string,
+ targetDatabaseMigration: number | undefined,
+ databaseMigration = 72,
+ ) =>
+ ServerSelfUpdate.trackSwitchBlockReason({
+ serverVersion,
+ targetVersion,
+ targetDatabaseMigration,
+ databaseMigration: () => databaseMigration,
+ });
+ const nightly = "0.1.4-nightly.20261027.3796";
+
+ expect(cross(nightly, "0.1.4", 72)).toBeNull();
+ // Another client moved this host to a newer Nightly after the switch was planned.
+ expect(cross(nightly, "0.1.4", 72, 73)).toContain("does not support yet");
+ expect(cross(nightly, "0.1.4", undefined)).toContain("Cannot confirm");
+ // A Stable tag can carry a migration the latest Nightly lacks.
+ expect(cross("0.1.4", nightly, 72, 73)).toContain("does not support yet");
+ expect(cross("0.1.3", "0.1.4", undefined)).toBeNull();
+ // A database that exists but cannot be read proves nothing.
+ expect(
+ ServerSelfUpdate.trackSwitchBlockReason({
+ serverVersion: nightly,
+ targetVersion: "0.1.4",
+ targetDatabaseMigration: 72,
+ databaseMigration: () => undefined,
+ }),
+ ).toContain("Cannot confirm");
+});
diff --git a/apps/server/src/cloud/selfUpdate.ts b/apps/server/src/cloud/selfUpdate.ts
index ab6a69fc50a..d72c5e9218d 100644
--- a/apps/server/src/cloud/selfUpdate.ts
+++ b/apps/server/src/cloud/selfUpdate.ts
@@ -20,11 +20,12 @@ import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/http";
-import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease";
+import { CLI_RELEASE_BASE_URL_ENV, crossesReleaseTrack } from "@t3tools/shared/cliRelease";
import packageJson from "../../package.json" with { type: "json" };
import * as ServerConfig from "../config.ts";
import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
+import { databaseMigrationHead } from "../persistence/databaseMigrationHead.ts";
import * as ProcessRunner from "../processRunner.ts";
import {
ensurePinnedRuntimeInstalled,
@@ -93,6 +94,26 @@ export const pruneRuntimesOnStart = Effect.fn("cloud.server_self_update.prune_on
},
);
+/** The client checks this when planning; the host checks again because its database may have
+ * moved on since (another client updated it). Stable and Nightly each build their own commits,
+ * so crossing tracks needs the target release to know every migration this database holds. */
+export function trackSwitchBlockReason(input: {
+ readonly serverVersion: string;
+ readonly targetVersion: string;
+ readonly targetDatabaseMigration: number | undefined;
+ /** Read only for a crossing; undefined when the database cannot be read. */
+ readonly databaseMigration: () => number | undefined;
+}): string | null {
+ if (!crossesReleaseTrack(input.serverVersion, input.targetVersion)) return null;
+ const databaseMigration = input.databaseMigration();
+ if (input.targetDatabaseMigration === undefined || databaseMigration === undefined) {
+ return `Cannot confirm this database works with t3@${input.targetVersion}. Switch tracks from Settings → About → Update track, which checks it first.`;
+ }
+ return input.targetDatabaseMigration < databaseMigration
+ ? `This database has changes t3@${input.targetVersion} does not support yet; it stays on this release.`
+ : null;
+}
+
export const make = Effect.fn("cloud.server_self_update.make")(function* () {
const serverConfig = yield* ServerConfig.ServerConfig;
const desktopAppUpdate = yield* DesktopAppUpdate.DesktopAppUpdate;
@@ -119,12 +140,27 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
? new ServerSelfUpdateError({ reason })
: new ServerSelfUpdateError({ reason, cause });
+ const crossesTrackUnsafely = (input: ServerSelfUpdateInput) =>
+ trackSwitchBlockReason({
+ serverVersion: packageJson.version,
+ targetVersion: input.targetVersion,
+ targetDatabaseMigration: input.targetDatabaseMigration,
+ databaseMigration: () => databaseMigrationHead(serverConfig.dbPath),
+ });
+
const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
"cloud.server_self_update.update",
)(function* (input, reportProgress = () => Effect.void, onHandoffAccepted = () => Effect.void) {
if (capability === "desktop-managed") {
+ const unsafeCrossing = input.channel === undefined ? null : crossesTrackUnsafely(input);
+ if (unsafeCrossing !== null) return yield* failWith(unsafeCrossing);
if (desktopAppUpdate.available) {
- return yield* desktopAppUpdate.run(reportProgress);
+ return yield* desktopAppUpdate.run(
+ reportProgress,
+ input.channel === undefined
+ ? undefined
+ : { channel: input.channel, targetVersion: input.targetVersion },
+ );
}
return yield* failWith(
"This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
@@ -136,6 +172,8 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
);
}
+ const unsafeCrossing = crossesTrackUnsafely(input);
+ if (unsafeCrossing !== null) return yield* failWith(unsafeCrossing);
const targetVersion = input.targetVersion.trim();
if (!isExactServiceVersion(targetVersion)) {
return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
diff --git a/apps/server/src/cloud/servicePreflight.test.ts b/apps/server/src/cloud/servicePreflight.test.ts
index 18a5323cd59..efc37266be8 100644
--- a/apps/server/src/cloud/servicePreflight.test.ts
+++ b/apps/server/src/cloud/servicePreflight.test.ts
@@ -1,4 +1,16 @@
+import * as NodeSqlite from "node:sqlite";
+
+import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Path from "effect/Path";
+
+import {
+ BUILD_MIGRATION_HEAD,
+ databaseMigrationHead,
+} from "../persistence/databaseMigrationHead.ts";
+import { migrationManifest } from "../persistence/Migrations.ts";
import { runServicePreflight } from "./servicePreflight.ts";
import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
@@ -20,3 +32,49 @@ it.each([1])("blocks legacy launcher protocol %i with exact recovery steps", (la
expect(reason).toContain("t3 --version");
expect(reason).toContain("which -a t3");
});
+
+it.layer(NodeServices.layer)("service preflight database", (it) => {
+ it.effect("blocks a database that a newer build migrated", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const databasePath = path.join(
+ yield* fs.makeTempDirectoryScoped({ prefix: "t3-preflight-" }),
+ "state.sqlite",
+ );
+ const db = new NodeSqlite.DatabaseSync(databasePath);
+ db.exec("CREATE TABLE effect_sql_migrations (migration_id INTEGER PRIMARY KEY, name TEXT)");
+ const insert = db.prepare("INSERT INTO effect_sql_migrations VALUES (?, ?)");
+ for (const [id, name] of migrationManifest) insert.run(id, name);
+ const preflight = () =>
+ runServicePreflight({ databasePath, launcherProtocol: SERVICE_LAUNCHER_PROTOCOL });
+
+ expect(preflight().status).toBe("ready");
+ expect(databaseMigrationHead(databasePath)).toBe(BUILD_MIGRATION_HEAD);
+
+ const newerId = Math.max(...migrationManifest.map(([id]) => id)) + 1;
+ insert.run(newerId, "FromNightly");
+ db.close();
+ const result = preflight();
+ expect(result.status).toBe("blocked");
+ expect(result.status === "blocked" ? result.reason : "").toContain(`${newerId}_FromNightly`);
+ // Servers report this head, so clients see a database a newer build migrated.
+ expect(databaseMigrationHead(databasePath)).toBe(newerId);
+
+ // A database that exists but cannot be read has an unknown history, so it blocks.
+ const unreadable = path.join(path.dirname(databasePath), "unreadable.sqlite");
+ yield* fs.writeFileString(unreadable, "not a database");
+ expect(databaseMigrationHead(unreadable)).toBeUndefined();
+ expect(
+ runServicePreflight({
+ databasePath: unreadable,
+ launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
+ }).status,
+ ).toBe("blocked");
+ // A missing database is a fresh install.
+ expect(databaseMigrationHead(path.join(path.dirname(databasePath), "missing.sqlite"))).toBe(
+ BUILD_MIGRATION_HEAD,
+ );
+ }),
+ );
+});
diff --git a/apps/server/src/cloud/servicePreflight.ts b/apps/server/src/cloud/servicePreflight.ts
index 8865ce7b3d1..9479f3f4a81 100644
--- a/apps/server/src/cloud/servicePreflight.ts
+++ b/apps/server/src/cloud/servicePreflight.ts
@@ -1,4 +1,5 @@
import packageJson from "../../package.json" with { type: "json" };
+import { BUILD_MIGRATION_HEAD, recordedMigrations } from "../persistence/databaseMigrationHead.ts";
import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
export type ServicePreflightResult =
@@ -34,9 +35,34 @@ export function runServicePreflight(input: {
};
}
+ const newer = newerRecordedMigrations(input.databasePath);
+ if (newer === null) {
+ return {
+ status: "blocked",
+ version,
+ reason: `Could not read this database to confirm t3@${version} supports it.`,
+ };
+ }
+ if (newer.length > 0) {
+ return {
+ status: "blocked",
+ version,
+ reason: `This database has migrations that t3@${version} does not know: ${newer.join(", ")}. A newer build wrote them, and running t3@${version} on this database is not safe. Stay on the newer release, or wait for a release that includes these migrations.`,
+ };
+ }
+
return { status: "ready", version, launcherProtocol: SERVICE_LAUNCHER_PROTOCOL };
}
+/** Migrations a newer build recorded, or null when the database exists but cannot be read.
+ * Startup already handles renamed ids this build knows. */
+function newerRecordedMigrations(databasePath: string): ReadonlyArray<string> | null {
+ const recorded = recordedMigrations(databasePath);
+ return recorded === null
+ ? null
+ : recorded.filter(({ id }) => id > BUILD_MIGRATION_HEAD).map(({ id, name }) => `${id}_${name}`);
+}
+
export function decodeServicePreflightResult(value: unknown): ServicePreflightResult | undefined {
if (typeof value !== "object" || value === null) {
return undefined;
diff --git a/apps/server/src/desktopUpdate/DesktopAppUpdate.test.ts b/apps/server/src/desktopUpdate/DesktopAppUpdate.test.ts
index 86d445d1a52..f90bef39fcf 100644
--- a/apps/server/src/desktopUpdate/DesktopAppUpdate.test.ts
+++ b/apps/server/src/desktopUpdate/DesktopAppUpdate.test.ts
@@ -132,6 +132,24 @@ it.layer(NodeServices.layer)("desktop app update", (it) => {
}),
);
+ it.effect("succeeds without an install when a track switch finds the host current", () =>
+ Effect.gen(function* () {
+ const { service } = yield* makeHarness({
+ reports: (requestId) => [
+ report(requestId, makeState({ status: "up-to-date", currentVersion: "1.2.3" }), {
+ outcome: "up-to-date",
+ }),
+ ],
+ });
+ const trackSwitch = { channel: "latest" as const, targetVersion: "1.2.3" };
+
+ expect(yield* service.run(() => Effect.void, trackSwitch)).toEqual({
+ targetVersion: "1.2.3",
+ method: "desktop-app",
+ });
+ }),
+ );
+
it.effect("replays a retained commit failure for the preparation token", () =>
Effect.gen(function* () {
const { service } = yield* makeHarness({
diff --git a/apps/server/src/desktopUpdate/DesktopAppUpdate.ts b/apps/server/src/desktopUpdate/DesktopAppUpdate.ts
index d02c3108777..e901b04cfb5 100644
--- a/apps/server/src/desktopUpdate/DesktopAppUpdate.ts
+++ b/apps/server/src/desktopUpdate/DesktopAppUpdate.ts
@@ -44,6 +44,7 @@ export class DesktopAppUpdate extends Context.Service<
reportProgress: (
stage: ServerSelfUpdateProgressStage,
) => Effect.Effect<void, ServerSelfUpdateError>,
+ trackSwitch?: DesktopTelemetryReceiver.DesktopTrackSwitch,
) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
/** Success stops the server; returns only on installation failure or timeout. */
readonly commit: (
@@ -71,6 +72,7 @@ export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* (
reportProgress: (
stage: ServerSelfUpdateProgressStage,
) => Effect.Effect<void, ServerSelfUpdateError>,
+ trackSwitch: boolean,
) {
const lastStage = yield* Ref.make<ServerSelfUpdateProgressStage | null>(null);
const emitStage = (
@@ -122,6 +124,11 @@ export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* (
return { targetVersion, method: "desktop-app" as const, desktopUpdateToken: requestId };
}
if (report.outcome === "up-to-date") {
+ // A switch's host already on the newest build of its track only saved the track.
+ if (trackSwitch) {
+ yield* Ref.set(inFlight, false);
+ return { targetVersion: report.state.currentVersion, method: "desktop-app" as const };
+ }
return yield* failWith(
`The T3 Code desktop app on this machine is already up to date on ${report.state.currentVersion}.`,
);
@@ -132,7 +139,7 @@ export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* (
});
const run: DesktopAppUpdate["Service"]["run"] = Effect.fn("desktopUpdate.desktopAppUpdate.run")(
- function* (reportProgress) {
+ function* (reportProgress, trackSwitch) {
if (!available) {
return yield* failWith(
"This server was not started by the T3 Code desktop app, so it cannot drive a desktop update.",
@@ -154,13 +161,18 @@ export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* (
// Subscribe before requesting to catch fast reports.
const { changes } = yield* receiver.desktopUpdates;
yield* receiver
- .requestDesktopUpdate(requestId)
+ .requestDesktopUpdate(requestId, trackSwitch)
.pipe(
Effect.mapError((error) =>
failWith("Could not reach the T3 Code desktop app on this machine.", error),
),
);
- return yield* consumeReports(requestId, changes, reportProgress).pipe(
+ return yield* consumeReports(
+ requestId,
+ changes,
+ reportProgress,
+ trackSwitch !== undefined,
+ ).pipe(
Effect.onInterrupt(() => receiver.cancelDesktopUpdate(requestId).pipe(Effect.ignore)),
);
}),
diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts
index 90ae4519bed..cef18fbe325 100644
--- a/apps/server/src/environment/ServerEnvironment.ts
+++ b/apps/server/src/environment/ServerEnvironment.ts
@@ -20,6 +20,7 @@ import { readAgentActivityPublishingActive } from "../cloud/config.ts";
import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";
import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
import * as ServerConfig from "../config.ts";
+import { databaseMigrationHead } from "../persistence/databaseMigrationHead.ts";
import * as ProcessRunner from "../processRunner.ts";
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
import { detectServerEnvironmentMachineKind } from "./ServerEnvironmentMachine.ts";
@@ -203,6 +204,7 @@ export const make = Effect.gen(function* () {
const desktopAppUpdate =
serverSelfUpdate === "desktop-managed" && serverConfig.desktopTelemetryControlFd !== undefined;
+ const databaseMigration = databaseMigrationHead(serverConfig.dbPath);
const descriptor: ExecutionEnvironmentDescriptor = {
environmentId,
label,
@@ -213,6 +215,7 @@ export const make = Effect.gen(function* () {
},
serverVersion: packageJson.version,
orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
+ ...(databaseMigration === undefined ? {} : { databaseMigration }),
capabilities: {
repositoryIdentity: true,
connectionProbe: true,
@@ -266,7 +269,7 @@ export const make = Effect.gen(function* () {
...(serverSelfUpdate === "boot-service" || desktopAppUpdate
? { serverSelfUpdateProgress: true }
: {}),
- ...(desktopAppUpdate ? { desktopAppUpdate: true } : {}),
+ ...(desktopAppUpdate ? { desktopAppUpdate: true, desktopAppChannelSwitch: true } : {}),
serverBrowser: true,
peerLinks: true,
mcpModeLimitHeader: true,
diff --git a/apps/server/src/persistence/Migrations.test.ts b/apps/server/src/persistence/Migrations.test.ts
index 67f238b7484..54e4a711aa8 100644
--- a/apps/server/src/persistence/Migrations.test.ts
+++ b/apps/server/src/persistence/Migrations.test.ts
@@ -1,7 +1,10 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
+import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
+import * as FileSystem from "effect/FileSystem";
+import * as Path from "effect/Path";
import * as SqlClient from "effect/sql/SqlClient";
import { migrationManifest, runMigrations } from "./Migrations.ts";
@@ -123,3 +126,20 @@ describe("runMigrations", () => {
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
);
});
+
+// The npm launcher reads the highest migration id from these file names.
+it.effect("registers every migration file", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const dir = path.join(import.meta.dirname, "Migrations");
+ const files = (yield* fs.readDirectory(dir)).flatMap((name) => {
+ const match = /^(\d+)_(\w+)\.ts$/.exec(name);
+ return match ? [[Number(match[1]), match[2]] as const] : [];
+ });
+ assert.deepStrictEqual(
+ files.toSorted(([a], [b]) => a - b),
+ migrationManifest,
+ );
+ }).pipe(Effect.provide(NodeServices.layer)),
+);
diff --git a/apps/server/src/persistence/databaseMigrationHead.ts b/apps/server/src/persistence/databaseMigrationHead.ts
new file mode 100644
index 00000000000..046039a7034
--- /dev/null
+++ b/apps/server/src/persistence/databaseMigrationHead.ts
@@ -0,0 +1,49 @@
+// @effect-diagnostics nodeBuiltinImport:off - read synchronously by the preflight subprocess and at startup.
+import * as NodeFS from "node:fs";
+import * as NodeSqlite from "node:sqlite";
+
+import { migrationManifest } from "./Migrations.ts";
+
+export const BUILD_MIGRATION_HEAD = Math.max(...migrationManifest.map(([id]) => id));
+
+/** Migrations the database records, read-only. A missing or new database records none; one that
+ * exists but cannot be read is null, since its history is unknown. */
+export function recordedMigrations(
+ databasePath: string,
+): ReadonlyArray<{ readonly id: number; readonly name: string }> | null {
+ let db: NodeSqlite.DatabaseSync;
+ try {
+ db = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
+ } catch {
+ return NodeFS.existsSync(databasePath) ? null : [];
+ }
+ try {
+ const hasTable = db
+ .prepare(
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations'",
+ )
+ .get();
+ if (hasTable === undefined) return [];
+ return db
+ .prepare("SELECT migration_id, name FROM effect_sql_migrations ORDER BY migration_id")
+ .all()
+ .map((row) => ({ id: Number(row.migration_id), name: String(row.name) }));
+ } catch {
+ return null;
+ } finally {
+ try {
+ db.close();
+ } catch {
+ // A read-only handle has nothing to flush; the result above already stands.
+ }
+ }
+}
+
+/** Highest migration the database holds once this build's startup migrations have run. A newer
+ * build may have recorded more than this build knows. Undefined when the database is unreadable. */
+export function databaseMigrationHead(databasePath: string): number | undefined {
+ const recorded = recordedMigrations(databasePath);
+ return recorded === null
+ ? undefined
+ : Math.max(BUILD_MIGRATION_HEAD, ...recorded.map(({ id }) => id));
+}
diff --git a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts
index 770359b3e93..70dc2e8d750 100644
--- a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts
+++ b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts
@@ -8,6 +8,7 @@ import {
type DesktopHostTelemetryMessage as DesktopHostTelemetryMessageValue,
type DesktopHostTelemetrySnapshot,
DesktopTelemetryControlMessage,
+ type DesktopUpdateChannel,
type DesktopUpdateStatusReport,
type ResourceTelemetrySourceStatus,
} from "@t3tools/contracts";
@@ -149,6 +150,12 @@ export interface DesktopTelemetryReceiverHealth {
readonly lastError: Option.Option<string>;
}
+/** Moves the desktop app to `channel` and installs only `targetVersion`. */
+export interface DesktopTrackSwitch {
+ readonly channel: DesktopUpdateChannel;
+ readonly targetVersion: string;
+}
+
export class DesktopTelemetryReceiver extends Context.Service<
DesktopTelemetryReceiver,
{
@@ -176,6 +183,7 @@ export class DesktopTelemetryReceiver extends Context.Service<
) => Effect.Effect<void, DesktopTelemetryControlError>;
readonly requestDesktopUpdate: (
requestId: string,
+ trackSwitch?: DesktopTrackSwitch,
) => Effect.Effect<void, DesktopTelemetryControlError>;
readonly commitDesktopUpdate: (
requestId: string,
@@ -633,11 +641,12 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
subscribeHealth: subscribeBeforeSnapshotWithoutMutex(healthChanges, Ref.get(health)),
setDiagnosticsDemand,
requestDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.requestDesktopUpdate")(
- function (requestId) {
+ function (requestId, trackSwitch) {
return sendControlMessage({
version: 1,
type: "requestDesktopUpdate",
requestId,
+ ...trackSwitch,
});
},
),
diff --git a/apps/web/src/components/ServerUpdateAction.browser.test.tsx b/apps/web/src/components/ServerUpdateAction.browser.test.tsx
index 5f793b3ca90..ed3a723652a 100644
--- a/apps/web/src/components/ServerUpdateAction.browser.test.tsx
+++ b/apps/web/src/components/ServerUpdateAction.browser.test.tsx
@@ -14,6 +14,7 @@ const testState = vi.hoisted(() => ({
toast: vi.fn(),
clipboard: vi.fn(),
sessionAtom: null as unknown,
+ serverVersions: new Map<string, string>(),
}));
vi.mock(import("~/hooks/useCopyToClipboard"), async (original) => ({
@@ -36,6 +37,16 @@ vi.mock(import("~/state/session"), async (original) => {
},
};
});
+vi.mock(import("~/state/entities"), async (original) => ({
+ ...(await original()),
+ useServerConfigs: (() =>
+ new Map(
+ [...testState.serverVersions].map(([id, serverVersion]) => [
+ id,
+ { environment: { serverVersion } },
+ ]),
+ )) as never,
+}));
vi.mock(import("~/state/use-atom-command"), async (original) => ({
...(await original()),
useAtomCommand: (() => testState.updateServer) as never,
@@ -84,6 +95,7 @@ function setup(): Disposable {
testState.updateServer.mockReset();
testState.toast.mockReset();
testState.clipboard.mockReset();
+ testState.serverVersions.clear();
sessionAtom = Atom.make<SessionResult>(AsyncResult.success(currentSession));
testState.sessionAtom = sessionAtom;
resetConfirmDialogForTests();
@@ -212,4 +224,17 @@ describe("ServerUpdatesAction", () => {
);
expect(button(screen, "Update all")!.disabled).toBe(false);
});
+
+ it("skips a machine whose update would cross Stable and Nightly", async () => {
+ using _state = setup();
+ testState.serverVersions.set("batch-a", "0.0.30-nightly.20261001.1");
+ testState.updateServer.mockResolvedValue(success());
+ await using screen = await mount();
+ await click(screen, "Update all");
+
+ expect(testState.updateServer).toHaveBeenCalledTimes(1);
+ expect(testState.toast).toHaveBeenCalledWith(
+ expect.objectContaining({ type: "success", title: "Office updated" }),
+ );
+ });
});
diff --git a/apps/web/src/components/ServerUpdateAction.tsx b/apps/web/src/components/ServerUpdateAction.tsx
index 3f7675cd966..141f139aefd 100644
--- a/apps/web/src/components/ServerUpdateAction.tsx
+++ b/apps/web/src/components/ServerUpdateAction.tsx
@@ -7,6 +7,7 @@ import {
import type { AsyncResult } from "effect/reactivity";
import { environmentSession } from "~/state/session";
import type {
+ DesktopUpdateChannel,
EnvironmentId,
ServerInstallation,
ServerSelfUpdateCapability,
@@ -26,6 +27,8 @@ import { serverEnvironment, updateOutdatedServer } from "~/state/server";
import { appAtomRegistry } from "~/rpc/atomRegistry";
import { useAtomCommand } from "~/state/use-atom-command";
import { manualServerUpdateCommand } from "~/versionSkew";
+import { useServerConfigs } from "~/state/entities";
+import { crossesReleaseTrack } from "@t3tools/shared/cliRelease";
import { Button } from "./ui/button";
import { toastManager } from "./ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
@@ -41,6 +44,29 @@ export function serverUpdateStageLabel(stage: ServerUpdateStage): string {
return UPDATE_STAGE_LABELS[stage];
}
+const CROSS_TRACK_NOTE = "Switch tracks in About → Update track";
+
+/** Hosts refuse a Stable/Nightly crossing outside a track switch, which checks the database first. */
+function refusedCrossing(
+ target: {
+ readonly selfUpdate: ServerSelfUpdateCapability | null;
+ readonly targetVersion: string;
+ readonly channel?: DesktopUpdateChannel | undefined;
+ },
+ serverVersion: string | undefined,
+): boolean {
+ return (
+ target.channel === undefined &&
+ target.selfUpdate !== null &&
+ serverVersion !== undefined &&
+ crossesReleaseTrack(serverVersion, target.targetVersion)
+ );
+}
+
+function CrossTrackNote() {
+ return <span className="text-muted-foreground text-xs">{CROSS_TRACK_NOTE}</span>;
+}
+
function updateFailureMessage(error: unknown): string {
return error instanceof Error ? error.message : "Server update failed.";
}
@@ -52,6 +78,12 @@ export interface ServerUpdateTarget {
readonly installation?: ServerInstallation | undefined;
readonly desktopAppUpdate?: boolean;
readonly targetVersion: string;
+ /** Set only by a track switch; the host's desktop app moves to this track. */
+ readonly channel?: DesktopUpdateChannel;
+ /** A track switch's checked release migration; the host re-checks its own database. */
+ readonly targetDatabaseMigration?: number;
+ /** The host already runs its track's newest build and only saves the track. */
+ readonly trackOnly?: boolean;
}
type UpdateButtonProps = Pick<ComponentProps<typeof Button>, "variant" | "size" | "className"> & {
@@ -79,7 +111,13 @@ export function useServerUpdate() {
pendingUpdateEnvironmentIds.add(environmentId);
const result = await updateServer({
environmentId,
- input: { targetVersion },
+ input: {
+ targetVersion,
+ ...(target.channel === undefined ? {} : { channel: target.channel }),
+ ...(target.targetDatabaseMigration === undefined
+ ? {}
+ : { targetDatabaseMigration: target.targetDatabaseMigration }),
+ },
});
pendingUpdateEnvironmentIds.delete(environmentId);
if (result._tag === "Failure") {
@@ -118,12 +156,14 @@ export function ServerUpdatesAction({
readonly targets: ReadonlyArray<ServerUpdateTarget>;
}) {
const update = useServerUpdate();
+ const serverConfigs = useServerConfigs();
const pending = useRef(false);
const [isPending, setIsPending] = useState(false);
const eligible = targets.filter(
(target) =>
target.selfUpdate !== null &&
- (target.selfUpdate !== "desktop-managed" || target.desktopAppUpdate),
+ (target.selfUpdate !== "desktop-managed" || target.desktopAppUpdate) &&
+ !refusedCrossing(target, serverConfigs.get(target.environmentId)?.environment.serverVersion),
);
const handleUpdate = async () => {
if (pending.current) return;
@@ -198,6 +238,7 @@ export function ServerUpdateAction({
installation,
desktopAppUpdate = false,
targetVersion,
+ channel,
label = "Update",
variant = "outline",
size = "xs",
@@ -205,6 +246,7 @@ export function ServerUpdateAction({
appearance = "button",
}: ServerUpdateTarget & UpdateButtonProps) {
const isDesktopAppUpdate = selfUpdate === "desktop-managed";
+ const serverVersion = useServerConfigs().get(environmentId)?.environment.serverVersion;
const sessionStateAtom = environmentSession.sessionStateAtom(environmentId);
const canUpdate = canUpdateServer(useAtomValue(sessionStateAtom));
const update = useServerUpdate();
@@ -264,6 +306,10 @@ export function ServerUpdateAction({
);
}
+ if (refusedCrossing({ selfUpdate, targetVersion, channel }, serverVersion)) {
+ return <CrossTrackNote />;
+ }
+
const manualCommand =
selfUpdate === null ? manualServerUpdateCommand(targetVersion, installation) : null;
const actionLabel =
@@ -351,6 +397,9 @@ export function OutdatedServerUpdateAction({
description: `Reconnected on t3@${result.value.targetVersion}.`,
});
};
+ if (fromVersion !== undefined && crossesReleaseTrack(fromVersion, targetVersion)) {
+ return <CrossTrackNote />;
+ }
return (
<Button size="xs" variant="outline" onClick={() => void handleUpdate()}>
{label}
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx
index 0cb00b86ac3..c4e3d27a07f 100644
--- a/apps/web/src/components/settings/SettingsPanels.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.tsx
@@ -1,3 +1,4 @@
+import { useAtomValue } from "@effect/atom-react";
import { NotificationSettings } from "./NotificationSettings";
import { PRIVACY_POLICY_URL } from "../../legalLinks";
import { CheckIcon } from "lucide-react";
@@ -20,6 +21,7 @@ import {
type QuitConfirmationMode,
SidebarProjectSortOrder,
} from "@t3tools/contracts/settings";
+import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
import { createModelSelection } from "@t3tools/shared/model";
import * as Equal from "effect/Equal";
import * as Schema from "effect/Schema";
@@ -64,7 +66,7 @@ import {
import { providerInstanceEntriesFor } from "../../providerInstances";
import { ensureLocalApi, readLocalApi } from "../../localApi";
import { isMacPlatform } from "../../lib/utils";
-import { useEnvironmentProviders } from "../../state/environments";
+import { useEnvironmentProviders, useEnvironments } from "../../state/environments";
import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
import { Button } from "../ui/button";
import { DraftInput } from "../ui/draft-input";
@@ -95,6 +97,13 @@ import { BackgroundActivitySettingsRow } from "./BackgroundActivitySettings";
import { AdvancedSettings } from "./AdvancedSettings";
import { PullRequestLinksOpenInAppSetting } from "./IntegrationsSettings";
import { StorageCleanupSections } from "./StorageSettings";
+import { UpdateTrackSwitchDialog } from "./UpdateTrackSwitchDialog";
+import { environmentIdsKey } from "~/state/environmentAtomList";
+import { environmentSessionStatesAtom } from "~/state/session";
+import { canUpdateServer } from "../ServerUpdateAction";
+import { useUpdateEverythingRun } from "../sidebar/updateEverythingRun";
+import { awaitsTrackSwitch, channelSwitchLabel } from "../sidebar/updateEverything.logic";
+import { isHostedByThisApp } from "../sidebar/useUpdateEverything";
const RESPONSE_STREAMING_MODE_LABELS: Record<ResponseStreamingMode, string> = {
turn: "Wait for the full response",
@@ -142,39 +151,38 @@ function AboutVersionTitle() {
function AboutVersionSection() {
const updateState = useDesktopUpdateState();
- const [isChangingUpdateChannel, setIsChangingUpdateChannel] = useState(false);
+ const [switchChannel, setSwitchChannel] = useState<DesktopUpdateChannel | null>(null);
const [isUpdateActionPending, setIsUpdateActionPending] = useState(false);
+ const { environments } = useEnvironments();
+ const sessionStates = useAtomValue(
+ environmentSessionStatesAtom(
+ environmentIdsKey(environments.map(({ environmentId }) => environmentId)),
+ ),
+ );
+ // A second run would replace the first run's progress and local download.
+ const updateRun = useUpdateEverythingRun();
const hasDesktopBridge = typeof window !== "undefined" && Boolean(window.desktopBridge);
const selectedUpdateChannel = updateState?.channel ?? "latest";
const selectedHostedAppChannel = hasDesktopBridge ? null : HOSTED_APP_CHANNEL;
-
- const handleUpdateChannelChange = (channel: DesktopUpdateChannel) => {
- const bridge = window.desktopBridge;
- if (
- !bridge ||
- typeof bridge.setUpdateChannel !== "function" ||
- channel === selectedUpdateChannel
- ) {
- return;
- }
-
- setIsChangingUpdateChannel(true);
- void bridge
- .setUpdateChannel(channel)
- .catch((error: unknown) => {
- toastManager.add(
- stackedThreadToast({
- type: "error",
- title: "Could not change update track",
- description: error instanceof Error ? error.message : "Update track change failed.",
- }),
- );
- })
- .finally(() => {
- setIsChangingUpdateChannel(false);
- });
- };
+ // A switch that failed part way leaves this app or a server on the other track.
+ // With its updater off, a switch cannot move this app, so it is not counted.
+ const appOffTrack =
+ updateState?.enabled !== false && desktopUpdateChannelOf(APP_VERSION) !== selectedUpdateChannel;
+ const unswitchedMachines =
+ (appOffTrack ? 1 : 0) +
+ environments.filter(
+ (environment, index) =>
+ environment.connection.phase === "connected" &&
+ canUpdateServer(sessionStates[index]!) &&
+ awaitsTrackSwitch(
+ {
+ serverConfig: environment.serverConfig,
+ hostedByThisApp: isHostedByThisApp(environment),
+ },
+ selectedUpdateChannel,
+ ),
+ ).length;
const handleButtonClick = async () => {
const bridge = window.desktopBridge;
@@ -272,7 +280,8 @@ function AboutVersionSection() {
const statusLabel: Record<string, string> = {
checking: "Checking…",
downloading: "Downloading…",
- "up-to-date": "Up to Date",
+ // Off its track, "up to date" only means no switch is pending; Review moves it.
+ ...(appOffTrack ? {} : { "up-to-date": "Up to Date" }),
};
const buttonLabel =
actionLabel[action] ?? statusLabel[updateState?.status ?? ""] ?? "Check for Updates";
@@ -308,23 +317,43 @@ function AboutVersionSection() {
{hasDesktopBridge ? (
<SettingsRow
{...searchableSetting("update-track")}
- description="Use stable releases or nightly builds. Switch back anytime."
+ description={
+ unswitchedMachines > 0 ? (
+ <>
+ {unswitchedMachines === 1
+ ? "1 machine still runs"
+ : `${unswitchedMachines} machines still run`}{" "}
+ {channelSwitchLabel(selectedUpdateChannel === "nightly" ? "latest" : "nightly")}.{" "}
+ {/* The dialog moves what it can and says why it skips the rest. */}
+ <Button
+ size="xs"
+ variant="link"
+ disabled={updateRun !== null}
+ onClick={() => setSwitchChannel(selectedUpdateChannel)}
+ >
+ Review
+ </Button>
+ </>
+ ) : (
+ "Switches this app and every connected machine whose database the target release supports."
+ )
+ }
control={
<Select
value={selectedUpdateChannel}
onValueChange={(value) => {
- handleUpdateChannelChange(value as DesktopUpdateChannel);
+ if (value !== selectedUpdateChannel) {
+ setSwitchChannel(value as DesktopUpdateChannel);
+ }
}}
>
<SelectTrigger
size="sm"
className="w-full sm:w-40"
aria-label="Update track"
- disabled={isChangingUpdateChannel}
+ disabled={switchChannel !== null || updateRun !== null}
>
- <SelectValue>
- {selectedUpdateChannel === "nightly" ? "Nightly" : "Stable"}
- </SelectValue>
+ <SelectValue>{channelSwitchLabel(selectedUpdateChannel)}</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
<SelectItem hideIndicator value="latest">
@@ -367,6 +396,9 @@ function AboutVersionSection() {
/>
) : null}
{hasDesktopBridge ? <CliCommandSettingsRow /> : null}
+ {switchChannel === null ? null : (
+ <UpdateTrackSwitchDialog channel={switchChannel} onClose={() => setSwitchChannel(null)} />
+ )}
</>
);
}
diff --git a/apps/web/src/components/settings/UpdateTrackSwitchDialog.tsx b/apps/web/src/components/settings/UpdateTrackSwitchDialog.tsx
new file mode 100644
index 00000000000..f746cff28c2
--- /dev/null
+++ b/apps/web/src/components/settings/UpdateTrackSwitchDialog.tsx
@@ -0,0 +1,178 @@
+import { useAtomValue } from "@effect/atom-react";
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import type { DesktopUpdateChannel } from "@t3tools/contracts";
+import { acceptsTrackSwitchRelease, desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
+import { isMacPlatform } from "@t3tools/shared/keybindings";
+import { useState } from "react";
+import { AsyncResult } from "effect/reactivity";
+
+import { APP_VERSION } from "~/branding";
+import { useDesktopUpdateState } from "~/state/desktopUpdate";
+import { useEnvironments } from "~/state/environments";
+import { npmReleaseAtom } from "~/state/npmRelease";
+import { downloadLocalUpdate, installLocalUpdate } from "../sidebar/SidebarUpdatePill";
+import { UpdateEverythingDialog } from "../sidebar/UpdateEverythingDialog";
+import {
+ channelSwitchLabel,
+ localSwitchBlockReason,
+ type ChannelSwitchRelease,
+} from "../sidebar/updateEverything.logic";
+import { isHostedByThisApp, useUpdateEverything } from "../sidebar/useUpdateEverything";
+import { prepareLocalTrackSwitch } from "./updateTrackSwitch.logic";
+import {
+ AlertDialog,
+ AlertDialogClose,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogPopup,
+ AlertDialogTitle,
+} from "../ui/alert-dialog";
+import { Button } from "../ui/button";
+import { stackedThreadToast, toastManager } from "../ui/toast";
+
+/** Moves this app and every connected machine to `channel`. */
+export function UpdateTrackSwitchDialog({
+ channel,
+ onClose,
+}: {
+ readonly channel: DesktopUpdateChannel;
+ readonly onClose: () => void;
+}) {
+ // npm dist-tags match the desktop channel names.
+ const release = useAtomValue(npmReleaseAtom(channel));
+ if (AsyncResult.isSuccess(release) && release.value !== null) {
+ return <SwitchPlan release={{ channel, ...release.value }} onClose={onClose} />;
+ }
+ const label = channelSwitchLabel(channel);
+ return (
+ <AlertDialog open onOpenChange={(open) => !open && onClose()}>
+ <AlertDialogPopup>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Switch to {label}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {AsyncResult.isFailure(release) || AsyncResult.isSuccess(release)
+ ? `Could not find the latest ${label} release on npm. Try again later.`
+ : "Checking releases…"}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
+ </AlertDialogFooter>
+ </AlertDialogPopup>
+ </AlertDialog>
+ );
+}
+
+function SwitchPlan({
+ release,
+ onClose,
+}: {
+ readonly release: ChannelSwitchRelease;
+ readonly onClose: () => void;
+}) {
+ const updateState = useDesktopUpdateState();
+ const { environments } = useEnvironments();
+ const crossesLocal = desktopUpdateChannelOf(APP_VERSION) !== release.channel;
+ // With its updater off (a .deb install, or no feed) this app stays put and only remotes move.
+ const updatesOff = updateState?.enabled === false;
+ // After a partial switch this app may already be on the track; then only remotes move.
+ const switchesLocal = crossesLocal && !updatesOff;
+ const [checking, setChecking] = useState(false);
+ const everything = useUpdateEverything(switchesLocal ? release.version : null, release);
+ const label = channelSwitchLabel(release.channel);
+ // This app's reinstall restarts every server it hosts, so each of their databases must allow it.
+ const localBlocked = localSwitchBlockReason(
+ APP_VERSION,
+ release,
+ environments.filter(isHostedByThisApp).map((environment) => ({
+ connected: environment.connection.phase === "connected",
+ databaseMigration: environment.serverConfig?.environment.databaseMigration,
+ })),
+ window.desktopBridge?.getLocalEnvironmentBootstraps().length ?? 0,
+ );
+
+ const run = async () => {
+ const bridge = window.desktopBridge;
+ if (!bridge) return;
+ // Stay open while the feed is checked; the run's own progress takes over after.
+ setChecking(true);
+ const fail = (description: string) =>
+ toastManager.add(
+ stackedThreadToast({ type: "error", title: `Could not switch to ${label}`, description }),
+ );
+ const prepared = await prepareLocalTrackSwitch(bridge, {
+ channel: release.channel,
+ version: release.version,
+ reinstall: switchesLocal,
+ });
+ onClose();
+ if (!prepared.ok) {
+ fail(prepared.message);
+ return;
+ }
+ const { local } = prepared;
+ const result = await settlePromise(() =>
+ everything.run(
+ local === null
+ ? {}
+ : {
+ ...(local.status === "available"
+ ? {
+ downloadLocal: (reportError) =>
+ downloadLocalUpdate(bridge, { notifyDownloaded: false, reportError }),
+ }
+ : {}),
+ // Install only a build the database check covers, pinned so nothing replaces it.
+ installLocal: async (reportError) => {
+ const { downloadedVersion } = await bridge.getUpdateState();
+ if (
+ downloadedVersion === null ||
+ !acceptsTrackSwitchRelease(downloadedVersion, release.channel, release.version)
+ ) {
+ reportError(
+ "Could not install update",
+ `This app downloaded ${downloadedVersion ?? "nothing"}, not ${release.version} or newer.`,
+ );
+ return false;
+ }
+ return installLocalUpdate(bridge, reportError, downloadedVersion);
+ },
+ },
+ ),
+ );
+ if (result._tag === "Failure") {
+ const error = squashAtomCommandFailure(result);
+ fail(error instanceof Error ? error.message : "An unexpected error occurred.");
+ }
+ };
+
+ return (
+ <UpdateEverythingDialog
+ open
+ onOpenChange={(open) => !open && !checking && onClose()}
+ title={`Switch to ${label}?`}
+ version={release.version}
+ providerCount={0}
+ rows={everything.rows}
+ notes={[
+ ...(everything.rows.length === 0 && !crossesLocal
+ ? [`Every connected machine is already on ${label}. This only saves the track.`]
+ : []),
+ ...(crossesLocal && updatesOff
+ ? ["This app's updates are off here, so reinstall it yourself to switch."]
+ : []),
+ ...(switchesLocal && isMacPlatform(navigator.platform)
+ ? ["If T3 Code does not reopen after it restarts, open it again."]
+ : []),
+ ]}
+ restarts={everything.restarts}
+ confirmLabel={checking ? "Checking…" : `Switch to ${label}`}
+ busy={checking}
+ disabledReason={
+ !switchesLocal || localBlocked === null ? null : `This app cannot switch: ${localBlocked}.`
+ }
+ onConfirm={() => void run()}
+ />
+ );
+}
diff --git a/apps/web/src/components/settings/updateTrackSwitch.logic.test.ts b/apps/web/src/components/settings/updateTrackSwitch.logic.test.ts
new file mode 100644
index 00000000000..63c4422f28a
--- /dev/null
+++ b/apps/web/src/components/settings/updateTrackSwitch.logic.test.ts
@@ -0,0 +1,76 @@
+import type { DesktopUpdateChannel, DesktopUpdateState } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import { prepareLocalTrackSwitch } from "./updateTrackSwitch.logic";
+
+const STABLE = "0.1.3";
+
+/** Like the desktop app, saving a track re-checks the feed and reports what it offers. */
+function fakeBridge(offer: string | null | Error) {
+ const saved: DesktopUpdateChannel[] = [];
+ const base: DesktopUpdateState = {
+ enabled: true,
+ status: "up-to-date",
+ channel: "nightly",
+ currentVersion: "0.1.4-nightly.20261027.3796",
+ hostArch: "x64",
+ appArch: "x64",
+ runningUnderArm64Translation: false,
+ availableVersion: null,
+ downloadedVersion: null,
+ releaseNotes: [],
+ omittedReleaseCount: 0,
+ downloadPercent: null,
+ checkedAt: null,
+ message: null,
+ errorContext: null,
+ canRetry: false,
+ };
+ return {
+ saved,
+ bridge: {
+ setUpdateChannel: async (channel: DesktopUpdateChannel) => {
+ saved.push(channel);
+ if (offer instanceof Error) throw offer;
+ return {
+ ...base,
+ channel,
+ status: offer === null ? ("up-to-date" as const) : ("available" as const),
+ availableVersion: offer,
+ };
+ },
+ },
+ };
+}
+
+const prepare = (bridge: ReturnType<typeof fakeBridge>["bridge"], reinstall = true) =>
+ prepareLocalTrackSwitch(bridge, { channel: "latest", version: STABLE, reinstall });
+
+describe("prepareLocalTrackSwitch", () => {
+ it("installs the checked release or a newer one on the track, never an older one", async () => {
+ expect(await prepare(fakeBridge(STABLE).bridge)).toMatchObject({ ok: true });
+ // A newer Stable knows every migration the checked one does.
+ expect(await prepare(fakeBridge("0.1.4").bridge)).toMatchObject({ ok: true });
+
+ const stale = fakeBridge("0.1.2");
+ expect(await prepare(stale.bridge)).toEqual({
+ ok: false,
+ message: "This app found 0.1.2, which is older than 0.1.3. Try again in a few minutes.",
+ });
+ // The saved track is intent; "Switch them" retries without re-picking it.
+ expect(stale.saved).toEqual(["latest"]);
+ });
+
+ it("reports a track that could not be saved", async () => {
+ expect(await prepare(fakeBridge(new Error("feed check failed")).bridge)).toEqual({
+ ok: false,
+ message: "feed check failed",
+ });
+ });
+
+ it("only saves the track when this app is already on it", async () => {
+ const undo = fakeBridge(null);
+ expect(await prepare(undo.bridge, false)).toEqual({ ok: true, local: null });
+ expect(undo.saved).toEqual(["latest"]);
+ });
+});
diff --git a/apps/web/src/components/settings/updateTrackSwitch.logic.ts b/apps/web/src/components/settings/updateTrackSwitch.logic.ts
new file mode 100644
index 00000000000..6e7e49898df
--- /dev/null
+++ b/apps/web/src/components/settings/updateTrackSwitch.logic.ts
@@ -0,0 +1,50 @@
+import type { DesktopBridge, DesktopUpdateChannel, DesktopUpdateState } from "@t3tools/contracts";
+import { acceptsTrackSwitchRelease } from "@t3tools/shared/cliRelease";
+
+type TrackSwitchBridge = Pick<DesktopBridge, "setUpdateChannel">;
+
+/** Saves the track, then, when this app must reinstall, finds a build the database check covers.
+ * The saved track is the user's intent and stays even when no such build is ready yet: a track
+ * saved toward Stable never offers an older build outside a guarded switch, and "Switch them"
+ * retries. Saving when nothing reinstalls lets picking the old track undo a partial switch. */
+export async function prepareLocalTrackSwitch(
+ bridge: TrackSwitchBridge,
+ input: {
+ readonly channel: DesktopUpdateChannel;
+ readonly version: string;
+ readonly reinstall: boolean;
+ },
+): Promise<
+ | { readonly ok: true; readonly local: DesktopUpdateState | null }
+ | { readonly ok: false; readonly message: string }
+> {
+ let local: DesktopUpdateState;
+ try {
+ // A build on another track re-checks the feed, older releases allowed down to the checked one.
+ local = await bridge.setUpdateChannel(
+ input.channel,
+ input.reinstall ? input.version : undefined,
+ );
+ } catch (error) {
+ return {
+ ok: false,
+ message: error instanceof Error ? error.message : "The update track did not change.",
+ };
+ }
+ if (!input.reinstall) return { ok: true, local: null };
+ const found = local.downloadedVersion ?? local.availableVersion;
+ if (
+ (local.status === "available" || local.status === "downloaded") &&
+ found !== null &&
+ acceptsTrackSwitchRelease(found, input.channel, input.version)
+ ) {
+ return { ok: true, local };
+ }
+ return {
+ ok: false,
+ message:
+ found !== null
+ ? `This app found ${found}, which is older than ${input.version}. Try again in a few minutes.`
+ : (local.message ?? `This app found no build of ${input.version} to install.`),
+ };
+}
diff --git a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx
index ecfeb4d664a..d9f45cf92f9 100644
--- a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx
+++ b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx
@@ -134,7 +134,7 @@ const toastUpdateError: ReportLocalUpdateError = (title, description) => {
toastManager.add(stackedThreadToast({ type: "error", title, description }));
};
-async function downloadLocalUpdate(
+export async function downloadLocalUpdate(
bridge: DesktopBridge,
{
notifyDownloaded,
@@ -160,12 +160,13 @@ async function downloadLocalUpdate(
}
}
-async function installLocalUpdate(
+export async function installLocalUpdate(
bridge: DesktopBridge,
reportError: ReportLocalUpdateError = toastUpdateError,
+ expectedVersion?: string,
): Promise<boolean> {
try {
- const result = await bridge.installUpdate();
+ const result = await bridge.installUpdate(expectedVersion);
if (!result.accepted) {
showDesktopUpdateDownloadedToast(bridge, result.state);
return false;
diff --git a/apps/web/src/components/sidebar/UpdateEverythingDialog.tsx b/apps/web/src/components/sidebar/UpdateEverythingDialog.tsx
index 8cd5c5ca777..9bf101b6fa4 100644
--- a/apps/web/src/components/sidebar/UpdateEverythingDialog.tsx
+++ b/apps/web/src/components/sidebar/UpdateEverythingDialog.tsx
@@ -47,6 +47,14 @@ interface UpdateEverythingDialogProps {
readonly rows: ReadonlyArray<UpdateEverythingRow>;
readonly restarts: ReadonlyArray<RestartingMachine>;
readonly onConfirm: () => void;
+ /** Overrides the "Update N machines?" title, for an update-track switch. */
+ readonly title?: string;
+ readonly confirmLabel?: string;
+ readonly notes?: ReadonlyArray<string>;
+ /** Shown in place of running-thread counts; disables the confirm button. */
+ readonly disabledReason?: string | null;
+ /** The confirmed work is starting; it cannot be cancelled from here. */
+ readonly busy?: boolean;
}
type UpdateEverythingDialogContentProps = Omit<
@@ -89,6 +97,11 @@ function UpdateEverythingDialogContent({
restarts,
onConfirm,
cancelRef,
+ title,
+ confirmLabel = "Update",
+ notes = [],
+ disabledReason = null,
+ busy = false,
}: UpdateEverythingDialogContentProps) {
const stopped = useAtomValue(
runningThreadCountAtom(
@@ -116,7 +129,7 @@ function UpdateEverythingDialogContent({
<>
<AlertDialogHeader className="shrink-0">
<AlertDialogTitle>
- Update {updating.length} {updating.length === 1 ? "machine" : "machines"}?
+ {title ?? `Update ${updating.length} ${updating.length === 1 ? "machine" : "machines"}?`}
</AlertDialogTitle>
<AlertDialogDescription>
{version !== null ? (
@@ -132,6 +145,11 @@ function UpdateEverythingDialogContent({
</AlertDialogHeader>
<ScrollArea scrollFade>
<div className="flex flex-col gap-3 px-6 pb-4">
+ {notes.map((note) => (
+ <p key={note} className="text-muted-foreground text-sm">
+ {note}
+ </p>
+ ))}
{/* Machine names truncate first. Provider lists wrap between names, never inside one. */}
<div className="grid grid-cols-[minmax(4rem,max-content)_max-content_minmax(min-content,1fr)_max-content] gap-x-4 text-sm">
<div className="col-span-full grid grid-cols-subgrid border-b pb-1.5 text-muted-foreground text-xs">
@@ -196,7 +214,11 @@ function UpdateEverythingDialogContent({
</div>
</ScrollArea>
<AlertDialogFooter>
- {running > 0 ? (
+ {disabledReason !== null ? (
+ <p className="self-center text-sm max-sm:order-1 max-sm:text-center sm:mr-auto">
+ {disabledReason}
+ </p>
+ ) : running > 0 ? (
<p className="self-center text-muted-foreground text-sm max-sm:order-1 max-sm:text-center sm:mr-auto">
{stopped === 0
? `${threads} will be interrupted and can resume after the restart.`
@@ -205,10 +227,12 @@ function UpdateEverythingDialogContent({
: `${threads} will be interrupted. ${continuing} can resume after the restart.`}
</p>
) : null}
- <AlertDialogClose ref={cancelRef} render={<Button variant="outline" />}>
+ <AlertDialogClose ref={cancelRef} render={<Button variant="outline" disabled={busy} />}>
Cancel
</AlertDialogClose>
- <Button onClick={onConfirm}>Update</Button>
+ <Button disabled={disabledReason !== null || busy} onClick={onConfirm}>
+ {confirmLabel}
+ </Button>
</AlertDialogFooter>
</>
);
diff --git a/apps/web/src/components/sidebar/updateEverything.logic.test.ts b/apps/web/src/components/sidebar/updateEverything.logic.test.ts
index 3739308f7b1..4c09823d405 100644
--- a/apps/web/src/components/sidebar/updateEverything.logic.test.ts
+++ b/apps/web/src/components/sidebar/updateEverything.logic.test.ts
@@ -2,8 +2,11 @@ import { EnvironmentId, type ServerSelfUpdateCapability } from "@t3tools/contrac
import { describe, expect, it } from "vite-plus/test";
import {
+ collectChannelSwitchTargets,
collectRestartingMachines,
+ localSwitchBlockReason,
collectServerUpdateTargets,
+ describeUpdateCapsule,
describeUpdateEverything,
runUpdateEverything,
type UpdateEverythingMachine,
@@ -27,7 +30,9 @@ function machine(
capabilities: {
repositoryIdentity: true,
...(selfUpdate ? { serverSelfUpdate: selfUpdate } : {}),
- ...(selfUpdate === "desktop-managed" ? { desktopAppUpdate: true } : {}),
+ ...(selfUpdate === "desktop-managed"
+ ? { desktopAppUpdate: true, desktopAppChannelSwitch: true }
+ : {}),
},
},
settings: { continueThreadsAfterServerUpdate: false },
@@ -81,6 +86,136 @@ describe("collectServerUpdateTargets", () => {
});
});
+describe("collectChannelSwitchTargets", () => {
+ const NIGHTLY = "0.1.4-nightly.20261027.3796";
+ const OLD_NIGHTLY = "0.1.3-nightly.20261001.3500";
+ const NEWER_NIGHTLY = "0.1.4-nightly.20261020.3700";
+ // What each server reports as its database's highest migration.
+ const host = (
+ base: UpdateEverythingMachine,
+ databaseMigration: number | undefined,
+ os: "linux" | "darwin" = "linux",
+ ): UpdateEverythingMachine => ({
+ ...base,
+ serverConfig: {
+ ...base.serverConfig!,
+ environment: {
+ ...base.serverConfig!.environment,
+ platform: { os, arch: "x64" },
+ ...(databaseMigration === undefined ? {} : { databaseMigration }),
+ },
+ },
+ });
+
+ it("moves nightly hosts to stable only when stable knows their database", () => {
+ const stable = { channel: "latest" as const, version: "0.1.3", databaseMigration: 69 };
+ const { targets, skipped } = collectChannelSwitchTargets(
+ [
+ host(machine("this-app", NIGHTLY, "desktop-managed", { hostedByThisApp: true }), 72),
+ host(machine("old-service", OLD_NIGHTLY, "boot-service"), 69),
+ // Service launchers refuse older versions, even when the database allows it.
+ host(machine("newer-service", NEWER_NIGHTLY, "boot-service"), 69),
+ host(machine("linux-desktop", OLD_NIGHTLY, "desktop-managed"), 69),
+ host(machine("new-service", NIGHTLY, "boot-service"), 72),
+ host(machine("old-server", "0.1.2-nightly.20260901.3000", "boot-service"), undefined),
+ host(machine("mac-desktop", OLD_NIGHTLY, "desktop-managed"), 69, "darwin"),
+ host(machine("preview", "0.1.3-preview.20261026.3702", "boot-service"), 69),
+ host(machine("stable", "0.1.3", "boot-service"), 69),
+ host(machine("stable-desktop", "0.1.2", "desktop-managed"), 68),
+ // Already current, but its saved track may still say Nightly.
+ host(machine("current-desktop", "0.1.3", "desktop-managed"), 69, "darwin"),
+ ],
+ stable,
+ );
+
+ expect(
+ targets.map((target) => [
+ target.serverLabel,
+ target.targetVersion,
+ target.channel,
+ target.trackOnly ?? false,
+ ]),
+ ).toEqual([
+ ["old-service", "0.1.3", undefined, false],
+ ["linux-desktop", "0.1.3", "latest", false],
+ ["stable-desktop", "0.1.3", "latest", false],
+ ["current-desktop", "0.1.3", "latest", true],
+ ]);
+ expect(targets.every((target) => target.targetDatabaseMigration === 69)).toBe(true);
+ expect(skipped.map((entry) => [entry.label, entry.reason])).toEqual([
+ ["newer-service", "run `t3 update --channel stable --allow-downgrade` there"],
+ [
+ "new-service",
+ "its database has changes 0.1.3 does not support yet; stay on Nightly until Stable has them",
+ ],
+ ["old-server", "its server predates database checks; update it on Nightly first"],
+ ["mac-desktop", "switch the Mac app on that Mac"],
+ ["preview", "runs a preview build"],
+ ]);
+ });
+
+ it("moves stable hosts to nightly only when nightly knows their database", () => {
+ const nightly = { channel: "nightly" as const, version: NIGHTLY, databaseMigration: 72 };
+ const { targets, skipped } = collectChannelSwitchTargets(
+ [
+ host(machine("service", "0.1.2", "boot-service"), 70),
+ // A Stable tag built a migration the latest Nightly does not have yet.
+ host(machine("ahead", "0.1.3", "boot-service"), 73),
+ machine("old-desktop", "0.1.2", "desktop-managed", {
+ serverConfig: {
+ ...machine("old-desktop", "0.1.2", "desktop-managed").serverConfig!,
+ environment: {
+ ...machine("old-desktop", "0.1.2", "desktop-managed").serverConfig!.environment,
+ capabilities: { repositoryIdentity: true, serverSelfUpdate: "desktop-managed" },
+ },
+ },
+ }),
+ machine("current", NIGHTLY, "boot-service"),
+ ],
+ nightly,
+ );
+
+ expect(targets.map((target) => [target.serverLabel, target.targetVersion])).toEqual([
+ ["service", NIGHTLY],
+ ]);
+ expect(skipped.map((entry) => [entry.label, entry.reason])).toEqual([
+ [
+ "ahead",
+ `its database has changes ${NIGHTLY} does not support yet; stay on Stable until Nightly has them`,
+ ],
+ ["old-desktop", "needs a newer desktop app"],
+ ]);
+ });
+});
+
+describe("localSwitchBlockReason", () => {
+ it("checks every server this app hosts, and only while connected", () => {
+ const stable = { channel: "latest" as const, version: "0.1.3", databaseMigration: 69 };
+ const nightly = "0.1.4-nightly.20261027.3796";
+
+ const windows = { connected: true, databaseMigration: 69 };
+ expect(localSwitchBlockReason(nightly, stable, [windows], 1)).toBeNull();
+ // A WSL server's newer migration blocks the reinstall that would restart it.
+ expect(
+ localSwitchBlockReason(
+ nightly,
+ stable,
+ [windows, { connected: true, databaseMigration: 72 }],
+ 2,
+ ),
+ ).toContain("does not support yet");
+ // A WSL backend still starting has no client entry, so its database is unchecked.
+ expect(localSwitchBlockReason(nightly, stable, [windows], 2)).toBe(
+ "its server is not connected, so its database cannot be checked",
+ );
+ // A cached head from a disconnected server proves nothing.
+ expect(
+ localSwitchBlockReason(nightly, stable, [{ connected: false, databaseMigration: 69 }], 1),
+ ).toBe("its server is not connected, so its database cannot be checked");
+ expect(localSwitchBlockReason("0.1.3", stable, [], 1)).toBeNull();
+ });
+});
+
describe("collectRestartingMachines", () => {
it("lists updated servers, and this app's servers only when it installs", () => {
const withContinuation = (
@@ -177,3 +312,33 @@ describe("describeUpdateEverything", () => {
]);
});
});
+
+describe("describeUpdateCapsule", () => {
+ it("sends failed track switches back through the planner instead of retrying their target", () => {
+ const failed = {
+ machine: {
+ environmentId: EnvironmentId.make("remote"),
+ label: "remote",
+ updatesProviders: false,
+ server: {
+ environmentId: EnvironmentId.make("remote"),
+ serverLabel: "remote",
+ selfUpdate: "boot-service" as const,
+ targetVersion: "0.1.3",
+ },
+ handedOffVersion: null,
+ startedAt: 0,
+ result: "failed" as const,
+ failure: "offline",
+ providerFailure: null,
+ },
+ status: "failed" as const,
+ };
+ const run = { localVersion: null, phase: "servers" as const, restartAt: null, machines: [] };
+
+ expect(describeUpdateCapsule(run, [failed], null, 0).action).toBe("retry");
+ expect(describeUpdateCapsule({ ...run, trackSwitch: true }, [failed], null, 0).action).toBe(
+ "dismiss",
+ );
+ });
+});
diff --git a/apps/web/src/components/sidebar/updateEverything.logic.ts b/apps/web/src/components/sidebar/updateEverything.logic.ts
index 469e5a0faf6..8d82b7b568e 100644
--- a/apps/web/src/components/sidebar/updateEverything.logic.ts
+++ b/apps/web/src/components/sidebar/updateEverything.logic.ts
@@ -1,6 +1,12 @@
import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
-import type { EnvironmentId, ServerConfig } from "@t3tools/contracts";
-import { cliReleaseChannelOf } from "@t3tools/shared/cliRelease";
+import type {
+ DesktopUpdateChannel,
+ EnvironmentId,
+ ServerConfig,
+ ServerSelfUpdateCapability,
+} from "@t3tools/contracts";
+import { cliReleaseChannelOf, desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
+import { compareSemverVersions } from "@t3tools/shared/semver";
import {
resolveServerSelfUpdateCapability,
@@ -76,16 +82,9 @@ export function collectServerUpdateTargets(
}
const skip = (reason: string) =>
skipped.push({ environmentId: machine.environmentId, label: machine.label, reason });
- if (config === null || !machine.connected) {
- skip("not connected");
- continue;
- }
- if (!machine.canMaintain) {
- skip("no permission");
- continue;
- }
- if (machine.updateState.status === "running") {
- skip("already updating");
+ const unavailable = unavailableReason(machine);
+ if (config === null || unavailable !== null) {
+ skip(unavailable ?? "not connected");
continue;
}
const selfUpdate = resolveServerSelfUpdateCapability(config);
@@ -118,6 +117,192 @@ export function collectServerUpdateTargets(
return { targets, skipped };
}
+function unavailableReason(machine: UpdateEverythingMachine): string | null {
+ if (machine.serverConfig === null || !machine.connected) return "not connected";
+ if (!machine.canMaintain) return "no permission";
+ if (machine.updateState.status === "running") return "already updating";
+ return null;
+}
+
+/** The latest release on the track a fleet switches to, as npm reports it. */
+export interface ChannelSwitchRelease {
+ readonly channel: DesktopUpdateChannel;
+ readonly version: string;
+ readonly databaseMigration: number | undefined;
+}
+
+export const channelSwitchLabel = (channel: DesktopUpdateChannel) =>
+ channel === "nightly" ? "Nightly" : "Stable";
+
+/** Stable and Nightly each build their own commits, so either can hold migrations the other lacks.
+ * Crossing tracks needs proof that the target release knows every migration the database holds. */
+const crossesTrack = (fromVersion: string, release: ChannelSwitchRelease) =>
+ desktopUpdateChannelOf(fromVersion) !== release.channel;
+
+function channelSwitchBlockReason(
+ fromVersion: string,
+ release: ChannelSwitchRelease,
+ currentMigration: number | undefined,
+): string | null {
+ if (!crossesTrack(fromVersion, release)) return null;
+ const from = channelSwitchLabel(desktopUpdateChannelOf(fromVersion));
+ // Servers and releases from before this check report no migration number.
+ if (currentMigration === undefined) {
+ return `its server predates database checks; update it on ${from} first`;
+ }
+ if (release.databaseMigration === undefined) {
+ return `${release.version} predates database checks; wait for a newer ${channelSwitchLabel(release.channel)} release`;
+ }
+ return currentMigration > release.databaseMigration
+ ? `its database has changes ${release.version} does not support yet; stay on ${from} until ${channelSwitchLabel(release.channel)} has them`
+ : null;
+}
+
+/** This app's reinstall restarts every server it hosts, so each of their databases must allow the
+ * switch. `backendCount` is the desktop's own inventory: a backend still starting has no client
+ * entry yet. A cached config can outlive its connection, so only a connected server's head counts. */
+export function localSwitchBlockReason(
+ appVersion: string,
+ release: ChannelSwitchRelease,
+ hosted: ReadonlyArray<{
+ readonly connected: boolean;
+ readonly databaseMigration: number | undefined;
+ }>,
+ backendCount: number,
+): string | null {
+ if (!crossesTrack(appVersion, release)) return null;
+ if (
+ hosted.length === 0 ||
+ hosted.length < backendCount ||
+ hosted.some((server) => !server.connected)
+ ) {
+ return "its server is not connected, so its database cannot be checked";
+ }
+ return (
+ hosted
+ .map((server) => channelSwitchBlockReason(appVersion, release, server.databaseMigration))
+ .find((reason) => reason !== null) ?? null
+ );
+}
+
+/** Servers move to the release; desktop-managed hosts reinstall their app on its track. A desktop
+ * host already current gets a track-only request, since its saved track may still differ. */
+export function collectChannelSwitchTargets(
+ machines: ReadonlyArray<UpdateEverythingMachine>,
+ release: ChannelSwitchRelease,
+): { readonly targets: ServerUpdateTarget[]; readonly skipped: SkippedMachine[] } {
+ const targets: ServerUpdateTarget[] = [];
+ const skipped: SkippedMachine[] = [];
+ for (const machine of machines) {
+ const config = machine.serverConfig;
+ if (machine.hostedByThisApp) continue;
+ const skip = (reason: string) =>
+ skipped.push({ environmentId: machine.environmentId, label: machine.label, reason });
+ const target = (
+ selfUpdate: ServerSelfUpdateCapability,
+ targetVersion: string,
+ ): ServerUpdateTarget => ({
+ environmentId: machine.environmentId,
+ serverLabel: machine.label,
+ selfUpdate,
+ installation: config?.environment.capabilities.serverInstallation,
+ desktopAppUpdate: config !== null && supportsDesktopAppUpdate(config),
+ targetVersion,
+ ...(selfUpdate === "desktop-managed" ? { channel: release.channel } : {}),
+ ...(release.databaseMigration === undefined
+ ? {}
+ : { targetDatabaseMigration: release.databaseMigration }),
+ });
+ const serverVersion = config?.environment.serverVersion;
+ const sameTrack = serverVersion !== undefined && isOnTrack(serverVersion, release.channel);
+ if (
+ config !== null &&
+ sameTrack &&
+ resolveVersionMismatch(serverVersion, release.version) === null
+ ) {
+ const move = trackSwitchMove(config, true);
+ if (
+ !("skip" in move) &&
+ move.selfUpdate === "desktop-managed" &&
+ unavailableReason(machine) === null
+ ) {
+ targets.push({ ...target(move.selfUpdate, serverVersion), trackOnly: true });
+ }
+ continue;
+ }
+ const unavailable = unavailableReason(machine);
+ if (config === null || serverVersion === undefined || unavailable !== null) {
+ skip(unavailable ?? "not connected");
+ continue;
+ }
+ const move = trackSwitchMove(config, sameTrack);
+ if ("skip" in move) {
+ skip(move.skip);
+ continue;
+ }
+ const blocked = channelSwitchBlockReason(
+ serverVersion,
+ release,
+ config.environment.databaseMigration,
+ );
+ if (blocked !== null) {
+ skip(blocked);
+ continue;
+ }
+ // Service launchers only accept newer versions, so leaving for an older release is manual.
+ if (
+ move.selfUpdate === "boot-service" &&
+ compareSemverVersions(release.version, serverVersion) <= 0
+ ) {
+ skip(
+ `run \`t3 update --channel ${release.channel === "nightly" ? "nightly" : "stable"} --allow-downgrade\` there`,
+ );
+ continue;
+ }
+ targets.push(target(move.selfUpdate, release.version));
+ }
+ return { targets, skipped };
+}
+
+/** A remote host on the other track that a switch can still move, for retrying a partial switch. */
+export function awaitsTrackSwitch(
+ machine: Pick<UpdateEverythingMachine, "serverConfig" | "hostedByThisApp">,
+ channel: DesktopUpdateChannel,
+): boolean {
+ const config = machine.serverConfig;
+ return (
+ !machine.hostedByThisApp &&
+ config !== null &&
+ !isOnTrack(config.environment.serverVersion, channel) &&
+ !("skip" in trackSwitchMove(config, false))
+ );
+}
+
+function isOnTrack(version: string, channel: DesktopUpdateChannel): boolean {
+ return cliReleaseChannelOf(version) !== "preview" && desktopUpdateChannelOf(version) === channel;
+}
+
+/** How a switch moves a host, or why it never can from here, whatever the release. */
+function trackSwitchMove(
+ config: NonNullable<UpdateEverythingMachine["serverConfig"]>,
+ sameTrack: boolean,
+): { readonly selfUpdate: ServerSelfUpdateCapability } | { readonly skip: string } {
+ if (cliReleaseChannelOf(config.environment.serverVersion) === "preview") {
+ return { skip: "runs a preview build" };
+ }
+ const selfUpdate = resolveServerSelfUpdateCapability(config);
+ if (selfUpdate === null) return { skip: "needs a manual update" };
+ if (selfUpdate !== "desktop-managed") return { selfUpdate };
+ if (config.environment.capabilities.desktopAppChannelSwitch !== true) {
+ return { skip: "needs a newer desktop app" };
+ }
+ // Squirrel.Mac renames the bundle for the new track and then cannot relaunch it.
+ if (!sameTrack && config.environment.platform.os === "darwin") {
+ return { skip: "switch the Mac app on that Mac" };
+ }
+ return { selfUpdate };
+}
+
export interface UpdateEverythingSteps<Providers, Servers> {
readonly downloadLocal?: () => Promise<boolean>;
readonly updateProviders: () => Promise<Providers>;
@@ -163,6 +348,8 @@ export interface UpdateRunMachine {
}
export interface UpdateEverythingRun {
+ /** Track switches retry through their planner, which re-checks each database. */
+ readonly trackSwitch?: boolean;
readonly localVersion: string | null;
readonly phase: "providers" | "servers" | "countdown" | "installing";
readonly restartAt: number | null;
@@ -265,7 +452,10 @@ export function describeUpdateCapsule(
return {
tone: "failed",
label: failed.length === 1 ? `${failed[0]!.machine.label} failed` : `${failed.length} failed`,
- action: failed.some(({ machine }) => machine.server !== null) ? "retry" : "dismiss",
+ action:
+ !run.trackSwitch && failed.some(({ machine }) => machine.server !== null)
+ ? "retry"
+ : "dismiss",
};
}
return { tone: "default", label: `${done} of ${machines.length} updated`, action: null };
diff --git a/apps/web/src/components/sidebar/useUpdateEverything.ts b/apps/web/src/components/sidebar/useUpdateEverything.ts
index af38bbf5d4b..84e9697cd65 100644
--- a/apps/web/src/components/sidebar/useUpdateEverything.ts
+++ b/apps/web/src/components/sidebar/useUpdateEverything.ts
@@ -13,7 +13,9 @@ import { getProviderUpdateRunOutcome } from "../ProviderUpdateLaunchNotification
import { useProviderUpdates } from "../ProviderUpdatesAction";
import { canUpdateServer, type ServerUpdateOutcome, useServerUpdate } from "../ServerUpdateAction";
import {
+ type ChannelSwitchRelease,
closeFinishedUpdateRun,
+ collectChannelSwitchTargets,
collectRestartingMachines,
collectServerUpdateTargets,
collectUpdateEverythingResult,
@@ -34,9 +36,24 @@ import {
const UPDATE_RESTART_DELAY_MS = 5_000;
+/** Servers this desktop app runs; they update with it. */
+export function isHostedByThisApp(
+ environment: ReturnType<typeof useEnvironments>["environments"][number],
+) {
+ return (
+ isElectron &&
+ (environment.entry.target._tag === "PrimaryConnectionTarget" ||
+ isDesktopLocalConnectionTarget(environment.entry.target))
+ );
+}
+
export type ReportLocalUpdateError = (title: string, description: string) => void;
-export function useUpdateEverything(localUpdateVersion: string | null) {
+/** `channelSwitch` makes the run move the fleet to that release's track instead of updating it. */
+export function useUpdateEverything(
+ localUpdateVersion: string | null,
+ channelSwitch?: ChannelSwitchRelease,
+) {
const targetVersion = localUpdateVersion ?? APP_VERSION;
const { environments } = useEnvironments();
const environmentIds = environmentIdsKey(environments.map(({ environmentId }) => environmentId));
@@ -47,23 +64,23 @@ export function useUpdateEverything(localUpdateVersion: string | null) {
label: environment.label,
serverConfig: environment.serverConfig,
connected: environment.connection.phase === "connected",
- hostedByThisApp:
- isElectron &&
- (environment.entry.target._tag === "PrimaryConnectionTarget" ||
- isDesktopLocalConnectionTarget(environment.entry.target)),
+ hostedByThisApp: isHostedByThisApp(environment),
canMaintain: canUpdateServer(sessionStates[index]!),
updateState: updateStates[index]!,
}));
- const { targets: behindServers, skipped: unreachable } = collectServerUpdateTargets(
- machines,
- targetVersion,
- );
+ const { targets: behindServers, skipped: unreachable } = channelSwitch
+ ? collectChannelSwitchTargets(machines, channelSwitch)
+ : collectServerUpdateTargets(machines, targetVersion);
// Desktop-managed servers use their app feed; only npm installs need to wait for publication.
- const needsNpm = behindServers.some((server) => server.selfUpdate !== "desktop-managed");
+ // A track switch's target came from npm already.
+ const needsNpm =
+ channelSwitch === undefined &&
+ behindServers.some((server) => server.selfUpdate !== "desktop-managed");
const published = useNpmReleasePublished(needsNpm ? targetVersion : null);
- const servers = published
- ? behindServers
- : behindServers.filter((server) => server.selfUpdate === "desktop-managed");
+ const servers =
+ published || channelSwitch !== undefined
+ ? behindServers
+ : behindServers.filter((server) => server.selfUpdate === "desktop-managed");
const skipped: ReadonlyArray<SkippedMachine> = [
...unreachable,
...behindServers
@@ -74,14 +91,18 @@ export function useUpdateEverything(localUpdateVersion: string | null) {
reason: `t3@${targetVersion} is not on npm yet`,
})),
];
- const restarts = collectRestartingMachines(machines, servers, localUpdateVersion !== null);
- const providers = useProviderUpdates();
+ // Track-only hosts save a setting and restart nothing, so they are neither listed nor counted.
+ const moving = servers.filter((server) => server.trackOnly !== true);
+ const restarts = collectRestartingMachines(machines, moving, localUpdateVersion !== null);
+ const providerUpdates = useProviderUpdates();
+ // A track switch moves app and servers only; provider updates stay a separate choice.
+ const providers = channelSwitch ? { machines: [], updateAll: async () => [] } : providerUpdates;
const updateServer = useServerUpdate();
const view = describeUpdateEverything({
localVersion: localUpdateVersion,
localMachines: machines.filter((machine) => machine.hostedByThisApp),
- servers,
+ servers: moving,
skipped,
providerMachines: providers.machines.map((machine) => ({
environmentId: machine.environmentId,
@@ -138,6 +159,7 @@ export function useUpdateEverything(localUpdateVersion: string | null) {
}
const localVersion = installLocal ? localUpdateVersion : null;
setUpdateEverythingRun(() => ({
+ ...(channelSwitch ? { trackSwitch: true } : {}),
localVersion,
phase: "providers",
restartAt: null,
diff --git a/apps/web/src/state/npmRelease.ts b/apps/web/src/state/npmRelease.ts
index 4436a42c29e..09db3b68c06 100644
--- a/apps/web/src/state/npmRelease.ts
+++ b/apps/web/src/state/npmRelease.ts
@@ -1,31 +1,51 @@
import { useAtomValue } from "@effect/atom-react";
+import { npmReleaseDatabaseMigration } from "@t3tools/shared/cliRelease";
import * as Effect from "effect/Effect";
import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
import { AsyncResult, Atom } from "effect/reactivity";
-export const npmReleasePublishedAtom = Atom.family((version: string) =>
+export interface NpmRelease {
+ readonly version: string;
+ /** Absent on releases published before npm manifests carried it. */
+ readonly databaseMigration: number | undefined;
+}
+
+/** `spec` is an exact version or a dist-tag such as `nightly`. Null when npm has no such release.
+ * Refreshes only while mounted; the published check below keeps its own versions alive. */
+export const npmReleaseAtom = Atom.family((spec: string) =>
Atom.make(
Effect.gen(function* () {
const response = yield* HttpClient.get(
- `https://registry.npmjs.org/t3/${encodeURIComponent(version)}`,
+ `https://registry.npmjs.org/t3/${encodeURIComponent(spec)}`,
);
- if (response.status === 404) return false;
+ if (response.status === 404) return null;
const body = yield* HttpClientResponse.filterStatusOk(response).pipe(
Effect.flatMap((ok) => ok.json),
);
- return typeof body === "object" && body !== null && "version" in body
- ? body.version === version
- : false;
+ if (
+ typeof body !== "object" ||
+ body === null ||
+ !("version" in body) ||
+ typeof body.version !== "string"
+ ) {
+ return null;
+ }
+ return {
+ version: body.version,
+ databaseMigration: npmReleaseDatabaseMigration(body),
+ } satisfies NpmRelease;
}).pipe(
// Tracing headers would make the browser send a CORS preflight, which npm rejects.
Effect.provideService(HttpClient.TracerPropagationEnabled, false),
Effect.provide(FetchHttpClient.layer),
),
- ).pipe(
- Atom.withRefresh("5 minutes"),
- Atom.keepAlive,
- Atom.withLabel(`npm-release-published:${version}`),
- ),
+ ).pipe(Atom.withRefresh("5 minutes"), Atom.withLabel(`npm-release:${spec}`)),
+);
+
+export const npmReleasePublishedAtom = Atom.family((version: string) =>
+ Atom.make((get) =>
+ get.result(npmReleaseAtom(version)).pipe(Effect.map((release) => release?.version === version)),
+ ).pipe(Atom.keepAlive, Atom.withLabel(`npm-release-published:${version}`)),
);
const NO_VERSION_ATOM = Atom.make(AsyncResult.success(false)).pipe(
diff --git a/docs/user/updating.md b/docs/user/updating.md
index ad5d93b5759..006c4985d43 100644
--- a/docs/user/updating.md
+++ b/docs/user/updating.md
@@ -35,6 +35,29 @@ The confirmation counts the running threads that the restarts will interrupt,
and how many can resume afterwards. See **Continue threads after restarts**
below.
+## Switch between Stable and Nightly
+
+In the desktop app, change **Settings → About → Update track**. T3 Code shows each
+connected machine it will move and each one it skips, then moves them in one
+step. Remote servers install the latest release on the new track. Remote desktop
+apps reinstall on the new track. This app reinstalls last. Your threads,
+settings, and data stay.
+
+A background service cannot move to an older release remotely. When Stable is
+older than its Nightly, run `t3 update --channel stable --allow-downgrade` on
+that machine.
+
+A switch is blocked for a machine whose database already has changes the
+target release does not support, or when T3 Code cannot confirm that it does.
+The dialog says why: update a machine on its current track first when its
+release is too old to check, or wait until the target track includes the
+changes. A Mac running the desktop app must switch on that Mac.
+
+Each machine keeps the new track even if its switch did not finish, but it
+moves to that track only through a switch. **Update track** shows how many
+machines still run the other track. **Review** opens the same dialog with fresh
+checks.
+
## Before you update
Server updates restart the connection and can interrupt active agents and
diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts
index c8ce8b38787..dadaf2dafb7 100644
--- a/packages/client-runtime/src/state/server.ts
+++ b/packages/client-runtime/src/state/server.ts
@@ -969,6 +969,17 @@ export function createServerEnvironmentAtoms<R, E>(
}),
);
+ // A track switch's desktop host already on its track's newest build only saved the
+ // track; nothing restarts.
+ if (
+ result.method === "desktop-app" &&
+ result.desktopUpdateToken === undefined &&
+ result.targetVersion === fromVersion
+ ) {
+ atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
+ return result;
+ }
+
yield* nudgeReconnectDuringUpdateRestart({
stateChanges: environmentRegistry.stateChanges(target.environmentId),
retryNow: environmentRegistry.retryNow(target.environmentId),
diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts
index fbbffeddc92..75a546bed87 100644
--- a/packages/contracts/src/environment.ts
+++ b/packages/contracts/src/environment.ts
@@ -133,6 +133,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
ignoredFileListing: Schema.optionalKey(Schema.Boolean),
environmentIcon: Schema.optionalKey(Schema.Boolean),
desktopAppUpdate: Schema.optionalKey(Schema.Boolean),
+ /** The desktop app switches update tracks when a server update request names one. */
+ desktopAppChannelSwitch: Schema.optionalKey(Schema.Boolean),
/** Subscribe to command output only when advertised; older servers never send it. */
commandOutputStreaming: Schema.optionalKey(Schema.Boolean),
/** Hosts headless Chromium tabs streamed over /api/preview-stream for clients without a local runtime. */
@@ -160,6 +162,8 @@ export const ExecutionEnvironmentDescriptor = Schema.Struct({
platform: ExecutionEnvironmentPlatform,
serverVersion: TrimmedNonEmptyString,
orchestrationProtocolVersion: Schema.optionalKey(Schema.Int),
+ /** Highest migration this server's database holds; absent on older servers. */
+ databaseMigration: Schema.optionalKey(Schema.Int),
capabilities: ExecutionEnvironmentCapabilities,
});
export type ExecutionEnvironmentDescriptor = typeof ExecutionEnvironmentDescriptor.Type;
diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
index 89fc70f2b72..8d848a86b22 100644
--- a/packages/contracts/src/ipc.ts
+++ b/packages/contracts/src/ipc.ts
@@ -1096,10 +1096,15 @@ export interface DesktopBridge {
onWindowFullscreenStateChange: (listener: (fullscreen: boolean) => void) => () => void;
getWindowZoomFactor: () => number;
getUpdateState: () => Promise<DesktopUpdateState>;
- setUpdateChannel: (channel: DesktopUpdateChannel) => Promise<DesktopUpdateState>;
+ /** `minimumVersion` is a track switch's checked release; nothing older is offered after. */
+ setUpdateChannel: (
+ channel: DesktopUpdateChannel,
+ minimumVersion?: string,
+ ) => Promise<DesktopUpdateState>;
checkForUpdate: () => Promise<DesktopUpdateCheckResult>;
downloadUpdate: () => Promise<DesktopUpdateActionResult>;
- installUpdate: () => Promise<DesktopUpdateActionResult>;
+ /** With a version, installs only that downloaded build. */
+ installUpdate: (expectedVersion?: string) => Promise<DesktopUpdateActionResult>;
onUpdateState: (listener: (state: DesktopUpdateState) => void) => () => void;
cliCommand: {
getState: () => Promise<DesktopCliCommandState>;
diff --git a/packages/contracts/src/resourceTelemetry.ts b/packages/contracts/src/resourceTelemetry.ts
index bce626b0c36..5a004f93a2a 100644
--- a/packages/contracts/src/resourceTelemetry.ts
+++ b/packages/contracts/src/resourceTelemetry.ts
@@ -2,7 +2,7 @@ import * as Schema from "effect/Schema";
import { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas.ts";
import { HostPowerSnapshot } from "./background.ts";
-import { DesktopUpdateStateSchema } from "./ipc.ts";
+import { DesktopUpdateChannelSchema, DesktopUpdateStateSchema } from "./ipc.ts";
export const RESOURCE_MONITOR_PROTOCOL_VERSION = 3 as const;
@@ -323,6 +323,9 @@ export const DesktopTelemetryRequestDesktopUpdate = Schema.Struct({
version: Schema.Literal(1),
type: Schema.Literal("requestDesktopUpdate"),
requestId: TrimmedNonEmptyString,
+ /** A track switch: move to this channel first, and install only `targetVersion`. */
+ channel: Schema.optionalKey(DesktopUpdateChannelSchema),
+ targetVersion: Schema.optionalKey(TrimmedNonEmptyString),
});
export type DesktopTelemetryRequestDesktopUpdate = typeof DesktopTelemetryRequestDesktopUpdate.Type;
diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts
index 134d8160642..92dc88be173 100644
--- a/packages/contracts/src/server.ts
+++ b/packages/contracts/src/server.ts
@@ -28,6 +28,7 @@ import { RuntimeMode } from "./providerPolicy.ts";
import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
import { ServerProviderUsageLimits, UsageLimitSourceSnapshots } from "./providerUsageLimits.ts";
import { ServerSettings } from "./settings.ts";
+import { DesktopUpdateChannelSchema } from "./ipc.ts";
const KeybindingsMalformedConfigIssue = Schema.Struct({
kind: Schema.Literal("keybindings.malformed-config"),
@@ -879,6 +880,10 @@ export class ServerProviderUpdateError extends Schema.TaggedError<ServerProvider
export const ServerSelfUpdateInput = Schema.Struct({
/** Exact npm version, never a dist-tag, so server and client agree on the request. */
targetVersion: TrimmedNonEmptyString,
+ /** Desktop-managed hosts move their app to this update track first. Sent only for a track switch. */
+ channel: Schema.optionalKey(DesktopUpdateChannelSchema),
+ /** The target release's highest migration; the host refuses to leave Nightly without it. */
+ targetDatabaseMigration: Schema.optionalKey(Schema.Int),
});
export type ServerSelfUpdateInput = typeof ServerSelfUpdateInput.Type;
diff --git a/packages/shared/src/cliRelease.ts b/packages/shared/src/cliRelease.ts
index 94bd3cffa16..66777cc0444 100644
--- a/packages/shared/src/cliRelease.ts
+++ b/packages/shared/src/cliRelease.ts
@@ -1,3 +1,8 @@
+import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
+
+import { compareSemverVersions } from "./semver.ts";
+
const CLI_RELEASE_REPOSITORY = "pingdotgg/t3code";
export const CLI_RELEASES_PAGE_URL = `https://github.com/${CLI_RELEASE_REPOSITORY}/releases`;
export const CLI_RELEASE_CHECKSUMS_FILE = "SHA256SUMS";
@@ -68,6 +73,32 @@ export function cliReleaseChannelOf(version: string): CliReleaseChannel {
return channel === "nightly" || channel === "preview" ? channel : "stable";
}
+/** Whether updating between these versions crosses Stable and Nightly. Preview builds cross nothing.
+ * Hosts refuse a crossing outside a track switch, which checks the database first. */
+export function crossesReleaseTrack(fromVersion: string, toVersion: string): boolean {
+ const from = cliReleaseChannelOf(fromVersion);
+ const to = cliReleaseChannelOf(toVersion);
+ return from !== to && from !== "preview" && to !== "preview";
+}
+
+/** The desktop update track a build belongs to. Preview builds have no feed and read as Stable. */
+export function desktopUpdateChannelOf(version: string): "latest" | "nightly" {
+ return cliReleaseChannelOf(version) === "nightly" ? "nightly" : "latest";
+}
+
+/** Whether a track switch may install `found` after its database check cleared `checked`: any build
+ * on the switch's track at least as new, since later releases only add migrations. */
+export function acceptsTrackSwitchRelease(
+ found: string,
+ channel: "latest" | "nightly",
+ checked: string,
+): boolean {
+ return (
+ cliReleaseChannelOf(found) === (channel === "nightly" ? "nightly" : "stable") &&
+ compareSemverVersions(found, checked) >= 0
+ );
+}
+
/** Page until the channel matches; nightlies can push preview/stable releases past the first page. */
export function cliReleaseIndexPageUrl(page: number): string {
return `https://api.github.com/repos/${CLI_RELEASE_REPOSITORY}/releases?per_page=100&page=${page}`;
@@ -89,3 +120,14 @@ export function newestCliReleaseVersion(
}
return undefined;
}
+
+const NpmReleaseMigrationManifest = Schema.Struct({
+ t3code: Schema.Struct({ databaseMigration: Schema.Int }),
+});
+const decodeNpmReleaseMigrationManifest = Schema.decodeUnknownOption(NpmReleaseMigrationManifest);
+
+/** Highest database migration a release's server knows, from its npm `t3` manifest. */
+export function npmReleaseDatabaseMigration(manifest: unknown): number | undefined {
+ return Option.getOrUndefined(decodeNpmReleaseMigrationManifest(manifest))?.t3code
+ .databaseMigration;
+}
diff --git a/scripts/build-npm-launcher.test.ts b/scripts/build-npm-launcher.test.ts
index 8dd98225cd0..749e27bd545 100644
--- a/scripts/build-npm-launcher.test.ts
+++ b/scripts/build-npm-launcher.test.ts
@@ -13,6 +13,8 @@ import * as NodeCrypto from "node:crypto";
import * as NodeEvents from "node:events";
import * as NodeHttp from "node:http";
+import { npmReleaseDatabaseMigration } from "@t3tools/shared/cliRelease";
+
import { buildNpmLauncher } from "./build-npm-launcher.ts";
const VERSION = "1.2.3";
@@ -118,6 +120,7 @@ it.layer(NodeServices.layer)("build-npm-launcher", (it) => {
assert.deepStrictEqual(manifest.bin, { t3: "./bin/t3.mjs" });
assert.isUndefined(manifest.dependencies);
assert.isUndefined(manifest.optionalDependencies);
+ assert.isAbove(npmReleaseDatabaseMigration(manifest) ?? 0, 0);
const installed = path.join(root, "installed");
yield* fs.makeDirectory(installed);
diff --git a/scripts/build-npm-launcher.ts b/scripts/build-npm-launcher.ts
index df1cc488814..bae124fb008 100644
--- a/scripts/build-npm-launcher.ts
+++ b/scripts/build-npm-launcher.ts
@@ -30,8 +30,8 @@ export class NpmLauncherCommandFailedError extends Schema.TaggedError<NpmLaunche
}
}
-/** engines requires import.meta.dirname and fetch. */
-export function npmLauncherPackageManifest(version: string) {
+/** engines requires import.meta.dirname and fetch. `t3code` is read back by npmReleaseDatabaseMigration. */
+export function npmLauncherPackageManifest(version: string, databaseMigration: number) {
return {
name: NPM_LAUNCHER_PACKAGE_NAME,
version,
@@ -42,9 +42,24 @@ export function npmLauncherPackageManifest(version: string) {
bin: { t3: "./bin/t3.mjs" },
files: ["bin", "dist"],
engines: { node: ">=20.11" },
+ t3code: { databaseMigration },
};
}
+/** Highest server migration id, from the `NNN_Name.ts` files the server registers. */
+const latestServerMigrationId = Effect.fn("latestServerMigrationId")(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const dir = yield* path.fromFileUrl(
+ new URL("../apps/server/src/persistence/Migrations/", import.meta.url),
+ );
+ const ids = (yield* fs.readDirectory(dir)).flatMap((name) => {
+ const id = /^(\d+)_\w+\.ts$/.exec(name)?.[1];
+ return id === undefined ? [] : [Number(id)];
+ });
+ return Math.max(0, ...ids);
+});
+
export const buildNpmLauncher = Effect.fn("buildNpmLauncher")(function* (input: {
readonly version: string;
readonly outputDir: string;
@@ -64,7 +79,9 @@ export const buildNpmLauncher = Effect.fn("buildNpmLauncher")(function* (input:
yield* fs.makeDirectory(path.join(stageDir, "dist"));
yield* fs.writeFileString(
path.join(stageDir, "package.json"),
- `${yield* encodePackageJson(npmLauncherPackageManifest(input.version))}\n`,
+ `${yield* encodePackageJson(
+ npmLauncherPackageManifest(input.version, yield* latestServerMigrationId()),
+ )}\n`,
);
yield* fs.copyFile(path.join(sourceDir, "t3.mjs"), path.join(stageDir, "bin/t3.mjs"));
yield* fs.chmod(path.join(stageDir, "bin/t3.mjs"), 0o755);