TypeScript
fix(desktop): align bundled versions with the artifact version (#12768)
Rohan Patnaik310f80ffc422
diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.tsindex abc616f2257..6fab8633672 100644--- a/scripts/build-desktop-artifact.test.ts+++ b/scripts/build-desktop-artifact.test.ts@@ -6,16 +6,23 @@ import * as NodeServices from "@effect/platform-node/NodeServices";import { extractFile } from "@electron/asar";import { assert, it } from "@effect/vitest";import * as ConfigProvider from "effect/ConfigProvider";+import * as Deferred from "effect/Deferred";+import * as Fiber from "effect/Fiber";+import * as Exit from "effect/Exit";import * as FileSystem from "effect/FileSystem";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";+import * as PlatformError from "effect/PlatformError";import * as Option from "effect/Option";import * as Path from "effect/Path";import * as Sink from "effect/Sink";+import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";import { ChildProcess, ChildProcessSpawner } from "effect/process";import {+ buildDesktopBundles,+ DesktopBuildManifestRestoreError,BundleNotSelfContainedError,BuildCommandFailedError,parseWslRuntimeArchiveMembers,@@ -94,10 +101,19 @@ import {WslRuntimeArchiveMissingError,wslRuntimeArchiveStem,} from "./build-desktop-artifact.ts";+import {+ ReleasePackageManifestError,+ releasePackageFiles,+} from "./update-release-package-versions.ts";import { BRAND_ASSET_PATHS } from "./lib/brand-assets.ts";import * as HostProcess from "@t3tools/shared/HostProcess";import { symlinksSupported } from "@t3tools/shared/testing/symlinks";+const encodeModuleUrl = Schema.encodeEffect(Schema.fromJsonString(Schema.String));+const decodePackageVersion = Schema.decodeUnknownEffect(+ Schema.fromJsonString(Schema.Struct({ version: Schema.String })),+);+// Keeps pnpm from auto-installing TypeScript, a types-only peer, into the app.const stagePackageExtensions = {"electron-webauthn": { peerDependenciesMeta: { typescript: { optional: true } } },@@ -262,6 +278,267 @@ const makeWindowsPayloadFixture = Effect.fn("test.makeWindowsPayloadFixture")(fu});it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {+ it.effect("rejects overlapping builds from another process until restoration finishes", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-concurrent-build-" });+ yield* fs.writeFileString(+ path.join(root, "package.json"),+ '{ "scripts": { "build:desktop": "node build.cjs" } }',+ );+ const original = '{ "version": "0.0.42", "private": true }\n';+ for (const relativePath of releasePackageFiles) {+ const filePath = path.join(root, relativePath);+ yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });+ yield* fs.writeFileString(filePath, original);+ }+ yield* fs.writeFileString(+ path.join(root, "build.cjs"),+ `require("node:fs").writeFileSync("version.txt", require("./apps/server/package.json").version);`,+ );+ const restoring = yield* Deferred.make<void>();+ const resume = yield* Deferred.make<void>();+ const contenderPath = path.join(root, "contender.mjs");+ yield* fs.writeFileString(+ contenderPath,+ `import * as Effect from ${yield* encodeModuleUrl(import.meta.resolve("effect/Effect"))};+ import * as NodeServices from ${yield* encodeModuleUrl(import.meta.resolve("@effect/platform-node/NodeServices"))};+ import { buildDesktopBundles } from ${yield* encodeModuleUrl(import.meta.resolve("./build-desktop-artifact.ts"))};+ const result = await Effect.runPromise(buildDesktopBundles(process.argv[2], "0.0.44", false).pipe(+ Effect.as("success"), Effect.catch(error => Effect.succeed(error._tag)),+ Effect.scoped, Effect.provide(NodeServices.layer)));+ process.stdout.write(result);`,+ );+ const first = yield* Effect.forkChild(+ Effect.exit(buildDesktopBundles(root, "0.0.43", false)).pipe(+ Effect.provideService(FileSystem.FileSystem, {+ ...fs,+ writeFileString: (filePath, contents, options) =>+ filePath === path.join(root, releasePackageFiles[0]) && contents === original+ ? Deferred.succeed(restoring, undefined).pipe(+ Effect.andThen(Deferred.await(resume)),+ Effect.andThen(fs.writeFileString(filePath, contents, options)),+ )+ : fs.writeFileString(filePath, contents, options),+ }),+ ),+ );+ yield* Deferred.await(restoring);+ yield* Effect.gen(function* () {+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const child = yield* spawner.spawn(+ ChildProcess.make(process.execPath, [contenderPath, root]),+ );+ const [stdout, stderr, exitCode] = yield* Effect.all(+ [+ child.stdout.pipe(Stream.decodeText, Stream.mkString),+ child.stderr.pipe(Stream.decodeText, Stream.mkString),+ child.exitCode,+ ],+ { concurrency: "unbounded" },+ );+ assert.equal(Number(exitCode), 0, stderr);+ assert.equal(stdout, "DesktopBuildAlreadyRunningError");+ }).pipe(Effect.ensuring(Deferred.succeed(resume, undefined)));+ const firstExit = yield* Fiber.join(first);+ assert.isTrue(Exit.isSuccess(firstExit));+ assert.equal(yield* fs.readFileString(path.join(root, "version.txt")), "0.0.43");+ for (const relativePath of releasePackageFiles) {+ assert.equal(yield* fs.readFileString(path.join(root, relativePath)), original);+ }+ yield* buildDesktopBundles(root, "0.0.44", false);+ assert.equal(yield* fs.readFileString(path.join(root, "version.txt")), "0.0.44");+ for (const relativePath of releasePackageFiles) {+ assert.equal(yield* fs.readFileString(path.join(root, relativePath)), original);+ }+ }),+ );++ it.effect("restores manifests and releases the checkout lock after interruption", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-interrupted-build-" });+ const original = '{ "version": "0.0.42", "private": true }\n';+ for (const relativePath of releasePackageFiles) {+ const filePath = path.join(root, relativePath);+ yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });+ yield* fs.writeFileString(filePath, original);+ }+ const started = yield* Deferred.make<void>();+ const childStopped = yield* Deferred.make<{ lockExists: boolean; version: string }>();+ const build = yield* Effect.forkChild(+ buildDesktopBundles(root, "0.0.43", false).pipe(+ Effect.provideService(+ ChildProcessSpawner.ChildProcessSpawner,+ ChildProcessSpawner.make(() =>+ Effect.acquireRelease(+ Effect.succeed({ ...mockProcess(0), exitCode: Effect.never }).pipe(+ Effect.tap(() => Deferred.succeed(started, undefined)),+ ),+ () =>+ Effect.gen(function* () {+ const lockExists = yield* fs.exists(path.join(root, ".desktop-build.lock"));+ const manifest = yield* decodePackageVersion(+ yield* fs.readFileString(path.join(root, releasePackageFiles[0])),+ );+ yield* Deferred.succeed(childStopped, {+ lockExists,+ version: manifest.version,+ });+ }).pipe(Effect.orDie),+ ),+ ),+ ),+ Effect.scoped,+ ),+ );+ yield* Deferred.await(started);+ const aligned = yield* decodePackageVersion(+ yield* fs.readFileString(path.join(root, releasePackageFiles[0])),+ );+ assert.equal(aligned.version, "0.0.43");+ yield* Fiber.interrupt(build);+ assert.deepEqual(yield* Deferred.await(childStopped), {+ lockExists: true,+ version: "0.0.43",+ });+ assert.isFalse(yield* fs.exists(path.join(root, ".desktop-build.lock")));+ for (const relativePath of releasePackageFiles) {+ assert.equal(yield* fs.readFileString(path.join(root, relativePath)), original);+ }+ yield* buildDesktopBundles(root, "0.0.44", false).pipe(+ Effect.provideService(+ ChildProcessSpawner.ChildProcessSpawner,+ ChildProcessSpawner.make(() => Effect.succeed(mockProcess(0))),+ ),+ );+ assert.isFalse(yield* fs.exists(path.join(root, ".desktop-build.lock")));+ }),+ );++ it.effect(+ "builds web, server and desktop with the resolved version, restores changed manifests and preserves edits to matching ones",+ () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-desktop-build-version-" });+ const packageJson = `{+ "name": "desktop-version-fixture",+ "version": "0.0.42",+ "scripts": { "build:desktop": "node build.cjs" }+ }`;+ yield* fs.writeFileString(path.join(root, "package.json"), packageJson);+ const version = "0.0.43-nightly.20260920.2018";+ const matchingPath = "packages/contracts/package.json";+ const originals = releasePackageFiles.map((relativePath, index) => ({+ relativePath,+ contents: `{ "version": "${relativePath === matchingPath ? version : `0.0.${index + 1}`}", "name": "${relativePath}" }\r\n`,+ }));+ const afterBuild = originals.map(({ relativePath, contents }) => ({+ relativePath,+ contents:+ relativePath === matchingPath+ ? `${JSON.stringify({ version, name: matchingPath, description: "edited during compilation" })}\n`+ : contents,+ }));+ for (const { relativePath, contents } of originals) {+ const filePath = path.join(root, relativePath);+ yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });+ yield* fs.writeFileString(filePath, contents);+ }+ yield* fs.writeFileString(+ path.join(root, "build.cjs"),+ `require("node:fs").writeFileSync("version.txt", [+ process.env.APP_VERSION,+ require("./apps/web/package.json").version,+ require("./apps/server/package.json").version,+ require("./apps/desktop/package.json").version+ ].join("\\n"));+ const manifest = require("./${matchingPath}");+ manifest.description = "edited during compilation";+ require("node:fs").writeFileSync("${matchingPath}", JSON.stringify(manifest) + "\\n");`,+ );+ yield* buildDesktopBundles(root, version, false);+ assert.equal(+ yield* fs.readFileString(path.join(root, "version.txt")),+ [version, version, version, version].join("\n"),+ );+ for (const { relativePath, contents } of afterBuild) {+ assert.equal(yield* fs.readFileString(path.join(root, relativePath)), contents);+ }+ assert.equal(yield* fs.readFileString(path.join(root, "package.json")), packageJson);+ yield* fs.writeFileString(path.join(root, "build.cjs"), "process.exit(1);");+ const failure = yield* Effect.flip(buildDesktopBundles(root, "0.0.44", false));+ assert.instanceOf(failure, BuildCommandFailedError);+ for (const { relativePath, contents } of afterBuild) {+ assert.equal(yield* fs.readFileString(path.join(root, relativePath)), contents);+ }+ const invalidPath = releasePackageFiles[releasePackageFiles.length - 1]!;+ yield* fs.writeFileString(path.join(root, invalidPath), "invalid manifest");+ // A successful child would leave a marker if partial alignment accidentally starts it.+ yield* fs.writeFileString(+ path.join(root, "build.cjs"),+ 'require("node:fs").writeFileSync("unexpected-build.txt", "started");',+ );+ const alignmentFailure = yield* Effect.flip(buildDesktopBundles(root, "0.0.44", false));+ assert.instanceOf(alignmentFailure, ReleasePackageManifestError);+ for (const { relativePath, contents } of afterBuild) {+ assert.equal(+ yield* fs.readFileString(path.join(root, relativePath)),+ relativePath === invalidPath ? "invalid manifest" : contents,+ );+ }+ assert.isFalse(yield* fs.exists(path.join(root, "unexpected-build.txt")));+ assert.isFalse(yield* fs.exists(path.join(root, ".desktop-build.lock")));+ assert.equal(yield* fs.readFileString(path.join(root, "package.json")), packageJson);+ }),+ );++ it.effect("reports a restore failure while still restoring the remaining manifests", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-manifest-restore-failure-" });+ yield* fs.writeFileString(+ path.join(root, "package.json"),+ `{+ "name": "restore-fixture", "scripts": { "build:desktop": "node build.cjs" }+ }`,+ );+ yield* fs.writeFileString(path.join(root, "build.cjs"), "process.exit(0);");+ const original = '{ "version": "0.0.42" }\n';+ for (const relativePath of releasePackageFiles) {+ const filePath = path.join(root, relativePath);+ yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });+ yield* fs.writeFileString(filePath, original);+ }+ const failedPath = path.join(root, releasePackageFiles[0]);+ const writeFailure = PlatformError.systemError({+ _tag: "PermissionDenied",+ module: "FileSystem",+ method: "writeFileString",+ pathOrDescriptor: failedPath,+ });+ const failure = yield* Effect.flip(buildDesktopBundles(root, "0.0.43", false)).pipe(+ Effect.provideService(FileSystem.FileSystem, {+ ...fs,+ writeFileString: (filePath, contents, options) =>+ filePath === failedPath && contents === original+ ? Effect.fail(writeFailure)+ : fs.writeFileString(filePath, contents, options),+ }),+ );+ assert.instanceOf(failure, DesktopBuildManifestRestoreError);+ assert.notEqual(yield* fs.readFileString(failedPath), original);+ for (const relativePath of releasePackageFiles.slice(1)) {+ assert.equal(yield* fs.readFileString(path.join(root, relativePath)), original);+ }+ }),+ );+it("resolves the dedicated nightly updater channel from nightly versions", () => {assert.equal(resolveDesktopUpdateChannel("0.0.17-nightly.20260413.42"), "nightly");assert.equal(resolveDesktopUpdateChannel("0.0.17"), "latest");diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.tsindex a8c535795cb..662e94f7f7d 100644--- a/scripts/build-desktop-artifact.ts+++ b/scripts/build-desktop-artifact.ts@@ -24,6 +24,11 @@ import desktopPackageJson from "../apps/desktop/package.json" with { type: "jsonimport gnomeCaptureBundle from "../apps/desktop/gnome-extension/bundle.json" with { type: "json" };import serverPackageJson from "../apps/server/package.json" with { type: "json" };+import {+ ReleasePackageManifestError,+ releasePackageFiles,+ updateReleasePackageVersions,+} from "./update-release-package-versions.ts";import { applyWebBrandAssets } from "./apply-web-brand-assets.ts";import {BRAND_ASSET_PATHS,@@ -44,6 +49,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";import * as Config from "effect/Config";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";+import * as Exit from "effect/Exit";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Logger from "effect/Logger";@@ -108,6 +114,9 @@ const RepoRoot = Effect.service(Path.Path).pipe(Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),);const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));+const decodeReleasePackageManifest = Schema.decodeEffect(+ Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),+);const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig));const encodeStageWorkspaceConfig = Schema.encodeEffect(fromYaml(StageWorkspaceConfig));@@ -302,6 +311,15 @@ export class InvalidMockUpdateServerPortError extends Schema.TaggedError<Invalid}}+export class DesktopBuildManifestRestoreError extends Schema.TaggedError<DesktopBuildManifestRestoreError>()(+ "DesktopBuildManifestRestoreError",+ { failures: Schema.Array(ReleasePackageManifestError) },+) {+ override get message(): string {+ return `Failed to restore release manifests: ${this.failures.map((failure) => failure.filePath).join(", ")}`;+ }+}+export class BuildCommandFailedError extends Schema.TaggedError<BuildCommandFailedError>()("BuildCommandFailedError",{@@ -1793,6 +1811,113 @@ const runCommand = Effect.fn("runCommand")(function* (}});+export class DesktopBuildAlreadyRunningError extends Schema.TaggedError<DesktopBuildAlreadyRunningError>()(+ "DesktopBuildAlreadyRunningError",+ { lockPath: Schema.String },+) {+ override get message(): string {+ return `Another desktop build owns '${this.lockPath}'. Wait for it to finish. If a build was killed, confirm no desktop build is running, inspect and restore any changed release manifests, then remove this lock.`;+ }+}++const withDesktopBuildLock = Effect.fn("withDesktopBuildLock")(function* <A, E, R>(+ repoRoot: string,+ build: Effect.Effect<A, E, R>,+) {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const lockPath = path.join(repoRoot, ".desktop-build.lock");+ return yield* Effect.acquireUseRelease(+ fs+ .makeDirectory(lockPath)+ .pipe(+ Effect.mapError((error) =>+ error.reason._tag === "AlreadyExists"+ ? new DesktopBuildAlreadyRunningError({ lockPath })+ : error,+ ),+ ),+ // Stop packaging children and finish stage cleanup before another build can enter.+ () => build.pipe(Effect.scoped),+ (_, exit) =>+ fs+ .remove(lockPath, { recursive: true })+ .pipe(+ Effect.catch((error) =>+ Exit.isFailure(exit) ? Effect.logError(error) : Effect.fail(error),+ ),+ ),+ );+});++// The artifact entry point holds the checkout lock through staging/packaging,+// so it calls this implementation without reacquiring its own lock.+const buildDesktopBundlesUnlocked = Effect.fn("buildDesktopBundlesUnlocked")(function* (+ repoRoot: string,+ appVersion: string,+ verbose: boolean,+) {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const spawnCommand = yield* resolveSpawnCommand("vp", ["run", "build:desktop"]);+ yield* Effect.acquireUseRelease(+ Effect.forEach(releasePackageFiles, (relativePath) =>+ Effect.gen(function* () {+ const filePath = path.join(repoRoot, relativePath);+ const contents = yield* fs.readFileString(filePath);+ const needsRestore = yield* decodeReleasePackageManifest(contents).pipe(+ Effect.map((manifest) => manifest.version !== appVersion),+ // Let alignment report invalid manifests after any preceding writes.+ Effect.orElseSucceed(() => false),+ );+ return { filePath, contents, needsRestore };+ }),+ ),+ () =>+ Effect.gen(function* () {+ yield* updateReleasePackageVersions(appVersion, { rootDir: repoRoot });+ // The compiler must stop reading the aligned manifests before restoration.+ yield* runCommand(+ ChildProcess.make(spawnCommand.command, spawnCommand.args, {+ cwd: repoRoot,+ shell: spawnCommand.shell,+ env: { APP_VERSION: appVersion },+ extendEnv: true,+ }),+ { label: "vp run build:desktop", verbose },+ ).pipe(Effect.scoped);+ }),+ (originals, exit) =>+ Effect.gen(function* () {+ const [, failures] = yield* Effect.partition(+ originals.filter(({ needsRestore }) => needsRestore),+ ({ filePath, contents }) =>+ fs+ .writeFileString(filePath, contents)+ .pipe(+ Effect.mapError(+ (cause) =>+ new ReleasePackageManifestError({ operation: "write", filePath, cause }),+ ),+ ),+ );+ if (failures.length === 0) return;+ const error = new DesktopBuildManifestRestoreError({ failures });+ if (Exit.isFailure(exit)) {+ // Cleanup must not hide the original build or alignment failure.+ yield* Effect.logError(error);+ } else {+ return yield* error;+ }+ }),+ );+});++export const buildDesktopBundles = Effect.fn("buildDesktopBundles")(+ (repoRoot: string, appVersion: string, verbose: boolean) =>+ withDesktopBuildLock(repoRoot, buildDesktopBundlesUnlocked(repoRoot, appVersion, verbose)),+);+const desktopBuildProbeSucceeds = Effect.fn("desktopBuildProbeSucceeds")(function* (command: ChildProcess.Command,label: string,@@ -3440,7 +3565,7 @@ export const validateWindowsPackagedPayload = Effect.fn(return { packagedAppDir, fileCount, unpackedFiles } as const;});-const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (+const buildDesktopArtifactUnlocked = Effect.fn("buildDesktopArtifactUnlocked")(function* (options: ResolvedBuildOptions,) {const repoRoot = yield* RepoRoot;@@ -3535,14 +3660,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (if (!options.skipBuild) {yield* Effect.log("[desktop-artifact] Building desktop/server/web artifacts...");- const spawnCommand = yield* resolveSpawnCommand("vp", ["run", "build:desktop"]);- yield* runCommand(- ChildProcess.make(spawnCommand.command, spawnCommand.args, {- cwd: repoRoot,- shell: spawnCommand.shell,- }),- { label: "vp run build:desktop", verbose: options.verbose },- );+ yield* buildDesktopBundlesUnlocked(repoRoot, appVersion, options.verbose);}const requiredBuildInputs = [@@ -3969,6 +4087,13 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* ();});+const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (+ options: ResolvedBuildOptions,+) {+ const repoRoot = yield* RepoRoot;+ return yield* withDesktopBuildLock(repoRoot, buildDesktopArtifactUnlocked(options));+});+const buildDesktopArtifactCli = Command.make("build-desktop-artifact", {platform: Flag.Literals("platform", BuildPlatform.literals).pipe(Flag.withDescription("Build platform (env: T3CODE_DESKTOP_PLATFORM)."),@@ -3985,7 +4110,9 @@ const buildDesktopArtifactCli = Command.make("build-desktop-artifact", {Flag.optional,),buildVersion: Flag.String("build-version").pipe(- Flag.withDescription("Artifact version metadata (env: T3CODE_DESKTOP_VERSION)."),+ Flag.withDescription(+ "Compiled bundle and desktop package version (env: T3CODE_DESKTOP_VERSION).",+ ),Flag.optional,),outputDir: Flag.String("output-dir").pipe(