@devries-cameron20 / t3code-1 / commits / f68d9704fc
Fork 0

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

fix(cli): t3 update checks the database before switching builds (#37873)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Jackson Miller committed Nov 16, 2026 at 21:42 UTC f68d9704fc9ada27a31726d3a907adc3b9b3c593
4 files changed +260 -106
apps/server/src/cli/update.test.ts
+145 -4
@@ -18,6 +18,7 @@ import { afterEach, vi } from "vite-plus/test";
18
19 import packageJson from "../../package.json" with { type: "json" };
20 import * as BootService from "../cloud/bootService.ts";
21 +import { SERVICE_LAUNCHER_PROTOCOL } from "../cloud/serviceProtocol.ts";
22 import {
23 pinnedRuntimePaths,
24 posixLauncherScript,
@@ -131,6 +132,7 @@ it.layer(NodeServices.layer)("t3 update under a managed policy", (it) => {
132 runUpdate({
133 baseDir: "/unused",
134 logsDir: "/unused",
135 + databasePath: "/unused",
136 serverRuntimeStatePath: "/unused",
137 channel: input.channel,
138 requestedVersion: input.requestedVersion,
@@ -565,16 +567,24 @@ it.layer(NodeServices.layer)("t3 update with a background service", (it) => {
567 vi.spyOn(BootService, "layer").mockReturnValue(service);
568 const runner = ProcessRunner.ProcessRunner.of({
569 run: (input) =>
568 - input.args?.includes("--version") === true
569 - ? unrelatedLsof
570 - .run(input)
571 - .pipe(Effect.map((result) => ({ ...result, stdout: `t3 v${version}\n` })))
570 + input.args?.includes("__service-preflight") === true
571 + ? unrelatedLsof.run(input).pipe(
572 + Effect.map((result) => ({
573 + ...result,
574 + stdout: JSON.stringify({
575 + status: "ready",
576 + version,
577 + launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
578 + }),
579 + })),
580 + )
581 : unrelatedLsof.run(input),
582 });
583
584 const output = yield* runUpdate({
585 baseDir,
586 logsDir: baseDir,
587 + databasePath: path.join(baseDir, "statev2.sqlite"),
588 serverRuntimeStatePath: path.join(baseDir, "server-runtime.json"),
589 channel: undefined,
590 requestedVersion: version,
@@ -607,3 +617,134 @@ it.layer(NodeServices.layer)("t3 update with a background service", (it) => {
617 ),
618 );
619 });
620 +
621 +it.layer(NodeServices.layer)("t3 update checks the database before switching", (it) => {
622 + const preflightOutput = (stdout: string, code = 0) => ({
623 + stdout,
624 + stderr: code === 0 ? "" : "Unknown command: __service-preflight",
625 + code: ChildProcessSpawner.ExitCode(code),
626 + timedOut: false,
627 + stdoutTruncated: false,
628 + stderrTruncated: false,
629 + stdoutInvalidUtf8: false,
630 + stderrInvalidUtf8: false,
631 + });
632 + const blockedReason = "This database has migrations that t3@0.1.8 does not know: 79_example.";
633 +
634 + it.effect.each([
635 + {
636 + name: "installs an older target that accepts this database",
637 + targetVersion: "0.1.8",
638 + launcherProtocol: 3,
639 + preflight: preflightOutput(
640 + JSON.stringify({ status: "ready", version: "0.1.8", launcherProtocol: 3 }),
641 + ),
642 + failure: undefined,
643 + },
644 + {
645 + name: "refuses an older target the database is too new for",
646 + targetVersion: "0.1.8",
647 + launcherProtocol: 3,
648 + preflight: preflightOutput(
649 + JSON.stringify({ status: "blocked", version: "0.1.8", reason: blockedReason }),
650 + ),
651 + failure: blockedReason,
652 + },
653 + {
654 + name: "refuses an older target too old to check the database",
655 + targetVersion: "0.1.8",
656 + launcherProtocol: 3,
657 + preflight: preflightOutput("", 1),
658 + failure:
659 + "t3@0.1.8 could not confirm it supports this database (its check exited with code 1), so t3 did not switch to it.",
660 + },
661 + {
662 + // Newer builds keep accepting the current launcher protocol, which may drop 3.
663 + name: "checks a newer target with the current launcher protocol",
664 + targetVersion: "99.0.0",
665 + launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
666 + preflight: preflightOutput(
667 + JSON.stringify({
668 + status: "ready",
669 + version: "99.0.0",
670 + launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
671 + }),
672 + ),
673 + failure: undefined,
674 + },
675 + ])("$name", ({ targetVersion, launcherProtocol, preflight, failure }) =>
676 + Effect.gen(function* () {
677 + const fs = yield* FileSystem.FileSystem;
678 + const path = yield* Path.Path;
679 + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
680 + const databasePath = path.join(baseDir, "userdata", "statev2.sqlite");
681 + const runtime = pinnedRuntimePaths(path, baseDir, targetVersion, "linux");
682 + yield* fs.makeDirectory(runtime.versionDir, { recursive: true });
683 + yield* fs.writeFileString(runtime.entryPath, "");
684 + yield* fs.writeFileString(runtime.sentinelPath, `${targetVersion}\n`);
685 + const service = Layer.mock(BootService.BootService, {
686 + status: Effect.succeed<BootService.BootServiceStatus>({
687 + supported: true,
688 + installed: false,
689 + current: false,
690 + unitPath: path.join(baseDir, "t3code.service"),
691 + logPath: path.join(baseDir, "boot-service.log"),
692 + }),
693 + });
694 + const preflightArgs: Array<ReadonlyArray<string>> = [];
695 + const runner = ProcessRunner.ProcessRunner.of({
696 + run: (input) => {
697 + if (input.args?.includes("__service-preflight") === true) {
698 + preflightArgs.push(input.args);
699 + return Effect.succeed(preflight);
700 + }
701 + // A target's --version always answers, whatever its database support.
702 + return input.args?.includes("--version") === true
703 + ? Effect.succeed(preflightOutput(`t3 v${targetVersion}\n`))
704 + : unrelatedLsof.run(input);
705 + },
706 + });
707 +
708 + const exit = yield* runUpdate({
709 + baseDir,
710 + logsDir: baseDir,
711 + databasePath,
712 + serverRuntimeStatePath: path.join(baseDir, "server-runtime.json"),
713 + channel: undefined,
714 + requestedVersion: targetVersion,
715 + allowDowngrade: true,
716 + assumeYes: true,
717 + }).pipe(
718 + Effect.exit,
719 + Effect.provide(
720 + Layer.mergeAll(
721 + service,
722 + Layer.succeed(ProcessRunner.ProcessRunner, runner),
723 + ManagedPolicy.layerTest(),
724 + Layer.succeed(
725 + HttpClient.HttpClient,
726 + HttpClient.make(() => Effect.die("unexpected release lookup")),
727 + ),
728 + Layer.fresh(TestConsole.layer),
729 + ),
730 + ),
731 + );
732 +
733 + const error = Option.getOrUndefined(Exit.findErrorOption(exit));
734 + assert.equal(error?.message, failure);
735 + assert.equal(Exit.isSuccess(exit), failure === undefined);
736 + assert.deepEqual(preflightArgs, [
737 + [
738 + "__service-preflight",
739 + "--database-path",
740 + databasePath,
741 + "--launcher-protocol",
742 + String(launcherProtocol),
743 + ],
744 + ]);
745 + }).pipe(
746 + Effect.provideService(HostProcess.Platform, "linux"),
747 + Effect.provideService(HostProcess.Environment, { PATH: "" }),
748 + ),
749 + );
750 +});
apps/server/src/cli/update.ts
+37 -25
@@ -26,10 +26,9 @@ import {
26 ensurePinnedRuntimeInstalled,
27 findPosixLauncher,
28 launcherOwnsVersionsDir,
29 - pinnedRuntimeCommand,
29 isUnpublishedRelease,
31 - PinnedRuntimeInstallError,
30 pinnedRuntimePaths,
31 + PinnedRuntimePreflightBlockedError,
32 pinnedRuntimeVersionsDir,
33 prunePinnedRuntimes,
34 recordPinnedRuntimeLauncher,
@@ -37,7 +36,12 @@ import {
36 windowsShimTarget,
37 writePosixLauncher,
38 } from "../cloud/pinnedRuntime.ts";
40 -import { compareExactServiceVersions, isExactServiceVersion } from "../cloud/serviceProtocol.ts";
39 +import {
40 + compareExactServiceVersions,
41 + isExactServiceVersion,
42 + SERVICE_LAUNCHER_PROTOCOL,
43 +} from "../cloud/serviceProtocol.ts";
44 +import { runStagedServicePreflight } from "../cloud/servicePreflight.ts";
45 import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
46 import { managedUpdateMirror, managedUpdateRefusal } from "../policy/managedUpdates.ts";
47 import * as ProcessRunner from "../processRunner.ts";
@@ -266,6 +270,7 @@ export const updateCommand = Command.make("update", {
270 return yield* runUpdate({
271 baseDir: config.baseDir,
272 logsDir: config.logsDir,
273 + databasePath: config.dbPath,
274 serverRuntimeStatePath: config.serverRuntimeStatePath,
275 channel: Option.getOrUndefined(flags.channel),
276 requestedVersion: Option.getOrUndefined(flags.version),
@@ -331,6 +336,7 @@ const belongsToBootService = Effect.fn("cli.update.belongs_to_boot_service")(fun
336 export const runUpdate = Effect.fn("cli.update.run")(function* (input: {
337 readonly baseDir: string;
338 readonly logsDir: string;
339 + readonly databasePath: string;
340 readonly serverRuntimeStatePath: string;
341 readonly channel: CliReleaseChannel | undefined;
342 readonly requestedVersion: string | undefined;
@@ -486,31 +492,37 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: {
492 arch,
493 releaseBaseUrl: mirror?.feedUrl ?? (environment[CLI_RELEASE_BASE_URL_ENV]?.trim() || undefined),
494 requirePublishedRelease: mirror !== undefined,
489 - validate: (paths) =>
490 - runner
491 - .run({
492 - command: pinnedRuntimeCommand(paths).command,
493 - args: [...pinnedRuntimeCommand(paths).args, "--version"],
494 - timeout: Duration.seconds(30),
495 - })
496 - .pipe(
497 - Effect.mapError(
498 - (cause) =>
499 - new PinnedRuntimeInstallError({ step: "verifying the downloaded t3", cause }),
500 - ),
501 - Effect.flatMap((result) =>
502 - result.code === 0 && /\bv(\S+)\s*$/.exec(result.stdout)?.[1] === targetVersion
503 - ? Effect.void
504 - : Effect.fail(
505 - new PinnedRuntimeInstallError({
506 - step: "verifying the downloaded t3",
507 - exitCode: Number(result.code),
495 + validate: (runtime) =>
496 + runStagedServicePreflight({
497 + runner,
498 + runtime,
499 + targetVersion,
500 + databasePath: input.databasePath,
501 + // The target then runs under its own launcher, so only its database check matters. Older
502 + // builds may predate protocol 4; every stable release since 0.0.43 accepts 3.
503 + launcherProtocol:
504 + compareExactServiceVersions(targetVersion, currentVersion) < 0
505 + ? 3
506 + : SERVICE_LAUNCHER_PROTOCOL,
507 + }).pipe(
508 + Effect.catchTags({
509 + PinnedRuntimeInstallError: (error) =>
510 + Effect.fail(
511 + error.exitCode === undefined
512 + ? error
513 + : new PinnedRuntimePreflightBlockedError({
514 + version: targetVersion,
515 + reason: `t3@${targetVersion} could not confirm it supports this database (its check exited with code ${error.exitCode}), so t3 did not switch to it.`,
516 }),
509 - ),
510 - ),
511 - ),
517 + ),
518 + }),
519 + ),
520 }).pipe(
521 Effect.ensuring(Effect.sync(progress.finish)),
522 + Effect.catchTags({
523 + PinnedRuntimePreflightBlockedError: (error) =>
524 + Effect.fail(new CliUpdateError({ reason: error.reason })),
525 + }),
526 Effect.catchIf(isUnpublishedRelease, () =>
527 Effect.fail(
528 new CliUpdateError({
apps/server/src/cloud/selfUpdate.ts
+8 -76
@@ -10,7 +10,6 @@ import {
10 import * as HostProcess from "@t3tools/shared/HostProcess";
11 import * as Config from "effect/Config";
12 import * as Context from "effect/Context";
13 -import * as Duration from "effect/Duration";
13 import * as Effect from "effect/Effect";
14 import * as Option from "effect/Option";
15 import * as Ref from "effect/Ref";
@@ -38,20 +37,14 @@ import * as ProcessRunner from "../processRunner.ts";
37 import {
38 ensurePinnedRuntimeInstalled,
39 isUnpublishedRelease,
41 - pinnedRuntimeCommand,
42 - PinnedRuntimeInstallError,
40 pinnedRuntimePaths,
44 - PinnedRuntimePreflightBlockedError,
41 prunePinnedRuntimes,
42 } from "./pinnedRuntime.ts";
43 import { bootServiceProgramOf, bootServiceUnitPath } from "./bootService.ts";
48 -import { decodeServicePreflightResult } from "./servicePreflight.ts";
44 +import { runStagedServicePreflight } from "./servicePreflight.ts";
45 import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
46 import { isExactServiceVersion } from "./serviceProtocol.ts";
47
52 -// A staged runtime's cold start can take over a minute on a loaded, swapping host.
53 -const PREFLIGHT_TIMEOUT = Duration.minutes(3);
54 -
48 export function resolveServerSelfUpdateCapability(input: {
49 readonly desktopManaged: boolean;
50 readonly launcherManaged: boolean;
@@ -233,74 +226,13 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
226 releaseBaseUrl,
227 requirePublishedRelease: mirror !== undefined,
228 validate: (runtime) =>
236 - runner
237 - .run({
238 - command: pinnedRuntimeCommand(runtime).command,
239 - args: [
240 - ...pinnedRuntimeCommand(runtime).args,
241 - "__service-preflight",
242 - "--database-path",
243 - serverConfig.dbPath,
244 - "--launcher-protocol",
245 - String(launcherProtocol),
246 - ],
247 - timeout: PREFLIGHT_TIMEOUT,
248 - })
249 - .pipe(
250 - Effect.mapError(
251 - (cause) =>
252 - new PinnedRuntimeInstallError({
253 - step: "running the staged service preflight",
254 - cause,
255 - }),
256 - ),
257 - Effect.flatMap(
258 - (
259 - result,
260 - ): Effect.Effect<
261 - void,
262 - PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError
263 - > => {
264 - if (result.code !== 0) {
265 - return Effect.fail(
266 - new PinnedRuntimeInstallError({
267 - step: "running the staged service preflight",
268 - exitCode: Number(result.code),
269 - stdoutLength: result.stdout.length,
270 - stderrLength: result.stderr.length,
271 - }),
272 - );
273 - }
274 - let parsed: unknown;
275 - try {
276 - parsed = JSON.parse(result.stdout.trim());
277 - } catch (cause) {
278 - return Effect.fail(
279 - new PinnedRuntimeInstallError({
280 - step: "decoding the staged service preflight",
281 - cause,
282 - }),
283 - );
284 - }
285 - const preflight = decodeServicePreflightResult(parsed, launcherProtocol);
286 - if (preflight === undefined || preflight.version !== targetVersion) {
287 - return Effect.fail(
288 - new PinnedRuntimeInstallError({
289 - step: "verifying the staged service preflight",
290 - }),
291 - );
292 - }
293 - return preflight.status === "ready"
294 - ? Effect.void
295 - : Effect.fail(
296 - new PinnedRuntimePreflightBlockedError({
297 - version: targetVersion,
298 - reason: preflight.reason,
299 - }),
300 - );
301 - },
302 - ),
303 - ),
229 + runStagedServicePreflight({
230 + runner,
231 + runtime,
232 + targetVersion,
233 + databasePath: serverConfig.dbPath,
234 + launcherProtocol,
235 + }),
236 }).pipe(
237 Effect.mapError((error) => {
238 if (error._tag === "PinnedRuntimePreflightBlockedError") {
apps/server/src/cloud/servicePreflight.ts
+70 -1
@@ -1,13 +1,28 @@
1 +import * as Duration from "effect/Duration";
2 +import * as Effect from "effect/Effect";
3 +import * as Schema from "effect/Schema";
4 +
5 import packageJson from "../../package.json" with { type: "json" };
6 import { BUILD_MIGRATION_HEAD, recordedMigrations } from "../persistence/databaseMigrationHead.ts";
7 import { skippedV2Migrations } from "../persistence/Migrations.ts";
8 import { reconciledV2PreviewHistory } from "../persistence/reconcileV2PreviewMigration.ts";
9 +import type * as ProcessRunner from "../processRunner.ts";
10 +import {
11 + pinnedRuntimeCommand,
12 + PinnedRuntimeInstallError,
13 + type PinnedRuntimePaths,
14 + PinnedRuntimePreflightBlockedError,
15 +} from "./pinnedRuntime.ts";
16 import {
17 isSupportedLauncherProtocol,
18 SERVICE_LAUNCHER_PROTOCOL,
19 type SupportedLauncherProtocol,
20 } from "./serviceProtocol.ts";
21
22 +// A staged runtime's cold start can take over a minute on a loaded, swapping host.
23 +const PREFLIGHT_TIMEOUT = Duration.minutes(3);
24 +const decodePreflightJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
25 +
26 export type ServicePreflightResult =
27 | {
28 readonly status: "ready";
@@ -77,7 +92,7 @@ export function runServicePreflight(input: {
92 return { status: "ready", version, launcherProtocol };
93 }
94
80 -export function decodeServicePreflightResult(
95 +function decodeServicePreflightResult(
96 value: unknown,
97 launcherProtocol: SupportedLauncherProtocol,
98 ): ServicePreflightResult | undefined {
@@ -101,3 +116,57 @@ export function decodeServicePreflightResult(
116 }
117 return undefined;
118 }
119 +
120 +/** Asks a staged runtime whether it can run on this database under this launcher protocol. */
121 +export const runStagedServicePreflight = Effect.fn("cloud.service_preflight.run_staged")(
122 + function* (input: {
123 + readonly runner: ProcessRunner.ProcessRunner["Service"];
124 + readonly runtime: PinnedRuntimePaths;
125 + readonly targetVersion: string;
126 + readonly databasePath: string;
127 + readonly launcherProtocol: SupportedLauncherProtocol;
128 + }) {
129 + const step = "running the staged service preflight";
130 + const command = pinnedRuntimeCommand(input.runtime);
131 + const result = yield* input.runner
132 + .run({
133 + command: command.command,
134 + args: [
135 + ...command.args,
136 + "__service-preflight",
137 + "--database-path",
138 + input.databasePath,
139 + "--launcher-protocol",
140 + String(input.launcherProtocol),
141 + ],
142 + timeout: PREFLIGHT_TIMEOUT,
143 + })
144 + .pipe(Effect.mapError((cause) => new PinnedRuntimeInstallError({ step, cause })));
145 + if (result.code !== 0) {
146 + return yield* new PinnedRuntimeInstallError({
147 + step,
148 + exitCode: Number(result.code),
149 + stdoutLength: result.stdout.length,
150 + stderrLength: result.stderr.length,
151 + });
152 + }
153 + const parsed = yield* decodePreflightJson(result.stdout.trim()).pipe(
154 + Effect.mapError(
155 + (cause) =>
156 + new PinnedRuntimeInstallError({ step: "decoding the staged service preflight", cause }),
157 + ),
158 + );
159 + const preflight = decodeServicePreflightResult(parsed, input.launcherProtocol);
160 + if (preflight === undefined || preflight.version !== input.targetVersion) {
161 + return yield* new PinnedRuntimeInstallError({
162 + step: "verifying the staged service preflight",
163 + });
164 + }
165 + if (preflight.status === "blocked") {
166 + return yield* new PinnedRuntimePreflightBlockedError({
167 + version: input.targetVersion,
168 + reason: preflight.reason,
169 + });
170 + }
171 + },
172 +);