Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as ConfigProvider from "effect/ConfigProvider";
4import * as FileSystem from "effect/FileSystem";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as Sink from "effect/Sink";
10import * as Stream from "effect/Stream";
11import { ChildProcessSpawner } from "effect/unstable/process";
12
13import {
14 BundleNotSelfContainedError,
15 BuildCommandFailedError,
16 createStageWorkspaceConfig,
17 createStagePatchedDependencies,
18 createBuildConfig,
19 DESKTOP_ELECTRON_LANGUAGES,
20 DESKTOP_FILE_EXCLUSIONS,
21 DESKTOP_EXTRA_RESOURCES,
22 InvalidMacPasskeyRpDomainError,
23 InvalidMacPasskeyPublishableKeyError,
24 InvalidMockUpdateServerPortError,
25 UnsupportedDesktopBuildArchitectureError,
26 isMacPasskeySigningConfigurationError,
27 LinuxIconResizeError,
28 MacPasskeySigningConfigurationResolutionError,
29 MissingMacPasskeyProvisioningProfileError,
30 packWindowsServerAsar,
31 renderMacPasskeyEntitlements,
32 resolveClerkPasskeyNativeArtifacts,
33 resolveMacPasskeySigningConfiguration,
34 resolveDesktopRuntimeDependencies,
35 resolveFffNativeDependencies,
36 resolveBuildOptions,
37 resolveDesktopBuildIconAssets,
38 resolveDesktopProductName,
39 resolveDesktopUpdateChannel,
40 resolveDesktopWebAssetBrand,
41 resolveLinuxTargets,
42 resolveResourceMonitorRustTargets,
43 resourceMonitorExecutableName,
44 resolveGitHubPublishConfig,
45 resolveMockUpdateServerPort,
46 resolveMockUpdateServerUrl,
47 resolvePackageManagerUserAgent,
48 stageLinuxIconSize,
49 STAGE_INSTALL_ARGS,
50 ancestorNodeModulesPaths,
51 copyDirectoryPreservingSymlinks,
52 validateWindowsPackagedPayload,
53 WindowsPrimaryNativeProbeError,
54 WindowsPackagedPayloadValidationError,
55 WINDOWS_PACKAGED_PAYLOAD_FILE_LIMIT,
56 WINDOWS_SERVER_ASAR_IGNORE_GLOBS,
57 WINDOWS_SERVER_EXTRA_RESOURCES,
58 WINDOWS_SERVER_ASAR_RESOURCE,
59 WINDOWS_SERVER_ASAR_UNPACK_GLOB,
60 WINDOWS_SERVER_RESOURCE_SOURCE_DIR,
61} from "./build-desktop-artifact.ts";
62import { BRAND_ASSET_PATHS } from "./lib/brand-assets.ts";
63import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
64
65function mockProcess(exitCode: number) {
66 return ChildProcessSpawner.makeHandle({
67 pid: ChildProcessSpawner.ProcessId(1),
68 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
69 isRunning: Effect.succeed(false),
70 kill: () => Effect.void,
71 unref: Effect.succeed(Effect.void),
72 stdin: Sink.drain,
73 stdout: Stream.empty,
74 stderr: Stream.empty,
75 all: Stream.empty,
76 getInputFd: () => Sink.drain,
77 getOutputFd: () => Stream.empty,
78 });
79}
80
81function iconResizeSpawnerLayer(
82 commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>,
83 exitCodes: ReadonlyArray<number>,
84) {
85 let commandIndex = 0;
86 return Layer.succeed(
87 ChildProcessSpawner.ChildProcessSpawner,
88 ChildProcessSpawner.make((command) => {
89 const childProcess = command as unknown as {
90 readonly command: string;
91 readonly args: ReadonlyArray<string>;
92 };
93 commands.push({
94 command: childProcess.command,
95 args: childProcess.args,
96 });
97 return Effect.succeed(mockProcess(exitCodes[commandIndex++] ?? 0));
98 }),
99 );
100}
101
102const makeWindowsPayloadFixture = Effect.fn("test.makeWindowsPayloadFixture")(function* (input: {
103 readonly copyUnpackedNatives: boolean;
104 readonly serverEntrySource?: string;
105}) {
106 const fs = yield* FileSystem.FileSystem;
107 const path = yield* Path.Path;
108 const tempDir = yield* fs.makeTempDirectoryScoped({
109 prefix: "t3-windows-payload-test-",
110 });
111 const sourceDir = path.join(tempDir, "server-source");
112 const serverEntryPath = path.join(sourceDir, "apps/server/dist/bin.mjs");
113 const nativePath = path.join(sourceDir, "node_modules/native/addon.node");
114 yield* fs.makeDirectory(path.dirname(serverEntryPath), { recursive: true });
115 yield* fs.makeDirectory(path.dirname(nativePath), { recursive: true });
116 yield* fs.writeFileString(serverEntryPath, input.serverEntrySource ?? "console.log('server');\n");
117 yield* fs.writeFileString(nativePath, "native-binary");
118
119 const generatedAsarPath = path.join(tempDir, WINDOWS_SERVER_ASAR_RESOURCE);
120 yield* packWindowsServerAsar({ sourceDir, asarPath: generatedAsarPath });
121
122 const stageDistDir = path.join(tempDir, "dist");
123 const packagedAppDir = path.join(stageDistDir, "win-unpacked");
124 const resourcesDir = path.join(packagedAppDir, "resources");
125 yield* fs.makeDirectory(path.join(resourcesDir, "resource-monitor"), { recursive: true });
126 yield* fs.copyFile(generatedAsarPath, path.join(resourcesDir, WINDOWS_SERVER_ASAR_RESOURCE));
127 if (input.copyUnpackedNatives) {
128 yield* fs.copy(
129 `${generatedAsarPath}.unpacked`,
130 path.join(resourcesDir, `${WINDOWS_SERVER_ASAR_RESOURCE}.unpacked`),
131 );
132 }
133 yield* fs.writeFileString(
134 path.join(resourcesDir, "resource-monitor/t3-resource-monitor.exe"),
135 "monitor",
136 );
137 const appExecutableName = "t3code.exe";
138 yield* fs.writeFileString(path.join(packagedAppDir, appExecutableName), "electron");
139 yield* fs.writeFileString(path.join(packagedAppDir, "chrome_crashpad_handler.exe"), "crashpad");
140
141 return {
142 stageDistDir,
143 packagedAppDir,
144 sourceDir,
145 generatedAsarPath,
146 appExecutableName,
147 } as const;
148});
149
150it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
151 it("resolves the dedicated nightly updater channel from nightly versions", () => {
152 assert.equal(resolveDesktopUpdateChannel("0.0.17-nightly.20260413.42"), "nightly");
153 assert.equal(resolveDesktopUpdateChannel("0.0.17"), "latest");
154 });
155
156 it("switches desktop packaging product names to nightly for nightly builds", () => {
157 assert.equal(resolveDesktopProductName("0.0.17"), "T3 Code (Alpha)");
158 assert.equal(resolveDesktopProductName("0.0.17-nightly.20260413.42"), "T3 Code (Nightly)");
159 });
160
161 it("switches desktop packaging icons to the nightly artwork for nightly versions", () => {
162 assert.deepStrictEqual(resolveDesktopBuildIconAssets("0.0.17"), {
163 macIconPng: BRAND_ASSET_PATHS.productionMacIconPng,
164 linuxIconPng: BRAND_ASSET_PATHS.productionLinuxIconPng,
165 windowsIconIco: BRAND_ASSET_PATHS.productionWindowsIconIco,
166 });
167
168 assert.deepStrictEqual(resolveDesktopBuildIconAssets("0.0.17-nightly.20260413.42"), {
169 macIconPng: BRAND_ASSET_PATHS.nightlyMacIconPng,
170 linuxIconPng: BRAND_ASSET_PATHS.nightlyLinuxIconPng,
171 windowsIconIco: BRAND_ASSET_PATHS.nightlyWindowsIconIco,
172 });
173 });
174
175 it("switches the bundled splash and favicon branding for nightly versions", () => {
176 assert.equal(resolveDesktopWebAssetBrand("0.0.17"), "production");
177 assert.equal(resolveDesktopWebAssetBrand("0.0.17-nightly.20260413.42"), "nightly");
178 });
179
180 it.effect("resolves GitHub desktop publish config from Effect config", () =>
181 Effect.gen(function* () {
182 const latestConfig = yield* resolveGitHubPublishConfig("latest").pipe(
183 Effect.provide(
184 ConfigProvider.layer(
185 ConfigProvider.fromEnv({
186 env: {
187 T3CODE_DESKTOP_UPDATE_REPOSITORY: "pingdotgg/t3code",
188 },
189 }),
190 ),
191 ),
192 );
193 const nightlyConfig = yield* resolveGitHubPublishConfig("nightly").pipe(
194 Effect.provide(
195 ConfigProvider.layer(
196 ConfigProvider.fromEnv({
197 env: {
198 GITHUB_REPOSITORY: "pingdotgg/t3code",
199 },
200 }),
201 ),
202 ),
203 );
204
205 assert.deepStrictEqual(latestConfig, {
206 provider: "github",
207 owner: "pingdotgg",
208 repo: "t3code",
209 releaseType: "release",
210 });
211 assert.deepStrictEqual(nightlyConfig, {
212 provider: "github",
213 owner: "pingdotgg",
214 repo: "t3code",
215 releaseType: "prerelease",
216 channel: "nightly",
217 });
218 }),
219 );
220
221 it("omits bundled workspace packages from staged desktop dependencies", () => {
222 assert.deepStrictEqual(
223 resolveDesktopRuntimeDependencies(
224 {
225 "@effect/platform-node": "catalog:",
226 "@t3tools/contracts": "workspace:*",
227 "@t3tools/shared": "workspace:*",
228 "@t3tools/ssh": "workspace:*",
229 "@t3tools/tailscale": "workspace:*",
230 effect: "catalog:",
231 electron: "41.5.0",
232 },
233 {
234 "@effect/platform-node": "4.0.0-beta.59",
235 effect: "4.0.0-beta.59",
236 },
237 ),
238 {
239 "@effect/platform-node": "4.0.0-beta.59",
240 effect: "4.0.0-beta.59",
241 },
242 );
243 });
244
245 it("carries only staged dependency patch metadata into staged desktop installs", () => {
246 assert.deepStrictEqual(
247 createStagePatchedDependencies(
248 {
249 "@expo/metro-config@56.0.13": "patches/@expo%2Fmetro-config@56.0.13.patch",
250 "@ff-labs/fff-node@0.9.4": "patches/@ff-labs__fff-node@0.9.4.patch",
251 "@pierre/diffs@1.1.20": "patches/@pierre%2Fdiffs@1.1.20.patch",
252 "alchemy@2.0.0-beta.49": "patches/alchemy@2.0.0-beta.49.patch",
253 "effect@4.0.0-beta.73": "patches/effect@4.0.0-beta.73.patch",
254 },
255 {
256 "@ff-labs/fff-node": "0.9.4",
257 "@pierre/diffs": "1.1.20",
258 effect: "4.0.0-beta.73",
259 },
260 ),
261 {
262 "@ff-labs/fff-node@0.9.4": "patches/@ff-labs__fff-node@0.9.4.patch",
263 "@pierre/diffs@1.1.20": "patches/@pierre%2Fdiffs@1.1.20.patch",
264 "effect@4.0.0-beta.73": "patches/effect@4.0.0-beta.73.patch",
265 },
266 );
267
268 assert.deepStrictEqual(
269 createStagePatchedDependencies(
270 {
271 "@expo/metro-config@56.0.13": "patches/@expo%2Fmetro-config@56.0.13.patch",
272 },
273 { effect: "4.0.0-beta.73" },
274 ),
275 {},
276 );
277 });
278
279 it("installs optional native dependencies for the target desktop architecture", () => {
280 assert.deepStrictEqual(STAGE_INSTALL_ARGS, ["install", "--prod"]);
281 assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "mac", arch: "x64" }), {
282 supportedArchitectures: {
283 os: ["darwin"],
284 cpu: ["x64"],
285 },
286 });
287 assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "linux", arch: "x64" }), {
288 supportedArchitectures: {
289 os: ["linux"],
290 cpu: ["x64"],
291 libc: ["glibc"],
292 },
293 });
294 // The Windows app stage only serves the desktop main process; the server
295 // sidecar stage is the one that needs Linux natives (below).
296 assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "win", arch: "x64" }), {
297 supportedArchitectures: {
298 os: ["win32"],
299 cpu: ["x64"],
300 },
301 });
302 // The server sidecar stage bundles the same-architecture WSL (Linux,
303 // glibc) backend, so its install must fetch Linux native optional deps
304 // (e.g. ffi-rs) too — and must be hoisted so the tree survives asar
305 // packing and runtime extraction without symlinks.
306 assert.deepStrictEqual(
307 createStageWorkspaceConfig({ platform: "win", arch: "x64", linuxServerBackend: true }),
308 {
309 supportedArchitectures: {
310 os: ["win32", "linux"],
311 cpu: ["x64"],
312 libc: ["glibc"],
313 },
314 nodeLinker: "hoisted",
315 },
316 );
317 assert.deepStrictEqual(
318 createStageWorkspaceConfig({ platform: "win", arch: "arm64", linuxServerBackend: true }),
319 {
320 supportedArchitectures: {
321 os: ["win32", "linux"],
322 cpu: ["arm64"],
323 libc: ["glibc"],
324 },
325 nodeLinker: "hoisted",
326 },
327 );
328 assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "mac", arch: "universal" }), {
329 supportedArchitectures: {
330 os: ["darwin"],
331 cpu: ["arm64", "x64"],
332 },
333 });
334 });
335
336 it("stages pnpm 11 allowBuilds and patchedDependencies in the workspace yaml", () => {
337 assert.deepStrictEqual(
338 createStageWorkspaceConfig({
339 platform: "linux",
340 arch: "x64",
341 allowBuilds: {
342 electron: true,
343 "node-pty": true,
344 "browser-tabs-lock": false,
345 },
346 patchedDependencies: {
347 "effect@4.0.0-beta.73": "patches/effect@4.0.0-beta.73.patch",
348 },
349 overrides: {
350 effect: "4.0.0-beta.73",
351 },
352 }),
353 {
354 supportedArchitectures: {
355 os: ["linux"],
356 cpu: ["x64"],
357 libc: ["glibc"],
358 },
359 allowBuilds: {
360 electron: true,
361 "node-pty": true,
362 "browser-tabs-lock": false,
363 },
364 patchedDependencies: {
365 "effect@4.0.0-beta.73": "patches/effect@4.0.0-beta.73.patch",
366 },
367 overrides: {
368 effect: "4.0.0-beta.73",
369 },
370 },
371 );
372
373 // Empty maps must not be written — pnpm would still require reviewed
374 // packages if allowBuilds is present but incomplete, and omitting empty
375 // patchedDependencies keeps the stage yaml minimal.
376 assert.deepStrictEqual(
377 createStageWorkspaceConfig({
378 platform: "mac",
379 arch: "arm64",
380 allowBuilds: {},
381 patchedDependencies: {},
382 overrides: {},
383 }),
384 {
385 supportedArchitectures: {
386 os: ["darwin"],
387 cpu: ["arm64"],
388 },
389 },
390 );
391 });
392
393 it("limits Electron locales and excludes the unused Claude SDK executable", () => {
394 assert.deepStrictEqual(DESKTOP_ELECTRON_LANGUAGES, ["en-US"]);
395 assert.deepStrictEqual(DESKTOP_FILE_EXCLUSIONS, [
396 "!**/node_modules/@anthropic-ai/claude-agent-sdk-*/**/*",
397 "!apps/desktop/prod-resources/windows-server",
398 "!apps/desktop/prod-resources/windows-server/**/*",
399 ]);
400 assert.equal(WINDOWS_SERVER_RESOURCE_SOURCE_DIR, "apps/desktop/prod-resources/windows-server");
401 assert.deepStrictEqual(WINDOWS_SERVER_EXTRA_RESOURCES, [
402 {
403 from: "apps/desktop/prod-resources/windows-server",
404 to: ".",
405 filter: ["server.asar", "server.asar.unpacked/**/*"],
406 },
407 ]);
408 });
409
410 it.effect("applies platform-specific packaging to the build config", () =>
411 Effect.gen(function* () {
412 const mac = yield* createBuildConfig(
413 "mac",
414 "dmg",
415 "1.2.3",
416 false,
417 false,
418 undefined,
419 undefined,
420 );
421 const linux = yield* createBuildConfig(
422 "linux",
423 "AppImage",
424 "1.2.3",
425 false,
426 false,
427 undefined,
428 undefined,
429 );
430 const win = yield* createBuildConfig(
431 "win",
432 "nsis",
433 "1.2.3",
434 false,
435 false,
436 undefined,
437 undefined,
438 );
439
440 // All platforms keep app.asar fully packed; Windows ships the server
441 // tree as the hand-packed server.asar sidecar in extraResources instead
442 // of unpacking thousands of loose files at install time.
443 assert.notProperty(mac, "asarUnpack");
444 assert.notProperty(linux, "asarUnpack");
445 assert.notProperty(win, "asarUnpack");
446 assert.deepStrictEqual(win.extraResources, [
447 {
448 from: "apps/desktop/prod-resources/resource-monitor",
449 to: "resource-monitor",
450 },
451 ...WINDOWS_SERVER_EXTRA_RESOURCES,
452 ]);
453 assert.deepStrictEqual(win.nsis, { differentialPackage: true });
454 // Native binaries and helper executables cannot load from inside an
455 // asar; everything else stays packed. The Claude SDK platform packages
456 // and .bin shims never ship.
457 assert.equal(
458 WINDOWS_SERVER_ASAR_UNPACK_GLOB,
459 "{**/*.node,**/*.dll,**/*.exe,**/*.so,**/*.so.*,**/*.dylib}",
460 );
461 assert.deepStrictEqual(WINDOWS_SERVER_ASAR_IGNORE_GLOBS, [
462 "**/node_modules/@anthropic-ai/claude-agent-sdk-*",
463 "**/node_modules/@anthropic-ai/claude-agent-sdk-*/**",
464 "**/node_modules/.bin",
465 "**/node_modules/.bin/**",
466 ]);
467 // Linux must register the renderer schemes so the generated .desktop
468 // entry advertises MimeType=x-scheme-handler/t3code; for OAuth deep links.
469 assert.deepStrictEqual((linux.linux as Record<string, unknown>).protocols, [
470 { name: "T3 Code", schemes: ["t3code", "t3code-dev"] },
471 ]);
472 for (const config of [mac, linux, win]) {
473 assert.deepStrictEqual(config.electronLanguages, DESKTOP_ELECTRON_LANGUAGES);
474 assert.deepStrictEqual(config.files, DESKTOP_FILE_EXCLUSIONS);
475 }
476 }).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))),
477 );
478
479 it.effect("validates every ASAR-unpacked native in the packaged Windows payload", () =>
480 Effect.scoped(
481 Effect.gen(function* () {
482 const fs = yield* FileSystem.FileSystem;
483 const path = yield* Path.Path;
484 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
485 const result = yield* validateWindowsPackagedPayload({
486 stageDistDir: fixture.stageDistDir,
487 appExecutableName: fixture.appExecutableName,
488 targetArch: "x64",
489 });
490
491 const secondAsarPath = path.join(path.dirname(fixture.generatedAsarPath), "second.asar");
492 yield* packWindowsServerAsar({
493 sourceDir: fixture.sourceDir,
494 asarPath: secondAsarPath,
495 });
496 const [firstAsar, secondAsar] = yield* Effect.all([
497 fs.readFile(fixture.generatedAsarPath),
498 fs.readFile(secondAsarPath),
499 ]);
500
501 assert.equal(result.packagedAppDir, fixture.packagedAppDir);
502 assert.deepStrictEqual(result.unpackedFiles, ["node_modules/native/addon.node"]);
503 assert.isBelow(result.fileCount, WINDOWS_PACKAGED_PAYLOAD_FILE_LIMIT);
504 assert.deepStrictEqual(secondAsar, firstAsar);
505 }),
506 ),
507 );
508
509 it.effect("probes fff through the packaged Windows primary instead of helper executables", () => {
510 const commands: Array<{
511 readonly command: string;
512 readonly args: ReadonlyArray<string>;
513 readonly options: {
514 readonly cwd?: string;
515 readonly env?: Readonly<Record<string, string | undefined>>;
516 };
517 }> = [];
518 const spawnerLayer = Layer.succeed(
519 ChildProcessSpawner.ChildProcessSpawner,
520 ChildProcessSpawner.make((command) => {
521 commands.push(command as unknown as (typeof commands)[number]);
522 return Effect.succeed(mockProcess(0));
523 }),
524 );
525
526 return Effect.scoped(
527 Effect.gen(function* () {
528 const path = yield* Path.Path;
529 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
530 yield* validateWindowsPackagedPayload({
531 stageDistDir: fixture.stageDistDir,
532 appExecutableName: fixture.appExecutableName,
533 targetArch: "x64",
534 });
535
536 const primaryProbe = commands.find(
537 (command) => command.options.env?.ELECTRON_RUN_AS_NODE === "1",
538 );
539 if (primaryProbe === undefined) return assert.fail("Windows primary probe was not spawned");
540
541 assert.equal(
542 primaryProbe.command,
543 path.join(fixture.packagedAppDir, fixture.appExecutableName),
544 );
545 assert.deepStrictEqual(primaryProbe.args.slice(0, 3), [
546 "--no-global-search-paths",
547 "--input-type=module",
548 "--eval",
549 ]);
550 assert.include(primaryProbe.args[3], "FileFinder.create");
551 assert.equal(
552 primaryProbe.args[4],
553 path.join(
554 fixture.packagedAppDir,
555 "resources/server.asar/node_modules/@ff-labs/fff-node/dist/src/index.js",
556 ),
557 );
558 assert.equal(primaryProbe.options.cwd, fixture.packagedAppDir);
559 assert.equal(primaryProbe.options.env?.NODE_PATH, "");
560 }),
561 ).pipe(
562 Effect.provide(
563 Layer.mergeAll(
564 spawnerLayer,
565 Layer.succeed(HostProcessPlatform, "win32"),
566 Layer.succeed(HostProcessArchitecture, "x64"),
567 ),
568 ),
569 );
570 });
571
572 it.effect("skips the primary native probe for cross-architecture Windows payloads", () => {
573 const commands: Array<{
574 readonly command: string;
575 readonly options: {
576 readonly env?: Readonly<Record<string, string | undefined>>;
577 };
578 }> = [];
579 const spawnerLayer = Layer.succeed(
580 ChildProcessSpawner.ChildProcessSpawner,
581 ChildProcessSpawner.make((command) => {
582 commands.push(command as unknown as (typeof commands)[number]);
583 return Effect.succeed(mockProcess(0));
584 }),
585 );
586
587 return Effect.scoped(
588 Effect.gen(function* () {
589 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
590 yield* validateWindowsPackagedPayload({
591 stageDistDir: fixture.stageDistDir,
592 appExecutableName: fixture.appExecutableName,
593 targetArch: "arm64",
594 });
595
596 assert.isFalse(
597 commands.some((command) => command.options.env?.ELECTRON_RUN_AS_NODE === "1"),
598 );
599 assert.isTrue(
600 commands.some(
601 (command) =>
602 command.command === process.execPath && command.options.env?.NODE_PATH === "",
603 ),
604 );
605 }),
606 ).pipe(
607 Effect.provide(
608 Layer.mergeAll(
609 spawnerLayer,
610 Layer.succeed(HostProcessPlatform, "win32"),
611 Layer.succeed(HostProcessArchitecture, "x64"),
612 ),
613 ),
614 );
615 });
616
617 it.effect("rejects a cross-architecture Windows payload without its primary executable", () =>
618 Effect.scoped(
619 Effect.gen(function* () {
620 const fs = yield* FileSystem.FileSystem;
621 const path = yield* Path.Path;
622 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
623 const executablePath = path.join(fixture.packagedAppDir, fixture.appExecutableName);
624 yield* fs.remove(executablePath);
625
626 const error = yield* validateWindowsPackagedPayload({
627 stageDistDir: fixture.stageDistDir,
628 appExecutableName: fixture.appExecutableName,
629 targetArch: "arm64",
630 }).pipe(Effect.flip);
631
632 assert.instanceOf(error, WindowsPrimaryNativeProbeError);
633 assert.equal(error.executablePath, executablePath);
634 }),
635 ).pipe(
636 Effect.provide(
637 Layer.mergeAll(
638 Layer.succeed(HostProcessPlatform, "win32"),
639 Layer.succeed(HostProcessArchitecture, "x64"),
640 ),
641 ),
642 ),
643 );
644
645 it.effect("rejects a packaged sidecar whose ASAR-unpacked native is missing", () =>
646 Effect.scoped(
647 Effect.gen(function* () {
648 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: false });
649 const error = yield* validateWindowsPackagedPayload({
650 stageDistDir: fixture.stageDistDir,
651 appExecutableName: fixture.appExecutableName,
652 targetArch: "x64",
653 }).pipe(Effect.flip);
654
655 assert.instanceOf(error, WindowsPackagedPayloadValidationError);
656 assert.equal(error.reason, "unpacked-native-missing");
657 assert.deepStrictEqual(error.missingFiles, [
658 "server.asar.unpacked/node_modules/native/addon.node",
659 ]);
660 }),
661 ),
662 );
663
664 it.effect("rejects directories in place of packaged executable files", () =>
665 Effect.scoped(
666 Effect.gen(function* () {
667 const fs = yield* FileSystem.FileSystem;
668 const path = yield* Path.Path;
669 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
670 const nativePath = path.join(
671 fixture.packagedAppDir,
672 "resources/server.asar.unpacked/node_modules/native/addon.node",
673 );
674 yield* fs.remove(nativePath);
675 yield* fs.makeDirectory(nativePath);
676
677 const nativeError = yield* validateWindowsPackagedPayload({
678 stageDistDir: fixture.stageDistDir,
679 appExecutableName: fixture.appExecutableName,
680 targetArch: "x64",
681 }).pipe(Effect.flip);
682 assert.instanceOf(nativeError, WindowsPackagedPayloadValidationError);
683 assert.equal(nativeError.reason, "unpacked-native-missing");
684 assert.deepStrictEqual(nativeError.missingFiles, [
685 "server.asar.unpacked/node_modules/native/addon.node",
686 ]);
687
688 yield* fs.remove(nativePath, { recursive: true });
689 yield* fs.writeFileString(nativePath, "native-binary");
690 const resourceMonitorPath = path.join(
691 fixture.packagedAppDir,
692 "resources/resource-monitor/t3-resource-monitor.exe",
693 );
694 yield* fs.remove(resourceMonitorPath);
695 yield* fs.makeDirectory(resourceMonitorPath);
696
697 const resourceMonitorError = yield* validateWindowsPackagedPayload({
698 stageDistDir: fixture.stageDistDir,
699 appExecutableName: fixture.appExecutableName,
700 targetArch: "x64",
701 }).pipe(Effect.flip);
702 assert.instanceOf(resourceMonitorError, WindowsPackagedPayloadValidationError);
703 assert.equal(resourceMonitorError.reason, "resource-monitor-missing");
704 assert.deepStrictEqual(resourceMonitorError.missingFiles, [
705 "resource-monitor/t3-resource-monitor.exe",
706 ]);
707 }),
708 ),
709 );
710
711 it.effect("rejects a Windows payload that regresses above the file-count budget", () =>
712 Effect.scoped(
713 Effect.gen(function* () {
714 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
715 const error = yield* validateWindowsPackagedPayload({
716 stageDistDir: fixture.stageDistDir,
717 appExecutableName: fixture.appExecutableName,
718 targetArch: "x64",
719 fileLimit: 2,
720 }).pipe(Effect.flip);
721
722 assert.instanceOf(error, WindowsPackagedPayloadValidationError);
723 assert.equal(error.reason, "file-limit-exceeded");
724 assert.isAbove(error.fileCount ?? 0, 2);
725 }),
726 ),
727 );
728
729 it.effect("rejects a sidecar whose extracted server bundle cannot resolve", () =>
730 Effect.scoped(
731 Effect.gen(function* () {
732 const fixture = yield* makeWindowsPayloadFixture({
733 copyUnpackedNatives: true,
734 serverEntrySource: 'import "t3code-deliberately-missing-package";\n',
735 });
736 const error = yield* validateWindowsPackagedPayload({
737 stageDistDir: fixture.stageDistDir,
738 appExecutableName: fixture.appExecutableName,
739 targetArch: "x64",
740 }).pipe(Effect.flip);
741
742 assert.instanceOf(error, BundleNotSelfContainedError);
743 assert.include(error.output, "t3code-deliberately-missing-package");
744 }),
745 ),
746 );
747
748 it.effect("preserves both Linux icon resize failures with structural context", () => {
749 const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> = [];
750
751 return Effect.gen(function* () {
752 const error = yield* stageLinuxIconSize("source.png", "target.png", 512, false).pipe(
753 Effect.provide(iconResizeSpawnerLayer(commands, [1, 2])),
754 Effect.flip,
755 );
756
757 assert.instanceOf(error, LinuxIconResizeError);
758 assert.equal(error.operation, "resize");
759 assert.equal(error.iconSize, 512);
760 assert.equal(error.primaryTool, "magick");
761 assert.equal(error.fallbackTool, "convert");
762 assert.include(error.message, "512x512");
763 assert.include(error.message, "`magick`");
764 assert.include(error.message, "`convert`");
765 assert.notInclude(error.message, "non-zero exit code");
766
767 assert.instanceOf(error.cause, AggregateError);
768 const aggregateCause = error.cause as AggregateError;
769 assert.lengthOf(aggregateCause.errors, 2);
770 assert.strictEqual(aggregateCause.cause, aggregateCause.errors[0]);
771 assert.instanceOf(aggregateCause.errors[0], BuildCommandFailedError);
772 assert.instanceOf(aggregateCause.errors[1], BuildCommandFailedError);
773 const primaryError = aggregateCause.errors[0] as BuildCommandFailedError;
774 const fallbackError = aggregateCause.errors[1] as BuildCommandFailedError;
775 assert.equal(primaryError.command, "magick linux icon 512x512");
776 assert.equal(primaryError.exitCode, 1);
777 assert.include(primaryError.message, "magick linux icon");
778 assert.equal(fallbackError.command, "convert linux icon 512x512");
779 assert.equal(fallbackError.exitCode, 2);
780 assert.include(fallbackError.message, "convert linux icon");
781 assert.deepStrictEqual(
782 commands.map(({ command }) => command),
783 ["magick", "convert"],
784 );
785 });
786 });
787
788 it("derives macOS passkey signing configuration from the Clerk publishable key", () => {
789 const configuration = resolveMacPasskeySigningConfiguration({
790 T3CODE_APPLE_TEAM_ID: "abc1234567",
791 T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
792 T3CODE_CLERK_PUBLISHABLE_KEY: `pk_test_${btoa("example.clerk.accounts.dev$")}`,
793 });
794
795 assert.deepStrictEqual(configuration, {
796 appId: "com.t3tools.t3code",
797 teamId: "ABC1234567",
798 rpDomains: ["example.clerk.accounts.dev"],
799 provisioningProfilePath: "/tmp/t3code.provisionprofile",
800 });
801 });
802
803 it("normalizes explicit macOS passkey RP domains and renders required entitlements", () => {
804 const configuration = resolveMacPasskeySigningConfiguration({
805 T3CODE_APPLE_TEAM_ID: "ABC1234567",
806 T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
807 T3CODE_CLERK_PASSKEY_RP_DOMAINS:
808 " Clerk.Example.com,example.clerk.accounts.dev,clerk.example.com ",
809 });
810 const entitlements = renderMacPasskeyEntitlements(configuration);
811
812 assert.deepStrictEqual(configuration.rpDomains, [
813 "clerk.example.com",
814 "example.clerk.accounts.dev",
815 ]);
816 assert.include(entitlements, "<string>ABC1234567.com.t3tools.t3code</string>");
817 assert.include(entitlements, "<string>webcredentials:clerk.example.com</string>");
818 assert.include(entitlements, "<string>webcredentials:example.clerk.accounts.dev</string>");
819 assert.include(entitlements, "<key>com.apple.security.cs.allow-jit</key>");
820 });
821
822 it("rejects incomplete macOS passkey signing configuration", () => {
823 const captureError = (env: Readonly<Record<string, string | undefined>>) => {
824 try {
825 resolveMacPasskeySigningConfiguration(env);
826 } catch (error) {
827 return error;
828 }
829 return assert.fail("Expected passkey signing configuration to fail.");
830 };
831
832 const missingProfileError = captureError({
833 T3CODE_APPLE_TEAM_ID: "ABC1234567",
834 T3CODE_CLERK_PASSKEY_RP_DOMAINS: "example.clerk.accounts.dev",
835 });
836 assert.instanceOf(missingProfileError, MissingMacPasskeyProvisioningProfileError);
837 assert.equal(
838 missingProfileError.message,
839 "T3CODE_MACOS_PROVISIONING_PROFILE must point to an Associated Domains provisioning profile.",
840 );
841
842 const unsafeDomain =
843 "https://domain-user:domain-secret@example.clerk.accounts.dev/path?token=query-secret";
844 const invalidDomainError = captureError({
845 T3CODE_APPLE_TEAM_ID: "ABC1234567",
846 T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
847 T3CODE_CLERK_PASSKEY_RP_DOMAINS: unsafeDomain,
848 });
849 assert.instanceOf(invalidDomainError, InvalidMacPasskeyRpDomainError);
850 assert.equal(invalidDomainError.reason, "scheme-not-allowed");
851 assert.equal(invalidDomainError.inputLength, unsafeDomain.length);
852 assert.equal(invalidDomainError.message, "Invalid passkey RP domain (scheme-not-allowed).");
853 assert.notProperty(invalidDomainError, "domain");
854 assert.notProperty(invalidDomainError, "cause");
855 const serializedInvalidDomainError = JSON.stringify(invalidDomainError);
856 assert.notInclude(serializedInvalidDomainError, unsafeDomain);
857 assert.notInclude(serializedInvalidDomainError, "domain-user");
858 assert.notInclude(serializedInvalidDomainError, "domain-secret");
859 assert.notInclude(serializedInvalidDomainError, "query-secret");
860 assert.throws(
861 () =>
862 resolveMacPasskeySigningConfiguration({
863 T3CODE_APPLE_TEAM_ID: "ABC1234567",
864 T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
865 T3CODE_CLERK_PASSKEY_RP_DOMAINS: "example.clerk.accounts.dev:8443",
866 }),
867 /Invalid passkey RP domain/u,
868 );
869 const invalidPublishableKeyError = captureError({
870 T3CODE_APPLE_TEAM_ID: "ABC1234567",
871 T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
872 T3CODE_CLERK_PUBLISHABLE_KEY: "pk_test_%",
873 });
874 assert.instanceOf(invalidPublishableKeyError, InvalidMacPasskeyPublishableKeyError);
875 assert.ok(invalidPublishableKeyError.cause);
876 assert.equal(invalidPublishableKeyError.message, "T3CODE_CLERK_PUBLISHABLE_KEY is invalid.");
877 assert.notProperty(invalidPublishableKeyError, "publishableKey");
878 assert.notInclude(invalidPublishableKeyError.message, "pk_test_%");
879 });
880
881 it("preserves known passkey signing configuration errors at the build boundary", () => {
882 const decodingCause = new Error("publishable-key-decode-failed");
883 const knownError = new InvalidMacPasskeyPublishableKeyError({ cause: decodingCause });
884 const error = MacPasskeySigningConfigurationResolutionError.fromCause(knownError);
885
886 assert.strictEqual(error, knownError);
887 assert.instanceOf(error, InvalidMacPasskeyPublishableKeyError);
888 assert.strictEqual(error.cause, decodingCause);
889 assert.isTrue(isMacPasskeySigningConfigurationError(error));
890 });
891
892 it("wraps unknown passkey signing configuration defects without copying cause text", () => {
893 const secret = "pk_test_do-not-retain";
894 const cause = new Error(secret);
895 const error = MacPasskeySigningConfigurationResolutionError.fromCause(cause);
896
897 assert.instanceOf(error, MacPasskeySigningConfigurationResolutionError);
898 assert.strictEqual(error.cause, cause);
899 assert.equal(error.message, "Failed to resolve macOS passkey signing configuration.");
900 assert.notInclude(error.message, secret);
901 });
902
903 it.effect("adds passkey entitlements and both renderer protocols to signed macOS builds", () =>
904 Effect.gen(function* () {
905 const config = yield* createBuildConfig("mac", "dmg", "1.2.3", true, false, undefined, {
906 entitlementsPath: "/tmp/entitlements.mac.plist",
907 provisioningProfilePath: "/tmp/t3code.provisionprofile",
908 });
909
910 const mac = config.mac as Record<string, unknown>;
911 assert.equal(config.appId, "com.t3tools.t3code");
912 assert.equal(mac.entitlements, "/tmp/entitlements.mac.plist");
913 assert.equal(mac.provisioningProfile, "/tmp/t3code.provisionprofile");
914 assert.deepStrictEqual(mac.protocols, [
915 { name: "T3 Code", schemes: ["t3code", "t3code-dev"] },
916 ]);
917 }).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))),
918 );
919
920 it.effect("keeps executable resource editing enabled for unsigned Windows builds", () =>
921 Effect.gen(function* () {
922 const config = yield* createBuildConfig(
923 "win",
924 "nsis",
925 "1.2.3",
926 false,
927 false,
928 undefined,
929 undefined,
930 );
931
932 const win = config.win as Record<string, unknown>;
933 assert.equal(win.icon, "icon.ico");
934 assert.equal(win.signAndEditExecutable, true);
935 assert.notProperty(win, "azureSignOptions");
936 }).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))),
937 );
938
939 it("splits a comma-separated Linux target into one target per package", () => {
940 assert.deepStrictEqual(resolveLinuxTargets("AppImage"), ["AppImage"]);
941 assert.deepStrictEqual(resolveLinuxTargets("AppImage,deb,rpm"), ["AppImage", "deb", "rpm"]);
942 assert.deepStrictEqual(resolveLinuxTargets(" AppImage , deb "), ["AppImage", "deb"]);
943 });
944
945 it.effect("emits every requested Linux package from a single build", () =>
946 Effect.gen(function* () {
947 const all = yield* createBuildConfig(
948 "linux",
949 "AppImage,deb,rpm",
950 "1.2.3",
951 false,
952 false,
953 undefined,
954 undefined,
955 );
956 const appImageOnly = yield* createBuildConfig(
957 "linux",
958 "AppImage",
959 "1.2.3",
960 false,
961 false,
962 undefined,
963 undefined,
964 );
965
966 assert.deepStrictEqual((all.linux as Record<string, unknown>).target, [
967 "AppImage",
968 "deb",
969 "rpm",
970 ]);
971 // Both fpm-backed formats are configured from the one run.
972 assert.property(all, "deb");
973 assert.property(all, "rpm");
974
975 // An AppImage-only build stays free of package-format sections.
976 assert.notProperty(appImageOnly, "deb");
977 assert.notProperty(appImageOnly, "rpm");
978 }).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))),
979 );
980
981 it.effect("includes distribution metadata in Linux package builds", () =>
982 Effect.gen(function* () {
983 const config = yield* createBuildConfig(
984 "linux",
985 "deb",
986 "1.2.3",
987 false,
988 false,
989 undefined,
990 undefined,
991 );
992
993 const linux = config.linux as Record<string, unknown>;
994 assert.deepStrictEqual(linux.target, ["deb"]);
995 assert.equal(linux.executableName, "t3code");
996 assert.equal(linux.category, "Development");
997 assert.equal(linux.maintainer, "T3 Tools <support@t3.gg>");
998 assert.equal(linux.vendor, "T3 Tools");
999 assert.equal(linux.synopsis, "A desktop GUI for AI coding agents");
1000 assert.equal(linux.syncDesktopName, true);
1001
1002 const deb = config.deb as Record<string, unknown>;
1003 assert.deepStrictEqual(deb.depends, [
1004 "libgtk-3-0",
1005 "libnotify4",
1006 "libnss3",
1007 "libxss1",
1008 "libxtst6",
1009 "xdg-utils",
1010 "libatspi2.0-0",
1011 "libuuid1",
1012 "libsecret-1-0",
1013 "libasound2t64 | libasound2",
1014 "libgbm1",
1015 ]);
1016 }).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))),
1017 );
1018
1019 it.effect("includes runtime dependencies in RPM packages", () =>
1020 Effect.gen(function* () {
1021 const config = yield* createBuildConfig(
1022 "linux",
1023 "rpm",
1024 "1.2.3",
1025 false,
1026 false,
1027 undefined,
1028 undefined,
1029 );
1030
1031 const rpm = config.rpm as Record<string, unknown>;
1032 assert.deepStrictEqual(rpm.depends, [
1033 "gtk3",
1034 "libnotify",
1035 "nss",
1036 "libXScrnSaver",
1037 "(libXtst or libXtst6)",
1038 "xdg-utils",
1039 "at-spi2-core",
1040 "(libuuid or libuuid1)",
1041 "alsa-lib",
1042 "libsecret",
1043 "mesa-libgbm",
1044 ]);
1045 }).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))),
1046 );
1047
1048 it("stages the resource monitor as an external executable resource", () => {
1049 assert.deepStrictEqual(DESKTOP_EXTRA_RESOURCES, [
1050 {
1051 from: "apps/desktop/prod-resources/resource-monitor",
1052 to: "resource-monitor",
1053 },
1054 ]);
1055 assert.deepStrictEqual(resolveResourceMonitorRustTargets("mac", "universal"), [
1056 "aarch64-apple-darwin",
1057 "x86_64-apple-darwin",
1058 ]);
1059 assert.deepStrictEqual(resolveResourceMonitorRustTargets("linux", "x64"), [
1060 "x86_64-unknown-linux-gnu",
1061 ]);
1062 assert.deepStrictEqual(resolveResourceMonitorRustTargets("win", "arm64"), [
1063 "aarch64-pc-windows-msvc",
1064 ]);
1065 assert.equal(resourceMonitorExecutableName("mac"), "t3-resource-monitor");
1066 assert.equal(resourceMonitorExecutableName("win"), "t3-resource-monitor.exe");
1067 });
1068 it("promotes target fff binaries to direct staged dependencies", () => {
1069 assert.deepStrictEqual(resolveFffNativeDependencies("mac", "arm64", "0.9.4"), {
1070 "@ff-labs/fff-bin-darwin-arm64": "0.9.4",
1071 });
1072 assert.deepStrictEqual(resolveFffNativeDependencies("mac", "universal", "0.9.4"), {
1073 "@ff-labs/fff-bin-darwin-arm64": "0.9.4",
1074 "@ff-labs/fff-bin-darwin-x64": "0.9.4",
1075 });
1076 assert.deepStrictEqual(resolveFffNativeDependencies("win", "x64", "0.9.4"), {
1077 "@ff-labs/fff-bin-win32-x64": "0.9.4",
1078 });
1079 assert.deepStrictEqual(resolveFffNativeDependencies("linux", "x64", "0.9.4"), {
1080 "@ff-labs/fff-bin-linux-x64-gnu": "0.9.4",
1081 "@ff-labs/fff-bin-linux-x64-musl": "0.9.4",
1082 });
1083 assert.deepStrictEqual(resolveFffNativeDependencies("linux", "arm64", "0.9.4"), {
1084 "@ff-labs/fff-bin-linux-arm64-gnu": "0.9.4",
1085 "@ff-labs/fff-bin-linux-arm64-musl": "0.9.4",
1086 });
1087 });
1088
1089 it("resolves target Clerk passkey native artifacts", () => {
1090 assert.deepStrictEqual(resolveClerkPasskeyNativeArtifacts("mac", "universal"), [
1091 {
1092 packageName: "@clerk/electron-passkeys-darwin-arm64",
1093 binaryFileName: "electron-passkeys.darwin-arm64.node",
1094 },
1095 {
1096 packageName: "@clerk/electron-passkeys-darwin-x64",
1097 binaryFileName: "electron-passkeys.darwin-x64.node",
1098 },
1099 ]);
1100 assert.deepStrictEqual(resolveClerkPasskeyNativeArtifacts("win", "x64"), [
1101 {
1102 packageName: "@clerk/electron-passkeys-win32-x64-msvc",
1103 binaryFileName: "electron-passkeys.win32-x64-msvc.node",
1104 },
1105 ]);
1106 assert.deepStrictEqual(resolveClerkPasskeyNativeArtifacts("linux", "x64"), []);
1107 });
1108
1109 it("falls back to the default mock update port when the configured port is blank", () => {
1110 assert.equal(resolveMockUpdateServerUrl(undefined), "http://localhost:3000");
1111 assert.equal(resolveMockUpdateServerUrl(4123), "http://localhost:4123");
1112 });
1113
1114 it("derives the electron-builder package manager user agent from packageManager", () => {
1115 assert.equal(resolvePackageManagerUserAgent("pnpm@11.10.0"), "pnpm/11.10.0");
1116 assert.equal(resolvePackageManagerUserAgent(" yarn@4.9.2 "), "yarn/4.9.2");
1117 assert.equal(resolvePackageManagerUserAgent("pnpm"), "pnpm");
1118 });
1119
1120 it.effect("normalizes mock update server ports from env-style strings", () =>
1121 Effect.gen(function* () {
1122 assert.equal(yield* resolveMockUpdateServerPort(undefined), undefined);
1123 assert.equal(yield* resolveMockUpdateServerPort(""), undefined);
1124 assert.equal(yield* resolveMockUpdateServerPort(" "), undefined);
1125 assert.equal(yield* resolveMockUpdateServerPort("4123"), 4123);
1126 }),
1127 );
1128
1129 it.effect("rejects non-numeric or out-of-range mock update ports", () =>
1130 Effect.gen(function* () {
1131 const invalidPorts = ["abc", "12.5", "0", "65536"];
1132 for (const port of invalidPorts) {
1133 const exit = yield* Effect.exit(resolveMockUpdateServerPort(port));
1134 assert.equal(exit._tag, "Failure");
1135 }
1136 }),
1137 );
1138
1139 it("classifies invalid configured ports with the decoder's number grammar", () => {
1140 const cause = new Error("invalid configured port");
1141
1142 assert.equal(
1143 InvalidMockUpdateServerPortError.fromConfigValue("0x10", cause).reason,
1144 "not-numeric",
1145 );
1146 assert.equal(
1147 InvalidMockUpdateServerPortError.fromConfigValue("12.5", cause).reason,
1148 "not-integer",
1149 );
1150 assert.equal(
1151 InvalidMockUpdateServerPortError.fromConfigValue("65536", cause).reason,
1152 "out-of-range",
1153 );
1154 assert.strictEqual(
1155 InvalidMockUpdateServerPortError.fromConfigValue("0x10", cause).cause,
1156 cause,
1157 );
1158 });
1159
1160 it.effect("resolves default platform and architecture from host references", () =>
1161 Effect.gen(function* () {
1162 const resolved = yield* resolveBuildOptions({
1163 platform: Option.none(),
1164 target: Option.none(),
1165 arch: Option.none(),
1166 buildVersion: Option.none(),
1167 outputDir: Option.none(),
1168 skipBuild: Option.none(),
1169 keepStage: Option.none(),
1170 signed: Option.none(),
1171 verbose: Option.none(),
1172 mockUpdates: Option.none(),
1173 mockUpdateServerPort: Option.none(),
1174 wslPrebuild: Option.none(),
1175 }).pipe(
1176 Effect.provide(
1177 Layer.mergeAll(
1178 Layer.succeed(HostProcessPlatform, "win32"),
1179 Layer.succeed(HostProcessArchitecture, "x64"),
1180 ConfigProvider.layer(
1181 ConfigProvider.fromEnv({
1182 env: {
1183 PROCESSOR_ARCHITECTURE: "AMD64",
1184 PROCESSOR_ARCHITEW6432: "ARM64",
1185 },
1186 }),
1187 ),
1188 ),
1189 ),
1190 );
1191
1192 assert.equal(resolved.platform, "win");
1193 assert.equal(resolved.target, "nsis");
1194 assert.equal(resolved.arch, "arm64");
1195 }),
1196 );
1197
1198 it.effect("rejects universal builds on Linux and Windows before staging binaries", () =>
1199 Effect.gen(function* () {
1200 for (const platform of ["linux", "win"] as const) {
1201 const error = yield* Effect.flip(
1202 resolveBuildOptions({
1203 platform: Option.some(platform),
1204 target: Option.none(),
1205 arch: Option.some("universal"),
1206 buildVersion: Option.none(),
1207 outputDir: Option.none(),
1208 skipBuild: Option.none(),
1209 keepStage: Option.none(),
1210 signed: Option.none(),
1211 verbose: Option.none(),
1212 mockUpdates: Option.none(),
1213 mockUpdateServerPort: Option.none(),
1214 wslPrebuild: Option.none(),
1215 }),
1216 );
1217
1218 assert.instanceOf(error, UnsupportedDesktopBuildArchitectureError);
1219 assert.deepStrictEqual(error.supportedArchitectures, ["x64", "arm64"]);
1220 }
1221 }),
1222 );
1223
1224 it.effect("preserves explicit false boolean flags over true env defaults", () =>
1225 Effect.gen(function* () {
1226 const resolved = yield* resolveBuildOptions({
1227 platform: Option.some("mac"),
1228 target: Option.none(),
1229 arch: Option.some("arm64"),
1230 buildVersion: Option.none(),
1231 outputDir: Option.some("release-test"),
1232 skipBuild: Option.some(false),
1233 keepStage: Option.some(false),
1234 signed: Option.some(false),
1235 verbose: Option.some(false),
1236 mockUpdates: Option.some(false),
1237 mockUpdateServerPort: Option.none(),
1238 wslPrebuild: Option.none(),
1239 }).pipe(
1240 Effect.provide(
1241 ConfigProvider.layer(
1242 ConfigProvider.fromEnv({
1243 env: {
1244 T3CODE_DESKTOP_SKIP_BUILD: "true",
1245 T3CODE_DESKTOP_KEEP_STAGE: "true",
1246 T3CODE_DESKTOP_SIGNED: "true",
1247 T3CODE_DESKTOP_VERBOSE: "true",
1248 T3CODE_DESKTOP_MOCK_UPDATES: "true",
1249 },
1250 }),
1251 ),
1252 ),
1253 );
1254
1255 assert.equal(resolved.skipBuild, false);
1256 assert.equal(resolved.keepStage, false);
1257 assert.equal(resolved.signed, false);
1258 assert.equal(resolved.verbose, false);
1259 assert.equal(resolved.mockUpdates, false);
1260 }),
1261 );
1262});
1263
1264// The self-containment check runs the packaged tree in a scratch directory. Its
1265// own node_modules holds the sidecar externals and must be ignored, but any
1266// node_modules *above* it would let Node's parent walk satisfy an import that is
1267// missing from the package, so the probe refuses to run in that case.
1268it("lists ancestor node_modules, nearest first, excluding the start directory", () => {
1269 assert.deepStrictEqual(ancestorNodeModulesPaths("C:\\tmp\\probe\\app", "\\"), [
1270 "C:\\tmp\\probe\\node_modules",
1271 "C:\\tmp\\node_modules",
1272 "C:\\node_modules",
1273 ]);
1274});
1275
1276it("includes the filesystem root for posix paths", () => {
1277 assert.deepStrictEqual(ancestorNodeModulesPaths("/tmp/probe", "/"), [
1278 "/tmp/node_modules",
1279 "/node_modules",
1280 ]);
1281});
1282
1283// A UNC root must keep its \\server\share prefix. Rebuilding it from segments
1284// produced relative paths, which fs.exists resolves against the build cwd, so
1285// the guard checked directories that do not exist and silently passed.
1286it("keeps the prefix of a UNC path instead of going relative", () => {
1287 const paths = ancestorNodeModulesPaths("\\\\server\\share\\tmp\\app", "\\");
1288 for (const candidate of paths) {
1289 assert.ok(candidate.startsWith("\\\\server\\share"), candidate);
1290 }
1291 assert.deepStrictEqual(paths[0], "\\\\server\\share\\tmp\\node_modules");
1292});
1293
1294it.effect("rebases packaged links into the isolated tree", () =>
1295 Effect.gen(function* () {
1296 const fs = yield* FileSystem.FileSystem;
1297 const path = yield* Path.Path;
1298 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-copy-symlinks-" });
1299 const source = path.join(root, "source");
1300 const destination = path.join(root, "destination");
1301 const packageDir = path.join(source, "node_modules/.pnpm/example@1/node_modules/example");
1302 const relativePackageLink = path.join(source, "node_modules/example-relative");
1303 const absolutePackageLink = path.join(source, "node_modules/example-absolute");
1304
1305 yield* fs.makeDirectory(packageDir, { recursive: true });
1306 yield* fs.writeFileString(path.join(packageDir, "index.js"), "module.exports = true;\n");
1307 yield* fs.symlink(
1308 path.join(".pnpm", "example@1", "node_modules", "example"),
1309 relativePackageLink,
1310 );
1311 yield* fs.symlink(packageDir, absolutePackageLink);
1312
1313 yield* copyDirectoryPreservingSymlinks(source, destination);
1314
1315 const copiedPackage = path.join(
1316 destination,
1317 "node_modules/.pnpm/example@1/node_modules/example",
1318 );
1319 const resolvedCopiedPackage = yield* fs.realPath(copiedPackage);
1320 assert.equal(
1321 yield* fs.readLink(path.join(destination, "node_modules/example-relative")),
1322 copiedPackage,
1323 );
1324 assert.equal(
1325 yield* fs.readLink(path.join(destination, "node_modules/example-absolute")),
1326 copiedPackage,
1327 );
1328 assert.equal(
1329 yield* fs.realPath(path.join(destination, "node_modules/example-relative")),
1330 resolvedCopiedPackage,
1331 );
1332 assert.equal(
1333 yield* fs.realPath(path.join(destination, "node_modules/example-absolute")),
1334 resolvedCopiedPackage,
1335 );
1336 }).pipe(Effect.provide(NodeServices.layer)),
1337);
1338
1339it("ignores trailing separators", () => {
1340 assert.deepStrictEqual(
1341 ancestorNodeModulesPaths("C:\\tmp\\probe\\app\\", "\\"),
1342 ancestorNodeModulesPaths("C:\\tmp\\probe\\app", "\\"),
1343 );
1344});