@devries-cameron20 / t3code Mirror · read-only / commits / f2943ee90e
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 13:15 UTC

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 29, 2026 at 03:54 UTC f2943ee90ef76b1db3fc1c1cd3808252418f5850
41 files changed +1959 -144
apps/desktop/src/ipc/methods/updates.ts
+12 -6
@@ -23,11 +23,14 @@ export const getUpdateState = DesktopIpc.makeIpcMethod({
23
24 export const setUpdateChannel = DesktopIpc.makeIpcMethod({
25 channel: IpcChannels.UPDATE_SET_CHANNEL_CHANNEL,
26 - payload: DesktopUpdateChannelSchema,
26 + payload: Schema.Struct({
27 + channel: DesktopUpdateChannelSchema,
28 + minimumVersion: Schema.optional(Schema.String),
29 + }),
30 result: DesktopUpdateStateSchema,
28 - handler: Effect.fn("desktop.ipc.updates.setChannel")(function* (channel) {
31 + handler: Effect.fn("desktop.ipc.updates.setChannel")(function* ({ channel, minimumVersion }) {
32 const updates = yield* DesktopUpdates.DesktopUpdates;
30 - return yield* updates.setChannel(channel);
33 + return yield* updates.setChannel(channel, { minimumVersion });
34 }),
35 });
36
@@ -43,11 +46,14 @@ export const downloadUpdate = DesktopIpc.makeIpcMethod({
46
47 export const installUpdate = DesktopIpc.makeIpcMethod({
48 channel: IpcChannels.UPDATE_INSTALL_CHANNEL,
46 - payload: Schema.Void,
49 + /** A version installs only that downloaded build, never one that replaced it. */
50 + payload: Schema.UndefinedOr(Schema.String),
51 result: DesktopUpdateActionResultSchema,
48 - handler: Effect.fn("desktop.ipc.updates.install")(function* () {
52 + handler: Effect.fn("desktop.ipc.updates.install")(function* (expectedVersion) {
53 const updates = yield* DesktopUpdates.DesktopUpdates;
50 - return yield* updates.install;
54 + if (expectedVersion === undefined) return yield* updates.install;
55 + const { accepted, completed, state } = yield* updates.installPrepared(expectedVersion);
56 + return { accepted, completed, state };
57 }),
58 });
59
apps/desktop/src/preload.ts
+4 -3
@@ -261,11 +261,12 @@ contextBridge.exposeInMainWorld("desktopBridge", {
261 };
262 },
263 getUpdateState: () => ipcRenderer.invoke(IpcChannels.UPDATE_GET_STATE_CHANNEL),
264 - setUpdateChannel: (channel) =>
265 - ipcRenderer.invoke(IpcChannels.UPDATE_SET_CHANNEL_CHANNEL, channel),
264 + setUpdateChannel: (channel, minimumVersion) =>
265 + ipcRenderer.invoke(IpcChannels.UPDATE_SET_CHANNEL_CHANNEL, { channel, minimumVersion }),
266 checkForUpdate: () => ipcRenderer.invoke(IpcChannels.UPDATE_CHECK_CHANNEL),
267 downloadUpdate: () => ipcRenderer.invoke(IpcChannels.UPDATE_DOWNLOAD_CHANNEL),
268 - installUpdate: () => ipcRenderer.invoke(IpcChannels.UPDATE_INSTALL_CHANNEL),
268 + installUpdate: (expectedVersion) =>
269 + ipcRenderer.invoke(IpcChannels.UPDATE_INSTALL_CHANNEL, expectedVersion),
270 cliCommand: {
271 getState: () => ipcRenderer.invoke(IpcChannels.CLI_COMMAND_GET_STATE_CHANNEL),
272 install: () => ipcRenderer.invoke(IpcChannels.CLI_COMMAND_INSTALL_CHANNEL),
apps/desktop/src/settings/DesktopAppSettings.ts
+2 -2
@@ -22,7 +22,7 @@ import {
22 normalizeLinuxPasswordStorePreference,
23 type LinuxPasswordStorePreference,
24 } from "../linuxSecretStorage.ts";
25 -import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
25 +import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
26 import { isValidDistroName } from "../wsl/wslPathParsing.ts";
27
28 export interface DesktopSettings {
@@ -180,7 +180,7 @@ export class DesktopAppSettings extends Context.Service<
180 export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
181 return {
182 ...DEFAULT_DESKTOP_SETTINGS,
183 - updateChannel: resolveDefaultDesktopUpdateChannel(appVersion),
183 + updateChannel: desktopUpdateChannelOf(appVersion),
184 };
185 }
186
apps/desktop/src/updates/DesktopRemoteUpdates.test.ts
+269
@@ -119,6 +119,239 @@ describe("DesktopRemoteUpdates", () => {
119 );
120 });
121
122 + it.effect("switches to the requested track before preparing its release", () => {
123 + // In-memory settings keep the channel write off real disk I/O.
124 + const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });
125 +
126 + return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
127 + Effect.gen(function* () {
128 + const updates = yield* DesktopUpdates.DesktopUpdates;
129 + yield* Queue.offer(requests, {
130 + ...request("req-switch"),
131 + channel: "nightly",
132 + targetVersion: "1.2.4-nightly.20261027.1",
133 + });
134 + yield* settle;
135 + assert.equal((yield* updates.getState).channel, "nightly");
136 +
137 + harness.emit("update-available", { version: "1.2.4-nightly.20261027.1" });
138 + yield* settle;
139 + harness.emit("update-downloaded", { version: "1.2.4-nightly.20261027.1" });
140 + yield* settle;
141 +
142 + const terminals = terminalReports(reports);
143 + assert.deepEqual(
144 + terminals.map((report) => [report.requestId, report.outcome]),
145 + [["req-switch", "ready-to-install"]],
146 + );
147 + assert.equal(terminals[0]?.state.downloadedVersion, "1.2.4-nightly.20261027.1");
148 + }),
149 + );
150 + });
151 +
152 + it.effect(
153 + "refuses a crossing whose feed has only an older build, and never offers it later",
154 + () => {
155 + const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });
156 +
157 + return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
158 + Effect.gen(function* () {
159 + const updates = yield* DesktopUpdates.DesktopUpdates;
160 + const older = "1.2.4-nightly.20261020.1";
161 + yield* Queue.offer(requests, {
162 + ...request("req-older"),
163 + channel: "nightly",
164 + targetVersion: "1.2.4-nightly.20261027.1",
165 + });
166 + yield* settle;
167 + // Answers the track change's check, then the request's own check.
168 + harness.emit("update-available", { version: older });
169 + yield* settle;
170 + harness.emit("update-available", { version: older });
171 + yield* settle;
172 +
173 + assert.deepEqual(
174 + terminalReports(reports).map((report) => [report.outcome, report.reason]),
175 + [["failed", "The desktop app found no build of 1.2.4-nightly.20261027.1."]],
176 + );
177 + // The saved track is the user's intent; a retry picks it up from here.
178 + assert.equal((yield* updates.getState).channel, "nightly");
179 +
180 + // A plain update afterwards cannot reach the build the switch refused.
181 + yield* Queue.offer(requests, request("req-plain"));
182 + yield* settle;
183 + harness.emit("update-available", { version: older });
184 + yield* settle;
185 + assert.isNull((yield* updates.getState).availableVersion);
186 + assert.equal(harness.downloadCount(), 0);
187 + }),
188 + );
189 + },
190 + );
191 +
192 + it.effect("only saves the track on a host already running the release", () => {
193 + const harness = makeHarness({ savedChannel: "nightly" });
194 +
195 + return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
196 + Effect.gen(function* () {
197 + const updates = yield* DesktopUpdates.DesktopUpdates;
198 + yield* Queue.offer(requests, {
199 + ...request("req-track-only"),
200 + channel: "latest",
201 + targetVersion: "1.2.3",
202 + });
203 + yield* settle;
204 + // Even with a newer build on the feed, the host only saves its track.
205 + harness.emit("update-available", { version: "1.2.4" });
206 + yield* settle;
207 +
208 + assert.deepEqual(
209 + terminalReports(reports).map((report) => report.outcome),
210 + ["up-to-date"],
211 + );
212 + assert.equal((yield* updates.getState).channel, "latest");
213 + assert.equal(harness.downloadCount(), 0);
214 + }),
215 + );
216 + });
217 +
218 + it.effect("drops a retained download below the switch's checked release", () => {
219 + const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });
220 +
221 + return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
222 + Effect.gen(function* () {
223 + const updates = yield* DesktopUpdates.DesktopUpdates;
224 + // Downloaded earlier on this Stable host, before the switch checked 1.2.5.
225 + harness.emit("update-downloaded", { version: "1.2.4" });
226 + yield* settle;
227 + assert.equal((yield* updates.getState).downloadedVersion, "1.2.4");
228 +
229 + yield* Queue.offer(requests, {
230 + ...request("req-floor"),
231 + channel: "latest",
232 + targetVersion: "1.2.5",
233 + });
234 + yield* settle;
235 + harness.emit("update-available", { version: "1.2.5" });
236 + yield* settle;
237 + harness.emit("update-downloaded", { version: "1.2.5" });
238 + yield* settle;
239 +
240 + assert.deepEqual(
241 + terminalReports(reports).map((report) => [
242 + report.outcome,
243 + report.state.downloadedVersion,
244 + ]),
245 + [["ready-to-install", "1.2.5"]],
246 + );
247 + }),
248 + );
249 + });
250 +
251 + it.effect("refuses to cross tracks remotely while WSL backends need their own checks", () => {
252 + const harness = makeHarness({ beforeSetUpdateChannel: Effect.void, wslBackend: true });
253 +
254 + return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
255 + Effect.gen(function* () {
256 + const updates = yield* DesktopUpdates.DesktopUpdates;
257 + yield* Queue.offer(requests, {
258 + ...request("req-wsl"),
259 + channel: "nightly",
260 + targetVersion: "1.2.4-nightly.20261027.1",
261 + });
262 + yield* settle;
263 +
264 + assert.deepEqual(
265 + terminalReports(reports).map((report) => report.outcome),
266 + ["failed"],
267 + );
268 + assert.include(terminalReports(reports)[0]?.reason ?? "", "Switch it on that machine");
269 + assert.equal((yield* updates.getState).channel, "latest");
270 + }),
271 + );
272 + });
273 +
274 + it.effect("fails a switch that leaves a same-track host below the checked release", () => {
275 + const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });
276 +
277 + return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
278 + Effect.gen(function* () {
279 + yield* Queue.offer(requests, {
280 + ...request("req-behind"),
281 + channel: "latest",
282 + targetVersion: "1.2.5",
283 + });
284 + yield* settle;
285 + // The feed lags npm and has nothing newer than this host's 1.2.3.
286 + harness.emit("update-not-available");
287 + yield* settle;
288 + harness.emit("update-not-available");
289 + yield* settle;
290 +
291 + assert.deepEqual(
292 + terminalReports(reports).map((report) => [report.outcome, report.reason]),
293 + [["failed", "The desktop app found no build of 1.2.5."]],
294 + );
295 + }),
296 + );
297 + });
298 +
299 + it.effect("fails a crossing to an older-numbered Stable that the feed does not offer", () => {
300 + const harness = makeHarness({
301 + appVersion: "1.2.4-nightly.20261027.1",
302 + beforeSetUpdateChannel: Effect.void,
303 + });
304 +
305 + return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
306 + Effect.gen(function* () {
307 + yield* Queue.offer(requests, {
308 + ...request("req-to-stable"),
309 + channel: "latest",
310 + targetVersion: "1.2.3",
311 + });
312 + yield* settle;
313 + harness.emit("update-not-available");
314 + yield* settle;
315 + harness.emit("update-not-available");
316 + yield* settle;
317 +
318 + // Still on Nightly, though the target is numbered below this build.
319 + assert.deepEqual(
320 + terminalReports(reports).map((report) => [report.outcome, report.reason]),
321 + [["failed", "The desktop app found no build of 1.2.3."]],
322 + );
323 + }),
324 + );
325 + });
326 +
327 + it.effect("accepts a newer build than the checked release on the requested track", () => {
328 + const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });
329 +
330 + return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
331 + Effect.gen(function* () {
332 + const newer = "1.2.4-nightly.20261028.2";
333 + yield* Queue.offer(requests, {
334 + ...request("req-newer"),
335 + channel: "nightly",
336 + targetVersion: "1.2.4-nightly.20261027.1",
337 + });
338 + yield* settle;
339 + harness.emit("update-available", { version: newer });
340 + yield* settle;
341 + harness.emit("update-downloaded", { version: newer });
342 + yield* settle;
343 +
344 + assert.deepEqual(
345 + terminalReports(reports).map((report) => [
346 + report.outcome,
347 + report.state.downloadedVersion,
348 + ]),
349 + [["ready-to-install", newer]],
350 + );
351 + }),
352 + );
353 + });
354 +
355 it.effect("reports a failed outcome when quitAndInstall fails", () => {
356 const harness = makeHarness({
357 quitAndInstall: Effect.fail(
@@ -525,6 +758,42 @@ describe("DesktopRemoteUpdates", () => {
758 );
759 });
760
761 + it.effect("cancels a track switch while its own feed check is still running", () => {
762 + const releaseCheck = Deferred.makeUnsafe<void>();
763 + const harness = makeHarness({
764 + beforeSetUpdateChannel: Effect.void,
765 + checkForUpdates: Deferred.await(releaseCheck),
766 + });
767 +
768 + return runRemoteUpdatesTest(harness, ({ requests, cancellations }) =>
769 + Effect.gen(function* () {
770 + yield* Queue.offer(requests, {
771 + ...request("req-switch-cancel"),
772 + channel: "nightly",
773 + targetVersion: "1.2.4-nightly.20261027.1",
774 + });
775 + yield* settle;
776 + const updates = yield* DesktopUpdates.DesktopUpdates;
777 + yield* Queue.offer(cancellations, {
778 + version: 1,
779 + type: "cancelDesktopUpdate",
780 + requestId: "req-switch-cancel",
781 + });
782 + yield* settle;
783 + // The next request starts without waiting for the cancelled switch's feed check.
784 + yield* Queue.offer(requests, {
785 + ...request("req-switch-back"),
786 + channel: "latest",
787 + targetVersion: "1.2.3",
788 + });
789 + yield* settle;
790 +
791 + assert.equal((yield* updates.getState).channel, "latest");
792 + yield* Deferred.succeed(releaseCheck, undefined);
793 + }),
794 + );
795 + });
796 +
797 it.effect("cancels an active preparation so the next request can run", () => {
798 const releaseCheck = Deferred.makeUnsafe<void>();
799 const harness = makeHarness({ checkForUpdates: Deferred.await(releaseCheck) });
apps/desktop/src/updates/DesktopRemoteUpdates.ts
+86 -8
@@ -10,10 +10,13 @@ import * as Effect from "effect/Effect";
10 import * as Option from "effect/Option";
11 import * as Queue from "effect/Queue";
12 import * as Ref from "effect/Ref";
13 +import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
14 +import { compareSemverVersions } from "@t3tools/shared/semver";
15 import type * as Scope from "effect/Scope";
16 import * as Stream from "effect/Stream";
17
18 import * as DesktopObservability from "../app/DesktopObservability.ts";
19 +import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
20 import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
21 import * as DesktopUpdates from "./DesktopUpdates.ts";
22 import {
@@ -44,9 +47,13 @@ type CommitClaim =
47 export const listen: Effect.Effect<
48 void,
49 never,
47 - DesktopUpdates.DesktopUpdates | DesktopTelemetryPublisher.DesktopTelemetryPublisher | Scope.Scope
50 + | DesktopUpdates.DesktopUpdates
51 + | DesktopTelemetryPublisher.DesktopTelemetryPublisher
52 + | DesktopBackendPool.DesktopBackendPool
53 + | Scope.Scope
54 > = Effect.gen(function* () {
55 const updates = yield* DesktopUpdates.DesktopUpdates;
56 + const backends = yield* DesktopBackendPool.DesktopBackendPool;
57 const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
58 const activeRequestIdRef = yield* Ref.make(Option.none<string>());
59 const requestControlRef = yield* Ref.make<{
@@ -171,7 +178,59 @@ export const listen: Effect.Effect<
178 return;
179 }
180 yield* Ref.set(activeRequestIdRef, Option.some(request.requestId));
174 - yield* logInfo("remote update requested", { requestId: request.requestId });
181 + yield* logInfo("remote update requested", {
182 + requestId: request.requestId,
183 + channel: request.channel,
184 + });
185 + // A switch saves its track first, so the step machine never sees the old track's offer.
186 + // The saved track is the user's intent and stays even if this request fails: a track saved
187 + // toward Stable never offers an older build outside a guarded switch.
188 + if (request.channel !== undefined) {
189 + // A reinstall restarts every backend, but the requesting server checked only its own
190 + // database. A WSL backend keeps its own, so cross tracks only where all can be checked.
191 + const current = yield* updates.getState;
192 + if (
193 + desktopUpdateChannelOf(current.currentVersion) !== request.channel &&
194 + (yield* backends.list).length > 1
195 + ) {
196 + yield* publishReport(
197 + current,
198 + {
199 + outcome: "failed",
200 + reason:
201 + "This desktop app also runs WSL backends, whose databases a remote switch cannot check. Switch it on that machine.",
202 + },
203 + request.requestId,
204 + );
205 + return;
206 + }
207 + const switched = yield* Effect.raceFirst(
208 + updates.setChannel(request.channel, { minimumVersion: request.targetVersion }).pipe(
209 + Effect.as(true),
210 + Effect.catch((error) =>
211 + updates.getState.pipe(
212 + Effect.flatMap((state) =>
213 + publishReport(
214 + state,
215 + { outcome: "failed", reason: error.message },
216 + request.requestId,
217 + ),
218 + ),
219 + Effect.as(false),
220 + ),
221 + ),
222 + ),
223 + Deferred.await(cancellation).pipe(Effect.as(false)),
224 + );
225 + if (!switched) return;
226 + // A host already running the target only needed its track saved; installing a newer
227 + // build here would restart it without the dialog having said so.
228 + const state = yield* updates.getState;
229 + if (request.targetVersion === state.currentVersion) {
230 + yield* publishReport(state, { outcome: "up-to-date" }, request.requestId);
231 + return;
232 + }
233 + }
234 const { latest, changes } = yield* updates.subscribe;
235 const disabledReason = Option.getOrNull(yield* updates.disabledReason);
236 let attempts: RemoteDesktopUpdateAttempts = { checks: 0, downloads: 0 };
@@ -184,6 +243,12 @@ export const listen: Effect.Effect<
243 Effect.forkScoped,
244 );
245
246 + // A host leaving its build's track may need an older build, down to the checked release;
247 + // the updater offers nothing below it.
248 + const crossing = (state: DesktopUpdateState) =>
249 + request.channel !== undefined &&
250 + request.targetVersion !== undefined &&
251 + desktopUpdateChannelOf(state.currentVersion) !== request.channel;
252 const step = Effect.fn("DesktopRemoteUpdates.step")(function* (
253 state: DesktopUpdateState,
254 ): Effect.fn.Return<boolean, never, Scope.Scope> {
@@ -193,7 +258,7 @@ export const listen: Effect.Effect<
258 return false;
259 case "check":
260 attempts = { ...attempts, checks: attempts.checks + 1 };
196 - yield* updates.check("remote-update").pipe(
261 + yield* updates.check("remote-update", { allowDowngrade: crossing(state) }).pipe(
262 Effect.flatMap((result) => {
263 if (result.checked) return Effect.void;
264 attempts = { ...attempts, checks: attempts.checks - 1 };
@@ -246,21 +311,34 @@ export const listen: Effect.Effect<
311 yield* logInfo("remote update prepared", { requestId: request.requestId });
312 return true;
313 }
249 - case "done":
314 + case "done": {
315 + // A switch that leaves the host on its old track, or below its checked release, did
316 + // not reach it; a track-only host already at the release is done.
317 + const done =
318 + request.targetVersion !== undefined &&
319 + next.outcome === "up-to-date" &&
320 + (crossing(state) ||
321 + compareSemverVersions(state.currentVersion, request.targetVersion) < 0)
322 + ? {
323 + outcome: "failed" as const,
324 + reason: `The desktop app found no build of ${request.targetVersion}.`,
325 + }
326 + : next;
327 yield* publishReport(
328 state,
329 {
253 - outcome: next.outcome,
254 - ...(next.reason === undefined ? {} : { reason: next.reason }),
330 + outcome: done.outcome,
331 + ...(done.reason === undefined ? {} : { reason: done.reason }),
332 },
333 request.requestId,
334 );
335 yield* logInfo("remote update finished", {
336 requestId: request.requestId,
260 - outcome: next.outcome,
261 - reason: next.reason ?? null,
337 + outcome: done.outcome,
338 + reason: done.reason ?? null,
339 });
340 return true;
341 + }
342 }
343 });
344
apps/desktop/src/updates/DesktopUpdates.test.ts
+170
@@ -2,6 +2,7 @@ import { assert, describe, it } from "@effect/vitest";
2 import { DESKTOP_UPDATE_RESTART_MARKER_FILE } from "@t3tools/contracts";
3 import * as Cause from "effect/Cause";
4 import * as Deferred from "effect/Deferred";
5 +import * as Duration from "effect/Duration";
6 import * as Effect from "effect/Effect";
7 import * as Fiber from "effect/Fiber";
8 import * as Layer from "effect/Layer";
@@ -694,6 +695,65 @@ describe("DesktopUpdates", () => {
695 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
696 });
697
698 + it.effect("ignores a finished download from a track it no longer follows", () => {
699 + const harness = makeHarness();
700 +
701 + return Effect.scoped(
702 + Effect.gen(function* () {
703 + const updates = yield* DesktopUpdates.DesktopUpdates;
704 + yield* updates.configure;
705 + // A backed-out switch's download keeps reporting progress until it finishes.
706 + harness.emit("download-progress", { percent: 40 });
707 + yield* flushCallbacks;
708 + harness.emit("update-downloaded", { version: "1.2.4-nightly.20261027.1" });
709 + yield* flushCallbacks;
710 +
711 + const state = yield* updates.getState;
712 + assert.equal(state.downloadedVersion, null);
713 + assert.notEqual(state.status, "downloading");
714 + }),
715 + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
716 + });
717 +
718 + it.effect("offers older releases only to checks that leave the running build's track", () => {
719 + const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });
720 +
721 + return Effect.scoped(
722 + Effect.gen(function* () {
723 + const updates = yield* DesktopUpdates.DesktopUpdates;
724 + yield* updates.configure;
725 + const before = harness.checkAllowedDowngrade.length;
726 + yield* updates.setChannel("nightly");
727 + yield* updates.setChannel("latest");
728 + yield* updates.check("remote-update", { allowDowngrade: true });
729 +
730 + // Back on its own Stable track the build never needs an older release.
731 + assert.deepEqual(harness.checkAllowedDowngrade.slice(before), [true, false, true]);
732 + assert.isFalse(harness.allowDowngrade());
733 + }),
734 + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
735 + });
736 +
737 + it.effect("re-checks a saved track that differs from the running build's track", () => {
738 + const harness = makeHarness({
739 + appVersion: "1.2.4-nightly.20261027.1",
740 + beforeSetUpdateChannel: Effect.void,
741 + });
742 +
743 + return Effect.scoped(
744 + Effect.gen(function* () {
745 + const updates = yield* DesktopUpdates.DesktopUpdates;
746 + yield* updates.configure;
747 + yield* updates.setChannel("latest");
748 + const checks = harness.checkCount();
749 +
750 + yield* updates.setChannel("latest");
751 +
752 + assert.equal(harness.checkCount(), checks + 1);
753 + }),
754 + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
755 + });
756 +
757 it.effect("does not persist an unchanged update channel as a user preference", () => {
758 const harness = makeHarness();
759
@@ -713,6 +773,116 @@ describe("DesktopUpdates", () => {
773 ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
774 });
775
776 + it.effect("offers nothing below a track switch's checked release", () => {
777 + const harness = makeHarness({
778 + appVersion: "1.2.4-nightly.20261027.1",
779 + beforeSetUpdateChannel: Effect.void,
780 + });
781 +
782 + return Effect.scoped(
783 + Effect.gen(function* () {
784 + const updates = yield* DesktopUpdates.DesktopUpdates;
785 + yield* updates.configure;
786 + yield* updates.setChannel("latest", { minimumVersion: "1.2.3" });
787 +
788 + harness.emit("update-available", { version: "1.2.2" });
789 + yield* flushCallbacks;
790 + assert.isNull((yield* updates.getState).availableVersion);
791 + harness.emit("update-downloaded", { version: "1.2.2" });
792 + yield* flushCallbacks;
793 + assert.isNull((yield* updates.getState).downloadedVersion);
794 +
795 + harness.emit("update-available", { version: "1.2.3" });
796 + yield* flushCallbacks;
797 + assert.equal((yield* updates.getState).availableVersion, "1.2.3");
798 + }),
799 + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
800 + });
801 +
802 + it.effect("keeps a saved Stable track across a restart without offering an older release", () => {
803 + // A Nightly build whose switch to Stable did not finish before the app quit.
804 + const harness = makeHarness({ appVersion: "1.2.4-nightly.20261027.1", savedChannel: "latest" });
805 +
806 + return Effect.scoped(
807 + Effect.gen(function* () {
808 + const updates = yield* DesktopUpdates.DesktopUpdates;
809 + yield* updates.configure;
810 + yield* updates.check("startup");
811 +
812 + assert.equal((yield* updates.getState).channel, "latest");
813 + assert.deepEqual(harness.checkAllowedDowngrade, [false]);
814 + // Semver ranks Stable 1.2.4 above this Nightly, but a Nightly built before the release's
815 + // version bump can hold migrations 1.2.4 lacks. Crossing needs a guarded switch.
816 + harness.emit("update-available", { version: "1.2.4" });
817 + yield* flushCallbacks;
818 + assert.isNull((yield* updates.getState).availableVersion);
819 + }),
820 + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
821 + });
822 +
823 + it.effect("keeps a saved Nightly track across a restart without crossing on its own", () => {
824 + // A Stable build whose switch to Nightly was refused before the app quit; its floor is gone.
825 + const harness = makeHarness({ savedChannel: "nightly" });
826 +
827 + return Effect.scoped(
828 + Effect.gen(function* () {
829 + const updates = yield* DesktopUpdates.DesktopUpdates;
830 + yield* updates.configure;
831 + yield* updates.check("startup");
832 + harness.emit("update-available", { version: "1.2.4-nightly.20261027.1" });
833 + yield* flushCallbacks;
834 +
835 + assert.equal((yield* updates.getState).channel, "nightly");
836 + assert.isNull((yield* updates.getState).availableVersion);
837 + assert.deepEqual(harness.checkAllowedDowngrade, [false]);
838 + }),
839 + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
840 + });
841 +
842 + it.effect("never offers an older Nightly to a Nightly build's own checks", () => {
843 + const harness = makeHarness({ appVersion: "1.2.4-nightly.20261027.1" });
844 +
845 + return Effect.scoped(
846 + Effect.gen(function* () {
847 + const updates = yield* DesktopUpdates.DesktopUpdates;
848 + yield* updates.configure;
849 + yield* updates.check("poll");
850 +
851 + assert.equal((yield* updates.getState).channel, "nightly");
852 + assert.deepEqual(harness.checkAllowedDowngrade, [false]);
853 + }),
854 + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
855 + });
856 +
857 + it.effect("waits out a background check instead of refusing a track change", () =>
858 + Effect.gen(function* () {
859 + const checkStarted = yield* Deferred.make<void>();
860 + const releaseCheck = yield* Deferred.make<void>();
861 + const harness = makeHarness({
862 + beforeSetUpdateChannel: Effect.void,
863 + checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe(
864 + Effect.andThen(Deferred.await(releaseCheck)),
865 + ),
866 + });
867 +
868 + yield* Effect.scoped(
869 + Effect.gen(function* () {
870 + const updates = yield* DesktopUpdates.DesktopUpdates;
871 + yield* updates.configure;
872 + yield* updates.check("poll").pipe(Effect.forkScoped);
873 + yield* Deferred.await(checkStarted);
874 +
875 + const channelFiber = yield* updates.setChannel("nightly").pipe(Effect.forkScoped);
876 + yield* Deferred.succeed(releaseCheck, undefined);
877 + yield* TestClock.adjust(Duration.seconds(2));
878 + const state = yield* Fiber.join(channelFiber);
879 +
880 + assert.equal(state.channel, "nightly");
881 + }),
882 + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
883 + }),
884 + );
885 +
886 it.effect("rejects checks while an update channel change is being persisted", () =>
887 Effect.gen(function* () {
888 const channelChangeStarted = yield* Deferred.make<void>();
apps/desktop/src/updates/DesktopUpdates.ts
+78 -14
@@ -19,6 +19,7 @@ import * as Layer from "effect/Layer";
19 import * as Option from "effect/Option";
20 import * as PubSub from "effect/PubSub";
21 import * as Ref from "effect/Ref";
22 +import * as Schedule from "effect/Schedule";
23 import * as Schema from "effect/Schema";
24 import * as Scope from "effect/Scope";
25 import * as Semaphore from "effect/Semaphore";
@@ -34,7 +35,8 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts";
35 import * as IpcChannels from "../ipc/channels.ts";
36 import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
37 import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
37 -import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
38 +import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
39 +import { compareSemverVersions } from "@t3tools/shared/semver";
40 import {
41 createInitialDesktopUpdateState,
42 reduceDesktopUpdateStateOnCheckFailure,
@@ -49,6 +51,8 @@ import {
51 resolveNotAppliedInstallVersion,
52 } from "./updateMachine.ts";
53
54 +const CHANNEL_CHANGE_RETRY_DELAY = Duration.seconds(1);
55 +const CHANNEL_CHANGE_RETRIES = 30;
56 const AUTO_UPDATE_STARTUP_DELAY = "15 seconds";
57 const AUTO_UPDATE_POLL_INTERVAL = "4 minutes";
58 const PREPARED_INSTALL_CHECK_WAIT = Duration.seconds(90);
@@ -179,10 +183,16 @@ export class DesktopUpdates extends Context.Service<
183 readonly emitState: Effect.Effect<void>;
184 readonly disabledReason: Effect.Effect<Option.Option<string>>;
185 readonly configure: Effect.Effect<void, never, Scope.Scope>;
186 + /** `minimumVersion` is a track switch's checked release; nothing older is offered after. */
187 readonly setChannel: (
188 channel: DesktopUpdateChannel,
189 + options?: { readonly minimumVersion?: string | undefined },
190 ) => Effect.Effect<DesktopUpdateState, DesktopUpdateSetChannelError>;
185 - readonly check: (reason: string) => Effect.Effect<DesktopUpdateCheckResult>;
191 + /** `allowDowngrade` is for a guarded track switch, which checked that older release. */
192 + readonly check: (
193 + reason: string,
194 + options?: { readonly allowDowngrade?: boolean },
195 + ) => Effect.Effect<DesktopUpdateCheckResult>;
196 readonly download: Effect.Effect<DesktopUpdateActionResult>;
197 readonly install: Effect.Effect<DesktopUpdateActionResult>;
198 readonly installPrepared: (
@@ -351,6 +361,20 @@ export const make = Effect.gen(function* () {
361 const updaterConfiguredRef = yield* Ref.make(false);
362 const lastLoggedDownloadMilestoneRef = yield* Ref.make(-1);
363 const notAppliedVersionRef = yield* Ref.make(Option.none<string>());
364 + // The release a track switch's database check cleared. A build crosses to another track only
365 + // through such a switch, and never below that release: version order alone cannot tell whether
366 + // a Stable knows a Nightly's migrations.
367 + const releaseFloorRef = yield* Ref.make(Option.none<string>());
368 + const offerable = (version: string, state: DesktopUpdateState) =>
369 + Ref.get(releaseFloorRef).pipe(
370 + Effect.map(
371 + (floor) =>
372 + desktopUpdateChannelOf(version) === state.channel &&
373 + (Option.isSome(floor)
374 + ? compareSemverVersions(version, floor.value) >= 0
375 + : desktopUpdateChannelOf(environment.appVersion) === state.channel),
376 + ),
377 + );
378 const updateStateRef = yield* Ref.make<DesktopUpdateState>(
379 createInitialDesktopUpdateState(
380 environment.appVersion,
@@ -454,12 +478,13 @@ export const make = Effect.gen(function* () {
478 const allowsPrerelease = channel === "nightly";
479 yield* electronUpdater.setChannel(channel);
480 yield* electronUpdater.setAllowPrerelease(allowsPrerelease);
457 - yield* electronUpdater.setAllowDowngrade(allowsPrerelease);
481 + // An older build can lack migrations this one ran. Only a guarded track switch's own check
482 + // may offer one.
483 + yield* electronUpdater.setAllowDowngrade(false);
484 yield* electronUpdater.setFullChangelog(allowsPrerelease);
485 yield* logUpdaterInfo("using update channel", {
486 channel,
487 allowPrerelease: allowsPrerelease,
462 - allowDowngrade: allowsPrerelease,
488 fullChangelog: allowsPrerelease,
489 });
490 });
@@ -467,6 +492,7 @@ export const make = Effect.gen(function* () {
492 const checkForUpdates = Effect.fn("desktop.updates.checkForUpdates")(function* (
493 reason: string,
494 actionReservation: "acquire" | "held" = "acquire",
495 + allowDowngrade = false,
496 ) {
497 yield* Effect.annotateCurrentSpan({ reason });
498 if (yield* Ref.get(desktopState.quitting)) return false;
@@ -488,7 +514,11 @@ export const make = Effect.gen(function* () {
514 yield* setState(reduceDesktopUpdateStateOnCheckStart(state, checkedAt));
515 yield* logUpdaterInfo("checking for updates", { reason });
516
517 + // The flag is shared updater state, so it flips only while this check holds the reservation.
518 + const restoreDowngrade = yield* electronUpdater.allowDowngrade;
519 + if (allowDowngrade) yield* electronUpdater.setAllowDowngrade(true);
520 return yield* electronUpdater.checkForUpdates.pipe(
521 + Effect.ensuring(electronUpdater.setAllowDowngrade(restoreDowngrade).pipe(Effect.ignore)),
522 Effect.as(true),
523 Effect.catchTags({
524 ElectronUpdaterCheckForUpdatesError: Effect.fn(
@@ -849,8 +879,8 @@ export const make = Effect.gen(function* () {
879 Effect.flatMap(
880 Effect.fn("desktop.updates.applyUpdateAvailable")(function* (info) {
881 const state = yield* Ref.get(updateStateRef);
852 - if (resolveDefaultDesktopUpdateChannel(info.version) !== state.channel) {
853 - yield* logUpdaterInfo("ignoring update that does not match selected channel", {
882 + if (!(yield* offerable(info.version, state))) {
883 + yield* logUpdaterInfo("ignoring update outside the selected channel or its floor", {
884 version: info.version,
885 channel: state.channel,
886 });
@@ -986,6 +1016,20 @@ export const make = Effect.gen(function* () {
1016 Effect.flatMap(
1017 Effect.fn("desktop.updates.applyUpdateDownloaded")(function* (info) {
1018 const state = yield* Ref.get(updateStateRef);
1019 + // A download can finish after its track switch moved on; never offer that build.
1020 + if (!(yield* offerable(info.version, state))) {
1021 + yield* logUpdaterInfo("ignoring download outside the selected channel or its floor", {
1022 + version: info.version,
1023 + channel: state.channel,
1024 + });
1025 + // Its progress events left the updater "downloading", which would block every check.
1026 + if (state.status === "downloading") {
1027 + yield* setState(
1028 + reduceDesktopUpdateStateOnNoUpdate(state, yield* currentIsoTimestamp),
1029 + );
1030 + }
1031 + return;
1032 + }
1033 yield* setState(reduceDesktopUpdateStateOnDownloadComplete(state, info.version));
1034 yield* logUpdaterInfo("update downloaded", { version: info.version });
1035 }),
@@ -1092,9 +1136,17 @@ export const make = Effect.gen(function* () {
1136 }).pipe(Effect.withSpan("desktop.updates.configure")),
1137 setChannel: Effect.fn("desktop.updates.setChannel")(function* (
1138 nextChannel: DesktopUpdateChannel,
1139 + options?: { readonly minimumVersion?: string | undefined },
1140 ) {
1141 yield* Effect.annotateCurrentSpan({ channel: nextChannel });
1097 - const activeAction = yield* tryStartChannelChange;
1142 + // A background check holds the updater only briefly, so wait it out instead of refusing.
1143 + const activeAction = yield* tryStartChannelChange.pipe(
1144 + Effect.repeat({
1145 + while: (active) => Option.isSome(active) && active.value === "check",
1146 + schedule: Schedule.spaced(CHANNEL_CHANGE_RETRY_DELAY),
1147 + times: CHANNEL_CHANGE_RETRIES,
1148 + }),
1149 + );
1150 if (Option.isSome(activeAction)) {
1151 return yield* new DesktopUpdateActionInProgressError({
1152 action: activeAction.value === "install-recovery" ? "install" : activeAction.value,
@@ -1103,8 +1155,16 @@ export const make = Effect.gen(function* () {
1155 }
1156
1157 return yield* Effect.gen(function* () {
1158 + yield* Ref.set(releaseFloorRef, Option.fromNullishOr(options?.minimumVersion));
1159 const state = yield* Ref.get(updateStateRef);
1107 - if (nextChannel === state.channel) {
1160 + const retained = state.downloadedVersion ?? state.availableVersion;
1161 + // A build from another track re-checks, so retrying a track switch finds an older release.
1162 + // So does a retained offer below the new floor, which must not install.
1163 + if (
1164 + nextChannel === state.channel &&
1165 + nextChannel === desktopUpdateChannelOf(environment.appVersion) &&
1166 + (retained === null || (yield* offerable(retained, state)))
1167 + ) {
1168 return state;
1169 }
1170
@@ -1124,15 +1184,19 @@ export const make = Effect.gen(function* () {
1184 }
1185
1186 yield* applyAutoUpdaterChannel(nextChannel);
1127 - const allowDowngrade = yield* electronUpdater.allowDowngrade;
1128 - yield* electronUpdater.setAllowDowngrade(true);
1129 - yield* checkForUpdates("channel-change", "held").pipe(
1130 - Effect.ensuring(electronUpdater.setAllowDowngrade(allowDowngrade).pipe(Effect.ignore)),
1187 + // Only leaving the running build's track can need an older release.
1188 + yield* checkForUpdates(
1189 + "channel-change",
1190 + "held",
1191 + nextChannel !== desktopUpdateChannelOf(environment.appVersion),
1192 );
1193 return yield* Ref.get(updateStateRef);
1194 }).pipe(Effect.ensuring(finishUpdateAction("channel")));
1195 }),
1135 - check: Effect.fn("desktop.updates.check")(function* (reason: string) {
1196 + check: Effect.fn("desktop.updates.check")(function* (
1197 + reason: string,
1198 + options?: { readonly allowDowngrade?: boolean },
1199 + ) {
1200 yield* Effect.annotateCurrentSpan({ reason });
1201 if (!(yield* Ref.get(updaterConfiguredRef))) {
1202 return {
@@ -1140,7 +1204,7 @@ export const make = Effect.gen(function* () {
1204 state: yield* Ref.get(updateStateRef),
1205 };
1206 }
1143 - const checked = yield* checkForUpdates(reason);
1207 + const checked = yield* checkForUpdates(reason, "acquire", options?.allowDowngrade === true);
1208 return {
1209 checked,
1210 state: yield* Ref.get(updateStateRef),
apps/desktop/src/updates/releaseNotes.ts
+2 -2
@@ -1,6 +1,6 @@
1 import type { DesktopUpdateChannel, DesktopUpdateReleaseNote } from "@t3tools/contracts";
2
3 -import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
3 +import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
4
5 interface ElectronReleaseNoteInfo {
6 readonly version: string;
@@ -134,7 +134,7 @@ export function normalizeDesktopUpdateReleaseNotes(
134 : Array.isArray(releaseNotes)
135 ? releaseNotes.filter(isElectronReleaseNoteInfo)
136 : []
137 - ).filter((entry) => resolveDefaultDesktopUpdateChannel(entry.version) === channel);
137 + ).filter((entry) => desktopUpdateChannelOf(entry.version) === channel);
138
139 const normalizedNotes = rawNotes.flatMap((entry) => {
140 const { items, totalItems } = extractReleaseNoteItems(entry.note);
apps/desktop/src/updates/updateChannels.ts
-7
@@ -1,13 +1,6 @@
1 -import type { DesktopUpdateChannel } from "@t3tools/contracts";
2 -
3 -const NIGHTLY_VERSION_PATTERN = /^[^-+]+-nightly\.\d{8}\.\d+$/;
1 // Preview builds share nightly branding but ship without an update feed.
2 const PRERELEASE_VERSION_PATTERN = /^[^-+]+-(?:nightly|preview)\.\d{8}\.\d+$/;
3
4 export function isNightlyDesktopVersion(version: string): boolean {
5 return PRERELEASE_VERSION_PATTERN.test(version);
6 }
10 -
11 -export function resolveDefaultDesktopUpdateChannel(appVersion: string): DesktopUpdateChannel {
12 - return NIGHTLY_VERSION_PATTERN.test(appVersion) ? "nightly" : "latest";
13 -}
apps/desktop/src/updates/updatesTestHarness.ts
+26 -3
@@ -35,6 +35,11 @@ export interface UpdatesHarnessOptions {
35 readonly platform?: NodeJS.Platform;
36 readonly packageType?: string | undefined;
37 readonly installRecord?: string | undefined;
38 + readonly appVersion?: string;
39 + /** Starts from in-memory settings with this track saved, as after a restart. */
40 + readonly savedChannel?: DesktopAppSettings.DesktopSettings["updateChannel"];
41 + /** Adds a WSL backend beside the primary, as on a Windows host with WSL enabled. */
42 + readonly wslBackend?: boolean;
43 }
44
45 export function makeHarness(options: UpdatesHarnessOptions = {}) {
@@ -42,6 +47,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
47 let quitAndInstallCount = 0;
48 let downloadCount = 0;
49 let allowDowngrade = false;
50 + const checkAllowedDowngrade: boolean[] = [];
51 let fullChangelog = false;
52 const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
53 const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
@@ -86,6 +92,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
92 setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
93 checkForUpdates: Effect.sync(() => {
94 checkCount += 1;
95 + checkAllowedDowngrade.push(allowDowngrade);
96 }).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
97 downloadUpdate: Effect.sync(() => {
98 downloadCount += 1;
@@ -149,7 +156,17 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
156 waitForReady: () => Effect.succeed(true),
157 };
158 const layerBackend = DesktopBackendPool.layerTest(
152 - options.backendInstances ?? [stubBackendInstance],
159 + options.backendInstances ??
160 + (options.wslBackend
161 + ? [
162 + stubBackendInstance,
163 + {
164 + ...stubBackendInstance,
165 + id: DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"),
166 + label: Effect.succeed("Ubuntu"),
167 + },
168 + ]
169 + : [stubBackendInstance]),
170 );
171
172 const layerEnvironment = DesktopEnvironment.layer({
@@ -157,7 +174,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
174 homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
175 platform: options.platform ?? "darwin",
176 processArch: "x64",
160 - appVersion: "1.2.3",
177 + appVersion: options.appVersion ?? "1.2.3",
178 appPath: "/repo",
179 isPackaged: true,
180 resourcesPath: "/missing/resources",
@@ -178,10 +195,13 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
195
196 let testSettings: DesktopAppSettings.DesktopSettings = {
197 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
198 + ...(options.savedChannel === undefined
199 + ? {}
200 + : { updateChannel: options.savedChannel, updateChannelConfiguredByUser: true }),
201 };
202 const setUpdateChannelError = options.setUpdateChannelError;
203 const layerSettings =
184 - setUpdateChannelError || options.beforeSetUpdateChannel
204 + setUpdateChannelError || options.beforeSetUpdateChannel || options.savedChannel
205 ? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
206 get: Effect.sync(() => testSettings),
207 load: Effect.sync(() => testSettings),
@@ -279,6 +299,9 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
299 downloadCount: () => downloadCount,
300 feedUrls: (): ElectronUpdater.ElectronUpdaterFeedUrl[] => feedUrls,
301 fullChangelog: () => fullChangelog,
302 + /** Whether each feed check could offer an older release, and the flag now. */
303 + checkAllowedDowngrade,
304 + allowDowngrade: () => allowDowngrade,
305 listenerCount: () =>
306 Array.from(listeners.values()).reduce(
307 (total, eventListeners) => total + eventListeners.size,
apps/server/src/cloud/selfUpdate.test.ts
+33
@@ -313,3 +313,36 @@ it.layer(NodeServices.layer)("pruning runtimes on start", (it) => {
313 }),
314 );
315 });
316 +
317 +it("a host crosses tracks only to a release that knows its whole database", () => {
318 + const cross = (
319 + serverVersion: string,
320 + targetVersion: string,
321 + targetDatabaseMigration: number | undefined,
322 + databaseMigration = 72,
323 + ) =>
324 + ServerSelfUpdate.trackSwitchBlockReason({
325 + serverVersion,
326 + targetVersion,
327 + targetDatabaseMigration,
328 + databaseMigration: () => databaseMigration,
329 + });
330 + const nightly = "0.1.4-nightly.20261027.3796";
331 +
332 + expect(cross(nightly, "0.1.4", 72)).toBeNull();
333 + // Another client moved this host to a newer Nightly after the switch was planned.
334 + expect(cross(nightly, "0.1.4", 72, 73)).toContain("does not support yet");
335 + expect(cross(nightly, "0.1.4", undefined)).toContain("Cannot confirm");
336 + // A Stable tag can carry a migration the latest Nightly lacks.
337 + expect(cross("0.1.4", nightly, 72, 73)).toContain("does not support yet");
338 + expect(cross("0.1.3", "0.1.4", undefined)).toBeNull();
339 + // A database that exists but cannot be read proves nothing.
340 + expect(
341 + ServerSelfUpdate.trackSwitchBlockReason({
342 + serverVersion: nightly,
343 + targetVersion: "0.1.4",
344 + targetDatabaseMigration: 72,
345 + databaseMigration: () => undefined,
346 + }),
347 + ).toContain("Cannot confirm");
348 +});
apps/server/src/cloud/selfUpdate.ts
+40 -2
@@ -20,11 +20,12 @@ import * as Queue from "effect/Queue";
20 import * as Stream from "effect/Stream";
21 import { HttpClient } from "effect/http";
22
23 -import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease";
23 +import { CLI_RELEASE_BASE_URL_ENV, crossesReleaseTrack } from "@t3tools/shared/cliRelease";
24
25 import packageJson from "../../package.json" with { type: "json" };
26 import * as ServerConfig from "../config.ts";
27 import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
28 +import { databaseMigrationHead } from "../persistence/databaseMigrationHead.ts";
29 import * as ProcessRunner from "../processRunner.ts";
30 import {
31 ensurePinnedRuntimeInstalled,
@@ -93,6 +94,26 @@ export const pruneRuntimesOnStart = Effect.fn("cloud.server_self_update.prune_on
94 },
95 );
96
97 +/** The client checks this when planning; the host checks again because its database may have
98 + * moved on since (another client updated it). Stable and Nightly each build their own commits,
99 + * so crossing tracks needs the target release to know every migration this database holds. */
100 +export function trackSwitchBlockReason(input: {
101 + readonly serverVersion: string;
102 + readonly targetVersion: string;
103 + readonly targetDatabaseMigration: number | undefined;
104 + /** Read only for a crossing; undefined when the database cannot be read. */
105 + readonly databaseMigration: () => number | undefined;
106 +}): string | null {
107 + if (!crossesReleaseTrack(input.serverVersion, input.targetVersion)) return null;
108 + const databaseMigration = input.databaseMigration();
109 + if (input.targetDatabaseMigration === undefined || databaseMigration === undefined) {
110 + return `Cannot confirm this database works with t3@${input.targetVersion}. Switch tracks from Settings → About → Update track, which checks it first.`;
111 + }
112 + return input.targetDatabaseMigration < databaseMigration
113 + ? `This database has changes t3@${input.targetVersion} does not support yet; it stays on this release.`
114 + : null;
115 +}
116 +
117 export const make = Effect.fn("cloud.server_self_update.make")(function* () {
118 const serverConfig = yield* ServerConfig.ServerConfig;
119 const desktopAppUpdate = yield* DesktopAppUpdate.DesktopAppUpdate;
@@ -119,12 +140,27 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
140 ? new ServerSelfUpdateError({ reason })
141 : new ServerSelfUpdateError({ reason, cause });
142
143 + const crossesTrackUnsafely = (input: ServerSelfUpdateInput) =>
144 + trackSwitchBlockReason({
145 + serverVersion: packageJson.version,
146 + targetVersion: input.targetVersion,
147 + targetDatabaseMigration: input.targetDatabaseMigration,
148 + databaseMigration: () => databaseMigrationHead(serverConfig.dbPath),
149 + });
150 +
151 const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
152 "cloud.server_self_update.update",
153 )(function* (input, reportProgress = () => Effect.void, onHandoffAccepted = () => Effect.void) {
154 if (capability === "desktop-managed") {
155 + const unsafeCrossing = input.channel === undefined ? null : crossesTrackUnsafely(input);
156 + if (unsafeCrossing !== null) return yield* failWith(unsafeCrossing);
157 if (desktopAppUpdate.available) {
127 - return yield* desktopAppUpdate.run(reportProgress);
158 + return yield* desktopAppUpdate.run(
159 + reportProgress,
160 + input.channel === undefined
161 + ? undefined
162 + : { channel: input.channel, targetVersion: input.targetVersion },
163 + );
164 }
165 return yield* failWith(
166 "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* () {
172 );
173 }
174
175 + const unsafeCrossing = crossesTrackUnsafely(input);
176 + if (unsafeCrossing !== null) return yield* failWith(unsafeCrossing);
177 const targetVersion = input.targetVersion.trim();
178 if (!isExactServiceVersion(targetVersion)) {
179 return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
apps/server/src/cloud/servicePreflight.test.ts
+58
@@ -1,4 +1,16 @@
1 +import * as NodeSqlite from "node:sqlite";
2 +
3 +import * as NodeServices from "@effect/platform-node/NodeServices";
4 import { expect, it } from "@effect/vitest";
5 +import * as Effect from "effect/Effect";
6 +import * as FileSystem from "effect/FileSystem";
7 +import * as Path from "effect/Path";
8 +
9 +import {
10 + BUILD_MIGRATION_HEAD,
11 + databaseMigrationHead,
12 +} from "../persistence/databaseMigrationHead.ts";
13 +import { migrationManifest } from "../persistence/Migrations.ts";
14
15 import { runServicePreflight } from "./servicePreflight.ts";
16 import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
@@ -20,3 +32,49 @@ it.each([1])("blocks legacy launcher protocol %i with exact recovery steps", (la
32 expect(reason).toContain("t3 --version");
33 expect(reason).toContain("which -a t3");
34 });
35 +
36 +it.layer(NodeServices.layer)("service preflight database", (it) => {
37 + it.effect("blocks a database that a newer build migrated", () =>
38 + Effect.gen(function* () {
39 + const fs = yield* FileSystem.FileSystem;
40 + const path = yield* Path.Path;
41 + const databasePath = path.join(
42 + yield* fs.makeTempDirectoryScoped({ prefix: "t3-preflight-" }),
43 + "state.sqlite",
44 + );
45 + const db = new NodeSqlite.DatabaseSync(databasePath);
46 + db.exec("CREATE TABLE effect_sql_migrations (migration_id INTEGER PRIMARY KEY, name TEXT)");
47 + const insert = db.prepare("INSERT INTO effect_sql_migrations VALUES (?, ?)");
48 + for (const [id, name] of migrationManifest) insert.run(id, name);
49 + const preflight = () =>
50 + runServicePreflight({ databasePath, launcherProtocol: SERVICE_LAUNCHER_PROTOCOL });
51 +
52 + expect(preflight().status).toBe("ready");
53 + expect(databaseMigrationHead(databasePath)).toBe(BUILD_MIGRATION_HEAD);
54 +
55 + const newerId = Math.max(...migrationManifest.map(([id]) => id)) + 1;
56 + insert.run(newerId, "FromNightly");
57 + db.close();
58 + const result = preflight();
59 + expect(result.status).toBe("blocked");
60 + expect(result.status === "blocked" ? result.reason : "").toContain(`${newerId}_FromNightly`);
61 + // Servers report this head, so clients see a database a newer build migrated.
62 + expect(databaseMigrationHead(databasePath)).toBe(newerId);
63 +
64 + // A database that exists but cannot be read has an unknown history, so it blocks.
65 + const unreadable = path.join(path.dirname(databasePath), "unreadable.sqlite");
66 + yield* fs.writeFileString(unreadable, "not a database");
67 + expect(databaseMigrationHead(unreadable)).toBeUndefined();
68 + expect(
69 + runServicePreflight({
70 + databasePath: unreadable,
71 + launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
72 + }).status,
73 + ).toBe("blocked");
74 + // A missing database is a fresh install.
75 + expect(databaseMigrationHead(path.join(path.dirname(databasePath), "missing.sqlite"))).toBe(
76 + BUILD_MIGRATION_HEAD,
77 + );
78 + }),
79 + );
80 +});
apps/server/src/cloud/servicePreflight.ts
+26
@@ -1,4 +1,5 @@
1 import packageJson from "../../package.json" with { type: "json" };
2 +import { BUILD_MIGRATION_HEAD, recordedMigrations } from "../persistence/databaseMigrationHead.ts";
3 import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
4
5 export type ServicePreflightResult =
@@ -34,9 +35,34 @@ export function runServicePreflight(input: {
35 };
36 }
37
38 + const newer = newerRecordedMigrations(input.databasePath);
39 + if (newer === null) {
40 + return {
41 + status: "blocked",
42 + version,
43 + reason: `Could not read this database to confirm t3@${version} supports it.`,
44 + };
45 + }
46 + if (newer.length > 0) {
47 + return {
48 + status: "blocked",
49 + version,
50 + 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.`,
51 + };
52 + }
53 +
54 return { status: "ready", version, launcherProtocol: SERVICE_LAUNCHER_PROTOCOL };
55 }
56
57 +/** Migrations a newer build recorded, or null when the database exists but cannot be read.
58 + * Startup already handles renamed ids this build knows. */
59 +function newerRecordedMigrations(databasePath: string): ReadonlyArray<string> | null {
60 + const recorded = recordedMigrations(databasePath);
61 + return recorded === null
62 + ? null
63 + : recorded.filter(({ id }) => id > BUILD_MIGRATION_HEAD).map(({ id, name }) => `${id}_${name}`);
64 +}
65 +
66 export function decodeServicePreflightResult(value: unknown): ServicePreflightResult | undefined {
67 if (typeof value !== "object" || value === null) {
68 return undefined;
apps/server/src/desktopUpdate/DesktopAppUpdate.test.ts
+18
@@ -132,6 +132,24 @@ it.layer(NodeServices.layer)("desktop app update", (it) => {
132 }),
133 );
134
135 + it.effect("succeeds without an install when a track switch finds the host current", () =>
136 + Effect.gen(function* () {
137 + const { service } = yield* makeHarness({
138 + reports: (requestId) => [
139 + report(requestId, makeState({ status: "up-to-date", currentVersion: "1.2.3" }), {
140 + outcome: "up-to-date",
141 + }),
142 + ],
143 + });
144 + const trackSwitch = { channel: "latest" as const, targetVersion: "1.2.3" };
145 +
146 + expect(yield* service.run(() => Effect.void, trackSwitch)).toEqual({
147 + targetVersion: "1.2.3",
148 + method: "desktop-app",
149 + });
150 + }),
151 + );
152 +
153 it.effect("replays a retained commit failure for the preparation token", () =>
154 Effect.gen(function* () {
155 const { service } = yield* makeHarness({
apps/server/src/desktopUpdate/DesktopAppUpdate.ts
+15 -3
@@ -44,6 +44,7 @@ export class DesktopAppUpdate extends Context.Service<
44 reportProgress: (
45 stage: ServerSelfUpdateProgressStage,
46 ) => Effect.Effect<void, ServerSelfUpdateError>,
47 + trackSwitch?: DesktopTelemetryReceiver.DesktopTrackSwitch,
48 ) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
49 /** Success stops the server; returns only on installation failure or timeout. */
50 readonly commit: (
@@ -71,6 +72,7 @@ export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* (
72 reportProgress: (
73 stage: ServerSelfUpdateProgressStage,
74 ) => Effect.Effect<void, ServerSelfUpdateError>,
75 + trackSwitch: boolean,
76 ) {
77 const lastStage = yield* Ref.make<ServerSelfUpdateProgressStage | null>(null);
78 const emitStage = (
@@ -122,6 +124,11 @@ export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* (
124 return { targetVersion, method: "desktop-app" as const, desktopUpdateToken: requestId };
125 }
126 if (report.outcome === "up-to-date") {
127 + // A switch's host already on the newest build of its track only saved the track.
128 + if (trackSwitch) {
129 + yield* Ref.set(inFlight, false);
130 + return { targetVersion: report.state.currentVersion, method: "desktop-app" as const };
131 + }
132 return yield* failWith(
133 `The T3 Code desktop app on this machine is already up to date on ${report.state.currentVersion}.`,
134 );
@@ -132,7 +139,7 @@ export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* (
139 });
140
141 const run: DesktopAppUpdate["Service"]["run"] = Effect.fn("desktopUpdate.desktopAppUpdate.run")(
135 - function* (reportProgress) {
142 + function* (reportProgress, trackSwitch) {
143 if (!available) {
144 return yield* failWith(
145 "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* (
161 // Subscribe before requesting to catch fast reports.
162 const { changes } = yield* receiver.desktopUpdates;
163 yield* receiver
157 - .requestDesktopUpdate(requestId)
164 + .requestDesktopUpdate(requestId, trackSwitch)
165 .pipe(
166 Effect.mapError((error) =>
167 failWith("Could not reach the T3 Code desktop app on this machine.", error),
168 ),
169 );
163 - return yield* consumeReports(requestId, changes, reportProgress).pipe(
170 + return yield* consumeReports(
171 + requestId,
172 + changes,
173 + reportProgress,
174 + trackSwitch !== undefined,
175 + ).pipe(
176 Effect.onInterrupt(() => receiver.cancelDesktopUpdate(requestId).pipe(Effect.ignore)),
177 );
178 }),
apps/server/src/environment/ServerEnvironment.ts
+4 -1
@@ -20,6 +20,7 @@ import { readAgentActivityPublishingActive } from "../cloud/config.ts";
20 import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";
21 import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
22 import * as ServerConfig from "../config.ts";
23 +import { databaseMigrationHead } from "../persistence/databaseMigrationHead.ts";
24 import * as ProcessRunner from "../processRunner.ts";
25 import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
26 import { detectServerEnvironmentMachineKind } from "./ServerEnvironmentMachine.ts";
@@ -203,6 +204,7 @@ export const make = Effect.gen(function* () {
204 const desktopAppUpdate =
205 serverSelfUpdate === "desktop-managed" && serverConfig.desktopTelemetryControlFd !== undefined;
206
207 + const databaseMigration = databaseMigrationHead(serverConfig.dbPath);
208 const descriptor: ExecutionEnvironmentDescriptor = {
209 environmentId,
210 label,
@@ -213,6 +215,7 @@ export const make = Effect.gen(function* () {
215 },
216 serverVersion: packageJson.version,
217 orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
218 + ...(databaseMigration === undefined ? {} : { databaseMigration }),
219 capabilities: {
220 repositoryIdentity: true,
221 connectionProbe: true,
@@ -266,7 +269,7 @@ export const make = Effect.gen(function* () {
269 ...(serverSelfUpdate === "boot-service" || desktopAppUpdate
270 ? { serverSelfUpdateProgress: true }
271 : {}),
269 - ...(desktopAppUpdate ? { desktopAppUpdate: true } : {}),
272 + ...(desktopAppUpdate ? { desktopAppUpdate: true, desktopAppChannelSwitch: true } : {}),
273 serverBrowser: true,
274 peerLinks: true,
275 mcpModeLimitHeader: true,
apps/server/src/persistence/Migrations.test.ts
+20
@@ -1,7 +1,10 @@
1 import { assert, describe, it } from "@effect/vitest";
2 import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
3 +import * as NodeServices from "@effect/platform-node/NodeServices";
4 import * as Effect from "effect/Effect";
5 import * as Exit from "effect/Exit";
6 +import * as FileSystem from "effect/FileSystem";
7 +import * as Path from "effect/Path";
8 import * as SqlClient from "effect/sql/SqlClient";
9
10 import { migrationManifest, runMigrations } from "./Migrations.ts";
@@ -123,3 +126,20 @@ describe("runMigrations", () => {
126 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
127 );
128 });
129 +
130 +// The npm launcher reads the highest migration id from these file names.
131 +it.effect("registers every migration file", () =>
132 + Effect.gen(function* () {
133 + const fs = yield* FileSystem.FileSystem;
134 + const path = yield* Path.Path;
135 + const dir = path.join(import.meta.dirname, "Migrations");
136 + const files = (yield* fs.readDirectory(dir)).flatMap((name) => {
137 + const match = /^(\d+)_(\w+)\.ts$/.exec(name);
138 + return match ? [[Number(match[1]), match[2]] as const] : [];
139 + });
140 + assert.deepStrictEqual(
141 + files.toSorted(([a], [b]) => a - b),
142 + migrationManifest,
143 + );
144 + }).pipe(Effect.provide(NodeServices.layer)),
145 +);
apps/server/src/persistence/databaseMigrationHead.ts new
+49
@@ -0,0 +1,49 @@
1 +// @effect-diagnostics nodeBuiltinImport:off - read synchronously by the preflight subprocess and at startup.
2 +import * as NodeFS from "node:fs";
3 +import * as NodeSqlite from "node:sqlite";
4 +
5 +import { migrationManifest } from "./Migrations.ts";
6 +
7 +export const BUILD_MIGRATION_HEAD = Math.max(...migrationManifest.map(([id]) => id));
8 +
9 +/** Migrations the database records, read-only. A missing or new database records none; one that
10 + * exists but cannot be read is null, since its history is unknown. */
11 +export function recordedMigrations(
12 + databasePath: string,
13 +): ReadonlyArray<{ readonly id: number; readonly name: string }> | null {
14 + let db: NodeSqlite.DatabaseSync;
15 + try {
16 + db = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
17 + } catch {
18 + return NodeFS.existsSync(databasePath) ? null : [];
19 + }
20 + try {
21 + const hasTable = db
22 + .prepare(
23 + "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations'",
24 + )
25 + .get();
26 + if (hasTable === undefined) return [];
27 + return db
28 + .prepare("SELECT migration_id, name FROM effect_sql_migrations ORDER BY migration_id")
29 + .all()
30 + .map((row) => ({ id: Number(row.migration_id), name: String(row.name) }));
31 + } catch {
32 + return null;
33 + } finally {
34 + try {
35 + db.close();
36 + } catch {
37 + // A read-only handle has nothing to flush; the result above already stands.
38 + }
39 + }
40 +}
41 +
42 +/** Highest migration the database holds once this build's startup migrations have run. A newer
43 + * build may have recorded more than this build knows. Undefined when the database is unreadable. */
44 +export function databaseMigrationHead(databasePath: string): number | undefined {
45 + const recorded = recordedMigrations(databasePath);
46 + return recorded === null
47 + ? undefined
48 + : Math.max(BUILD_MIGRATION_HEAD, ...recorded.map(({ id }) => id));
49 +}
apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts
+10 -1
@@ -8,6 +8,7 @@ import {
8 type DesktopHostTelemetryMessage as DesktopHostTelemetryMessageValue,
9 type DesktopHostTelemetrySnapshot,
10 DesktopTelemetryControlMessage,
11 + type DesktopUpdateChannel,
12 type DesktopUpdateStatusReport,
13 type ResourceTelemetrySourceStatus,
14 } from "@t3tools/contracts";
@@ -149,6 +150,12 @@ export interface DesktopTelemetryReceiverHealth {
150 readonly lastError: Option.Option<string>;
151 }
152
153 +/** Moves the desktop app to `channel` and installs only `targetVersion`. */
154 +export interface DesktopTrackSwitch {
155 + readonly channel: DesktopUpdateChannel;
156 + readonly targetVersion: string;
157 +}
158 +
159 export class DesktopTelemetryReceiver extends Context.Service<
160 DesktopTelemetryReceiver,
161 {
@@ -176,6 +183,7 @@ export class DesktopTelemetryReceiver extends Context.Service<
183 ) => Effect.Effect<void, DesktopTelemetryControlError>;
184 readonly requestDesktopUpdate: (
185 requestId: string,
186 + trackSwitch?: DesktopTrackSwitch,
187 ) => Effect.Effect<void, DesktopTelemetryControlError>;
188 readonly commitDesktopUpdate: (
189 requestId: string,
@@ -633,11 +641,12 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
641 subscribeHealth: subscribeBeforeSnapshotWithoutMutex(healthChanges, Ref.get(health)),
642 setDiagnosticsDemand,
643 requestDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.requestDesktopUpdate")(
636 - function (requestId) {
644 + function (requestId, trackSwitch) {
645 return sendControlMessage({
646 version: 1,
647 type: "requestDesktopUpdate",
648 requestId,
649 + ...trackSwitch,
650 });
651 },
652 ),
apps/web/src/components/ServerUpdateAction.browser.test.tsx
+25
@@ -14,6 +14,7 @@ const testState = vi.hoisted(() => ({
14 toast: vi.fn(),
15 clipboard: vi.fn(),
16 sessionAtom: null as unknown,
17 + serverVersions: new Map<string, string>(),
18 }));
19
20 vi.mock(import("~/hooks/useCopyToClipboard"), async (original) => ({
@@ -36,6 +37,16 @@ vi.mock(import("~/state/session"), async (original) => {
37 },
38 };
39 });
40 +vi.mock(import("~/state/entities"), async (original) => ({
41 + ...(await original()),
42 + useServerConfigs: (() =>
43 + new Map(
44 + [...testState.serverVersions].map(([id, serverVersion]) => [
45 + id,
46 + { environment: { serverVersion } },
47 + ]),
48 + )) as never,
49 +}));
50 vi.mock(import("~/state/use-atom-command"), async (original) => ({
51 ...(await original()),
52 useAtomCommand: (() => testState.updateServer) as never,
@@ -84,6 +95,7 @@ function setup(): Disposable {
95 testState.updateServer.mockReset();
96 testState.toast.mockReset();
97 testState.clipboard.mockReset();
98 + testState.serverVersions.clear();
99 sessionAtom = Atom.make<SessionResult>(AsyncResult.success(currentSession));
100 testState.sessionAtom = sessionAtom;
101 resetConfirmDialogForTests();
@@ -212,4 +224,17 @@ describe("ServerUpdatesAction", () => {
224 );
225 expect(button(screen, "Update all")!.disabled).toBe(false);
226 });
227 +
228 + it("skips a machine whose update would cross Stable and Nightly", async () => {
229 + using _state = setup();
230 + testState.serverVersions.set("batch-a", "0.0.30-nightly.20261001.1");
231 + testState.updateServer.mockResolvedValue(success());
232 + await using screen = await mount();
233 + await click(screen, "Update all");
234 +
235 + expect(testState.updateServer).toHaveBeenCalledTimes(1);
236 + expect(testState.toast).toHaveBeenCalledWith(
237 + expect.objectContaining({ type: "success", title: "Office updated" }),
238 + );
239 + });
240 });
apps/web/src/components/ServerUpdateAction.tsx
+51 -2
@@ -7,6 +7,7 @@ import {
7 import type { AsyncResult } from "effect/reactivity";
8 import { environmentSession } from "~/state/session";
9 import type {
10 + DesktopUpdateChannel,
11 EnvironmentId,
12 ServerInstallation,
13 ServerSelfUpdateCapability,
@@ -26,6 +27,8 @@ import { serverEnvironment, updateOutdatedServer } from "~/state/server";
27 import { appAtomRegistry } from "~/rpc/atomRegistry";
28 import { useAtomCommand } from "~/state/use-atom-command";
29 import { manualServerUpdateCommand } from "~/versionSkew";
30 +import { useServerConfigs } from "~/state/entities";
31 +import { crossesReleaseTrack } from "@t3tools/shared/cliRelease";
32 import { Button } from "./ui/button";
33 import { toastManager } from "./ui/toast";
34 import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
@@ -41,6 +44,29 @@ export function serverUpdateStageLabel(stage: ServerUpdateStage): string {
44 return UPDATE_STAGE_LABELS[stage];
45 }
46
47 +const CROSS_TRACK_NOTE = "Switch tracks in About → Update track";
48 +
49 +/** Hosts refuse a Stable/Nightly crossing outside a track switch, which checks the database first. */
50 +function refusedCrossing(
51 + target: {
52 + readonly selfUpdate: ServerSelfUpdateCapability | null;
53 + readonly targetVersion: string;
54 + readonly channel?: DesktopUpdateChannel | undefined;
55 + },
56 + serverVersion: string | undefined,
57 +): boolean {
58 + return (
59 + target.channel === undefined &&
60 + target.selfUpdate !== null &&
61 + serverVersion !== undefined &&
62 + crossesReleaseTrack(serverVersion, target.targetVersion)
63 + );
64 +}
65 +
66 +function CrossTrackNote() {
67 + return <span className="text-muted-foreground text-xs">{CROSS_TRACK_NOTE}</span>;
68 +}
69 +
70 function updateFailureMessage(error: unknown): string {
71 return error instanceof Error ? error.message : "Server update failed.";
72 }
@@ -52,6 +78,12 @@ export interface ServerUpdateTarget {
78 readonly installation?: ServerInstallation | undefined;
79 readonly desktopAppUpdate?: boolean;
80 readonly targetVersion: string;
81 + /** Set only by a track switch; the host's desktop app moves to this track. */
82 + readonly channel?: DesktopUpdateChannel;
83 + /** A track switch's checked release migration; the host re-checks its own database. */
84 + readonly targetDatabaseMigration?: number;
85 + /** The host already runs its track's newest build and only saves the track. */
86 + readonly trackOnly?: boolean;
87 }
88
89 type UpdateButtonProps = Pick<ComponentProps<typeof Button>, "variant" | "size" | "className"> & {
@@ -79,7 +111,13 @@ export function useServerUpdate() {
111 pendingUpdateEnvironmentIds.add(environmentId);
112 const result = await updateServer({
113 environmentId,
82 - input: { targetVersion },
114 + input: {
115 + targetVersion,
116 + ...(target.channel === undefined ? {} : { channel: target.channel }),
117 + ...(target.targetDatabaseMigration === undefined
118 + ? {}
119 + : { targetDatabaseMigration: target.targetDatabaseMigration }),
120 + },
121 });
122 pendingUpdateEnvironmentIds.delete(environmentId);
123 if (result._tag === "Failure") {
@@ -118,12 +156,14 @@ export function ServerUpdatesAction({
156 readonly targets: ReadonlyArray<ServerUpdateTarget>;
157 }) {
158 const update = useServerUpdate();
159 + const serverConfigs = useServerConfigs();
160 const pending = useRef(false);
161 const [isPending, setIsPending] = useState(false);
162 const eligible = targets.filter(
163 (target) =>
164 target.selfUpdate !== null &&
126 - (target.selfUpdate !== "desktop-managed" || target.desktopAppUpdate),
165 + (target.selfUpdate !== "desktop-managed" || target.desktopAppUpdate) &&
166 + !refusedCrossing(target, serverConfigs.get(target.environmentId)?.environment.serverVersion),
167 );
168 const handleUpdate = async () => {
169 if (pending.current) return;
@@ -198,6 +238,7 @@ export function ServerUpdateAction({
238 installation,
239 desktopAppUpdate = false,
240 targetVersion,
241 + channel,
242 label = "Update",
243 variant = "outline",
244 size = "xs",
@@ -205,6 +246,7 @@ export function ServerUpdateAction({
246 appearance = "button",
247 }: ServerUpdateTarget & UpdateButtonProps) {
248 const isDesktopAppUpdate = selfUpdate === "desktop-managed";
249 + const serverVersion = useServerConfigs().get(environmentId)?.environment.serverVersion;
250 const sessionStateAtom = environmentSession.sessionStateAtom(environmentId);
251 const canUpdate = canUpdateServer(useAtomValue(sessionStateAtom));
252 const update = useServerUpdate();
@@ -264,6 +306,10 @@ export function ServerUpdateAction({
306 );
307 }
308
309 + if (refusedCrossing({ selfUpdate, targetVersion, channel }, serverVersion)) {
310 + return <CrossTrackNote />;
311 + }
312 +
313 const manualCommand =
314 selfUpdate === null ? manualServerUpdateCommand(targetVersion, installation) : null;
315 const actionLabel =
@@ -351,6 +397,9 @@ export function OutdatedServerUpdateAction({
397 description: `Reconnected on t3@${result.value.targetVersion}.`,
398 });
399 };
400 + if (fromVersion !== undefined && crossesReleaseTrack(fromVersion, targetVersion)) {
401 + return <CrossTrackNote />;
402 + }
403 return (
404 <Button size="xs" variant="outline" onClick={() => void handleUpdate()}>
405 {label}
apps/web/src/components/settings/SettingsPanels.tsx
+68 -36
@@ -1,3 +1,4 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 import { NotificationSettings } from "./NotificationSettings";
3 import { PRIVACY_POLICY_URL } from "../../legalLinks";
4 import { CheckIcon } from "lucide-react";
@@ -20,6 +21,7 @@ import {
21 type QuitConfirmationMode,
22 SidebarProjectSortOrder,
23 } from "@t3tools/contracts/settings";
24 +import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
25 import { createModelSelection } from "@t3tools/shared/model";
26 import * as Equal from "effect/Equal";
27 import * as Schema from "effect/Schema";
@@ -64,7 +66,7 @@ import {
66 import { providerInstanceEntriesFor } from "../../providerInstances";
67 import { ensureLocalApi, readLocalApi } from "../../localApi";
68 import { isMacPlatform } from "../../lib/utils";
67 -import { useEnvironmentProviders } from "../../state/environments";
69 +import { useEnvironmentProviders, useEnvironments } from "../../state/environments";
70 import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
71 import { Button } from "../ui/button";
72 import { DraftInput } from "../ui/draft-input";
@@ -95,6 +97,13 @@ import { BackgroundActivitySettingsRow } from "./BackgroundActivitySettings";
97 import { AdvancedSettings } from "./AdvancedSettings";
98 import { PullRequestLinksOpenInAppSetting } from "./IntegrationsSettings";
99 import { StorageCleanupSections } from "./StorageSettings";
100 +import { UpdateTrackSwitchDialog } from "./UpdateTrackSwitchDialog";
101 +import { environmentIdsKey } from "~/state/environmentAtomList";
102 +import { environmentSessionStatesAtom } from "~/state/session";
103 +import { canUpdateServer } from "../ServerUpdateAction";
104 +import { useUpdateEverythingRun } from "../sidebar/updateEverythingRun";
105 +import { awaitsTrackSwitch, channelSwitchLabel } from "../sidebar/updateEverything.logic";
106 +import { isHostedByThisApp } from "../sidebar/useUpdateEverything";
107
108 const RESPONSE_STREAMING_MODE_LABELS: Record<ResponseStreamingMode, string> = {
109 turn: "Wait for the full response",
@@ -142,39 +151,38 @@ function AboutVersionTitle() {
151
152 function AboutVersionSection() {
153 const updateState = useDesktopUpdateState();
145 - const [isChangingUpdateChannel, setIsChangingUpdateChannel] = useState(false);
154 + const [switchChannel, setSwitchChannel] = useState<DesktopUpdateChannel | null>(null);
155 const [isUpdateActionPending, setIsUpdateActionPending] = useState(false);
156 + const { environments } = useEnvironments();
157 + const sessionStates = useAtomValue(
158 + environmentSessionStatesAtom(
159 + environmentIdsKey(environments.map(({ environmentId }) => environmentId)),
160 + ),
161 + );
162 + // A second run would replace the first run's progress and local download.
163 + const updateRun = useUpdateEverythingRun();
164
165 const hasDesktopBridge = typeof window !== "undefined" && Boolean(window.desktopBridge);
166 const selectedUpdateChannel = updateState?.channel ?? "latest";
167 const selectedHostedAppChannel = hasDesktopBridge ? null : HOSTED_APP_CHANNEL;
151 -
152 - const handleUpdateChannelChange = (channel: DesktopUpdateChannel) => {
153 - const bridge = window.desktopBridge;
154 - if (
155 - !bridge ||
156 - typeof bridge.setUpdateChannel !== "function" ||
157 - channel === selectedUpdateChannel
158 - ) {
159 - return;
160 - }
161 -
162 - setIsChangingUpdateChannel(true);
163 - void bridge
164 - .setUpdateChannel(channel)
165 - .catch((error: unknown) => {
166 - toastManager.add(
167 - stackedThreadToast({
168 - type: "error",
169 - title: "Could not change update track",
170 - description: error instanceof Error ? error.message : "Update track change failed.",
171 - }),
172 - );
173 - })
174 - .finally(() => {
175 - setIsChangingUpdateChannel(false);
176 - });
177 - };
168 + // A switch that failed part way leaves this app or a server on the other track.
169 + // With its updater off, a switch cannot move this app, so it is not counted.
170 + const appOffTrack =
171 + updateState?.enabled !== false && desktopUpdateChannelOf(APP_VERSION) !== selectedUpdateChannel;
172 + const unswitchedMachines =
173 + (appOffTrack ? 1 : 0) +
174 + environments.filter(
175 + (environment, index) =>
176 + environment.connection.phase === "connected" &&
177 + canUpdateServer(sessionStates[index]!) &&
178 + awaitsTrackSwitch(
179 + {
180 + serverConfig: environment.serverConfig,
181 + hostedByThisApp: isHostedByThisApp(environment),
182 + },
183 + selectedUpdateChannel,
184 + ),
185 + ).length;
186
187 const handleButtonClick = async () => {
188 const bridge = window.desktopBridge;
@@ -272,7 +280,8 @@ function AboutVersionSection() {
280 const statusLabel: Record<string, string> = {
281 checking: "Checking…",
282 downloading: "Downloading…",
275 - "up-to-date": "Up to Date",
283 + // Off its track, "up to date" only means no switch is pending; Review moves it.
284 + ...(appOffTrack ? {} : { "up-to-date": "Up to Date" }),
285 };
286 const buttonLabel =
287 actionLabel[action] ?? statusLabel[updateState?.status ?? ""] ?? "Check for Updates";
@@ -308,23 +317,43 @@ function AboutVersionSection() {
317 {hasDesktopBridge ? (
318 <SettingsRow
319 {...searchableSetting("update-track")}
311 - description="Use stable releases or nightly builds. Switch back anytime."
320 + description={
321 + unswitchedMachines > 0 ? (
322 + <>
323 + {unswitchedMachines === 1
324 + ? "1 machine still runs"
325 + : `${unswitchedMachines} machines still run`}{" "}
326 + {channelSwitchLabel(selectedUpdateChannel === "nightly" ? "latest" : "nightly")}.{" "}
327 + {/* The dialog moves what it can and says why it skips the rest. */}
328 + <Button
329 + size="xs"
330 + variant="link"
331 + disabled={updateRun !== null}
332 + onClick={() => setSwitchChannel(selectedUpdateChannel)}
333 + >
334 + Review
335 + </Button>
336 + </>
337 + ) : (
338 + "Switches this app and every connected machine whose database the target release supports."
339 + )
340 + }
341 control={
342 <Select
343 value={selectedUpdateChannel}
344 onValueChange={(value) => {
316 - handleUpdateChannelChange(value as DesktopUpdateChannel);
345 + if (value !== selectedUpdateChannel) {
346 + setSwitchChannel(value as DesktopUpdateChannel);
347 + }
348 }}
349 >
350 <SelectTrigger
351 size="sm"
352 className="w-full sm:w-40"
353 aria-label="Update track"
323 - disabled={isChangingUpdateChannel}
354 + disabled={switchChannel !== null || updateRun !== null}
355 >
325 - <SelectValue>
326 - {selectedUpdateChannel === "nightly" ? "Nightly" : "Stable"}
327 - </SelectValue>
356 + <SelectValue>{channelSwitchLabel(selectedUpdateChannel)}</SelectValue>
357 </SelectTrigger>
358 <SelectPopup align="end" alignItemWithTrigger={false}>
359 <SelectItem hideIndicator value="latest">
@@ -367,6 +396,9 @@ function AboutVersionSection() {
396 />
397 ) : null}
398 {hasDesktopBridge ? <CliCommandSettingsRow /> : null}
399 + {switchChannel === null ? null : (
400 + <UpdateTrackSwitchDialog channel={switchChannel} onClose={() => setSwitchChannel(null)} />
401 + )}
402 </>
403 );
404 }
apps/web/src/components/settings/UpdateTrackSwitchDialog.tsx new
+178
@@ -0,0 +1,178 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3 +import type { DesktopUpdateChannel } from "@t3tools/contracts";
4 +import { acceptsTrackSwitchRelease, desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
5 +import { isMacPlatform } from "@t3tools/shared/keybindings";
6 +import { useState } from "react";
7 +import { AsyncResult } from "effect/reactivity";
8 +
9 +import { APP_VERSION } from "~/branding";
10 +import { useDesktopUpdateState } from "~/state/desktopUpdate";
11 +import { useEnvironments } from "~/state/environments";
12 +import { npmReleaseAtom } from "~/state/npmRelease";
13 +import { downloadLocalUpdate, installLocalUpdate } from "../sidebar/SidebarUpdatePill";
14 +import { UpdateEverythingDialog } from "../sidebar/UpdateEverythingDialog";
15 +import {
16 + channelSwitchLabel,
17 + localSwitchBlockReason,
18 + type ChannelSwitchRelease,
19 +} from "../sidebar/updateEverything.logic";
20 +import { isHostedByThisApp, useUpdateEverything } from "../sidebar/useUpdateEverything";
21 +import { prepareLocalTrackSwitch } from "./updateTrackSwitch.logic";
22 +import {
23 + AlertDialog,
24 + AlertDialogClose,
25 + AlertDialogDescription,
26 + AlertDialogFooter,
27 + AlertDialogHeader,
28 + AlertDialogPopup,
29 + AlertDialogTitle,
30 +} from "../ui/alert-dialog";
31 +import { Button } from "../ui/button";
32 +import { stackedThreadToast, toastManager } from "../ui/toast";
33 +
34 +/** Moves this app and every connected machine to `channel`. */
35 +export function UpdateTrackSwitchDialog({
36 + channel,
37 + onClose,
38 +}: {
39 + readonly channel: DesktopUpdateChannel;
40 + readonly onClose: () => void;
41 +}) {
42 + // npm dist-tags match the desktop channel names.
43 + const release = useAtomValue(npmReleaseAtom(channel));
44 + if (AsyncResult.isSuccess(release) && release.value !== null) {
45 + return <SwitchPlan release={{ channel, ...release.value }} onClose={onClose} />;
46 + }
47 + const label = channelSwitchLabel(channel);
48 + return (
49 + <AlertDialog open onOpenChange={(open) => !open && onClose()}>
50 + <AlertDialogPopup>
51 + <AlertDialogHeader>
52 + <AlertDialogTitle>Switch to {label}</AlertDialogTitle>
53 + <AlertDialogDescription>
54 + {AsyncResult.isFailure(release) || AsyncResult.isSuccess(release)
55 + ? `Could not find the latest ${label} release on npm. Try again later.`
56 + : "Checking releases…"}
57 + </AlertDialogDescription>
58 + </AlertDialogHeader>
59 + <AlertDialogFooter>
60 + <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
61 + </AlertDialogFooter>
62 + </AlertDialogPopup>
63 + </AlertDialog>
64 + );
65 +}
66 +
67 +function SwitchPlan({
68 + release,
69 + onClose,
70 +}: {
71 + readonly release: ChannelSwitchRelease;
72 + readonly onClose: () => void;
73 +}) {
74 + const updateState = useDesktopUpdateState();
75 + const { environments } = useEnvironments();
76 + const crossesLocal = desktopUpdateChannelOf(APP_VERSION) !== release.channel;
77 + // With its updater off (a .deb install, or no feed) this app stays put and only remotes move.
78 + const updatesOff = updateState?.enabled === false;
79 + // After a partial switch this app may already be on the track; then only remotes move.
80 + const switchesLocal = crossesLocal && !updatesOff;
81 + const [checking, setChecking] = useState(false);
82 + const everything = useUpdateEverything(switchesLocal ? release.version : null, release);
83 + const label = channelSwitchLabel(release.channel);
84 + // This app's reinstall restarts every server it hosts, so each of their databases must allow it.
85 + const localBlocked = localSwitchBlockReason(
86 + APP_VERSION,
87 + release,
88 + environments.filter(isHostedByThisApp).map((environment) => ({
89 + connected: environment.connection.phase === "connected",
90 + databaseMigration: environment.serverConfig?.environment.databaseMigration,
91 + })),
92 + window.desktopBridge?.getLocalEnvironmentBootstraps().length ?? 0,
93 + );
94 +
95 + const run = async () => {
96 + const bridge = window.desktopBridge;
97 + if (!bridge) return;
98 + // Stay open while the feed is checked; the run's own progress takes over after.
99 + setChecking(true);
100 + const fail = (description: string) =>
101 + toastManager.add(
102 + stackedThreadToast({ type: "error", title: `Could not switch to ${label}`, description }),
103 + );
104 + const prepared = await prepareLocalTrackSwitch(bridge, {
105 + channel: release.channel,
106 + version: release.version,
107 + reinstall: switchesLocal,
108 + });
109 + onClose();
110 + if (!prepared.ok) {
111 + fail(prepared.message);
112 + return;
113 + }
114 + const { local } = prepared;
115 + const result = await settlePromise(() =>
116 + everything.run(
117 + local === null
118 + ? {}
119 + : {
120 + ...(local.status === "available"
121 + ? {
122 + downloadLocal: (reportError) =>
123 + downloadLocalUpdate(bridge, { notifyDownloaded: false, reportError }),
124 + }
125 + : {}),
126 + // Install only a build the database check covers, pinned so nothing replaces it.
127 + installLocal: async (reportError) => {
128 + const { downloadedVersion } = await bridge.getUpdateState();
129 + if (
130 + downloadedVersion === null ||
131 + !acceptsTrackSwitchRelease(downloadedVersion, release.channel, release.version)
132 + ) {
133 + reportError(
134 + "Could not install update",
135 + `This app downloaded ${downloadedVersion ?? "nothing"}, not ${release.version} or newer.`,
136 + );
137 + return false;
138 + }
139 + return installLocalUpdate(bridge, reportError, downloadedVersion);
140 + },
141 + },
142 + ),
143 + );
144 + if (result._tag === "Failure") {
145 + const error = squashAtomCommandFailure(result);
146 + fail(error instanceof Error ? error.message : "An unexpected error occurred.");
147 + }
148 + };
149 +
150 + return (
151 + <UpdateEverythingDialog
152 + open
153 + onOpenChange={(open) => !open && !checking && onClose()}
154 + title={`Switch to ${label}?`}
155 + version={release.version}
156 + providerCount={0}
157 + rows={everything.rows}
158 + notes={[
159 + ...(everything.rows.length === 0 && !crossesLocal
160 + ? [`Every connected machine is already on ${label}. This only saves the track.`]
161 + : []),
162 + ...(crossesLocal && updatesOff
163 + ? ["This app's updates are off here, so reinstall it yourself to switch."]
164 + : []),
165 + ...(switchesLocal && isMacPlatform(navigator.platform)
166 + ? ["If T3 Code does not reopen after it restarts, open it again."]
167 + : []),
168 + ]}
169 + restarts={everything.restarts}
170 + confirmLabel={checking ? "Checking…" : `Switch to ${label}`}
171 + busy={checking}
172 + disabledReason={
173 + !switchesLocal || localBlocked === null ? null : `This app cannot switch: ${localBlocked}.`
174 + }
175 + onConfirm={() => void run()}
176 + />
177 + );
178 +}
apps/web/src/components/settings/updateTrackSwitch.logic.test.ts new
+76
@@ -0,0 +1,76 @@
1 +import type { DesktopUpdateChannel, DesktopUpdateState } from "@t3tools/contracts";
2 +import { describe, expect, it } from "vite-plus/test";
3 +
4 +import { prepareLocalTrackSwitch } from "./updateTrackSwitch.logic";
5 +
6 +const STABLE = "0.1.3";
7 +
8 +/** Like the desktop app, saving a track re-checks the feed and reports what it offers. */
9 +function fakeBridge(offer: string | null | Error) {
10 + const saved: DesktopUpdateChannel[] = [];
11 + const base: DesktopUpdateState = {
12 + enabled: true,
13 + status: "up-to-date",
14 + channel: "nightly",
15 + currentVersion: "0.1.4-nightly.20261027.3796",
16 + hostArch: "x64",
17 + appArch: "x64",
18 + runningUnderArm64Translation: false,
19 + availableVersion: null,
20 + downloadedVersion: null,
21 + releaseNotes: [],
22 + omittedReleaseCount: 0,
23 + downloadPercent: null,
24 + checkedAt: null,
25 + message: null,
26 + errorContext: null,
27 + canRetry: false,
28 + };
29 + return {
30 + saved,
31 + bridge: {
32 + setUpdateChannel: async (channel: DesktopUpdateChannel) => {
33 + saved.push(channel);
34 + if (offer instanceof Error) throw offer;
35 + return {
36 + ...base,
37 + channel,
38 + status: offer === null ? ("up-to-date" as const) : ("available" as const),
39 + availableVersion: offer,
40 + };
41 + },
42 + },
43 + };
44 +}
45 +
46 +const prepare = (bridge: ReturnType<typeof fakeBridge>["bridge"], reinstall = true) =>
47 + prepareLocalTrackSwitch(bridge, { channel: "latest", version: STABLE, reinstall });
48 +
49 +describe("prepareLocalTrackSwitch", () => {
50 + it("installs the checked release or a newer one on the track, never an older one", async () => {
51 + expect(await prepare(fakeBridge(STABLE).bridge)).toMatchObject({ ok: true });
52 + // A newer Stable knows every migration the checked one does.
53 + expect(await prepare(fakeBridge("0.1.4").bridge)).toMatchObject({ ok: true });
54 +
55 + const stale = fakeBridge("0.1.2");
56 + expect(await prepare(stale.bridge)).toEqual({
57 + ok: false,
58 + message: "This app found 0.1.2, which is older than 0.1.3. Try again in a few minutes.",
59 + });
60 + // The saved track is intent; "Switch them" retries without re-picking it.
61 + expect(stale.saved).toEqual(["latest"]);
62 + });
63 +
64 + it("reports a track that could not be saved", async () => {
65 + expect(await prepare(fakeBridge(new Error("feed check failed")).bridge)).toEqual({
66 + ok: false,
67 + message: "feed check failed",
68 + });
69 + });
70 +
71 + it("only saves the track when this app is already on it", async () => {
72 + const undo = fakeBridge(null);
73 + expect(await prepare(undo.bridge, false)).toEqual({ ok: true, local: null });
74 + expect(undo.saved).toEqual(["latest"]);
75 + });
76 +});
apps/web/src/components/settings/updateTrackSwitch.logic.ts new
+50
@@ -0,0 +1,50 @@
1 +import type { DesktopBridge, DesktopUpdateChannel, DesktopUpdateState } from "@t3tools/contracts";
2 +import { acceptsTrackSwitchRelease } from "@t3tools/shared/cliRelease";
3 +
4 +type TrackSwitchBridge = Pick<DesktopBridge, "setUpdateChannel">;
5 +
6 +/** Saves the track, then, when this app must reinstall, finds a build the database check covers.
7 + * The saved track is the user's intent and stays even when no such build is ready yet: a track
8 + * saved toward Stable never offers an older build outside a guarded switch, and "Switch them"
9 + * retries. Saving when nothing reinstalls lets picking the old track undo a partial switch. */
10 +export async function prepareLocalTrackSwitch(
11 + bridge: TrackSwitchBridge,
12 + input: {
13 + readonly channel: DesktopUpdateChannel;
14 + readonly version: string;
15 + readonly reinstall: boolean;
16 + },
17 +): Promise<
18 + | { readonly ok: true; readonly local: DesktopUpdateState | null }
19 + | { readonly ok: false; readonly message: string }
20 +> {
21 + let local: DesktopUpdateState;
22 + try {
23 + // A build on another track re-checks the feed, older releases allowed down to the checked one.
24 + local = await bridge.setUpdateChannel(
25 + input.channel,
26 + input.reinstall ? input.version : undefined,
27 + );
28 + } catch (error) {
29 + return {
30 + ok: false,
31 + message: error instanceof Error ? error.message : "The update track did not change.",
32 + };
33 + }
34 + if (!input.reinstall) return { ok: true, local: null };
35 + const found = local.downloadedVersion ?? local.availableVersion;
36 + if (
37 + (local.status === "available" || local.status === "downloaded") &&
38 + found !== null &&
39 + acceptsTrackSwitchRelease(found, input.channel, input.version)
40 + ) {
41 + return { ok: true, local };
42 + }
43 + return {
44 + ok: false,
45 + message:
46 + found !== null
47 + ? `This app found ${found}, which is older than ${input.version}. Try again in a few minutes.`
48 + : (local.message ?? `This app found no build of ${input.version} to install.`),
49 + };
50 +}
apps/web/src/components/sidebar/SidebarUpdatePill.tsx
+4 -3
@@ -134,7 +134,7 @@ const toastUpdateError: ReportLocalUpdateError = (title, description) => {
134 toastManager.add(stackedThreadToast({ type: "error", title, description }));
135 };
136
137 -async function downloadLocalUpdate(
137 +export async function downloadLocalUpdate(
138 bridge: DesktopBridge,
139 {
140 notifyDownloaded,
@@ -160,12 +160,13 @@ async function downloadLocalUpdate(
160 }
161 }
162
163 -async function installLocalUpdate(
163 +export async function installLocalUpdate(
164 bridge: DesktopBridge,
165 reportError: ReportLocalUpdateError = toastUpdateError,
166 + expectedVersion?: string,
167 ): Promise<boolean> {
168 try {
168 - const result = await bridge.installUpdate();
169 + const result = await bridge.installUpdate(expectedVersion);
170 if (!result.accepted) {
171 showDesktopUpdateDownloadedToast(bridge, result.state);
172 return false;
apps/web/src/components/sidebar/UpdateEverythingDialog.tsx
+28 -4
@@ -47,6 +47,14 @@ interface UpdateEverythingDialogProps {
47 readonly rows: ReadonlyArray<UpdateEverythingRow>;
48 readonly restarts: ReadonlyArray<RestartingMachine>;
49 readonly onConfirm: () => void;
50 + /** Overrides the "Update N machines?" title, for an update-track switch. */
51 + readonly title?: string;
52 + readonly confirmLabel?: string;
53 + readonly notes?: ReadonlyArray<string>;
54 + /** Shown in place of running-thread counts; disables the confirm button. */
55 + readonly disabledReason?: string | null;
56 + /** The confirmed work is starting; it cannot be cancelled from here. */
57 + readonly busy?: boolean;
58 }
59
60 type UpdateEverythingDialogContentProps = Omit<
@@ -89,6 +97,11 @@ function UpdateEverythingDialogContent({
97 restarts,
98 onConfirm,
99 cancelRef,
100 + title,
101 + confirmLabel = "Update",
102 + notes = [],
103 + disabledReason = null,
104 + busy = false,
105 }: UpdateEverythingDialogContentProps) {
106 const stopped = useAtomValue(
107 runningThreadCountAtom(
@@ -116,7 +129,7 @@ function UpdateEverythingDialogContent({
129 <>
130 <AlertDialogHeader className="shrink-0">
131 <AlertDialogTitle>
119 - Update {updating.length} {updating.length === 1 ? "machine" : "machines"}?
132 + {title ?? `Update ${updating.length} ${updating.length === 1 ? "machine" : "machines"}?`}
133 </AlertDialogTitle>
134 <AlertDialogDescription>
135 {version !== null ? (
@@ -132,6 +145,11 @@ function UpdateEverythingDialogContent({
145 </AlertDialogHeader>
146 <ScrollArea scrollFade>
147 <div className="flex flex-col gap-3 px-6 pb-4">
148 + {notes.map((note) => (
149 + <p key={note} className="text-muted-foreground text-sm">
150 + {note}
151 + </p>
152 + ))}
153 {/* Machine names truncate first. Provider lists wrap between names, never inside one. */}
154 <div className="grid grid-cols-[minmax(4rem,max-content)_max-content_minmax(min-content,1fr)_max-content] gap-x-4 text-sm">
155 <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({
214 </div>
215 </ScrollArea>
216 <AlertDialogFooter>
199 - {running > 0 ? (
217 + {disabledReason !== null ? (
218 + <p className="self-center text-sm max-sm:order-1 max-sm:text-center sm:mr-auto">
219 + {disabledReason}
220 + </p>
221 + ) : running > 0 ? (
222 <p className="self-center text-muted-foreground text-sm max-sm:order-1 max-sm:text-center sm:mr-auto">
223 {stopped === 0
224 ? `${threads} will be interrupted and can resume after the restart.`
@@ -205,10 +227,12 @@ function UpdateEverythingDialogContent({
227 : `${threads} will be interrupted. ${continuing} can resume after the restart.`}
228 </p>
229 ) : null}
208 - <AlertDialogClose ref={cancelRef} render={<Button variant="outline" />}>
230 + <AlertDialogClose ref={cancelRef} render={<Button variant="outline" disabled={busy} />}>
231 Cancel
232 </AlertDialogClose>
211 - <Button onClick={onConfirm}>Update</Button>
233 + <Button disabled={disabledReason !== null || busy} onClick={onConfirm}>
234 + {confirmLabel}
235 + </Button>
236 </AlertDialogFooter>
237 </>
238 );
apps/web/src/components/sidebar/updateEverything.logic.test.ts
+166 -1
@@ -2,8 +2,11 @@ import { EnvironmentId, type ServerSelfUpdateCapability } from "@t3tools/contrac
2 import { describe, expect, it } from "vite-plus/test";
3
4 import {
5 + collectChannelSwitchTargets,
6 collectRestartingMachines,
7 + localSwitchBlockReason,
8 collectServerUpdateTargets,
9 + describeUpdateCapsule,
10 describeUpdateEverything,
11 runUpdateEverything,
12 type UpdateEverythingMachine,
@@ -27,7 +30,9 @@ function machine(
30 capabilities: {
31 repositoryIdentity: true,
32 ...(selfUpdate ? { serverSelfUpdate: selfUpdate } : {}),
30 - ...(selfUpdate === "desktop-managed" ? { desktopAppUpdate: true } : {}),
33 + ...(selfUpdate === "desktop-managed"
34 + ? { desktopAppUpdate: true, desktopAppChannelSwitch: true }
35 + : {}),
36 },
37 },
38 settings: { continueThreadsAfterServerUpdate: false },
@@ -81,6 +86,136 @@ describe("collectServerUpdateTargets", () => {
86 });
87 });
88
89 +describe("collectChannelSwitchTargets", () => {
90 + const NIGHTLY = "0.1.4-nightly.20261027.3796";
91 + const OLD_NIGHTLY = "0.1.3-nightly.20261001.3500";
92 + const NEWER_NIGHTLY = "0.1.4-nightly.20261020.3700";
93 + // What each server reports as its database's highest migration.
94 + const host = (
95 + base: UpdateEverythingMachine,
96 + databaseMigration: number | undefined,
97 + os: "linux" | "darwin" = "linux",
98 + ): UpdateEverythingMachine => ({
99 + ...base,
100 + serverConfig: {
101 + ...base.serverConfig!,
102 + environment: {
103 + ...base.serverConfig!.environment,
104 + platform: { os, arch: "x64" },
105 + ...(databaseMigration === undefined ? {} : { databaseMigration }),
106 + },
107 + },
108 + });
109 +
110 + it("moves nightly hosts to stable only when stable knows their database", () => {
111 + const stable = { channel: "latest" as const, version: "0.1.3", databaseMigration: 69 };
112 + const { targets, skipped } = collectChannelSwitchTargets(
113 + [
114 + host(machine("this-app", NIGHTLY, "desktop-managed", { hostedByThisApp: true }), 72),
115 + host(machine("old-service", OLD_NIGHTLY, "boot-service"), 69),
116 + // Service launchers refuse older versions, even when the database allows it.
117 + host(machine("newer-service", NEWER_NIGHTLY, "boot-service"), 69),
118 + host(machine("linux-desktop", OLD_NIGHTLY, "desktop-managed"), 69),
119 + host(machine("new-service", NIGHTLY, "boot-service"), 72),
120 + host(machine("old-server", "0.1.2-nightly.20260901.3000", "boot-service"), undefined),
121 + host(machine("mac-desktop", OLD_NIGHTLY, "desktop-managed"), 69, "darwin"),
122 + host(machine("preview", "0.1.3-preview.20261026.3702", "boot-service"), 69),
123 + host(machine("stable", "0.1.3", "boot-service"), 69),
124 + host(machine("stable-desktop", "0.1.2", "desktop-managed"), 68),
125 + // Already current, but its saved track may still say Nightly.
126 + host(machine("current-desktop", "0.1.3", "desktop-managed"), 69, "darwin"),
127 + ],
128 + stable,
129 + );
130 +
131 + expect(
132 + targets.map((target) => [
133 + target.serverLabel,
134 + target.targetVersion,
135 + target.channel,
136 + target.trackOnly ?? false,
137 + ]),
138 + ).toEqual([
139 + ["old-service", "0.1.3", undefined, false],
140 + ["linux-desktop", "0.1.3", "latest", false],
141 + ["stable-desktop", "0.1.3", "latest", false],
142 + ["current-desktop", "0.1.3", "latest", true],
143 + ]);
144 + expect(targets.every((target) => target.targetDatabaseMigration === 69)).toBe(true);
145 + expect(skipped.map((entry) => [entry.label, entry.reason])).toEqual([
146 + ["newer-service", "run `t3 update --channel stable --allow-downgrade` there"],
147 + [
148 + "new-service",
149 + "its database has changes 0.1.3 does not support yet; stay on Nightly until Stable has them",
150 + ],
151 + ["old-server", "its server predates database checks; update it on Nightly first"],
152 + ["mac-desktop", "switch the Mac app on that Mac"],
153 + ["preview", "runs a preview build"],
154 + ]);
155 + });
156 +
157 + it("moves stable hosts to nightly only when nightly knows their database", () => {
158 + const nightly = { channel: "nightly" as const, version: NIGHTLY, databaseMigration: 72 };
159 + const { targets, skipped } = collectChannelSwitchTargets(
160 + [
161 + host(machine("service", "0.1.2", "boot-service"), 70),
162 + // A Stable tag built a migration the latest Nightly does not have yet.
163 + host(machine("ahead", "0.1.3", "boot-service"), 73),
164 + machine("old-desktop", "0.1.2", "desktop-managed", {
165 + serverConfig: {
166 + ...machine("old-desktop", "0.1.2", "desktop-managed").serverConfig!,
167 + environment: {
168 + ...machine("old-desktop", "0.1.2", "desktop-managed").serverConfig!.environment,
169 + capabilities: { repositoryIdentity: true, serverSelfUpdate: "desktop-managed" },
170 + },
171 + },
172 + }),
173 + machine("current", NIGHTLY, "boot-service"),
174 + ],
175 + nightly,
176 + );
177 +
178 + expect(targets.map((target) => [target.serverLabel, target.targetVersion])).toEqual([
179 + ["service", NIGHTLY],
180 + ]);
181 + expect(skipped.map((entry) => [entry.label, entry.reason])).toEqual([
182 + [
183 + "ahead",
184 + `its database has changes ${NIGHTLY} does not support yet; stay on Stable until Nightly has them`,
185 + ],
186 + ["old-desktop", "needs a newer desktop app"],
187 + ]);
188 + });
189 +});
190 +
191 +describe("localSwitchBlockReason", () => {
192 + it("checks every server this app hosts, and only while connected", () => {
193 + const stable = { channel: "latest" as const, version: "0.1.3", databaseMigration: 69 };
194 + const nightly = "0.1.4-nightly.20261027.3796";
195 +
196 + const windows = { connected: true, databaseMigration: 69 };
197 + expect(localSwitchBlockReason(nightly, stable, [windows], 1)).toBeNull();
198 + // A WSL server's newer migration blocks the reinstall that would restart it.
199 + expect(
200 + localSwitchBlockReason(
201 + nightly,
202 + stable,
203 + [windows, { connected: true, databaseMigration: 72 }],
204 + 2,
205 + ),
206 + ).toContain("does not support yet");
207 + // A WSL backend still starting has no client entry, so its database is unchecked.
208 + expect(localSwitchBlockReason(nightly, stable, [windows], 2)).toBe(
209 + "its server is not connected, so its database cannot be checked",
210 + );
211 + // A cached head from a disconnected server proves nothing.
212 + expect(
213 + localSwitchBlockReason(nightly, stable, [{ connected: false, databaseMigration: 69 }], 1),
214 + ).toBe("its server is not connected, so its database cannot be checked");
215 + expect(localSwitchBlockReason("0.1.3", stable, [], 1)).toBeNull();
216 + });
217 +});
218 +
219 describe("collectRestartingMachines", () => {
220 it("lists updated servers, and this app's servers only when it installs", () => {
221 const withContinuation = (
@@ -177,3 +312,33 @@ describe("describeUpdateEverything", () => {
312 ]);
313 });
314 });
315 +
316 +describe("describeUpdateCapsule", () => {
317 + it("sends failed track switches back through the planner instead of retrying their target", () => {
318 + const failed = {
319 + machine: {
320 + environmentId: EnvironmentId.make("remote"),
321 + label: "remote",
322 + updatesProviders: false,
323 + server: {
324 + environmentId: EnvironmentId.make("remote"),
325 + serverLabel: "remote",
326 + selfUpdate: "boot-service" as const,
327 + targetVersion: "0.1.3",
328 + },
329 + handedOffVersion: null,
330 + startedAt: 0,
331 + result: "failed" as const,
332 + failure: "offline",
333 + providerFailure: null,
334 + },
335 + status: "failed" as const,
336 + };
337 + const run = { localVersion: null, phase: "servers" as const, restartAt: null, machines: [] };
338 +
339 + expect(describeUpdateCapsule(run, [failed], null, 0).action).toBe("retry");
340 + expect(describeUpdateCapsule({ ...run, trackSwitch: true }, [failed], null, 0).action).toBe(
341 + "dismiss",
342 + );
343 + });
344 +});
apps/web/src/components/sidebar/updateEverything.logic.ts
+203 -13
@@ -1,6 +1,12 @@
1 import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
2 -import type { EnvironmentId, ServerConfig } from "@t3tools/contracts";
3 -import { cliReleaseChannelOf } from "@t3tools/shared/cliRelease";
2 +import type {
3 + DesktopUpdateChannel,
4 + EnvironmentId,
5 + ServerConfig,
6 + ServerSelfUpdateCapability,
7 +} from "@t3tools/contracts";
8 +import { cliReleaseChannelOf, desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
9 +import { compareSemverVersions } from "@t3tools/shared/semver";
10
11 import {
12 resolveServerSelfUpdateCapability,
@@ -76,16 +82,9 @@ export function collectServerUpdateTargets(
82 }
83 const skip = (reason: string) =>
84 skipped.push({ environmentId: machine.environmentId, label: machine.label, reason });
79 - if (config === null || !machine.connected) {
80 - skip("not connected");
81 - continue;
82 - }
83 - if (!machine.canMaintain) {
84 - skip("no permission");
85 - continue;
86 - }
87 - if (machine.updateState.status === "running") {
88 - skip("already updating");
85 + const unavailable = unavailableReason(machine);
86 + if (config === null || unavailable !== null) {
87 + skip(unavailable ?? "not connected");
88 continue;
89 }
90 const selfUpdate = resolveServerSelfUpdateCapability(config);
@@ -118,6 +117,192 @@ export function collectServerUpdateTargets(
117 return { targets, skipped };
118 }
119
120 +function unavailableReason(machine: UpdateEverythingMachine): string | null {
121 + if (machine.serverConfig === null || !machine.connected) return "not connected";
122 + if (!machine.canMaintain) return "no permission";
123 + if (machine.updateState.status === "running") return "already updating";
124 + return null;
125 +}
126 +
127 +/** The latest release on the track a fleet switches to, as npm reports it. */
128 +export interface ChannelSwitchRelease {
129 + readonly channel: DesktopUpdateChannel;
130 + readonly version: string;
131 + readonly databaseMigration: number | undefined;
132 +}
133 +
134 +export const channelSwitchLabel = (channel: DesktopUpdateChannel) =>
135 + channel === "nightly" ? "Nightly" : "Stable";
136 +
137 +/** Stable and Nightly each build their own commits, so either can hold migrations the other lacks.
138 + * Crossing tracks needs proof that the target release knows every migration the database holds. */
139 +const crossesTrack = (fromVersion: string, release: ChannelSwitchRelease) =>
140 + desktopUpdateChannelOf(fromVersion) !== release.channel;
141 +
142 +function channelSwitchBlockReason(
143 + fromVersion: string,
144 + release: ChannelSwitchRelease,
145 + currentMigration: number | undefined,
146 +): string | null {
147 + if (!crossesTrack(fromVersion, release)) return null;
148 + const from = channelSwitchLabel(desktopUpdateChannelOf(fromVersion));
149 + // Servers and releases from before this check report no migration number.
150 + if (currentMigration === undefined) {
151 + return `its server predates database checks; update it on ${from} first`;
152 + }
153 + if (release.databaseMigration === undefined) {
154 + return `${release.version} predates database checks; wait for a newer ${channelSwitchLabel(release.channel)} release`;
155 + }
156 + return currentMigration > release.databaseMigration
157 + ? `its database has changes ${release.version} does not support yet; stay on ${from} until ${channelSwitchLabel(release.channel)} has them`
158 + : null;
159 +}
160 +
161 +/** This app's reinstall restarts every server it hosts, so each of their databases must allow the
162 + * switch. `backendCount` is the desktop's own inventory: a backend still starting has no client
163 + * entry yet. A cached config can outlive its connection, so only a connected server's head counts. */
164 +export function localSwitchBlockReason(
165 + appVersion: string,
166 + release: ChannelSwitchRelease,
167 + hosted: ReadonlyArray<{
168 + readonly connected: boolean;
169 + readonly databaseMigration: number | undefined;
170 + }>,
171 + backendCount: number,
172 +): string | null {
173 + if (!crossesTrack(appVersion, release)) return null;
174 + if (
175 + hosted.length === 0 ||
176 + hosted.length < backendCount ||
177 + hosted.some((server) => !server.connected)
178 + ) {
179 + return "its server is not connected, so its database cannot be checked";
180 + }
181 + return (
182 + hosted
183 + .map((server) => channelSwitchBlockReason(appVersion, release, server.databaseMigration))
184 + .find((reason) => reason !== null) ?? null
185 + );
186 +}
187 +
188 +/** Servers move to the release; desktop-managed hosts reinstall their app on its track. A desktop
189 + * host already current gets a track-only request, since its saved track may still differ. */
190 +export function collectChannelSwitchTargets(
191 + machines: ReadonlyArray<UpdateEverythingMachine>,
192 + release: ChannelSwitchRelease,
193 +): { readonly targets: ServerUpdateTarget[]; readonly skipped: SkippedMachine[] } {
194 + const targets: ServerUpdateTarget[] = [];
195 + const skipped: SkippedMachine[] = [];
196 + for (const machine of machines) {
197 + const config = machine.serverConfig;
198 + if (machine.hostedByThisApp) continue;
199 + const skip = (reason: string) =>
200 + skipped.push({ environmentId: machine.environmentId, label: machine.label, reason });
201 + const target = (
202 + selfUpdate: ServerSelfUpdateCapability,
203 + targetVersion: string,
204 + ): ServerUpdateTarget => ({
205 + environmentId: machine.environmentId,
206 + serverLabel: machine.label,
207 + selfUpdate,
208 + installation: config?.environment.capabilities.serverInstallation,
209 + desktopAppUpdate: config !== null && supportsDesktopAppUpdate(config),
210 + targetVersion,
211 + ...(selfUpdate === "desktop-managed" ? { channel: release.channel } : {}),
212 + ...(release.databaseMigration === undefined
213 + ? {}
214 + : { targetDatabaseMigration: release.databaseMigration }),
215 + });
216 + const serverVersion = config?.environment.serverVersion;
217 + const sameTrack = serverVersion !== undefined && isOnTrack(serverVersion, release.channel);
218 + if (
219 + config !== null &&
220 + sameTrack &&
221 + resolveVersionMismatch(serverVersion, release.version) === null
222 + ) {
223 + const move = trackSwitchMove(config, true);
224 + if (
225 + !("skip" in move) &&
226 + move.selfUpdate === "desktop-managed" &&
227 + unavailableReason(machine) === null
228 + ) {
229 + targets.push({ ...target(move.selfUpdate, serverVersion), trackOnly: true });
230 + }
231 + continue;
232 + }
233 + const unavailable = unavailableReason(machine);
234 + if (config === null || serverVersion === undefined || unavailable !== null) {
235 + skip(unavailable ?? "not connected");
236 + continue;
237 + }
238 + const move = trackSwitchMove(config, sameTrack);
239 + if ("skip" in move) {
240 + skip(move.skip);
241 + continue;
242 + }
243 + const blocked = channelSwitchBlockReason(
244 + serverVersion,
245 + release,
246 + config.environment.databaseMigration,
247 + );
248 + if (blocked !== null) {
249 + skip(blocked);
250 + continue;
251 + }
252 + // Service launchers only accept newer versions, so leaving for an older release is manual.
253 + if (
254 + move.selfUpdate === "boot-service" &&
255 + compareSemverVersions(release.version, serverVersion) <= 0
256 + ) {
257 + skip(
258 + `run \`t3 update --channel ${release.channel === "nightly" ? "nightly" : "stable"} --allow-downgrade\` there`,
259 + );
260 + continue;
261 + }
262 + targets.push(target(move.selfUpdate, release.version));
263 + }
264 + return { targets, skipped };
265 +}
266 +
267 +/** A remote host on the other track that a switch can still move, for retrying a partial switch. */
268 +export function awaitsTrackSwitch(
269 + machine: Pick<UpdateEverythingMachine, "serverConfig" | "hostedByThisApp">,
270 + channel: DesktopUpdateChannel,
271 +): boolean {
272 + const config = machine.serverConfig;
273 + return (
274 + !machine.hostedByThisApp &&
275 + config !== null &&
276 + !isOnTrack(config.environment.serverVersion, channel) &&
277 + !("skip" in trackSwitchMove(config, false))
278 + );
279 +}
280 +
281 +function isOnTrack(version: string, channel: DesktopUpdateChannel): boolean {
282 + return cliReleaseChannelOf(version) !== "preview" && desktopUpdateChannelOf(version) === channel;
283 +}
284 +
285 +/** How a switch moves a host, or why it never can from here, whatever the release. */
286 +function trackSwitchMove(
287 + config: NonNullable<UpdateEverythingMachine["serverConfig"]>,
288 + sameTrack: boolean,
289 +): { readonly selfUpdate: ServerSelfUpdateCapability } | { readonly skip: string } {
290 + if (cliReleaseChannelOf(config.environment.serverVersion) === "preview") {
291 + return { skip: "runs a preview build" };
292 + }
293 + const selfUpdate = resolveServerSelfUpdateCapability(config);
294 + if (selfUpdate === null) return { skip: "needs a manual update" };
295 + if (selfUpdate !== "desktop-managed") return { selfUpdate };
296 + if (config.environment.capabilities.desktopAppChannelSwitch !== true) {
297 + return { skip: "needs a newer desktop app" };
298 + }
299 + // Squirrel.Mac renames the bundle for the new track and then cannot relaunch it.
300 + if (!sameTrack && config.environment.platform.os === "darwin") {
301 + return { skip: "switch the Mac app on that Mac" };
302 + }
303 + return { selfUpdate };
304 +}
305 +
306 export interface UpdateEverythingSteps<Providers, Servers> {
307 readonly downloadLocal?: () => Promise<boolean>;
308 readonly updateProviders: () => Promise<Providers>;
@@ -163,6 +348,8 @@ export interface UpdateRunMachine {
348 }
349
350 export interface UpdateEverythingRun {
351 + /** Track switches retry through their planner, which re-checks each database. */
352 + readonly trackSwitch?: boolean;
353 readonly localVersion: string | null;
354 readonly phase: "providers" | "servers" | "countdown" | "installing";
355 readonly restartAt: number | null;
@@ -265,7 +452,10 @@ export function describeUpdateCapsule(
452 return {
453 tone: "failed",
454 label: failed.length === 1 ? `${failed[0]!.machine.label} failed` : `${failed.length} failed`,
268 - action: failed.some(({ machine }) => machine.server !== null) ? "retry" : "dismiss",
455 + action:
456 + !run.trackSwitch && failed.some(({ machine }) => machine.server !== null)
457 + ? "retry"
458 + : "dismiss",
459 };
460 }
461 return { tone: "default", label: `${done} of ${machines.length} updated`, action: null };
apps/web/src/components/sidebar/useUpdateEverything.ts
+38 -16
@@ -13,7 +13,9 @@ import { getProviderUpdateRunOutcome } from "../ProviderUpdateLaunchNotification
13 import { useProviderUpdates } from "../ProviderUpdatesAction";
14 import { canUpdateServer, type ServerUpdateOutcome, useServerUpdate } from "../ServerUpdateAction";
15 import {
16 + type ChannelSwitchRelease,
17 closeFinishedUpdateRun,
18 + collectChannelSwitchTargets,
19 collectRestartingMachines,
20 collectServerUpdateTargets,
21 collectUpdateEverythingResult,
@@ -34,9 +36,24 @@ import {
36
37 const UPDATE_RESTART_DELAY_MS = 5_000;
38
39 +/** Servers this desktop app runs; they update with it. */
40 +export function isHostedByThisApp(
41 + environment: ReturnType<typeof useEnvironments>["environments"][number],
42 +) {
43 + return (
44 + isElectron &&
45 + (environment.entry.target._tag === "PrimaryConnectionTarget" ||
46 + isDesktopLocalConnectionTarget(environment.entry.target))
47 + );
48 +}
49 +
50 export type ReportLocalUpdateError = (title: string, description: string) => void;
51
39 -export function useUpdateEverything(localUpdateVersion: string | null) {
52 +/** `channelSwitch` makes the run move the fleet to that release's track instead of updating it. */
53 +export function useUpdateEverything(
54 + localUpdateVersion: string | null,
55 + channelSwitch?: ChannelSwitchRelease,
56 +) {
57 const targetVersion = localUpdateVersion ?? APP_VERSION;
58 const { environments } = useEnvironments();
59 const environmentIds = environmentIdsKey(environments.map(({ environmentId }) => environmentId));
@@ -47,23 +64,23 @@ export function useUpdateEverything(localUpdateVersion: string | null) {
64 label: environment.label,
65 serverConfig: environment.serverConfig,
66 connected: environment.connection.phase === "connected",
50 - hostedByThisApp:
51 - isElectron &&
52 - (environment.entry.target._tag === "PrimaryConnectionTarget" ||
53 - isDesktopLocalConnectionTarget(environment.entry.target)),
67 + hostedByThisApp: isHostedByThisApp(environment),
68 canMaintain: canUpdateServer(sessionStates[index]!),
69 updateState: updateStates[index]!,
70 }));
57 - const { targets: behindServers, skipped: unreachable } = collectServerUpdateTargets(
58 - machines,
59 - targetVersion,
60 - );
71 + const { targets: behindServers, skipped: unreachable } = channelSwitch
72 + ? collectChannelSwitchTargets(machines, channelSwitch)
73 + : collectServerUpdateTargets(machines, targetVersion);
74 // Desktop-managed servers use their app feed; only npm installs need to wait for publication.
62 - const needsNpm = behindServers.some((server) => server.selfUpdate !== "desktop-managed");
75 + // A track switch's target came from npm already.
76 + const needsNpm =
77 + channelSwitch === undefined &&
78 + behindServers.some((server) => server.selfUpdate !== "desktop-managed");
79 const published = useNpmReleasePublished(needsNpm ? targetVersion : null);
64 - const servers = published
65 - ? behindServers
66 - : behindServers.filter((server) => server.selfUpdate === "desktop-managed");
80 + const servers =
81 + published || channelSwitch !== undefined
82 + ? behindServers
83 + : behindServers.filter((server) => server.selfUpdate === "desktop-managed");
84 const skipped: ReadonlyArray<SkippedMachine> = [
85 ...unreachable,
86 ...behindServers
@@ -74,14 +91,18 @@ export function useUpdateEverything(localUpdateVersion: string | null) {
91 reason: `t3@${targetVersion} is not on npm yet`,
92 })),
93 ];
77 - const restarts = collectRestartingMachines(machines, servers, localUpdateVersion !== null);
78 - const providers = useProviderUpdates();
94 + // Track-only hosts save a setting and restart nothing, so they are neither listed nor counted.
95 + const moving = servers.filter((server) => server.trackOnly !== true);
96 + const restarts = collectRestartingMachines(machines, moving, localUpdateVersion !== null);
97 + const providerUpdates = useProviderUpdates();
98 + // A track switch moves app and servers only; provider updates stay a separate choice.
99 + const providers = channelSwitch ? { machines: [], updateAll: async () => [] } : providerUpdates;
100 const updateServer = useServerUpdate();
101
102 const view = describeUpdateEverything({
103 localVersion: localUpdateVersion,
104 localMachines: machines.filter((machine) => machine.hostedByThisApp),
84 - servers,
105 + servers: moving,
106 skipped,
107 providerMachines: providers.machines.map((machine) => ({
108 environmentId: machine.environmentId,
@@ -138,6 +159,7 @@ export function useUpdateEverything(localUpdateVersion: string | null) {
159 }
160 const localVersion = installLocal ? localUpdateVersion : null;
161 setUpdateEverythingRun(() => ({
162 + ...(channelSwitch ? { trackSwitch: true } : {}),
163 localVersion,
164 phase: "providers",
165 restartAt: null,
apps/web/src/state/npmRelease.ts
+31 -11
@@ -1,31 +1,51 @@
1 import { useAtomValue } from "@effect/atom-react";
2 +import { npmReleaseDatabaseMigration } from "@t3tools/shared/cliRelease";
3 import * as Effect from "effect/Effect";
4 import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
5 import { AsyncResult, Atom } from "effect/reactivity";
6
6 -export const npmReleasePublishedAtom = Atom.family((version: string) =>
7 +export interface NpmRelease {
8 + readonly version: string;
9 + /** Absent on releases published before npm manifests carried it. */
10 + readonly databaseMigration: number | undefined;
11 +}
12 +
13 +/** `spec` is an exact version or a dist-tag such as `nightly`. Null when npm has no such release.
14 + * Refreshes only while mounted; the published check below keeps its own versions alive. */
15 +export const npmReleaseAtom = Atom.family((spec: string) =>
16 Atom.make(
17 Effect.gen(function* () {
18 const response = yield* HttpClient.get(
10 - `https://registry.npmjs.org/t3/${encodeURIComponent(version)}`,
19 + `https://registry.npmjs.org/t3/${encodeURIComponent(spec)}`,
20 );
12 - if (response.status === 404) return false;
21 + if (response.status === 404) return null;
22 const body = yield* HttpClientResponse.filterStatusOk(response).pipe(
23 Effect.flatMap((ok) => ok.json),
24 );
16 - return typeof body === "object" && body !== null && "version" in body
17 - ? body.version === version
18 - : false;
25 + if (
26 + typeof body !== "object" ||
27 + body === null ||
28 + !("version" in body) ||
29 + typeof body.version !== "string"
30 + ) {
31 + return null;
32 + }
33 + return {
34 + version: body.version,
35 + databaseMigration: npmReleaseDatabaseMigration(body),
36 + } satisfies NpmRelease;
37 }).pipe(
38 // Tracing headers would make the browser send a CORS preflight, which npm rejects.
39 Effect.provideService(HttpClient.TracerPropagationEnabled, false),
40 Effect.provide(FetchHttpClient.layer),
41 ),
24 - ).pipe(
25 - Atom.withRefresh("5 minutes"),
26 - Atom.keepAlive,
27 - Atom.withLabel(`npm-release-published:${version}`),
28 - ),
42 + ).pipe(Atom.withRefresh("5 minutes"), Atom.withLabel(`npm-release:${spec}`)),
43 +);
44 +
45 +export const npmReleasePublishedAtom = Atom.family((version: string) =>
46 + Atom.make((get) =>
47 + get.result(npmReleaseAtom(version)).pipe(Effect.map((release) => release?.version === version)),
48 + ).pipe(Atom.keepAlive, Atom.withLabel(`npm-release-published:${version}`)),
49 );
50
51 const NO_VERSION_ATOM = Atom.make(AsyncResult.success(false)).pipe(
docs/user/updating.md
+23
@@ -35,6 +35,29 @@ The confirmation counts the running threads that the restarts will interrupt,
35 and how many can resume afterwards. See **Continue threads after restarts**
36 below.
37
38 +## Switch between Stable and Nightly
39 +
40 +In the desktop app, change **Settings → About → Update track**. T3 Code shows each
41 +connected machine it will move and each one it skips, then moves them in one
42 +step. Remote servers install the latest release on the new track. Remote desktop
43 +apps reinstall on the new track. This app reinstalls last. Your threads,
44 +settings, and data stay.
45 +
46 +A background service cannot move to an older release remotely. When Stable is
47 +older than its Nightly, run `t3 update --channel stable --allow-downgrade` on
48 +that machine.
49 +
50 +A switch is blocked for a machine whose database already has changes the
51 +target release does not support, or when T3 Code cannot confirm that it does.
52 +The dialog says why: update a machine on its current track first when its
53 +release is too old to check, or wait until the target track includes the
54 +changes. A Mac running the desktop app must switch on that Mac.
55 +
56 +Each machine keeps the new track even if its switch did not finish, but it
57 +moves to that track only through a switch. **Update track** shows how many
58 +machines still run the other track. **Review** opens the same dialog with fresh
59 +checks.
60 +
61 ## Before you update
62
63 Server updates restart the connection and can interrupt active agents and
packages/client-runtime/src/state/server.ts
+11
@@ -969,6 +969,17 @@ export function createServerEnvironmentAtoms<R, E>(
969 }),
970 );
971
972 + // A track switch's desktop host already on its track's newest build only saved the
973 + // track; nothing restarts.
974 + if (
975 + result.method === "desktop-app" &&
976 + result.desktopUpdateToken === undefined &&
977 + result.targetVersion === fromVersion
978 + ) {
979 + atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
980 + return result;
981 + }
982 +
983 yield* nudgeReconnectDuringUpdateRestart({
984 stateChanges: environmentRegistry.stateChanges(target.environmentId),
985 retryNow: environmentRegistry.retryNow(target.environmentId),
packages/contracts/src/environment.ts
+4
@@ -133,6 +133,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
133 ignoredFileListing: Schema.optionalKey(Schema.Boolean),
134 environmentIcon: Schema.optionalKey(Schema.Boolean),
135 desktopAppUpdate: Schema.optionalKey(Schema.Boolean),
136 + /** The desktop app switches update tracks when a server update request names one. */
137 + desktopAppChannelSwitch: Schema.optionalKey(Schema.Boolean),
138 /** Subscribe to command output only when advertised; older servers never send it. */
139 commandOutputStreaming: Schema.optionalKey(Schema.Boolean),
140 /** Hosts headless Chromium tabs streamed over /api/preview-stream for clients without a local runtime. */
@@ -160,6 +162,8 @@ export const ExecutionEnvironmentDescriptor = Schema.Struct({
162 platform: ExecutionEnvironmentPlatform,
163 serverVersion: TrimmedNonEmptyString,
164 orchestrationProtocolVersion: Schema.optionalKey(Schema.Int),
165 + /** Highest migration this server's database holds; absent on older servers. */
166 + databaseMigration: Schema.optionalKey(Schema.Int),
167 capabilities: ExecutionEnvironmentCapabilities,
168 });
169 export type ExecutionEnvironmentDescriptor = typeof ExecutionEnvironmentDescriptor.Type;
packages/contracts/src/ipc.ts
+7 -2
@@ -1096,10 +1096,15 @@ export interface DesktopBridge {
1096 onWindowFullscreenStateChange: (listener: (fullscreen: boolean) => void) => () => void;
1097 getWindowZoomFactor: () => number;
1098 getUpdateState: () => Promise<DesktopUpdateState>;
1099 - setUpdateChannel: (channel: DesktopUpdateChannel) => Promise<DesktopUpdateState>;
1099 + /** `minimumVersion` is a track switch's checked release; nothing older is offered after. */
1100 + setUpdateChannel: (
1101 + channel: DesktopUpdateChannel,
1102 + minimumVersion?: string,
1103 + ) => Promise<DesktopUpdateState>;
1104 checkForUpdate: () => Promise<DesktopUpdateCheckResult>;
1105 downloadUpdate: () => Promise<DesktopUpdateActionResult>;
1102 - installUpdate: () => Promise<DesktopUpdateActionResult>;
1106 + /** With a version, installs only that downloaded build. */
1107 + installUpdate: (expectedVersion?: string) => Promise<DesktopUpdateActionResult>;
1108 onUpdateState: (listener: (state: DesktopUpdateState) => void) => () => void;
1109 cliCommand: {
1110 getState: () => Promise<DesktopCliCommandState>;
packages/contracts/src/resourceTelemetry.ts
+4 -1
@@ -2,7 +2,7 @@ import * as Schema from "effect/Schema";
2
3 import { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas.ts";
4 import { HostPowerSnapshot } from "./background.ts";
5 -import { DesktopUpdateStateSchema } from "./ipc.ts";
5 +import { DesktopUpdateChannelSchema, DesktopUpdateStateSchema } from "./ipc.ts";
6
7 export const RESOURCE_MONITOR_PROTOCOL_VERSION = 3 as const;
8
@@ -323,6 +323,9 @@ export const DesktopTelemetryRequestDesktopUpdate = Schema.Struct({
323 version: Schema.Literal(1),
324 type: Schema.Literal("requestDesktopUpdate"),
325 requestId: TrimmedNonEmptyString,
326 + /** A track switch: move to this channel first, and install only `targetVersion`. */
327 + channel: Schema.optionalKey(DesktopUpdateChannelSchema),
328 + targetVersion: Schema.optionalKey(TrimmedNonEmptyString),
329 });
330 export type DesktopTelemetryRequestDesktopUpdate = typeof DesktopTelemetryRequestDesktopUpdate.Type;
331
packages/contracts/src/server.ts
+5
@@ -28,6 +28,7 @@ import { RuntimeMode } from "./providerPolicy.ts";
28 import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
29 import { ServerProviderUsageLimits, UsageLimitSourceSnapshots } from "./providerUsageLimits.ts";
30 import { ServerSettings } from "./settings.ts";
31 +import { DesktopUpdateChannelSchema } from "./ipc.ts";
32
33 const KeybindingsMalformedConfigIssue = Schema.Struct({
34 kind: Schema.Literal("keybindings.malformed-config"),
@@ -879,6 +880,10 @@ export class ServerProviderUpdateError extends Schema.TaggedError<ServerProvider
880 export const ServerSelfUpdateInput = Schema.Struct({
881 /** Exact npm version, never a dist-tag, so server and client agree on the request. */
882 targetVersion: TrimmedNonEmptyString,
883 + /** Desktop-managed hosts move their app to this update track first. Sent only for a track switch. */
884 + channel: Schema.optionalKey(DesktopUpdateChannelSchema),
885 + /** The target release's highest migration; the host refuses to leave Nightly without it. */
886 + targetDatabaseMigration: Schema.optionalKey(Schema.Int),
887 });
888 export type ServerSelfUpdateInput = typeof ServerSelfUpdateInput.Type;
889
packages/shared/src/cliRelease.ts
+42
@@ -1,3 +1,8 @@
1 +import * as Option from "effect/Option";
2 +import * as Schema from "effect/Schema";
3 +
4 +import { compareSemverVersions } from "./semver.ts";
5 +
6 const CLI_RELEASE_REPOSITORY = "pingdotgg/t3code";
7 export const CLI_RELEASES_PAGE_URL = `https://github.com/${CLI_RELEASE_REPOSITORY}/releases`;
8 export const CLI_RELEASE_CHECKSUMS_FILE = "SHA256SUMS";
@@ -68,6 +73,32 @@ export function cliReleaseChannelOf(version: string): CliReleaseChannel {
73 return channel === "nightly" || channel === "preview" ? channel : "stable";
74 }
75
76 +/** Whether updating between these versions crosses Stable and Nightly. Preview builds cross nothing.
77 + * Hosts refuse a crossing outside a track switch, which checks the database first. */
78 +export function crossesReleaseTrack(fromVersion: string, toVersion: string): boolean {
79 + const from = cliReleaseChannelOf(fromVersion);
80 + const to = cliReleaseChannelOf(toVersion);
81 + return from !== to && from !== "preview" && to !== "preview";
82 +}
83 +
84 +/** The desktop update track a build belongs to. Preview builds have no feed and read as Stable. */
85 +export function desktopUpdateChannelOf(version: string): "latest" | "nightly" {
86 + return cliReleaseChannelOf(version) === "nightly" ? "nightly" : "latest";
87 +}
88 +
89 +/** Whether a track switch may install `found` after its database check cleared `checked`: any build
90 + * on the switch's track at least as new, since later releases only add migrations. */
91 +export function acceptsTrackSwitchRelease(
92 + found: string,
93 + channel: "latest" | "nightly",
94 + checked: string,
95 +): boolean {
96 + return (
97 + cliReleaseChannelOf(found) === (channel === "nightly" ? "nightly" : "stable") &&
98 + compareSemverVersions(found, checked) >= 0
99 + );
100 +}
101 +
102 /** Page until the channel matches; nightlies can push preview/stable releases past the first page. */
103 export function cliReleaseIndexPageUrl(page: number): string {
104 return `https://api.github.com/repos/${CLI_RELEASE_REPOSITORY}/releases?per_page=100&page=${page}`;
@@ -89,3 +120,14 @@ export function newestCliReleaseVersion(
120 }
121 return undefined;
122 }
123 +
124 +const NpmReleaseMigrationManifest = Schema.Struct({
125 + t3code: Schema.Struct({ databaseMigration: Schema.Int }),
126 +});
127 +const decodeNpmReleaseMigrationManifest = Schema.decodeUnknownOption(NpmReleaseMigrationManifest);
128 +
129 +/** Highest database migration a release's server knows, from its npm `t3` manifest. */
130 +export function npmReleaseDatabaseMigration(manifest: unknown): number | undefined {
131 + return Option.getOrUndefined(decodeNpmReleaseMigrationManifest(manifest))?.t3code
132 + .databaseMigration;
133 +}
scripts/build-npm-launcher.test.ts
+3
@@ -13,6 +13,8 @@ import * as NodeCrypto from "node:crypto";
13 import * as NodeEvents from "node:events";
14 import * as NodeHttp from "node:http";
15
16 +import { npmReleaseDatabaseMigration } from "@t3tools/shared/cliRelease";
17 +
18 import { buildNpmLauncher } from "./build-npm-launcher.ts";
19
20 const VERSION = "1.2.3";
@@ -118,6 +120,7 @@ it.layer(NodeServices.layer)("build-npm-launcher", (it) => {
120 assert.deepStrictEqual(manifest.bin, { t3: "./bin/t3.mjs" });
121 assert.isUndefined(manifest.dependencies);
122 assert.isUndefined(manifest.optionalDependencies);
123 + assert.isAbove(npmReleaseDatabaseMigration(manifest) ?? 0, 0);
124
125 const installed = path.join(root, "installed");
126 yield* fs.makeDirectory(installed);
scripts/build-npm-launcher.ts
+20 -3
@@ -30,8 +30,8 @@ export class NpmLauncherCommandFailedError extends Schema.TaggedError<NpmLaunche
30 }
31 }
32
33 -/** engines requires import.meta.dirname and fetch. */
34 -export function npmLauncherPackageManifest(version: string) {
33 +/** engines requires import.meta.dirname and fetch. `t3code` is read back by npmReleaseDatabaseMigration. */
34 +export function npmLauncherPackageManifest(version: string, databaseMigration: number) {
35 return {
36 name: NPM_LAUNCHER_PACKAGE_NAME,
37 version,
@@ -42,9 +42,24 @@ export function npmLauncherPackageManifest(version: string) {
42 bin: { t3: "./bin/t3.mjs" },
43 files: ["bin", "dist"],
44 engines: { node: ">=20.11" },
45 + t3code: { databaseMigration },
46 };
47 }
48
49 +/** Highest server migration id, from the `NNN_Name.ts` files the server registers. */
50 +const latestServerMigrationId = Effect.fn("latestServerMigrationId")(function* () {
51 + const fs = yield* FileSystem.FileSystem;
52 + const path = yield* Path.Path;
53 + const dir = yield* path.fromFileUrl(
54 + new URL("../apps/server/src/persistence/Migrations/", import.meta.url),
55 + );
56 + const ids = (yield* fs.readDirectory(dir)).flatMap((name) => {
57 + const id = /^(\d+)_\w+\.ts$/.exec(name)?.[1];
58 + return id === undefined ? [] : [Number(id)];
59 + });
60 + return Math.max(0, ...ids);
61 +});
62 +
63 export const buildNpmLauncher = Effect.fn("buildNpmLauncher")(function* (input: {
64 readonly version: string;
65 readonly outputDir: string;
@@ -64,7 +79,9 @@ export const buildNpmLauncher = Effect.fn("buildNpmLauncher")(function* (input:
79 yield* fs.makeDirectory(path.join(stageDir, "dist"));
80 yield* fs.writeFileString(
81 path.join(stageDir, "package.json"),
67 - `${yield* encodePackageJson(npmLauncherPackageManifest(input.version))}\n`,
82 + `${yield* encodePackageJson(
83 + npmLauncherPackageManifest(input.version, yield* latestServerMigrationId()),
84 + )}\n`,
85 );
86 yield* fs.copyFile(path.join(sourceDir, "t3.mjs"), path.join(stageDir, "bin/t3.mjs"));
87 yield* fs.chmod(path.join(stageDir, "bin/t3.mjs"), 0o755);