@devries-cameron20 / t3code Mirror · read-only
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 21, 03:37 UTC

main
ts 4,306 lines 154 KB
Raw
1 #!/usr/bin/env node
2 // @effect-diagnostics nodeBuiltinImport:off - Node's typed junction API avoids Windows symlink privileges while keeping the probe isolated.
3
4 import * as NodeFSP from "node:fs/promises";
5 import * as NodeCrypto from "node:crypto";
6 import * as NodeModule from "node:module";
7 // plist is CommonJS; Node cannot load its named exports from an ES module.
8 import Plist from "plist";
9
10 import {
11 createPackageWithOptions,
12 extractAll,
13 getRawHeader,
14 statFile,
15 type DirectoryRecord,
16 } from "@electron/asar";
17
18 import { fromYaml } from "@t3tools/shared/schemaYaml";
19 import * as HostProcess from "@t3tools/shared/HostProcess";
20 import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
21 import { resolveSpawnCommand } from "@t3tools/shared/shell";
22 import rootPackageJson from "../package.json" with { type: "json" };
23 import desktopPackageJson from "../apps/desktop/package.json" with { type: "json" };
24 import gnomeCaptureBundle from "../apps/desktop/gnome-extension/bundle.json" with { type: "json" };
25 import serverPackageJson from "../apps/server/package.json" with { type: "json" };
26
27 import {
28 ReleasePackageManifestError,
29 releasePackageFiles,
30 updateReleasePackageVersions,
31 } from "./update-release-package-versions.ts";
32 import { applyWebBrandAssets } from "./apply-web-brand-assets.ts";
33 import {
34 BRAND_ASSET_PATHS,
35 resolveWebAssetBrandForChannel,
36 type WebAssetBrand,
37 } from "./lib/brand-assets.ts";
38 import { getDefaultBuildArch } from "./lib/build-target-arch.ts";
39 import {
40 findInlinedExternalPackages,
41 selectCliRuntimeExternalDependencies,
42 } from "./lib/cli-external-packages.ts";
43 import { loadRepoEnv } from "./lib/public-config.ts";
44 import { selectDesktopRuntimeExternalDependencies } from "./lib/desktop-external-packages.ts";
45 import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts";
46 import { resolveTaggedSourceVersion } from "./lib/tagged-source-version.ts";
47
48 import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
49 import * as NodeServices from "@effect/platform-node/NodeServices";
50 import * as Config from "effect/Config";
51 import * as Duration from "effect/Duration";
52 import * as Effect from "effect/Effect";
53 import * as Exit from "effect/Exit";
54 import * as FileSystem from "effect/FileSystem";
55 import * as Layer from "effect/Layer";
56 import * as Logger from "effect/Logger";
57 import * as Option from "effect/Option";
58 import type { PlatformError } from "effect/PlatformError";
59 import * as Path from "effect/Path";
60 import * as Schema from "effect/Schema";
61 import * as Stream from "effect/Stream";
62 import { Command, Flag } from "effect/cli";
63 import { ChildProcess, ChildProcessSpawner } from "effect/process";
64
65 const LINUX_ICON_SIZES = [16, 22, 24, 32, 48, 64, 128, 256, 512] as const;
66 const DESKTOP_APP_ID = "com.t3tools.t3code";
67 const APPLE_TEAM_ID_PATTERN = /^[A-Z0-9]{10}$/u;
68
69 const BuildPlatform = Schema.Literals(["mac", "linux", "win"]);
70 const BuildArch = Schema.Literals(["arm64", "x64", "universal"]);
71
72 const WorkspaceConfig = Schema.Struct({
73 catalog: Schema.optional(Schema.Record(Schema.String, Schema.String)),
74 overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
75 patchedDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
76 allowBuilds: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)),
77 });
78 type WorkspaceConfig = typeof WorkspaceConfig.Type;
79
80 const StageWorkspaceConfig = Schema.Struct({
81 supportedArchitectures: Schema.Struct({
82 os: Schema.Array(Schema.String),
83 cpu: Schema.Array(Schema.String),
84 libc: Schema.optional(Schema.Array(Schema.String)),
85 }),
86 // pnpm 11 reads build approvals only from pnpm-workspace.yaml; omission fails staged lifecycle installs.
87 allowBuilds: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)),
88 patchedDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
89 overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
90 packageExtensions: Schema.optional(
91 Schema.Record(
92 Schema.String,
93 Schema.Struct({
94 peerDependenciesMeta: Schema.Record(
95 Schema.String,
96 Schema.Struct({ optional: Schema.Boolean }),
97 ),
98 }),
99 ),
100 ),
101 nodeLinker: Schema.optional(Schema.Literals(["hoisted"])),
102 });
103 type StageWorkspaceConfig = typeof StageWorkspaceConfig.Type;
104
105 // TypeScript is a typings-only peer; pnpm auto-installation would ship a compiler.
106 const STAGE_PACKAGE_EXTENSIONS = {
107 "electron-webauthn": { peerDependenciesMeta: { typescript: { optional: true } } },
108 "@electron-webauthn/macos": { peerDependenciesMeta: { typescript: { optional: true } } },
109 } as const;
110
111 const RepoRoot = Effect.service(Path.Path).pipe(
112 Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
113 );
114 const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
115 const decodeReleasePackageManifest = Schema.decodeEffect(
116 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
117 );
118 const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig));
119 const encodeStageWorkspaceConfig = Schema.encodeEffect(fromYaml(StageWorkspaceConfig));
120
121 export const readWorkspaceConfig = Effect.fn("readWorkspaceConfig")(function* () {
122 const fs = yield* FileSystem.FileSystem;
123 const path = yield* Path.Path;
124 const repoRoot = yield* RepoRoot;
125 const workspaceYaml = yield* fs.readFileString(path.join(repoRoot, "pnpm-workspace.yaml"));
126 return yield* decodeWorkspaceConfig(workspaceYaml);
127 });
128
129 interface DesktopBuildIconAssets {
130 readonly macIconPng: string;
131 readonly linuxIconPng: string;
132 readonly windowsIconIco: string;
133 }
134
135 interface PlatformConfig {
136 readonly cliFlag: "--mac" | "--linux" | "--win";
137 readonly defaultTarget: string;
138 readonly archChoices: ReadonlyArray<typeof BuildArch.Type>;
139 }
140
141 export function resolveResourceMonitorRustTargets(
142 platform: typeof BuildPlatform.Type,
143 arch: typeof BuildArch.Type,
144 ): ReadonlyArray<string> {
145 if (platform === "mac") {
146 if (arch === "universal") {
147 return ["aarch64-apple-darwin", "x86_64-apple-darwin"];
148 }
149 return [arch === "arm64" ? "aarch64-apple-darwin" : "x86_64-apple-darwin"];
150 }
151 if (platform === "linux") {
152 return [arch === "arm64" ? "aarch64-unknown-linux-gnu" : "x86_64-unknown-linux-gnu"];
153 }
154 return [arch === "arm64" ? "aarch64-pc-windows-msvc" : "x86_64-pc-windows-msvc"];
155 }
156
157 export function resourceMonitorExecutableName(platform: typeof BuildPlatform.Type): string {
158 return platform === "win" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
159 }
160
161 const PLATFORM_CONFIG: Record<typeof BuildPlatform.Type, PlatformConfig> = {
162 mac: {
163 cliFlag: "--mac",
164 defaultTarget: "dmg",
165 archChoices: ["arm64", "x64", "universal"],
166 },
167 linux: {
168 cliFlag: "--linux",
169 defaultTarget: "AppImage",
170 archChoices: ["x64", "arm64"],
171 },
172 win: {
173 cliFlag: "--win",
174 defaultTarget: "nsis",
175 archChoices: ["x64", "arm64"],
176 },
177 };
178
179 interface BuildCliInput {
180 readonly platform: Option.Option<typeof BuildPlatform.Type>;
181 readonly target: Option.Option<string>;
182 readonly arch: Option.Option<typeof BuildArch.Type>;
183 readonly buildVersion: Option.Option<string>;
184 readonly outputDir: Option.Option<string>;
185 readonly skipBuild: Option.Option<boolean>;
186 readonly keepStage: Option.Option<boolean>;
187 readonly signed: Option.Option<boolean>;
188 readonly verbose: Option.Option<boolean>;
189 readonly mockUpdates: Option.Option<boolean>;
190 readonly mockUpdateServerPort: Option.Option<number>;
191 readonly wslRuntime: Option.Option<string>;
192 }
193
194 function detectHostBuildPlatform(hostPlatform: string): typeof BuildPlatform.Type | undefined {
195 if (hostPlatform === "darwin") return "mac";
196 if (hostPlatform === "linux") return "linux";
197 if (hostPlatform === "win32") return "win";
198 return undefined;
199 }
200
201 const getDefaultArch = Effect.fn("getDefaultArch")(function* (platform: typeof BuildPlatform.Type) {
202 const config = PLATFORM_CONFIG[platform];
203 if (!config) {
204 return "x64";
205 }
206
207 return yield* getDefaultBuildArch(platform, config);
208 });
209
210 export class MacPasskeySigningConfigurationResolutionError extends Schema.TaggedError<MacPasskeySigningConfigurationResolutionError>()(
211 "MacPasskeySigningConfigurationResolutionError",
212 {
213 cause: Schema.Defect(),
214 },
215 ) {
216 static fromCause(
217 cause: unknown,
218 ): MacPasskeySigningConfigurationError | MacPasskeySigningConfigurationResolutionError {
219 return isMacPasskeySigningConfigurationError(cause)
220 ? cause
221 : new MacPasskeySigningConfigurationResolutionError({ cause });
222 }
223
224 override get message(): string {
225 return "Failed to resolve macOS passkey signing configuration.";
226 }
227 }
228
229 export class KeyringNativePackageMissingError extends Schema.TaggedError<KeyringNativePackageMissingError>()(
230 "KeyringNativePackageMissingError",
231 {
232 packageName: Schema.String,
233 binaryFileName: Schema.String,
234 packageEntryPath: Schema.String,
235 platform: BuildPlatform,
236 arch: BuildArch,
237 cause: Schema.Defect(),
238 },
239 ) {
240 override get message(): string {
241 return `Keyring native package is missing: ${this.packageName}`;
242 }
243 }
244
245 export class ClerkPasskeyNativePackageMissingError extends Schema.TaggedError<ClerkPasskeyNativePackageMissingError>()(
246 "ClerkPasskeyNativePackageMissingError",
247 {
248 packageName: Schema.String,
249 binaryFileName: Schema.String,
250 packageEntryPath: Schema.String,
251 platform: BuildPlatform,
252 arch: BuildArch,
253 cause: Schema.Defect(),
254 },
255 ) {
256 override get message(): string {
257 return `Clerk passkey native package is missing: ${this.packageName}`;
258 }
259 }
260
261 export class UnsupportedHostBuildPlatformError extends Schema.TaggedError<UnsupportedHostBuildPlatformError>()(
262 "UnsupportedHostBuildPlatformError",
263 {
264 hostPlatform: Schema.String,
265 },
266 ) {
267 override get message(): string {
268 return `Unsupported host platform '${this.hostPlatform}'.`;
269 }
270 }
271
272 export class UnsupportedDesktopBuildArchitectureError extends Schema.TaggedError<UnsupportedDesktopBuildArchitectureError>()(
273 "UnsupportedDesktopBuildArchitectureError",
274 {
275 platform: BuildPlatform,
276 arch: BuildArch,
277 supportedArchitectures: Schema.Array(BuildArch),
278 },
279 ) {
280 override get message(): string {
281 return `Unsupported architecture '${this.arch}' for ${this.platform}.`;
282 }
283 }
284
285 const InvalidMockUpdateServerPortReason = Schema.Literals([
286 "not-numeric",
287 "not-integer",
288 "out-of-range",
289 ]);
290
291 export class InvalidMockUpdateServerPortError extends Schema.TaggedError<InvalidMockUpdateServerPortError>()(
292 "InvalidMockUpdateServerPortError",
293 {
294 reason: InvalidMockUpdateServerPortReason,
295 inputLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
296 cause: Schema.Defect(),
297 },
298 ) {
299 override get message(): string {
300 return "Invalid mock update server port.";
301 }
302
303 static fromConfigValue(configuredPort: string, cause: unknown) {
304 return new InvalidMockUpdateServerPortError({
305 reason: invalidMockUpdateServerPortReason(configuredPort),
306 inputLength: configuredPort.length,
307 cause,
308 });
309 }
310 }
311
312 export class DesktopBuildManifestRestoreError extends Schema.TaggedError<DesktopBuildManifestRestoreError>()(
313 "DesktopBuildManifestRestoreError",
314 { failures: Schema.Array(ReleasePackageManifestError) },
315 ) {
316 override get message(): string {
317 return `Failed to restore release manifests: ${this.failures.map((failure) => failure.filePath).join(", ")}`;
318 }
319 }
320
321 export class BuildCommandFailedError extends Schema.TaggedError<BuildCommandFailedError>()(
322 "BuildCommandFailedError",
323 {
324 command: Schema.String,
325 exitCode: Schema.Int,
326 stdoutTail: Schema.optionalKey(Schema.String),
327 stderrTail: Schema.optionalKey(Schema.String),
328 },
329 ) {
330 override get message(): string {
331 const outputSections = [
332 `Command: ${this.command}`,
333 formatOutputSection("stdout", this.stdoutTail ?? ""),
334 formatOutputSection("stderr", this.stderrTail ?? ""),
335 ].filter((section): section is string => section !== undefined);
336 const outputSuffix = outputSections.length > 0 ? `\n\n${outputSections.join("\n\n")}` : "";
337 return `Command exited with non-zero exit code (${this.exitCode})${outputSuffix}`;
338 }
339 }
340
341 export const LINUX_DESKTOP_BUILD_PREREQUISITES = [
342 { id: "cargo", description: "Rust compiler and Cargo", packages: ["cargo", "rustc"] },
343 { id: "rust-target", description: "Requested Rust standard library", packages: [] },
344 { id: "cc", description: "C/C++ build toolchain", packages: ["build-essential"] },
345 { id: "make", description: "Make", packages: ["build-essential"] },
346 {
347 id: "libsecret",
348 description: "libsecret development headers and pkg-config",
349 packages: ["libsecret-1-dev", "pkg-config"],
350 },
351 { id: "imagemagick", description: "ImageMagick", packages: ["imagemagick"] },
352 ] as const;
353
354 export class LinuxDesktopBuildPrerequisitesMissingError extends Schema.TaggedError<LinuxDesktopBuildPrerequisitesMissingError>()(
355 "LinuxDesktopBuildPrerequisitesMissingError",
356 {
357 missing: Schema.Array(Schema.String),
358 rustTarget: Schema.String,
359 },
360 ) {
361 override get message(): string {
362 const missingRequirements = LINUX_DESKTOP_BUILD_PREREQUISITES.filter((requirement) =>
363 this.missing.includes(requirement.id),
364 );
365 const details = missingRequirements
366 .map((requirement) =>
367 requirement.packages.length > 0
368 ? ` - ${requirement.description} (${requirement.packages.join(", ")})`
369 : ` - ${requirement.description}`,
370 )
371 .join("\n");
372 const packages = [
373 ...new Set(missingRequirements.flatMap((requirement) => requirement.packages)),
374 ];
375 return [
376 "Linux desktop build prerequisites are missing:",
377 details,
378 "",
379 ...(packages.length > 0
380 ? ["On Ubuntu/Debian, install them with:", ` sudo apt-get install ${packages.join(" ")}`]
381 : []),
382 ...(this.missing.includes("rust-target")
383 ? ["Add the requested Rust target with:", ` rustup target add ${this.rustTarget}`]
384 : []),
385 "",
386 "For other distributions, see docs/operations/development.md#linux-appimage-prerequisites.",
387 "Then rerun `vp run dist:desktop:linux`.",
388 ].join("\n");
389 }
390 }
391
392 const MAC_DESKTOP_BUILD_PREREQUISITES = [
393 { id: "rust", description: "Rust/Cargo and the requested Rust target" },
394 { id: "clang", description: "Xcode Command Line Tools (clang)" },
395 { id: "make", description: "Xcode Command Line Tools (make)" },
396 { id: "sips", description: "macOS image tool (sips)" },
397 { id: "iconutil", description: "macOS icon tool (iconutil)" },
398 { id: "lipo", description: "Xcode universal-binary tool (lipo)" },
399 ] as const;
400
401 export class MacDesktopBuildPrerequisitesMissingError extends Schema.TaggedError<MacDesktopBuildPrerequisitesMissingError>()(
402 "MacDesktopBuildPrerequisitesMissingError",
403 {
404 missing: Schema.Array(Schema.String),
405 rustTargets: Schema.Array(Schema.String),
406 },
407 ) {
408 override get message(): string {
409 const details = MAC_DESKTOP_BUILD_PREREQUISITES.filter((requirement) =>
410 this.missing.includes(requirement.id),
411 )
412 .map((requirement) => ` - ${requirement.description}`)
413 .join("\n");
414 return [
415 "macOS desktop build prerequisites are missing:",
416 details,
417 "",
418 "Install Apple's build tools with:",
419 " xcode-select --install",
420 "Install Rust from https://rustup.rs, then add the requested target(s):",
421 ` rustup target add ${this.rustTargets.join(" ")}`,
422 "",
423 "Then rerun the desktop artifact command.",
424 ].join("\n");
425 }
426 }
427
428 const WINDOWS_DESKTOP_BUILD_PREREQUISITES = [
429 { id: "rust", description: "Rust/Cargo and the requested MSVC Rust target" },
430 { id: "python", description: "Python 3 for node-gyp" },
431 {
432 id: "msvc",
433 description: "Visual Studio Build Tools with C++, Windows SDK, and Spectre libraries",
434 },
435 { id: "tar", description: "tar to inspect the bundled WSL runtime archive" },
436 ] as const;
437
438 export class WindowsDesktopBuildPrerequisitesMissingError extends Schema.TaggedError<WindowsDesktopBuildPrerequisitesMissingError>()(
439 "WindowsDesktopBuildPrerequisitesMissingError",
440 {
441 missing: Schema.Array(Schema.String),
442 rustTarget: Schema.String,
443 },
444 ) {
445 override get message(): string {
446 const details = WINDOWS_DESKTOP_BUILD_PREREQUISITES.filter((requirement) =>
447 this.missing.includes(requirement.id),
448 )
449 .map((requirement) => ` - ${requirement.description}`)
450 .join("\n");
451 return [
452 "Windows desktop build prerequisites are missing:",
453 details,
454 "",
455 "Install Rust from https://rustup.rs and add the requested target:",
456 ` rustup target add ${this.rustTarget}`,
457 "Install Python 3 and the Visual Studio Build Tools components listed in",
458 "docs/operations/development.md#windows-installer-prerequisites.",
459 "",
460 "Then rerun the desktop artifact command.",
461 ].join("\n");
462 }
463 }
464
465 export class ResourceMonitorBuildOutputMissingError extends Schema.TaggedError<ResourceMonitorBuildOutputMissingError>()(
466 "ResourceMonitorBuildOutputMissingError",
467 {
468 binaryPath: Schema.String,
469 rustTarget: Schema.String,
470 platform: BuildPlatform,
471 arch: BuildArch,
472 },
473 ) {
474 override get message(): string {
475 return `Resource monitor build for ${this.rustTarget} did not produce ${this.binaryPath}.`;
476 }
477 }
478
479 const desktopIconPlatformNames = {
480 mac: "macOS",
481 linux: "Linux",
482 win: "Windows",
483 } satisfies Record<typeof BuildPlatform.Type, string>;
484
485 export class LinuxBrowserSecretHostError extends Schema.TaggedError<LinuxBrowserSecretHostError>()(
486 "LinuxBrowserSecretHostError",
487 { hostPlatform: Schema.String },
488 ) {
489 override get message(): string {
490 return `Linux desktop builds must run on a Linux host: the browser secret helper links against libsecret and cannot be built on '${this.hostPlatform}'.`;
491 }
492 }
493
494 export class DesktopIconSourceMissingError extends Schema.TaggedError<DesktopIconSourceMissingError>()(
495 "DesktopIconSourceMissingError",
496 {
497 platform: BuildPlatform,
498 sourcePath: Schema.String,
499 },
500 ) {
501 override get message(): string {
502 return `Desktop ${desktopIconPlatformNames[this.platform]} icon source is missing at ${this.sourcePath}`;
503 }
504 }
505
506 export class DesktopDmgBackgroundSourceMissingError extends Schema.TaggedError<DesktopDmgBackgroundSourceMissingError>()(
507 "DesktopDmgBackgroundSourceMissingError",
508 {
509 channel: Schema.Literals(["latest", "nightly"]),
510 sourcePath: Schema.String,
511 },
512 ) {
513 override get message(): string {
514 return `Desktop ${this.channel} DMG background source is missing at ${this.sourcePath}`;
515 }
516 }
517
518 export class BundledClientAssetsMissingError extends Schema.TaggedError<BundledClientAssetsMissingError>()(
519 "BundledClientAssetsMissingError",
520 {
521 indexPath: Schema.String,
522 missingFiles: Schema.Array(Schema.String),
523 },
524 ) {
525 override get message(): string {
526 const preview = this.missingFiles.slice(0, 6).join(", ");
527 const suffix = this.missingFiles.length > 6 ? ` (+${this.missingFiles.length - 6} more)` : "";
528 return `Bundled client references missing files in ${this.indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`;
529 }
530 }
531
532 export class UnsupportedDesktopBuildPlatformError extends Schema.TaggedError<UnsupportedDesktopBuildPlatformError>()(
533 "UnsupportedDesktopBuildPlatformError",
534 {
535 platform: Schema.String,
536 },
537 ) {
538 override get message(): string {
539 return `Unsupported platform '${this.platform}'.`;
540 }
541 }
542
543 const dependencyResolutionDescriptions = {
544 "server-production": "production dependencies",
545 "workspace-overrides": "overrides",
546 "desktop-runtime": "desktop runtime dependencies",
547 } as const;
548 const DependencyResolutionKind = Schema.Literals([
549 "server-production",
550 "workspace-overrides",
551 "desktop-runtime",
552 ]);
553
554 export class DesktopBuildDependencyResolutionError extends Schema.TaggedError<DesktopBuildDependencyResolutionError>()(
555 "DesktopBuildDependencyResolutionError",
556 {
557 kind: DependencyResolutionKind,
558 manifestPath: Schema.String,
559 cause: Schema.Defect(),
560 },
561 ) {
562 override get message(): string {
563 return `Could not resolve ${dependencyResolutionDescriptions[this.kind]} from ${this.manifestPath}.`;
564 }
565 }
566
567 export class MissingServerProductionDependenciesError extends Schema.TaggedError<MissingServerProductionDependenciesError>()(
568 "MissingServerProductionDependenciesError",
569 {
570 manifestPath: Schema.String,
571 },
572 ) {
573 override get message(): string {
574 return `Could not resolve production dependencies from ${this.manifestPath}.`;
575 }
576 }
577
578 const DesktopBuildInputArtifact = Schema.Literals([
579 "desktop-dist",
580 "desktop-resources",
581 "server-dist",
582 "bundled-server-client",
583 ]);
584 type DesktopBuildInputArtifact = typeof DesktopBuildInputArtifact.Type;
585 const desktopBuildInputArtifactNames = {
586 "desktop-dist": "desktopDist",
587 "desktop-resources": "desktopResources",
588 "server-dist": "serverDist",
589 "bundled-server-client": "bundled server client",
590 } satisfies Record<DesktopBuildInputArtifact, string>;
591
592 /** Effect is always inlined; absence signals externalized dependencies beyond the sidecar runtime closure. */
593 const BUNDLE_SELF_CONTAINED_SENTINEL = "effect";
594
595 const BUNDLE_SELF_CHECK_TIMEOUT = Duration.seconds(120);
596 const WINDOWS_PRIMARY_NATIVE_PROBE_TIMEOUT = Duration.seconds(30);
597
598 const WINDOWS_PRIMARY_FFF_PROBE_SOURCE = `
599 const { join } = await import("node:path");
600 const { pathToFileURL } = await import("node:url");
601 const { FileFinder } = await import(pathToFileURL(process.argv[1]).href);
602 const probeRoot = process.argv[2];
603 const result = FileFinder.create({
604 basePath: probeRoot,
605 frecencyDbPath: join(probeRoot, "frecency.mdb"),
606 historyDbPath: join(probeRoot, "history.mdb"),
607 disableWatch: true,
608 disableMmapCache: true,
609 disableContentIndexing: true,
610 });
611 if (!result.ok) throw new Error(result.error);
612 result.value.destroy();
613 `;
614
615 export class ExternalizedBundleError extends Schema.TaggedError<ExternalizedBundleError>()(
616 "ExternalizedBundleError",
617 { sentinel: Schema.String, inlinedPackageCount: Schema.Number },
618 ) {
619 override get message(): string {
620 return `The server bundle did not inline "${this.sentinel}" (${this.inlinedPackageCount} packages inlined). The bundle is meant to be self-contained apart from the runtime externals; if its dependencies are external again they will be absent from the sidecar, and the backend will fail with ERR_MODULE_NOT_FOUND. Check the deps.alwaysBundle wiring in apps/server/vite.config.ts.`;
621 }
622 }
623
624 export class BundleNotSelfContainedError extends Schema.TaggedError<BundleNotSelfContainedError>()(
625 "BundleNotSelfContainedError",
626 { exitCode: Schema.Number, output: Schema.String },
627 ) {
628 override get message(): string {
629 return `The packaged server bundle could not load from the isolated, extracted sidecar (exit ${this.exitCode}). Anything it imports that is neither a Node built-in nor in the selected runtime-external closure is unavailable to both backends. Output:
630 ${this.output}`;
631 }
632 }
633
634 export class InlinedNativePackageError extends Schema.TaggedError<InlinedNativePackageError>()(
635 "InlinedNativePackageError",
636 { packages: Schema.Array(Schema.String) },
637 ) {
638 override get message(): string {
639 return `The server bundle inlined packages that load native binaries: ${this.packages.join(", ")}. A node-gyp-build style loader resolves prebuilds relative to its own file, so inlined into a chunk it finds none and the importer quietly falls back to a slower JS path. Add them to CLI_RUNTIME_EXTERNAL_PREFIXES in scripts/lib/cli-external-packages.ts so they stay external and are staged in the sidecar.`;
640 }
641 }
642
643 export class InlinedExternalPackageError extends Schema.TaggedError<InlinedExternalPackageError>()(
644 "InlinedExternalPackageError",
645 { packages: Schema.Array(Schema.String) },
646 ) {
647 override get message(): string {
648 return `The server bundle inlined packages that must stay external: ${this.packages.join(", ")}. These are native addons or their loaders; inlined, they resolve prebuilds relative to the bundle and silently lose native acceleration. Check the deps.neverBundle wiring in apps/server/vite.config.ts.`;
649 }
650 }
651
652 export class MissingDesktopBuildInputError extends Schema.TaggedError<MissingDesktopBuildInputError>()(
653 "MissingDesktopBuildInputError",
654 {
655 artifact: DesktopBuildInputArtifact,
656 artifactPath: Schema.String,
657 buildCommand: Schema.Literal("vp run build:desktop"),
658 },
659 ) {
660 override get message(): string {
661 return `Missing ${desktopBuildInputArtifactNames[this.artifact]} at ${this.artifactPath}. Run '${this.buildCommand}' first.`;
662 }
663 }
664
665 export class MacProvisioningProfileNotFoundError extends Schema.TaggedError<MacProvisioningProfileNotFoundError>()(
666 "MacProvisioningProfileNotFoundError",
667 {
668 provisioningProfilePath: Schema.String,
669 },
670 ) {
671 override get message(): string {
672 return `macOS provisioning profile not found: ${this.provisioningProfilePath}`;
673 }
674 }
675
676 export class DesktopBuildDistDirectoryMissingError extends Schema.TaggedError<DesktopBuildDistDirectoryMissingError>()(
677 "DesktopBuildDistDirectoryMissingError",
678 {
679 distPath: Schema.String,
680 platform: BuildPlatform,
681 arch: BuildArch,
682 },
683 ) {
684 override get message(): string {
685 return `Build completed but dist directory was not found at ${this.distPath}`;
686 }
687 }
688
689 export class DesktopBuildArtifactCopyError extends Schema.TaggedError<DesktopBuildArtifactCopyError>()(
690 "DesktopBuildArtifactCopyError",
691 { from: Schema.String, to: Schema.String, cause: Schema.Defect() },
692 ) {
693 override get message(): string {
694 return `Failed to copy build artifact ${this.from} to ${this.to}.`;
695 }
696 }
697
698 export class DesktopBuildNoArtifactsProducedError extends Schema.TaggedError<DesktopBuildNoArtifactsProducedError>()(
699 "DesktopBuildNoArtifactsProducedError",
700 {
701 distPath: Schema.String,
702 platform: BuildPlatform,
703 arch: BuildArch,
704 },
705 ) {
706 override get message(): string {
707 return `Build completed but no files were produced in ${this.distPath}`;
708 }
709 }
710
711 export class WslRuntimeArchiveMissingError extends Schema.TaggedError<WslRuntimeArchiveMissingError>()(
712 "WslRuntimeArchiveMissingError",
713 {
714 archivePath: Schema.String,
715 },
716 ) {
717 override get message(): string {
718 return `WSL runtime archive not found at ${this.archivePath}.`;
719 }
720 }
721
722 export class WindowsServerSidecarPackError extends Schema.TaggedError<WindowsServerSidecarPackError>()(
723 "WindowsServerSidecarPackError",
724 {
725 asarPath: Schema.String,
726 cause: Schema.optionalKey(Schema.Defect()),
727 },
728 ) {
729 override get message(): string {
730 return `Failed to pack the Windows server sidecar at ${this.asarPath}.`;
731 }
732 }
733
734 export class WindowsPrimaryNativeProbeError extends Schema.TaggedError<WindowsPrimaryNativeProbeError>()(
735 "WindowsPrimaryNativeProbeError",
736 {
737 executablePath: Schema.String,
738 exitCode: Schema.Number,
739 output: Schema.String,
740 },
741 ) {
742 override get message(): string {
743 return `The packaged Windows primary could not load fff from server.asar (exit ${this.exitCode}). Output:\n${this.output}`;
744 }
745 }
746
747 const WindowsPackagedPayloadValidationReason = Schema.Literals([
748 "packaged-app-missing",
749 "sidecar-missing",
750 "sidecar-invalid",
751 "unpacked-native-missing",
752 "resource-monitor-missing",
753 "wsl-runtime-missing",
754 "wsl-runtime-invalid",
755 "file-limit-exceeded",
756 ]);
757
758 export class WindowsPackagedPayloadValidationError extends Schema.TaggedError<WindowsPackagedPayloadValidationError>()(
759 "WindowsPackagedPayloadValidationError",
760 {
761 reason: WindowsPackagedPayloadValidationReason,
762 packagedAppDir: Schema.String,
763 missingFiles: Schema.optionalKey(Schema.Array(Schema.String)),
764 fileCount: Schema.optionalKey(Schema.Int),
765 fileLimit: Schema.optionalKey(Schema.Int),
766 cause: Schema.optionalKey(Schema.Defect()),
767 },
768 ) {
769 override get message(): string {
770 if (this.reason === "file-limit-exceeded") {
771 return `Windows packaged payload contains ${String(this.fileCount)} files; expected at most ${String(this.fileLimit)}.`;
772 }
773 if (this.reason === "unpacked-native-missing") {
774 return `Windows server sidecar is missing ${String(this.missingFiles?.length ?? 0)} unpacked native files.`;
775 }
776 if (this.reason === "resource-monitor-missing") {
777 return "Windows packaged payload is missing the resource monitor executable.";
778 }
779 if (this.reason === "wsl-runtime-missing") {
780 return "Windows packaged payload is missing the WSL runtime archive or SHA-256 sidecar.";
781 }
782 if (this.reason === "wsl-runtime-invalid") {
783 return "Windows packaged payload contains an invalid WSL runtime archive.";
784 }
785 if (this.reason === "sidecar-invalid") {
786 return "Windows packaged payload contains an invalid server.asar sidecar.";
787 }
788 if (this.reason === "sidecar-missing") {
789 return "Windows packaged payload is missing resources/server.asar.";
790 }
791 return `Windows packaged application directory was not found at ${this.packagedAppDir}.`;
792 }
793 }
794
795 export class LinuxIconResizeError extends Schema.TaggedError<LinuxIconResizeError>()(
796 "LinuxIconResizeError",
797 {
798 operation: Schema.Literal("resize"),
799 iconSize: Schema.Int,
800 primaryTool: Schema.Literal("magick"),
801 fallbackTool: Schema.Literal("convert"),
802 cause: Schema.Defect(),
803 },
804 ) {
805 override get message(): string {
806 return `Failed to ${this.operation} the Linux desktop icon to ${this.iconSize}x${this.iconSize} with \`${this.primaryTool}\` or \`${this.fallbackTool}\`. Install ImageMagick so either tool is available.`;
807 }
808 }
809
810 const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
811 stream.pipe(
812 Stream.decodeText(),
813 Stream.runFold(
814 () => "",
815 (acc, chunk) => acc + chunk,
816 ),
817 );
818
819 const COMMAND_OUTPUT_TAIL_LENGTH = 20_000;
820
821 function appendOutputTail(acc: string, chunk: string): string {
822 const next = acc + chunk;
823 return next.length > COMMAND_OUTPUT_TAIL_LENGTH ? next.slice(-COMMAND_OUTPUT_TAIL_LENGTH) : next;
824 }
825
826 function formatOutputSection(label: string, output: string): string | undefined {
827 const trimmed = output.trim();
828 if (!trimmed) return undefined;
829 return `${label} tail:\n${trimmed}`;
830 }
831
832 const collectCommandStream = <E>(
833 stream: Stream.Stream<Uint8Array, E>,
834 output: NodeJS.WriteStream,
835 verbose: boolean,
836 ): Effect.Effect<string, E> =>
837 stream.pipe(
838 Stream.decodeText(),
839 Stream.runFoldEffect(
840 () => "",
841 (acc, chunk) =>
842 Effect.as(
843 verbose ? Effect.sync(() => output.write(chunk)) : Effect.void,
844 appendOutputTail(acc, chunk),
845 ),
846 ),
847 );
848
849 const spawnAndCollectOutput = Effect.fn("spawnAndCollectOutput")(function* (
850 command: ChildProcess.Command,
851 ) {
852 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
853 const child = yield* spawner.spawn(command);
854
855 const [stdout, stderr, exitCode] = yield* Effect.all(
856 [
857 collectStreamAsString(child.stdout),
858 collectStreamAsString(child.stderr),
859 child.exitCode.pipe(Effect.map(Number)),
860 ],
861 { concurrency: "unbounded" },
862 );
863
864 return { stdout, stderr, exitCode } as const;
865 });
866
867 const resolveGitCommitHash = Effect.fn("resolveGitCommitHash")(function* (repoRoot: string) {
868 const result = yield* spawnAndCollectOutput(
869 ChildProcess.make("git", ["rev-parse", "--short=12", "HEAD"], {
870 cwd: repoRoot,
871 }),
872 ).pipe(
873 Effect.orElseSucceed(() => ({
874 stdout: "",
875 stderr: "",
876 exitCode: 1,
877 })),
878 );
879
880 if (result.exitCode !== 0) {
881 return "unknown";
882 }
883 const hash = result.stdout.trim();
884 if (!/^[0-9a-f]{7,40}$/i.test(hash)) {
885 return "unknown";
886 }
887 return hash.toLowerCase();
888 });
889
890 const resolvePythonForNodeGyp = Effect.fn("resolvePythonForNodeGyp")(function* () {
891 const fs = yield* FileSystem.FileSystem;
892 const path = yield* Path.Path;
893 const hostPlatform = yield* HostProcess.Platform;
894 const env = yield* Config.all({
895 configuredPython: Config.String("npm_config_python").pipe(
896 Config.orElse(() => Config.String("PYTHON")),
897 Config.option,
898 ),
899 localAppData: Config.String("LOCALAPPDATA").pipe(Config.option),
900 });
901 const isPython3 = (candidate: string) =>
902 spawnAndCollectOutput(
903 ChildProcess.make(candidate, [
904 "-c",
905 "import sys; raise SystemExit(0 if sys.version_info.major == 3 else 1)",
906 ]),
907 ).pipe(
908 Effect.map((result) => result.exitCode === 0),
909 Effect.orElseSucceed(() => false),
910 );
911 const configured = Option.getOrUndefined(env.configuredPython);
912 if (configured && (yield* fs.exists(configured)) && (yield* isPython3(configured))) {
913 return configured;
914 }
915
916 if (hostPlatform === "win32") {
917 const localAppData = Option.getOrUndefined(env.localAppData);
918 if (localAppData) {
919 for (const version of ["Python313", "Python312", "Python311", "Python310"]) {
920 const candidate = path.join(localAppData, "Programs", "Python", version, "python.exe");
921 if ((yield* fs.exists(candidate)) && (yield* isPython3(candidate))) {
922 return candidate;
923 }
924 }
925 }
926 }
927
928 const probe = yield* spawnAndCollectOutput(
929 ChildProcess.make("python", ["-c", "import sys;print(sys.executable)"]),
930 ).pipe(
931 Effect.orElseSucceed(() => ({
932 stdout: "",
933 stderr: "",
934 exitCode: 1,
935 })),
936 );
937
938 if (probe.exitCode !== 0) {
939 return undefined;
940 }
941
942 const executable = probe.stdout.trim();
943 if (!executable || !(yield* fs.exists(executable)) || !(yield* isPython3(executable))) {
944 return undefined;
945 }
946
947 return executable;
948 });
949
950 interface ResolvedBuildOptions {
951 readonly platform: typeof BuildPlatform.Type;
952 readonly target: string;
953 readonly arch: typeof BuildArch.Type;
954 readonly version: string | undefined;
955 readonly outputDir: string;
956 readonly skipBuild: boolean;
957 readonly keepStage: boolean;
958 readonly signed: boolean;
959 readonly verbose: boolean;
960 readonly mockUpdates: boolean;
961 readonly mockUpdateServerPort: number | undefined;
962 readonly wslRuntime: string | undefined;
963 }
964
965 interface StagePackageJson {
966 readonly name: string;
967 readonly version: string;
968 readonly buildVersion: string;
969 readonly t3codeCommitHash: string;
970 readonly t3codeWebAuthn?: MacWebAuthnEntitlements;
971 readonly private: true;
972 readonly packageManager: string;
973 readonly description: string;
974 readonly license: string;
975 readonly homepage: string;
976 readonly author: string;
977 readonly main: string;
978 readonly build: Record<string, unknown>;
979 readonly dependencies: Record<string, unknown>;
980 readonly devDependencies: {
981 readonly electron: string;
982 };
983 }
984
985 export const STAGE_INSTALL_ARGS = ["install", "--prod"] as const;
986 export const DESKTOP_ELECTRON_LANGUAGES = ["en-US"] as const;
987 export const DESKTOP_FILE_EXCLUSIONS = [
988 // Cursor walks from argv[1] to platform assets; helpers and native addons need real paths outside ASAR.
989 "!**/node_modules/@cursor/sdk-*/**/*",
990 "!apps/desktop/prod-resources/cursor-sdk",
991 "!apps/desktop/prod-resources/cursor-sdk/**/*",
992 // The installed Claude CLI is supplied explicitly; exclude optional bundled executables, retaining SDK JavaScript.
993 "!**/node_modules/@anthropic-ai/claude-agent-sdk-*/**/*",
994 "!**/*.map",
995 "!**/*.d.cts",
996 "!apps/desktop/resources/browser-secret",
997 "!apps/desktop/resources/browser-secret/**/*",
998 "!apps/desktop/prod-resources/browser-secret",
999 "!apps/desktop/prod-resources/browser-secret/**/*",
1000 "!apps/desktop/prod-resources/apple-speech",
1001 "!apps/desktop/prod-resources/apple-speech/**/*",
1002 "!apps/desktop/prod-resources/windows-server",
1003 "!apps/desktop/prod-resources/windows-server/**/*",
1004 "!apps/desktop/prod-resources/wsl-runtime.tar.gz",
1005 "!apps/desktop/prod-resources/wsl-runtime.tar.gz.sha256",
1006 "!apps/desktop/gnome-extension",
1007 "!apps/desktop/gnome-extension/**/*",
1008 ] as const;
1009 // Windows terminal helpers cannot run on macOS and slow signing and notarization.
1010 export const MAC_FILE_EXCLUSIONS = [
1011 "!**/node_modules/node-pty/prebuilds/win32-*/**/*",
1012 "!**/node_modules/node-pty/third_party/conpty/**/*",
1013 ] as const;
1014 // Linux builds node-pty from source; its prebuilds target other platforms.
1015 export const LINUX_FILE_EXCLUSIONS = [
1016 ...MAC_FILE_EXCLUSIONS,
1017 "!**/node_modules/node-pty/prebuilds/darwin-*/**/*",
1018 ] as const;
1019
1020 // Native packages (node-pty, objc-js) ship prebuilds for both Darwin architectures; only universal
1021 // apps need both. macOS 27 warns that an arm64 app holding x64-only code won't open on macOS 28.
1022 export function resolveMacFileExclusions(arch?: typeof BuildArch.Type) {
1023 if (arch === undefined || arch === "universal") {
1024 return [...MAC_FILE_EXCLUSIONS];
1025 }
1026
1027 const unusedArch = arch === "arm64" ? "x64" : "arm64";
1028 return [...MAC_FILE_EXCLUSIONS, `!**/node_modules/**/prebuilds/darwin-${unusedArch}/**/*`];
1029 }
1030 // Large ASAR sidecars avoid NSIS extracting thousands of loose files during installs and updates.
1031 export const WINDOWS_SERVER_ASAR_RESOURCE = "server.asar";
1032 // Native modules and executables need real paths, so place them in ASAR's .unpacked sibling.
1033 export const WINDOWS_NATIVE_ASAR_UNPACK_GLOB =
1034 "{**/*.node,**/*.dll,**/*.exe,**/*.so,**/*.so.*,**/*.dylib}";
1035 export const WINDOWS_SERVER_ASAR_UNPACK_GLOBS = [
1036 "**/*.dll",
1037 "**/*.exe",
1038 "**/*.so",
1039 "**/*.so.*",
1040 "**/*.dylib",
1041 ] as const;
1042 // Keep sidecar exclusions aligned with the app; .bin symlinks are unused and unsupported by ASAR extraction.
1043 export const WINDOWS_SERVER_ASAR_IGNORE_GLOBS = [
1044 "**/node_modules/@cursor/sdk-*",
1045 "**/node_modules/@cursor/sdk-*/**",
1046 "**/node_modules/@anthropic-ai/claude-agent-sdk-*",
1047 "**/node_modules/@anthropic-ai/claude-agent-sdk-*/**",
1048 "**/node_modules/.bin",
1049 "**/node_modules/.bin/**",
1050 "**/*.map",
1051 ] as const;
1052
1053 export function resolveWindowsServerAsarIgnoreGlobs(arch: typeof BuildArch.Type) {
1054 const unusedArch = arch === "arm64" ? "x64" : "arm64";
1055 const unusedPrebuild = `**/node_modules/node-pty/prebuilds/win32-${unusedArch}`;
1056 const unusedConpty = `**/node_modules/node-pty/third_party/conpty/*/win10-${unusedArch}`;
1057
1058 return [
1059 ...WINDOWS_SERVER_ASAR_IGNORE_GLOBS,
1060 unusedPrebuild,
1061 `${unusedPrebuild}/**`,
1062 unusedConpty,
1063 `${unusedConpty}/**`,
1064 ];
1065 }
1066
1067 export const WINDOWS_PACKAGED_PAYLOAD_FILE_LIMIT = 80;
1068 export const WINDOWS_SERVER_RESOURCE_SOURCE_DIR = "apps/desktop/prod-resources/windows-server";
1069 export const WINDOWS_SERVER_EXTRA_RESOURCES = [
1070 {
1071 from: WINDOWS_SERVER_RESOURCE_SOURCE_DIR,
1072 to: ".",
1073 filter: [WINDOWS_SERVER_ASAR_RESOURCE, `${WINDOWS_SERVER_ASAR_RESOURCE}.unpacked/**/*`],
1074 },
1075 ] as const;
1076 export const WSL_RUNTIME_ARCHIVE_NAME = "wsl-runtime.tar.gz";
1077 export const WSL_RUNTIME_ARCHIVE_HASH_NAME = `${WSL_RUNTIME_ARCHIVE_NAME}.sha256`;
1078 export const WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE = {
1079 from: `apps/desktop/prod-resources/${WSL_RUNTIME_ARCHIVE_NAME}`,
1080 to: WSL_RUNTIME_ARCHIVE_NAME,
1081 } as const;
1082 export const WSL_RUNTIME_ARCHIVE_HASH_EXTRA_RESOURCE = {
1083 from: `apps/desktop/prod-resources/${WSL_RUNTIME_ARCHIVE_HASH_NAME}`,
1084 to: WSL_RUNTIME_ARCHIVE_HASH_NAME,
1085 } as const;
1086
1087 export const bundlesWslRuntime = (input: {
1088 readonly platform: typeof BuildPlatform.Type;
1089 readonly runtimeArchivePath: string | undefined;
1090 }): boolean => input.platform === "win" && input.runtimeArchivePath !== undefined;
1091
1092 export const WSL_RUNTIME_EXTRA_RESOURCES = [
1093 WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE,
1094 WSL_RUNTIME_ARCHIVE_HASH_EXTRA_RESOURCE,
1095 ] as const;
1096 export const DESKTOP_EXTRA_RESOURCES = [
1097 {
1098 from: "apps/desktop/prod-resources/cursor-sdk",
1099 to: "node_modules/@cursor",
1100 },
1101 {
1102 from: "apps/desktop/prod-resources/resource-monitor",
1103 to: "resource-monitor",
1104 },
1105 ] as const;
1106 export const LINUX_CAPTURE_EXTRA_RESOURCES = [
1107 {
1108 from: "apps/desktop/prod-resources/hyprland-capture",
1109 to: "hyprland-capture",
1110 },
1111 {
1112 from: "apps/desktop/prod-resources/kde-capture",
1113 to: "kde-capture",
1114 },
1115 {
1116 from: "apps/desktop/gnome-extension",
1117 to: "gnome-extension",
1118 filter: gnomeCaptureBundle.files,
1119 },
1120 ] as const;
1121 export const LINUX_BROWSER_SECRET_EXTRA_RESOURCES = [
1122 { from: "apps/desktop/prod-resources/browser-secret", to: "browser-secret" },
1123 ] as const;
1124 export const MAC_APPLE_SPEECH_EXTRA_RESOURCES = [
1125 { from: "apps/desktop/prod-resources/apple-speech", to: "apple-speech" },
1126 ] as const;
1127
1128 export interface MacPasskeySigningConfiguration {
1129 readonly appId: string;
1130 readonly teamId: string;
1131 readonly rpDomains: readonly string[];
1132 readonly provisioningProfilePath: string;
1133 }
1134
1135 export const InvalidMacPasskeyRpDomainReason = Schema.Literals([
1136 "empty",
1137 "scheme-not-allowed",
1138 "parse-failed",
1139 "credentials-not-allowed",
1140 "port-not-allowed",
1141 "path-not-allowed",
1142 "query-not-allowed",
1143 "fragment-not-allowed",
1144 "hostname-mismatch",
1145 ]);
1146 export type InvalidMacPasskeyRpDomainReason = typeof InvalidMacPasskeyRpDomainReason.Type;
1147
1148 export class InvalidMacPasskeyRpDomainError extends Schema.TaggedError<InvalidMacPasskeyRpDomainError>()(
1149 "InvalidMacPasskeyRpDomainError",
1150 {
1151 reason: InvalidMacPasskeyRpDomainReason,
1152 inputLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
1153 cause: Schema.optionalKey(Schema.Defect()),
1154 },
1155 ) {
1156 override get message(): string {
1157 return `Invalid passkey RP domain (${this.reason}).`;
1158 }
1159 }
1160
1161 export class InvalidAppleTeamIdError extends Schema.TaggedError<InvalidAppleTeamIdError>()(
1162 "InvalidAppleTeamIdError",
1163 {
1164 teamId: Schema.String,
1165 },
1166 ) {
1167 override get message(): string {
1168 return `T3CODE_APPLE_TEAM_ID '${this.teamId}' must be a 10-character Apple Developer Team ID.`;
1169 }
1170 }
1171
1172 export class MissingMacPasskeyProvisioningProfileError extends Schema.TaggedError<MissingMacPasskeyProvisioningProfileError>()(
1173 "MissingMacPasskeyProvisioningProfileError",
1174 {},
1175 ) {
1176 override get message(): string {
1177 return "T3CODE_MACOS_PROVISIONING_PROFILE must point to an Associated Domains provisioning profile.";
1178 }
1179 }
1180
1181 export class MissingMacPasskeyDomainConfigurationError extends Schema.TaggedError<MissingMacPasskeyDomainConfigurationError>()(
1182 "MissingMacPasskeyDomainConfigurationError",
1183 {},
1184 ) {
1185 override get message(): string {
1186 return "T3CODE_CLERK_PUBLISHABLE_KEY or T3CODE_CLERK_PASSKEY_RP_DOMAINS is required for signed macOS passkey builds.";
1187 }
1188 }
1189
1190 export class InvalidMacPasskeyPublishableKeyError extends Schema.TaggedError<InvalidMacPasskeyPublishableKeyError>()(
1191 "InvalidMacPasskeyPublishableKeyError",
1192 {
1193 cause: Schema.Defect(),
1194 },
1195 ) {
1196 override get message(): string {
1197 return "T3CODE_CLERK_PUBLISHABLE_KEY is invalid.";
1198 }
1199 }
1200
1201 export class MissingMacPasskeyRpDomainError extends Schema.TaggedError<MissingMacPasskeyRpDomainError>()(
1202 "MissingMacPasskeyRpDomainError",
1203 {},
1204 ) {
1205 override get message(): string {
1206 return "At least one Clerk passkey RP domain is required.";
1207 }
1208 }
1209
1210 export const MacPasskeySigningConfigurationError = Schema.Union([
1211 InvalidMacPasskeyRpDomainError,
1212 InvalidAppleTeamIdError,
1213 MissingMacPasskeyProvisioningProfileError,
1214 MissingMacPasskeyDomainConfigurationError,
1215 InvalidMacPasskeyPublishableKeyError,
1216 MissingMacPasskeyRpDomainError,
1217 ]);
1218 export type MacPasskeySigningConfigurationError = typeof MacPasskeySigningConfigurationError.Type;
1219 export const isMacPasskeySigningConfigurationError = Schema.is(MacPasskeySigningConfigurationError);
1220
1221 function normalizePasskeyRpDomain(value: string): string {
1222 const normalized = value.trim().toLowerCase();
1223 const inputLength = value.length;
1224 if (normalized.length === 0) {
1225 throw new InvalidMacPasskeyRpDomainError({ reason: "empty", inputLength });
1226 }
1227 if (/^[a-z][a-z\d+.-]*:\/\//u.test(normalized)) {
1228 throw new InvalidMacPasskeyRpDomainError({
1229 reason: "scheme-not-allowed",
1230 inputLength,
1231 });
1232 }
1233
1234 let parsed: URL;
1235 try {
1236 parsed = new URL(`https://${normalized}`);
1237 } catch (cause) {
1238 throw new InvalidMacPasskeyRpDomainError({ reason: "parse-failed", inputLength, cause });
1239 }
1240
1241 let reason: InvalidMacPasskeyRpDomainReason | undefined;
1242 if (parsed.username.length > 0 || parsed.password.length > 0) {
1243 reason = "credentials-not-allowed";
1244 } else if (parsed.port.length > 0) {
1245 reason = "port-not-allowed";
1246 } else if (parsed.pathname !== "/") {
1247 reason = "path-not-allowed";
1248 } else if (parsed.search.length > 0) {
1249 reason = "query-not-allowed";
1250 } else if (parsed.hash.length > 0) {
1251 reason = "fragment-not-allowed";
1252 } else if (parsed.host !== normalized) {
1253 reason = "hostname-mismatch";
1254 }
1255 if (reason) {
1256 throw new InvalidMacPasskeyRpDomainError({ reason, inputLength });
1257 }
1258
1259 return parsed.hostname;
1260 }
1261
1262 export function resolveMacPasskeySigningConfiguration(
1263 env: Readonly<Record<string, string | undefined>>,
1264 ): MacPasskeySigningConfiguration {
1265 const teamId = env.T3CODE_APPLE_TEAM_ID?.trim().toUpperCase() ?? "";
1266 if (!APPLE_TEAM_ID_PATTERN.test(teamId)) {
1267 throw new InvalidAppleTeamIdError({ teamId });
1268 }
1269
1270 const provisioningProfilePath = env.T3CODE_MACOS_PROVISIONING_PROFILE?.trim() ?? "";
1271 if (provisioningProfilePath.length === 0) {
1272 throw new MissingMacPasskeyProvisioningProfileError();
1273 }
1274
1275 const configuredRpDomains = env.T3CODE_CLERK_PASSKEY_RP_DOMAINS?.trim();
1276 let rpDomains: readonly string[];
1277 if (configuredRpDomains) {
1278 rpDomains = configuredRpDomains.split(",").map(normalizePasskeyRpDomain);
1279 } else {
1280 const publishableKey = env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim();
1281 if (!publishableKey) {
1282 throw new MissingMacPasskeyDomainConfigurationError();
1283 }
1284 let hostname: string;
1285 try {
1286 hostname = clerkFrontendApiHostnameFromPublishableKey(publishableKey);
1287 } catch (cause) {
1288 throw new InvalidMacPasskeyPublishableKeyError({ cause });
1289 }
1290 rpDomains = [normalizePasskeyRpDomain(hostname)];
1291 }
1292
1293 const uniqueRpDomains = [...new Set(rpDomains)];
1294 if (uniqueRpDomains.length === 0) {
1295 throw new MissingMacPasskeyRpDomainError();
1296 }
1297
1298 return {
1299 appId: DESKTOP_APP_ID,
1300 teamId,
1301 rpDomains: uniqueRpDomains,
1302 provisioningProfilePath,
1303 };
1304 }
1305
1306 function escapeXml(value: string): string {
1307 return value
1308 .replaceAll("&", "&amp;")
1309 .replaceAll("<", "&lt;")
1310 .replaceAll(">", "&gt;")
1311 .replaceAll('"', "&quot;")
1312 .replaceAll("'", "&apos;");
1313 }
1314
1315 /** macOS refuses restricted entitlements absent from the provisioning profile. */
1316 export interface MacWebAuthnEntitlements {
1317 readonly touchIdKeychainAccessGroup: string | undefined;
1318 readonly browserPasskeys: boolean;
1319 }
1320
1321 const BROWSER_PASSKEYS_ENTITLEMENT = "com.apple.developer.web-browser.public-key-credential";
1322
1323 const ProvisioningProfilePlist = Schema.Struct({
1324 Entitlements: Schema.Struct({
1325 "keychain-access-groups": Schema.optional(Schema.Array(Schema.String)),
1326 [BROWSER_PASSKEYS_ENTITLEMENT]: Schema.optional(Schema.Boolean),
1327 }),
1328 });
1329 const isProvisioningProfilePlist = Schema.is(ProvisioningProfilePlist);
1330
1331 const readProfileEntitlements = (provisioningProfile: string) => {
1332 const start = provisioningProfile.indexOf("<?xml");
1333 const end = provisioningProfile.indexOf("</plist>", start);
1334 if (start === -1 || end === -1) return undefined;
1335 try {
1336 const profile: unknown = Plist.parse(provisioningProfile.slice(start, end + "</plist>".length));
1337 return isProvisioningProfilePlist(profile) ? profile.Entitlements : undefined;
1338 } catch {
1339 return undefined;
1340 }
1341 };
1342
1343 export function resolveMacWebAuthnEntitlements(
1344 provisioningProfile: string,
1345 configuration: Pick<MacPasskeySigningConfiguration, "appId" | "teamId">,
1346 ): MacWebAuthnEntitlements {
1347 const entitlements = readProfileEntitlements(provisioningProfile);
1348 const keychainAccessGroup = `${configuration.teamId}.${configuration.appId}.webauthn`;
1349 const keychainGroupAuthorized = (entitlements?.["keychain-access-groups"] ?? []).some((group) =>
1350 group.endsWith("*")
1351 ? keychainAccessGroup.startsWith(group.slice(0, -1))
1352 : group === keychainAccessGroup,
1353 );
1354 return {
1355 touchIdKeychainAccessGroup: keychainGroupAuthorized ? keychainAccessGroup : undefined,
1356 browserPasskeys: entitlements?.[BROWSER_PASSKEYS_ENTITLEMENT] === true,
1357 };
1358 }
1359
1360 export function renderMacPasskeyEntitlements(
1361 configuration: MacPasskeySigningConfiguration,
1362 webAuthn: MacWebAuthnEntitlements,
1363 ): string {
1364 const associatedDomains = configuration.rpDomains
1365 .map((domain) => ` <string>webcredentials:${escapeXml(domain)}</string>`)
1366 .join("\n");
1367 const keychainAccessGroups = webAuthn.touchIdKeychainAccessGroup
1368 ? `
1369 <key>keychain-access-groups</key>
1370 <array>
1371 <string>${escapeXml(webAuthn.touchIdKeychainAccessGroup)}</string>
1372 </array>`
1373 : "";
1374 const browserPasskeys = webAuthn.browserPasskeys
1375 ? `
1376 <key>${BROWSER_PASSKEYS_ENTITLEMENT}</key>
1377 <true/>`
1378 : "";
1379
1380 return `<?xml version="1.0" encoding="UTF-8"?>
1381 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1382 <plist version="1.0">
1383 <dict>
1384 <key>com.apple.application-identifier</key>
1385 <string>${escapeXml(`${configuration.teamId}.${configuration.appId}`)}</string>
1386 <key>com.apple.developer.team-identifier</key>
1387 <string>${escapeXml(configuration.teamId)}</string>
1388 <key>com.apple.developer.associated-domains</key>
1389 <array>
1390 ${associatedDomains}
1391 </array>${keychainAccessGroups}${browserPasskeys}
1392 <key>com.apple.security.cs.allow-jit</key>
1393 <true/>
1394 <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
1395 <true/>
1396 <key>com.apple.security.cs.disable-library-validation</key>
1397 <true/>
1398 <!-- The hardened runtime denies camera and microphone to the app and every
1399 child process, with no prompt, unless the app claims these. Terminals
1400 and coding agents inherit the app's TCC identity, so without these a
1401 command like ffmpeg or imagesnap gets silent access-denied. -->
1402 <key>com.apple.security.device.camera</key>
1403 <true/>
1404 <key>com.apple.security.device.audio-input</key>
1405 <true/>
1406 </dict>
1407 </plist>
1408 `;
1409 }
1410
1411 export function resolveFffNativeDependencies(
1412 platform: typeof BuildPlatform.Type,
1413 arch: typeof BuildArch.Type,
1414 version: string,
1415 ): Record<string, string> {
1416 const architectures = arch === "universal" ? (["arm64", "x64"] as const) : [arch];
1417
1418 if (platform === "mac") {
1419 return Object.fromEntries(
1420 architectures.map((architecture) => [`@ff-labs/fff-bin-darwin-${architecture}`, version]),
1421 );
1422 }
1423
1424 if (platform === "win") {
1425 return Object.fromEntries(
1426 architectures.map((architecture) => [`@ff-labs/fff-bin-win32-${architecture}`, version]),
1427 );
1428 }
1429
1430 return Object.fromEntries(
1431 architectures.flatMap((architecture) =>
1432 ["gnu", "musl"].map((libc) => [`@ff-labs/fff-bin-linux-${architecture}-${libc}`, version]),
1433 ),
1434 );
1435 }
1436
1437 // macOS and Linux share one app.asar; stage the union of both bundles' external dependencies.
1438 export function resolveMergedStageDependencies(input: {
1439 readonly platform: "mac" | "linux";
1440 readonly serverDependencies: Record<string, string>;
1441 readonly desktopDependencies: Record<string, string>;
1442 readonly arch: typeof BuildArch.Type;
1443 readonly fffNodeVersion: string;
1444 }) {
1445 return {
1446 ...selectCliRuntimeExternalDependencies(input.serverDependencies),
1447 ...input.desktopDependencies,
1448 ...resolveFffNativeDependencies(input.platform, input.arch, input.fffNodeVersion),
1449 };
1450 }
1451
1452 /** Cursor's helper lookup falls through the archive to this real resources tree. */
1453 export const stageCursorSdkPlatformPackages = Effect.fn("stageCursorSdkPlatformPackages")(
1454 function* (nodeModulesDir: string, destination: string) {
1455 const fs = yield* FileSystem.FileSystem;
1456 const path = yield* Path.Path;
1457 yield* fs.makeDirectory(destination, { recursive: true });
1458 const sdkDirectory = path.join(nodeModulesDir, "@cursor/sdk");
1459 if (!(yield* fs.exists(sdkDirectory))) return;
1460 const cursorDirectory = path.dirname(yield* fs.realPath(sdkDirectory));
1461 for (const name of yield* fs.readDirectory(cursorDirectory)) {
1462 if (!name.startsWith("sdk-")) continue;
1463 const source = yield* fs.realPath(path.join(cursorDirectory, name));
1464 yield* fs.copy(source, path.join(destination, name));
1465 }
1466 },
1467 );
1468
1469 export interface ClerkPasskeyNativeArtifact {
1470 readonly packageName: string;
1471 readonly binaryFileName: string;
1472 }
1473
1474 export function resolveClerkPasskeyNativeArtifacts(
1475 platform: typeof BuildPlatform.Type,
1476 arch: typeof BuildArch.Type,
1477 ): readonly ClerkPasskeyNativeArtifact[] {
1478 const architectures = arch === "universal" ? (["arm64", "x64"] as const) : [arch];
1479
1480 if (platform === "mac") {
1481 return architectures.map((architecture) => ({
1482 packageName: `@clerk/electron-passkeys-darwin-${architecture}`,
1483 binaryFileName: `electron-passkeys.darwin-${architecture}.node`,
1484 }));
1485 }
1486
1487 if (platform === "win") {
1488 return architectures.map((architecture) => ({
1489 packageName: `@clerk/electron-passkeys-win32-${architecture}-msvc`,
1490 binaryFileName: `electron-passkeys.win32-${architecture}-msvc.node`,
1491 }));
1492 }
1493
1494 return [];
1495 }
1496
1497 export function resolveKeyringNativeArtifacts(
1498 platform: typeof BuildPlatform.Type,
1499 arch: typeof BuildArch.Type,
1500 ): readonly ClerkPasskeyNativeArtifact[] {
1501 const architectures = arch === "universal" ? (["arm64", "x64"] as const) : [arch];
1502
1503 if (platform === "mac") {
1504 return architectures.map((architecture) => ({
1505 packageName: `@napi-rs/keyring-darwin-${architecture}`,
1506 binaryFileName: `keyring.darwin-${architecture}.node`,
1507 }));
1508 }
1509
1510 if (platform === "win") {
1511 return architectures.map((architecture) => ({
1512 packageName: `@napi-rs/keyring-win32-${architecture}-msvc`,
1513 binaryFileName: `keyring.win32-${architecture}-msvc.node`,
1514 }));
1515 }
1516
1517 return architectures.map((architecture) => ({
1518 packageName: `@napi-rs/keyring-linux-${architecture}-gnu`,
1519 binaryFileName: `keyring.linux-${architecture}-gnu.node`,
1520 }));
1521 }
1522
1523 /** electron-builder omits pnpm-nested platform packages; stage keyring's binary beside its loader, which checks there first. */
1524 const stageKeyringNativeBinaries = Effect.fn("stageKeyringNativeBinaries")(function* (
1525 stageAppDir: string,
1526 platform: typeof BuildPlatform.Type,
1527 arch: typeof BuildArch.Type,
1528 ) {
1529 const fs = yield* FileSystem.FileSystem;
1530 const path = yield* Path.Path;
1531 const packageEntryPath = yield* fs.realPath(
1532 path.join(stageAppDir, "node_modules", "@napi-rs", "keyring", "index.js"),
1533 );
1534 const packageDir = path.dirname(packageEntryPath);
1535 const packageRequire = NodeModule.createRequire(packageEntryPath);
1536
1537 for (const artifact of resolveKeyringNativeArtifacts(platform, arch)) {
1538 const sourcePath = yield* Effect.try({
1539 try: () => packageRequire.resolve(`${artifact.packageName}/${artifact.binaryFileName}`),
1540 catch: (cause) =>
1541 new KeyringNativePackageMissingError({
1542 packageName: artifact.packageName,
1543 binaryFileName: artifact.binaryFileName,
1544 packageEntryPath,
1545 platform,
1546 arch,
1547 cause,
1548 }),
1549 });
1550 yield* fs.copyFile(sourcePath, path.join(packageDir, artifact.binaryFileName));
1551 }
1552 });
1553
1554 // Stage pnpm-nested Clerk binaries beside index.js so the loader finds them and electron-builder unpacks them.
1555 const stageClerkPasskeyNativeBinaries = Effect.fn("stageClerkPasskeyNativeBinaries")(function* (
1556 stageAppDir: string,
1557 platform: typeof BuildPlatform.Type,
1558 arch: typeof BuildArch.Type,
1559 ) {
1560 const fs = yield* FileSystem.FileSystem;
1561 const path = yield* Path.Path;
1562 const packageEntryPath = yield* fs.realPath(
1563 path.join(stageAppDir, "node_modules", "@clerk", "electron-passkeys", "index.js"),
1564 );
1565 const packageDir = path.dirname(packageEntryPath);
1566 const packageRequire = NodeModule.createRequire(packageEntryPath);
1567
1568 for (const artifact of resolveClerkPasskeyNativeArtifacts(platform, arch)) {
1569 const sourcePath = yield* Effect.try({
1570 try: () => packageRequire.resolve(artifact.packageName),
1571 catch: (cause) =>
1572 new ClerkPasskeyNativePackageMissingError({
1573 packageName: artifact.packageName,
1574 binaryFileName: artifact.binaryFileName,
1575 packageEntryPath,
1576 platform,
1577 arch,
1578 cause,
1579 }),
1580 });
1581 yield* fs.copyFile(sourcePath, path.join(packageDir, artifact.binaryFileName));
1582 }
1583 });
1584
1585 export function createStageWorkspaceConfig(input: {
1586 readonly platform: typeof BuildPlatform.Type;
1587 readonly arch: typeof BuildArch.Type;
1588 readonly allowBuilds?: Record<string, boolean>;
1589 readonly patchedDependencies?: Record<string, string>;
1590 readonly overrides?: Record<string, string>;
1591 }): StageWorkspaceConfig {
1592 const { platform, arch, allowBuilds, patchedDependencies, overrides } = input;
1593 const hostOs = platform === "mac" ? "darwin" : platform === "win" ? "win32" : "linux";
1594 const hostCpu = arch === "universal" ? ["arm64", "x64"] : [arch];
1595 // Linux AppImages require glibc native optional dependencies; tell pnpm explicitly.
1596 const supportedArchitectures =
1597 platform === "linux"
1598 ? {
1599 os: [hostOs],
1600 cpu: hostCpu,
1601 libc: ["glibc"],
1602 }
1603 : {
1604 os: [hostOs],
1605 cpu: hostCpu,
1606 };
1607
1608 return {
1609 supportedArchitectures,
1610 ...(allowBuilds && Object.keys(allowBuilds).length > 0 ? { allowBuilds } : {}),
1611 ...(patchedDependencies && Object.keys(patchedDependencies).length > 0
1612 ? { patchedDependencies }
1613 : {}),
1614 ...(overrides && Object.keys(overrides).length > 0 ? { overrides } : {}),
1615 packageExtensions: STAGE_PACKAGE_EXTENSIONS,
1616 };
1617 }
1618
1619 export function createStagePatchedDependencies(
1620 patchedDependencies: Record<string, string>,
1621 dependencies: Record<string, unknown>,
1622 ): Record<string, string> {
1623 return Object.fromEntries(
1624 Object.entries(patchedDependencies).filter(([patchKey]) =>
1625 Object.hasOwn(dependencies, getPatchedDependencyPackageName(patchKey)),
1626 ),
1627 );
1628 }
1629
1630 function getPatchedDependencyPackageName(patchKey: string): string {
1631 const versionSeparator = patchKey.lastIndexOf("@");
1632 return versionSeparator > 0 ? patchKey.slice(0, versionSeparator) : patchKey;
1633 }
1634
1635 const AzureTrustedSigningOptionsConfig = Config.all({
1636 publisherName: Config.String("AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"),
1637 endpoint: Config.String("AZURE_TRUSTED_SIGNING_ENDPOINT"),
1638 certificateProfileName: Config.String("AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME"),
1639 codeSigningAccountName: Config.String("AZURE_TRUSTED_SIGNING_ACCOUNT_NAME"),
1640 fileDigest: Config.String("AZURE_TRUSTED_SIGNING_FILE_DIGEST").pipe(Config.withDefault("SHA256")),
1641 timestampDigest: Config.String("AZURE_TRUSTED_SIGNING_TIMESTAMP_DIGEST").pipe(
1642 Config.withDefault("SHA256"),
1643 ),
1644 timestampRfc3161: Config.String("AZURE_TRUSTED_SIGNING_TIMESTAMP_RFC3161").pipe(
1645 Config.withDefault("http://timestamp.acs.microsoft.com"),
1646 ),
1647 });
1648
1649 const BuildEnvConfig = Config.all({
1650 platform: Config.schema(BuildPlatform, "T3CODE_DESKTOP_PLATFORM").pipe(Config.option),
1651 target: Config.String("T3CODE_DESKTOP_TARGET").pipe(Config.option),
1652 arch: Config.schema(BuildArch, "T3CODE_DESKTOP_ARCH").pipe(Config.option),
1653 version: Config.String("T3CODE_DESKTOP_VERSION").pipe(Config.option),
1654 outputDir: Config.String("T3CODE_DESKTOP_OUTPUT_DIR").pipe(Config.option),
1655 skipBuild: Config.Boolean("T3CODE_DESKTOP_SKIP_BUILD").pipe(Config.withDefault(false)),
1656 keepStage: Config.Boolean("T3CODE_DESKTOP_KEEP_STAGE").pipe(Config.withDefault(false)),
1657 signed: Config.Boolean("T3CODE_DESKTOP_SIGNED").pipe(Config.withDefault(false)),
1658 verbose: Config.Boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(false)),
1659 mockUpdates: Config.Boolean("T3CODE_DESKTOP_MOCK_UPDATES").pipe(Config.withDefault(false)),
1660 mockUpdateServerPort: Config.String("T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT").pipe(Config.option),
1661 wslRuntime: Config.String("T3CODE_DESKTOP_WSL_RUNTIME").pipe(Config.option),
1662 });
1663
1664 const MockUpdateServerPortSchema = Schema.NumberFromString.check(
1665 Schema.isInt(),
1666 Schema.isBetween({ minimum: 1, maximum: 65535 }),
1667 );
1668 const decodeMockUpdateServerPort = Schema.decodeUnknownEffect(MockUpdateServerPortSchema);
1669
1670 function invalidMockUpdateServerPortReason(
1671 configuredPort: string,
1672 ): typeof InvalidMockUpdateServerPortReason.Type {
1673 const parsed = Number(configuredPort);
1674 if (!Number.isFinite(parsed)) return "not-numeric";
1675 if (!Number.isInteger(parsed)) return "not-integer";
1676 if (parsed < 1 || parsed > 65535) return "out-of-range";
1677 // Decoding already failed; valid integers here used unsupported representations.
1678 return "not-numeric";
1679 }
1680
1681 const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
1682 Option.getOrElse(flag, () => envValue);
1683 const mergeOptions = <A>(a: Option.Option<A>, b: Option.Option<A>, defaultValue: A) =>
1684 Option.getOrElse(a, () => Option.getOrElse(b, () => defaultValue));
1685
1686 export const resolveMockUpdateServerPort = Effect.fn("resolveMockUpdateServerPort")(function* (
1687 mockUpdateServerPort: string | undefined,
1688 ) {
1689 const port = mockUpdateServerPort?.trim();
1690 if (!port) {
1691 return undefined;
1692 }
1693
1694 return yield* decodeMockUpdateServerPort(port);
1695 });
1696
1697 export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (
1698 input: BuildCliInput,
1699 ) {
1700 const path = yield* Path.Path;
1701 const repoRoot = yield* RepoRoot;
1702 const env = yield* BuildEnvConfig;
1703 const hostPlatform = yield* HostProcess.Platform;
1704
1705 const platform = mergeOptions(
1706 input.platform,
1707 env.platform,
1708 detectHostBuildPlatform(hostPlatform),
1709 );
1710
1711 if (!platform) {
1712 return yield* new UnsupportedHostBuildPlatformError({ hostPlatform });
1713 }
1714
1715 const target = mergeOptions(input.target, env.target, PLATFORM_CONFIG[platform].defaultTarget);
1716 const defaultArch = yield* getDefaultArch(platform);
1717 const arch = mergeOptions(input.arch, env.arch, defaultArch);
1718 const supportedArchitectures = PLATFORM_CONFIG[platform].archChoices;
1719 if (!supportedArchitectures.includes(arch)) {
1720 return yield* new UnsupportedDesktopBuildArchitectureError({
1721 platform,
1722 arch,
1723 supportedArchitectures: [...supportedArchitectures],
1724 });
1725 }
1726 const version = mergeOptions(input.buildVersion, env.version, undefined);
1727 const releaseDir = resolveBooleanFlag(input.mockUpdates, env.mockUpdates)
1728 ? "release-mock"
1729 : "release";
1730 const outputDir = path.resolve(
1731 repoRoot,
1732 mergeOptions(input.outputDir, env.outputDir, releaseDir),
1733 );
1734
1735 const skipBuild = resolveBooleanFlag(input.skipBuild, env.skipBuild);
1736 const keepStage = resolveBooleanFlag(input.keepStage, env.keepStage);
1737 const signed = resolveBooleanFlag(input.signed, env.signed);
1738 const verbose = resolveBooleanFlag(input.verbose, env.verbose);
1739
1740 const mockUpdates = resolveBooleanFlag(input.mockUpdates, env.mockUpdates);
1741 const configuredMockUpdateServerPort = Option.getOrUndefined(env.mockUpdateServerPort);
1742 const mockUpdateServerPort =
1743 Option.getOrUndefined(input.mockUpdateServerPort) ??
1744 (configuredMockUpdateServerPort === undefined
1745 ? undefined
1746 : yield* resolveMockUpdateServerPort(configuredMockUpdateServerPort).pipe(
1747 Effect.mapError((cause) =>
1748 InvalidMockUpdateServerPortError.fromConfigValue(configuredMockUpdateServerPort, cause),
1749 ),
1750 ));
1751
1752 const wslRuntime =
1753 Option.getOrUndefined(input.wslRuntime) ?? Option.getOrUndefined(env.wslRuntime);
1754
1755 return {
1756 platform,
1757 target,
1758 arch,
1759 version,
1760 outputDir,
1761 skipBuild,
1762 keepStage,
1763 signed,
1764 verbose,
1765 mockUpdates,
1766 mockUpdateServerPort,
1767 wslRuntime,
1768 } satisfies ResolvedBuildOptions;
1769 });
1770
1771 const runCommand = Effect.fn("runCommand")(function* (
1772 command: ChildProcess.Command,
1773 options: {
1774 readonly label: string;
1775 readonly verbose: boolean;
1776 },
1777 ) {
1778 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1779 const child = yield* commandSpawner.spawn(command);
1780 const [stdout, stderr, exitCode] = yield* Effect.all(
1781 [
1782 collectCommandStream(child.stdout, process.stdout, options.verbose),
1783 collectCommandStream(child.stderr, process.stderr, options.verbose),
1784 child.exitCode.pipe(Effect.map(Number)),
1785 ],
1786 { concurrency: "unbounded" },
1787 );
1788
1789 if (exitCode !== 0) {
1790 return yield* new BuildCommandFailedError({
1791 command: options.label,
1792 exitCode,
1793 ...(stdout.trim() ? { stdoutTail: stdout } : {}),
1794 ...(stderr.trim() ? { stderrTail: stderr } : {}),
1795 });
1796 }
1797 });
1798
1799 export class DesktopBuildAlreadyRunningError extends Schema.TaggedError<DesktopBuildAlreadyRunningError>()(
1800 "DesktopBuildAlreadyRunningError",
1801 { lockPath: Schema.String },
1802 ) {
1803 override get message(): string {
1804 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.`;
1805 }
1806 }
1807
1808 const withDesktopBuildLock = Effect.fn("withDesktopBuildLock")(function* <A, E, R>(
1809 repoRoot: string,
1810 build: Effect.Effect<A, E, R>,
1811 ) {
1812 const fs = yield* FileSystem.FileSystem;
1813 const path = yield* Path.Path;
1814 const lockPath = path.join(repoRoot, ".desktop-build.lock");
1815 return yield* Effect.acquireUseRelease(
1816 fs
1817 .makeDirectory(lockPath)
1818 .pipe(
1819 Effect.mapError((error) =>
1820 error.reason._tag === "AlreadyExists"
1821 ? new DesktopBuildAlreadyRunningError({ lockPath })
1822 : error,
1823 ),
1824 ),
1825 // Stop packaging children and finish stage cleanup before another build can enter.
1826 () => build.pipe(Effect.scoped),
1827 (_, exit) =>
1828 fs
1829 .remove(lockPath, { recursive: true })
1830 .pipe(
1831 Effect.catch((error) =>
1832 Exit.isFailure(exit) ? Effect.logError(error) : Effect.fail(error),
1833 ),
1834 ),
1835 );
1836 });
1837
1838 // The artifact entry point holds the checkout lock through staging/packaging,
1839 // so it calls this implementation without reacquiring its own lock.
1840 const buildDesktopBundlesUnlocked = Effect.fn("buildDesktopBundlesUnlocked")(function* (
1841 repoRoot: string,
1842 appVersion: string,
1843 verbose: boolean,
1844 ) {
1845 const fs = yield* FileSystem.FileSystem;
1846 const path = yield* Path.Path;
1847 const spawnCommand = yield* resolveSpawnCommand("vp", ["run", "build:desktop"]);
1848 yield* Effect.acquireUseRelease(
1849 Effect.forEach(releasePackageFiles, (relativePath) =>
1850 Effect.gen(function* () {
1851 const filePath = path.join(repoRoot, relativePath);
1852 const contents = yield* fs.readFileString(filePath);
1853 const needsRestore = yield* decodeReleasePackageManifest(contents).pipe(
1854 Effect.map((manifest) => manifest.version !== appVersion),
1855 // Let alignment report invalid manifests after any preceding writes.
1856 Effect.orElseSucceed(() => false),
1857 );
1858 return { filePath, contents, needsRestore };
1859 }),
1860 ),
1861 () =>
1862 Effect.gen(function* () {
1863 yield* updateReleasePackageVersions(appVersion, { rootDir: repoRoot });
1864 // The compiler must stop reading the aligned manifests before restoration.
1865 yield* runCommand(
1866 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
1867 cwd: repoRoot,
1868 shell: spawnCommand.shell,
1869 env: { APP_VERSION: appVersion },
1870 extendEnv: true,
1871 }),
1872 { label: "vp run build:desktop", verbose },
1873 ).pipe(Effect.scoped);
1874 }),
1875 (originals, exit) =>
1876 Effect.gen(function* () {
1877 const [, failures] = yield* Effect.partition(
1878 originals.filter(({ needsRestore }) => needsRestore),
1879 ({ filePath, contents }) =>
1880 fs
1881 .writeFileString(filePath, contents)
1882 .pipe(
1883 Effect.mapError(
1884 (cause) =>
1885 new ReleasePackageManifestError({ operation: "write", filePath, cause }),
1886 ),
1887 ),
1888 );
1889 if (failures.length === 0) return;
1890 const error = new DesktopBuildManifestRestoreError({ failures });
1891 if (Exit.isFailure(exit)) {
1892 // Cleanup must not hide the original build or alignment failure.
1893 yield* Effect.logError(error);
1894 } else {
1895 return yield* error;
1896 }
1897 }),
1898 );
1899 });
1900
1901 export const buildDesktopBundles = Effect.fn("buildDesktopBundles")(
1902 (repoRoot: string, appVersion: string, verbose: boolean) =>
1903 withDesktopBuildLock(repoRoot, buildDesktopBundlesUnlocked(repoRoot, appVersion, verbose)),
1904 );
1905
1906 const desktopBuildProbeSucceeds = Effect.fn("desktopBuildProbeSucceeds")(function* (
1907 command: ChildProcess.Command,
1908 label: string,
1909 ) {
1910 return yield* runCommand(command, { label, verbose: false }).pipe(
1911 Effect.as(true),
1912 Effect.orElseSucceed(() => false),
1913 );
1914 });
1915
1916 const rustTargetIsInstalled = Effect.fn("rustTargetIsInstalled")(function* (target: string) {
1917 const fs = yield* FileSystem.FileSystem;
1918 const result = yield* spawnAndCollectOutput(
1919 ChildProcess.make("rustc", ["--print", "target-libdir", "--target", target]),
1920 ).pipe(Effect.orElseSucceed(() => null));
1921 if (result === null || result.exitCode !== 0) return false;
1922
1923 const targetLibDir = result.stdout.trim();
1924 if (targetLibDir === "") return false;
1925 const entries = yield* fs.readDirectory(targetLibDir).pipe(Effect.orElseSucceed(() => []));
1926 return entries.some((entry) => entry.startsWith("libstd-") && entry.endsWith(".rlib"));
1927 });
1928
1929 export const preflightLinuxDesktopBuild = Effect.fn("preflightLinuxDesktopBuild")(function* (
1930 arch: typeof BuildArch.Type = "x64",
1931 ) {
1932 const reuseResourceMonitor = yield* Config.Boolean("T3CODE_DESKTOP_REUSE_RESOURCE_MONITOR").pipe(
1933 Config.withDefault(false),
1934 );
1935 const reuseCaptureHelpers = yield* Config.Boolean(
1936 "T3CODE_DESKTOP_REUSE_LINUX_CAPTURE_HELPERS",
1937 ).pipe(Config.withDefault(false));
1938 const needsRust = !reuseResourceMonitor || !reuseCaptureHelpers;
1939 const rustTarget = resolveResourceMonitorRustTargets("linux", arch)[0]!;
1940
1941 const checks = yield* Effect.all(
1942 {
1943 cargo: needsRust
1944 ? desktopBuildProbeSucceeds(ChildProcess.make("cargo", ["--version"]), "cargo")
1945 : Effect.succeed(true),
1946 "rust-target": needsRust ? rustTargetIsInstalled(rustTarget) : Effect.succeed(true),
1947 cc: desktopBuildProbeSucceeds(ChildProcess.make("cc", ["--version"]), "cc"),
1948 make: desktopBuildProbeSucceeds(ChildProcess.make("make", ["--version"]), "make"),
1949 libsecret: desktopBuildProbeSucceeds(
1950 ChildProcess.make("pkg-config", ["--exists", "libsecret-1"]),
1951 "libsecret",
1952 ),
1953 imagemagick: Effect.all([
1954 desktopBuildProbeSucceeds(ChildProcess.make("magick", ["-version"]), "magick"),
1955 desktopBuildProbeSucceeds(ChildProcess.make("convert", ["-version"]), "convert"),
1956 ]).pipe(Effect.map(([magick, convert]) => magick || convert)),
1957 },
1958 { concurrency: "unbounded" },
1959 );
1960 const missing = LINUX_DESKTOP_BUILD_PREREQUISITES.filter(
1961 (requirement) => !checks[requirement.id],
1962 ).map((requirement) => requirement.id);
1963
1964 if (missing.length > 0) {
1965 return yield* new LinuxDesktopBuildPrerequisitesMissingError({ missing, rustTarget });
1966 }
1967 });
1968
1969 export const preflightMacDesktopBuild = Effect.fn("preflightMacDesktopBuild")(function* (
1970 arch: typeof BuildArch.Type,
1971 ) {
1972 const rustTargets = resolveResourceMonitorRustTargets("mac", arch);
1973 const reuseResourceMonitor = yield* Config.Boolean("T3CODE_DESKTOP_REUSE_RESOURCE_MONITOR").pipe(
1974 Config.withDefault(false),
1975 );
1976 const checks = yield* Effect.all(
1977 {
1978 rust: reuseResourceMonitor
1979 ? Effect.succeed(true)
1980 : Effect.all([
1981 desktopBuildProbeSucceeds(ChildProcess.make("cargo", ["--version"]), "cargo"),
1982 Effect.forEach(rustTargets, rustTargetIsInstalled).pipe(
1983 Effect.map((results) => results.every(Boolean)),
1984 ),
1985 ]).pipe(Effect.map(([cargo, targets]) => cargo && targets)),
1986 clang: desktopBuildProbeSucceeds(ChildProcess.make("clang", ["--version"]), "clang"),
1987 make: desktopBuildProbeSucceeds(ChildProcess.make("make", ["--version"]), "make"),
1988 sips: desktopBuildProbeSucceeds(ChildProcess.make("sips", ["--help"]), "sips"),
1989 iconutil: desktopBuildProbeSucceeds(
1990 ChildProcess.make("xcrun", ["--find", "iconutil"]),
1991 "iconutil",
1992 ),
1993 lipo:
1994 arch === "universal"
1995 ? desktopBuildProbeSucceeds(ChildProcess.make("lipo", ["-version"]), "lipo")
1996 : Effect.succeed(true),
1997 },
1998 { concurrency: "unbounded" },
1999 );
2000 const missing = MAC_DESKTOP_BUILD_PREREQUISITES.filter(
2001 (requirement) => !checks[requirement.id],
2002 ).map((requirement) => requirement.id);
2003 if (missing.length > 0) {
2004 return yield* new MacDesktopBuildPrerequisitesMissingError({ missing, rustTargets });
2005 }
2006 });
2007
2008 function windowsVswherePrerequisiteScript(arch: typeof BuildArch.Type): string {
2009 const toolComponents =
2010 arch === "arm64"
2011 ? ["Microsoft.VisualStudio.Component.VC.Tools.ARM64"]
2012 : ["Microsoft.VisualStudio.Component.VC.Tools.x86.x64"];
2013 const spectreArch = arch === "arm64" ? "arm64" : "x64";
2014 return [
2015 "$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\\Installer\\vswhere.exe'",
2016 "if (!(Test-Path $vswhere)) { exit 1 }",
2017 `$install = & $vswhere -latest -products * -requires ${toolComponents.join(" ")} -property installationPath`,
2018 "if (!$install) { exit 1 }",
2019 "$kitsRoot = Get-ItemPropertyValue 'HKLM:\\SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots' -Name KitsRoot10 -ErrorAction SilentlyContinue",
2020 "if (!$kitsRoot -or !(Test-Path (Join-Path $kitsRoot 'Lib'))) { exit 1 }",
2021 "$msvcToolset = Get-ChildItem (Join-Path $install 'VC\\Tools\\MSVC') -Directory | Sort-Object { [version]$_.Name } -Descending | Select-Object -First 1",
2022 "if (!$msvcToolset) { exit 1 }",
2023 `if (!(Test-Path (Join-Path $msvcToolset.FullName 'lib\\spectre\\${spectreArch}'))) { exit 1 }`,
2024 ].join("; ");
2025 }
2026
2027 export const preflightWindowsDesktopBuild = Effect.fn("preflightWindowsDesktopBuild")(
2028 function* (input: { readonly arch: typeof BuildArch.Type; readonly bundlesWslRuntime: boolean }) {
2029 const rustTarget = resolveResourceMonitorRustTargets("win", input.arch)[0]!;
2030 const reuseResourceMonitor = yield* Config.Boolean(
2031 "T3CODE_DESKTOP_REUSE_RESOURCE_MONITOR",
2032 ).pipe(Config.withDefault(false));
2033 const python = yield* resolvePythonForNodeGyp();
2034 const checks = yield* Effect.all(
2035 {
2036 rust: reuseResourceMonitor
2037 ? Effect.succeed(true)
2038 : Effect.all([
2039 desktopBuildProbeSucceeds(ChildProcess.make("cargo", ["--version"]), "cargo"),
2040 rustTargetIsInstalled(rustTarget),
2041 ]).pipe(Effect.map(([cargo, target]) => cargo && target)),
2042 python: Effect.succeed(python !== undefined),
2043 msvc: reuseResourceMonitor
2044 ? Effect.succeed(true)
2045 : desktopBuildProbeSucceeds(
2046 ChildProcess.make("powershell.exe", [
2047 "-NoLogo",
2048 "-NoProfile",
2049 "-NonInteractive",
2050 "-Command",
2051 windowsVswherePrerequisiteScript(input.arch),
2052 ]),
2053 "Visual Studio Build Tools",
2054 ),
2055 tar: input.bundlesWslRuntime
2056 ? desktopBuildProbeSucceeds(ChildProcess.make("tar.exe", ["--version"]), "tar")
2057 : Effect.succeed(true),
2058 },
2059 { concurrency: "unbounded" },
2060 );
2061 const missing = WINDOWS_DESKTOP_BUILD_PREREQUISITES.filter(
2062 (requirement) => !checks[requirement.id],
2063 ).map((requirement) => requirement.id);
2064 if (missing.length > 0) {
2065 return yield* new WindowsDesktopBuildPrerequisitesMissingError({ missing, rustTarget });
2066 }
2067 },
2068 );
2069
2070 function trimTrailingSeparators(value: string): string {
2071 let end = value.length;
2072 while (end > 1 && (value[end - 1] === "/" || value[end - 1] === "\\")) end -= 1;
2073 return value.slice(0, end);
2074 }
2075
2076 /** Stop UNC ancestor walks at the share; a bare server is not a directory root. */
2077 function uncShareRootLength(value: string): number {
2078 const isUnc = value.startsWith("\\\\") || value.startsWith("//");
2079 if (!isUnc) return 0;
2080 const separator = /[\\/]/;
2081 const serverEnd = value.slice(2).search(separator);
2082 if (serverEnd < 0) return value.length;
2083 const shareStart = 2 + serverEnd + 1;
2084 const shareEnd = value.slice(shareStart).search(separator);
2085 return shareEnd < 0 ? value.length : shareStart + shareEnd;
2086 }
2087
2088 export function ancestorNodeModulesPaths(
2089 startDir: string,
2090 separator: string,
2091 ): ReadonlyArray<string> {
2092 // Splitting/rebuilding can lose UNC or drive roots; preserve their prefixes with lastIndexOf.
2093 const paths: string[] = [];
2094 let current = trimTrailingSeparators(startDir);
2095 const uncRootLength = uncShareRootLength(current);
2096 for (;;) {
2097 const cut = Math.max(current.lastIndexOf("/"), current.lastIndexOf("\\"));
2098 if (cut < 0 || (uncRootLength > 0 && cut < uncRootLength)) break;
2099 const parent = cut === 0 ? current.slice(0, 1) : current.slice(0, cut);
2100 if (parent === current) break;
2101 paths.push(
2102 parent.endsWith(separator) ? `${parent}node_modules` : `${parent}${separator}node_modules`,
2103 );
2104 if (cut === 0) break;
2105 current = parent;
2106 }
2107 return paths;
2108 }
2109
2110 const NativeMarkerManifest = Schema.Struct({
2111 dependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
2112 optionalDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
2113 });
2114 const decodeNativeMarkerManifest = Schema.decodeUnknownOption(
2115 Schema.fromJsonString(NativeMarkerManifest),
2116 );
2117
2118 const findStorePackageDirectory = Effect.fn("findStorePackageDirectory")(function* (
2119 repoRoot: string,
2120 packageName: string,
2121 ) {
2122 const fs = yield* FileSystem.FileSystem;
2123 const path = yield* Path.Path;
2124 const storeDir = path.join(repoRoot, "node_modules/.pnpm");
2125 const exists = (candidate: string) =>
2126 fs.exists(candidate).pipe(Effect.orElseSucceed(() => false));
2127 if (!(yield* exists(storeDir))) return null;
2128
2129 const flattened = `${packageName.replace("/", "+")}@`;
2130 const entries = yield* fs
2131 .readDirectory(storeDir)
2132 .pipe(Effect.orElseSucceed(() => [] as string[]));
2133 for (const entry of entries) {
2134 if (!entry.startsWith(flattened)) continue;
2135 const candidate = path.join(storeDir, entry, "node_modules", packageName);
2136 if (yield* exists(candidate)) return candidate;
2137 }
2138 return null;
2139 });
2140
2141 const hasNativeLoaderMarkers = Effect.fn("hasNativeLoaderMarkers")(function* (packageDir: string) {
2142 const fs = yield* FileSystem.FileSystem;
2143 const path = yield* Path.Path;
2144 const exists = (candidate: string) =>
2145 fs.exists(candidate).pipe(Effect.orElseSucceed(() => false));
2146
2147 if (yield* exists(path.join(packageDir, "binding.gyp"))) return true;
2148 if (yield* exists(path.join(packageDir, "prebuilds"))) return true;
2149
2150 const manifestPath = path.join(packageDir, "package.json");
2151 if (!(yield* exists(manifestPath))) return false;
2152 const source = yield* fs.readFileString(manifestPath).pipe(Effect.orElseSucceed(() => ""));
2153 if (source === "") return false;
2154 const manifest = decodeNativeMarkerManifest(source);
2155 if (Option.isNone(manifest)) return false;
2156 return Object.keys({
2157 ...manifest.value.dependencies,
2158 ...manifest.value.optionalDependencies,
2159 }).some((dependency) => dependency.startsWith("node-gyp-build"));
2160 });
2161
2162 export const copyDirectoryPreservingSymlinks = Effect.fn("copyDirectoryPreservingSymlinks")(
2163 function* (source: string, destination: string) {
2164 const fs = yield* FileSystem.FileSystem;
2165 const path = yield* Path.Path;
2166
2167 // fs.cp rewrites links into the source tree. Recreate local junctions so probes remain isolated without symlink privileges.
2168 yield* fs.copy(source, destination);
2169
2170 const restoreRelativeSymlinks = Effect.fn("build-desktop-artifact.restoreRelativeSymlinks")(
2171 function* (
2172 sourceDirectory: string,
2173 destinationDirectory: string,
2174 ): Effect.fn.Return<void, PlatformError | BundleNotSelfContainedError> {
2175 for (const entry of yield* fs.readDirectory(sourceDirectory)) {
2176 const sourceEntry = path.join(sourceDirectory, entry);
2177 const destinationEntry = path.join(destinationDirectory, entry);
2178 const linkTarget = yield* fs.readLink(sourceEntry).pipe(Effect.option);
2179 if (Option.isSome(linkTarget)) {
2180 const absoluteSourceTarget = path.isAbsolute(linkTarget.value)
2181 ? linkTarget.value
2182 : path.resolve(path.dirname(sourceEntry), linkTarget.value);
2183 const sourceRelativeTarget = path.relative(source, absoluteSourceTarget);
2184 if (
2185 sourceRelativeTarget === ".." ||
2186 sourceRelativeTarget.startsWith(`..${path.sep}`) ||
2187 path.isAbsolute(sourceRelativeTarget)
2188 ) {
2189 return yield* new BundleNotSelfContainedError({
2190 exitCode: -1,
2191 output: `Refusing to copy symlink ${sourceEntry}: its target ${absoluteSourceTarget} escapes the packaged tree.`,
2192 });
2193 }
2194 const target = path.join(destination, sourceRelativeTarget);
2195 yield* fs.remove(destinationEntry, { recursive: true, force: true });
2196 yield* Effect.tryPromise({
2197 try: () => NodeFSP.symlink(target, destinationEntry, "junction"),
2198 catch: (cause) =>
2199 new BundleNotSelfContainedError({
2200 exitCode: -1,
2201 output: `Could not isolate ${sourceEntry}: ${String(cause)}`,
2202 }),
2203 });
2204 } else {
2205 const info = yield* fs.stat(sourceEntry);
2206 if (info.type === "Directory") {
2207 yield* restoreRelativeSymlinks(sourceEntry, destinationEntry);
2208 }
2209 }
2210 }
2211 },
2212 );
2213
2214 yield* restoreRelativeSymlinks(source, destination);
2215 },
2216 );
2217
2218 export const verifyPackagedBundleIsSelfContained = Effect.fn("verifyPackagedBundleIsSelfContained")(
2219 function* (input: { readonly asarPath: string; readonly verbose: boolean }) {
2220 // A PR preview's bundle is untrusted and this job may hold signing secrets, so never run it.
2221 if (yield* Config.Boolean("T3CODE_DESKTOP_UNTRUSTED_BUNDLE").pipe(Config.withDefault(false))) {
2222 yield* Effect.log(
2223 "[desktop-artifact] Skipped the bundle self-check for an untrusted bundle.",
2224 );
2225 return;
2226 }
2227 const fs = yield* FileSystem.FileSystem;
2228 const path = yield* Path.Path;
2229
2230 const probeRoot = yield* fs.makeTempDirectoryScoped({
2231 prefix: "t3code-bundle-selfcheck-",
2232 });
2233 const extractedApp = path.join(probeRoot, "extracted");
2234 const probeApp = path.join(probeRoot, "app");
2235 yield* Effect.try({
2236 try: () => extractAll(input.asarPath, extractedApp),
2237 catch: (cause) =>
2238 new BundleNotSelfContainedError({
2239 exitCode: -1,
2240 output: `Could not extract ${input.asarPath} for the bundle self-containment check: ${String(cause)}`,
2241 }),
2242 });
2243 yield* copyDirectoryPreservingSymlinks(extractedApp, probeApp);
2244
2245 // Ancestor node_modules could satisfy missing packaged dependencies and hide a broken stage.
2246 for (const candidate of ancestorNodeModulesPaths(probeApp, path.sep)) {
2247 if (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
2248 return yield* new BundleNotSelfContainedError({
2249 exitCode: -1,
2250 output: `Refusing to report success: ${candidate} is visible from the probe directory, so bare imports could resolve outside the packaged tree. Remove or rename it, or point TMPDIR somewhere without one.`,
2251 });
2252 }
2253 }
2254
2255 const entryPoint = path.join(probeApp, "apps/server/dist/bin.mjs");
2256 if (!(yield* fs.exists(entryPoint).pipe(Effect.orElseSucceed(() => false)))) {
2257 return yield* new BundleNotSelfContainedError({
2258 exitCode: -1,
2259 output: `Expected the server entry at ${entryPoint}.`,
2260 });
2261 }
2262
2263 yield* runCommand(
2264 ChildProcess.make(
2265 process.execPath,
2266 // Clearing NODE_PATH leaves CommonJS global fallbacks; disable them so host packages cannot satisfy missing dependencies.
2267 ["--no-global-search-paths", entryPoint, "--version"],
2268 {
2269 cwd: probeApp,
2270 stdout: "pipe",
2271 stderr: "pipe",
2272 env: { ...process.env, NODE_PATH: "" },
2273 },
2274 ),
2275 {
2276 label: "server sidecar self-containment check (node bin.mjs --version)",
2277 verbose: input.verbose,
2278 },
2279 ).pipe(
2280 Effect.timeout(BUNDLE_SELF_CHECK_TIMEOUT),
2281 Effect.catchTags({
2282 TimeoutError: () =>
2283 Effect.fail(
2284 new BundleNotSelfContainedError({
2285 exitCode: -1,
2286 output: `The packaged bundle did not print its version within ${Duration.toSeconds(BUNDLE_SELF_CHECK_TIMEOUT)}s; it is hanging rather than failing to resolve.`,
2287 }),
2288 ),
2289 BuildCommandFailedError: (error) =>
2290 Effect.fail(
2291 new BundleNotSelfContainedError({
2292 exitCode: error.exitCode,
2293 output: `${error.stderrTail ?? ""}${error.stdoutTail ?? ""}`.trim(),
2294 }),
2295 ),
2296 }),
2297 );
2298 },
2299 );
2300
2301 export const stageLinuxCaptureHelper = Effect.fn("stageLinuxCaptureHelper")(function* (input: {
2302 readonly backend: "kde" | "hyprland";
2303 readonly repoRoot: string;
2304 readonly stageResourcesDir: string;
2305 readonly arch: typeof BuildArch.Type;
2306 readonly verbose: boolean;
2307 }) {
2308 const fs = yield* FileSystem.FileSystem;
2309 const path = yield* Path.Path;
2310 const [rustTarget] = resolveResourceMonitorRustTargets("linux", input.arch);
2311 // CI skips Rust on helper-cache hits; allow reuse without rebuilding.
2312 const reuseHelpers = yield* Config.Boolean("T3CODE_DESKTOP_REUSE_LINUX_CAPTURE_HELPERS").pipe(
2313 Config.withDefault(false),
2314 );
2315 const binaryPath = path.join(
2316 input.repoRoot,
2317 `native/${input.backend}-snap-shot/target`,
2318 rustTarget!,
2319 `release/t3-${input.backend}-snap-shot`,
2320 );
2321 if (!reuseHelpers) {
2322 const spawnCommand = yield* resolveSpawnCommand("cargo", [
2323 "build",
2324 "--locked",
2325 "--release",
2326 "--manifest-path",
2327 path.join(input.repoRoot, `native/${input.backend}-snap-shot/Cargo.toml`),
2328 "--target",
2329 rustTarget!,
2330 ]);
2331 yield* runCommand(
2332 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
2333 cwd: input.repoRoot,
2334 shell: spawnCommand.shell,
2335 }),
2336 {
2337 label: `cargo build ${input.backend} capture helper (${rustTarget})`,
2338 verbose: input.verbose,
2339 },
2340 );
2341 } else if (!(yield* fs.exists(binaryPath))) {
2342 return yield* new ResourceMonitorBuildOutputMissingError({
2343 binaryPath,
2344 rustTarget: rustTarget!,
2345 platform: "linux",
2346 arch: input.arch,
2347 });
2348 }
2349 const destination = path.join(input.stageResourcesDir, `${input.backend}-capture`);
2350 yield* fs.makeDirectory(destination, { recursive: true });
2351 const executable = path.join(destination, `t3-${input.backend}-snap-shot`);
2352 yield* fs.copyFile(binaryPath, executable);
2353 yield* fs.chmod(executable, 0o755);
2354 if (input.backend === "hyprland") {
2355 // The official protocol XML includes the BSD notices required with binary distribution.
2356 yield* fs.copy(
2357 path.join(input.repoRoot, "native/hyprland-snap-shot/protocols"),
2358 path.join(destination, "protocols"),
2359 );
2360 }
2361 });
2362
2363 export const stageResourceMonitor = Effect.fn("stageResourceMonitor")(function* (input: {
2364 readonly repoRoot: string;
2365 readonly stageResourcesDir: string;
2366 readonly platform: typeof BuildPlatform.Type;
2367 readonly arch: typeof BuildArch.Type;
2368 readonly verbose: boolean;
2369 }) {
2370 const fs = yield* FileSystem.FileSystem;
2371 const path = yield* Path.Path;
2372 const manifestPath = path.join(input.repoRoot, "native/resource-monitor/Cargo.toml");
2373 const executableName = resourceMonitorExecutableName(input.platform);
2374 const rustTargets = resolveResourceMonitorRustTargets(input.platform, input.arch);
2375 const reuseResourceMonitor = yield* Config.Boolean("T3CODE_DESKTOP_REUSE_RESOURCE_MONITOR").pipe(
2376 Config.withDefault(false),
2377 );
2378 const builtBinaries: string[] = [];
2379
2380 for (const rustTarget of rustTargets) {
2381 if (!reuseResourceMonitor) {
2382 const spawnCommand = yield* resolveSpawnCommand("cargo", [
2383 "build",
2384 "--locked",
2385 "--release",
2386 "--manifest-path",
2387 manifestPath,
2388 "--target",
2389 rustTarget,
2390 ]);
2391 yield* runCommand(
2392 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
2393 cwd: input.repoRoot,
2394 shell: spawnCommand.shell,
2395 }),
2396 {
2397 label: `cargo build resource monitor (${rustTarget})`,
2398 verbose: input.verbose,
2399 },
2400 );
2401 }
2402
2403 const binaryPath = path.join(
2404 input.repoRoot,
2405 "native/resource-monitor/target",
2406 rustTarget,
2407 "release",
2408 executableName,
2409 );
2410 if (!(yield* fs.exists(binaryPath))) {
2411 return yield* new ResourceMonitorBuildOutputMissingError({
2412 binaryPath,
2413 rustTarget,
2414 platform: input.platform,
2415 arch: input.arch,
2416 });
2417 }
2418 if (reuseResourceMonitor) {
2419 yield* Effect.log(`[desktop-artifact] Reusing cached resource monitor (${rustTarget}).`);
2420 }
2421 builtBinaries.push(binaryPath);
2422 }
2423
2424 const destinationDirectory = path.join(input.stageResourcesDir, "resource-monitor");
2425 const destinationPath = path.join(destinationDirectory, executableName);
2426 yield* fs.remove(destinationDirectory, { recursive: true, force: true }).pipe(Effect.ignore);
2427 yield* fs.makeDirectory(destinationDirectory, { recursive: true });
2428
2429 if (builtBinaries.length === 1) {
2430 yield* fs.copyFile(builtBinaries[0]!, destinationPath);
2431 } else {
2432 yield* runCommand(
2433 ChildProcess.make("lipo", ["-create", ...builtBinaries, "-output", destinationPath]),
2434 {
2435 label: "lipo resource monitor universal binary",
2436 verbose: input.verbose,
2437 },
2438 );
2439 }
2440
2441 if (input.platform !== "win") {
2442 yield* fs.chmod(destinationPath, 0o755);
2443 }
2444 });
2445
2446 export const stageBrowserSecret = Effect.fn("stageBrowserSecret")(function* (input: {
2447 readonly repoRoot: string;
2448 readonly stageResourcesDir: string;
2449 readonly platform: typeof BuildPlatform.Type;
2450 readonly arch: typeof BuildArch.Type;
2451 readonly verbose: boolean;
2452 }) {
2453 if (input.platform !== "linux") return;
2454 // The helper links host libsecret and only builds on Linux; reject cross-host packaging that would silently omit it.
2455 const hostPlatform = yield* HostProcess.Platform;
2456 if (hostPlatform !== "linux") {
2457 return yield* new LinuxBrowserSecretHostError({ hostPlatform });
2458 }
2459 const path = yield* Path.Path;
2460 yield* runCommand(
2461 ChildProcess.make(
2462 "node",
2463 [
2464 path.join(input.repoRoot, "apps/desktop/scripts/build-browser-secret.mjs"),
2465 "--arch",
2466 input.arch === "arm64" ? "arm64" : "x64",
2467 "--output",
2468 path.join(input.stageResourcesDir, "browser-secret", "t3-browser-secret"),
2469 ],
2470 { cwd: input.repoRoot },
2471 ),
2472 { label: "build Linux browser secret helper", verbose: input.verbose },
2473 );
2474 });
2475
2476 export const stageAppleSpeech = Effect.fn("stageAppleSpeech")(function* (input: {
2477 readonly repoRoot: string;
2478 readonly stageResourcesDir: string;
2479 readonly platform: typeof BuildPlatform.Type;
2480 readonly arch: typeof BuildArch.Type;
2481 readonly verbose: boolean;
2482 }) {
2483 if (input.platform !== "mac") return;
2484 const path = yield* Path.Path;
2485 yield* runCommand(
2486 ChildProcess.make(
2487 "node",
2488 [
2489 path.join(input.repoRoot, "apps/desktop/scripts/build-apple-speech.mjs"),
2490 "--arch",
2491 input.arch,
2492 "--output",
2493 path.join(input.stageResourcesDir, "apple-speech", "t3-apple-speech"),
2494 ],
2495 { cwd: input.repoRoot },
2496 ),
2497 { label: "build macOS Apple Speech helper", verbose: input.verbose },
2498 );
2499 });
2500
2501 const generateMacIconSet = Effect.fn("build-desktop-artifact.generateMacIconSet")(function* (
2502 sourcePng: string,
2503 targetIcns: string,
2504 tmpRoot: string,
2505 path: Path.Path,
2506 verbose: boolean,
2507 ) {
2508 const fs = yield* FileSystem.FileSystem;
2509 const iconsetDir = path.join(tmpRoot, "icon.iconset");
2510 yield* fs.makeDirectory(iconsetDir, { recursive: true });
2511
2512 const iconSizes = [16, 32, 128, 256, 512] as const;
2513 for (const size of iconSizes) {
2514 yield* runCommand(
2515 ChildProcess.make(
2516 {},
2517 )`sips -z ${size} ${size} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}.png`)}`,
2518 { label: `sips icon ${size}x${size}`, verbose },
2519 );
2520
2521 const retinaSize = size * 2;
2522 yield* runCommand(
2523 ChildProcess.make(
2524 {},
2525 )`sips -z ${retinaSize} ${retinaSize} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}@2x.png`)}`,
2526 { label: `sips icon ${size}x${size}@2x`, verbose },
2527 );
2528 }
2529
2530 yield* runCommand(ChildProcess.make({})`iconutil -c icns ${iconsetDir} -o ${targetIcns}`, {
2531 label: "iconutil icns",
2532 verbose,
2533 });
2534 });
2535
2536 const stageMacIcons = Effect.fn("build-desktop-artifact.stageMacIcons")(function* (
2537 stageResourcesDir: string,
2538 sourcePng: string,
2539 verbose: boolean,
2540 ) {
2541 const fs = yield* FileSystem.FileSystem;
2542 const path = yield* Path.Path;
2543 if (!(yield* fs.exists(sourcePng))) {
2544 return yield* new DesktopIconSourceMissingError({
2545 platform: "mac",
2546 sourcePath: sourcePng,
2547 });
2548 }
2549
2550 const tmpRoot = yield* fs.makeTempDirectoryScoped({
2551 prefix: "t3code-icon-build-",
2552 });
2553
2554 const iconPngPath = path.join(stageResourcesDir, "icon.png");
2555 const iconIcnsPath = path.join(stageResourcesDir, "icon.icns");
2556
2557 yield* runCommand(ChildProcess.make({})`sips -z 512 512 ${sourcePng} --out ${iconPngPath}`, {
2558 label: "sips mac icon",
2559 verbose,
2560 });
2561
2562 yield* generateMacIconSet(sourcePng, iconIcnsPath, tmpRoot, path, verbose);
2563 });
2564
2565 export const stageDesktopDmgBackground = Effect.fn("stageDesktopDmgBackground")(function* (
2566 stageResourcesDir: string,
2567 channel: "latest" | "nightly",
2568 verbose: boolean,
2569 ) {
2570 const fs = yield* FileSystem.FileSystem;
2571 const path = yield* Path.Path;
2572 const sourcePath = path.join(stageResourcesDir, "dmg", `dmg-background-${channel}.svg`);
2573 if (!(yield* fs.exists(sourcePath))) {
2574 return yield* new DesktopDmgBackgroundSourceMissingError({ channel, sourcePath });
2575 }
2576
2577 for (const output of [
2578 { suffix: "", width: 640, height: 432 },
2579 { suffix: "@2x", width: 1280, height: 864 },
2580 ] as const) {
2581 const targetPath = path.join(
2582 stageResourcesDir,
2583 "dmg",
2584 `dmg-background-${channel}${output.suffix}.png`,
2585 );
2586 yield* runCommand(
2587 ChildProcess.make(
2588 {},
2589 )`sips -s format png -z ${output.height} ${output.width} ${sourcePath} --out ${targetPath}`,
2590 {
2591 label: `sips ${channel} DMG background${output.suffix || "@1x"}`,
2592 verbose,
2593 },
2594 );
2595 }
2596 });
2597
2598 const stageLinuxIcons = Effect.fn("build-desktop-artifact.stageLinuxIcons")(function* (
2599 stageResourcesDir: string,
2600 sourcePng: string,
2601 verbose: boolean,
2602 ) {
2603 const fs = yield* FileSystem.FileSystem;
2604 const path = yield* Path.Path;
2605 if (!(yield* fs.exists(sourcePng))) {
2606 return yield* new DesktopIconSourceMissingError({
2607 platform: "linux",
2608 sourcePath: sourcePng,
2609 });
2610 }
2611
2612 const iconPath = path.join(stageResourcesDir, "icon.png");
2613 yield* fs.copyFile(sourcePng, iconPath);
2614
2615 const iconsDir = path.join(stageResourcesDir, "icons");
2616 yield* fs.makeDirectory(iconsDir, { recursive: true });
2617 for (const iconSize of LINUX_ICON_SIZES) {
2618 yield* stageLinuxIconSize(
2619 sourcePng,
2620 path.join(iconsDir, `${iconSize}x${iconSize}.png`),
2621 iconSize,
2622 verbose,
2623 );
2624 }
2625 });
2626
2627 export function stageLinuxIconSize(
2628 sourcePng: string,
2629 targetPng: string,
2630 iconSize: number,
2631 verbose: boolean,
2632 ) {
2633 const resize = (command: string) =>
2634 runCommand(
2635 ChildProcess.make(command, [sourcePng, "-resize", `${iconSize}x${iconSize}`, targetPng]),
2636 { label: `${command} linux icon ${iconSize}x${iconSize}`, verbose },
2637 );
2638
2639 return resize("magick").pipe(
2640 Effect.catch((primaryCause) =>
2641 resize("convert").pipe(
2642 Effect.mapError(
2643 (fallbackCause) =>
2644 new LinuxIconResizeError({
2645 operation: "resize",
2646 iconSize,
2647 primaryTool: "magick",
2648 fallbackTool: "convert",
2649 cause: new AggregateError(
2650 [primaryCause, fallbackCause],
2651 "Both Linux icon resize tool attempts failed.",
2652 { cause: primaryCause },
2653 ),
2654 }),
2655 ),
2656 ),
2657 ),
2658 );
2659 }
2660
2661 const stageWindowsIcons = Effect.fn("build-desktop-artifact.stageWindowsIcons")(function* (
2662 stageResourcesDir: string,
2663 sourceIco: string,
2664 ) {
2665 const fs = yield* FileSystem.FileSystem;
2666 const path = yield* Path.Path;
2667 if (!(yield* fs.exists(sourceIco))) {
2668 return yield* new DesktopIconSourceMissingError({
2669 platform: "win",
2670 sourcePath: sourceIco,
2671 });
2672 }
2673
2674 const iconPath = path.join(stageResourcesDir, "icon.ico");
2675 yield* fs.copyFile(sourceIco, iconPath);
2676 });
2677
2678 const validateBundledClientAssets = Effect.fn("build-desktop-artifact.validateBundledClientAssets")(
2679 function* (clientDir: string) {
2680 const fs = yield* FileSystem.FileSystem;
2681 const path = yield* Path.Path;
2682 const indexPath = path.join(clientDir, "index.html");
2683 const indexHtml = yield* fs.readFileString(indexPath);
2684 const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)]
2685 .map((match) => match[1])
2686 .filter((value): value is string => value !== undefined);
2687 const missing: string[] = [];
2688
2689 for (const ref of refs) {
2690 const normalizedRef = ref.split("#")[0]?.split("?")[0] ?? "";
2691 if (!normalizedRef) continue;
2692 if (normalizedRef.startsWith("http://") || normalizedRef.startsWith("https://")) continue;
2693 if (normalizedRef.startsWith("data:") || normalizedRef.startsWith("mailto:")) continue;
2694
2695 const ext = path.extname(normalizedRef);
2696 if (!ext) continue;
2697
2698 const relativePath = normalizedRef.replace(/^\/+/, "");
2699 const assetPath = path.join(clientDir, relativePath);
2700 if (!(yield* fs.exists(assetPath))) {
2701 missing.push(normalizedRef);
2702 }
2703 }
2704
2705 if (missing.length > 0) {
2706 return yield* new BundledClientAssetsMissingError({
2707 indexPath,
2708 missingFiles: missing,
2709 });
2710 }
2711 },
2712 );
2713
2714 export function resolveDesktopRuntimeDependencies(
2715 dependencies: Record<string, string> | undefined,
2716 catalog: Record<string, string>,
2717 ): Record<string, string> {
2718 if (!dependencies || Object.keys(dependencies).length === 0) {
2719 return {};
2720 }
2721
2722 return resolveCatalogDependencies(
2723 selectDesktopRuntimeExternalDependencies(dependencies),
2724 catalog,
2725 "apps/desktop",
2726 );
2727 }
2728
2729 export const resolveGitHubPublishConfig = Effect.fn("resolveGitHubPublishConfig")(function* (
2730 updateChannel: "latest" | "nightly",
2731 ) {
2732 const env = yield* Config.all({
2733 updateRepository: Config.String("T3CODE_DESKTOP_UPDATE_REPOSITORY").pipe(Config.option),
2734 githubRepository: Config.String("GITHUB_REPOSITORY").pipe(Config.option),
2735 });
2736 const rawRepo = (
2737 Option.getOrUndefined(env.updateRepository)?.trim() ||
2738 Option.getOrUndefined(env.githubRepository)?.trim() ||
2739 ""
2740 ).trim();
2741 if (!rawRepo) return undefined;
2742
2743 const [owner, repo, ...rest] = rawRepo.split("/");
2744 if (!owner || !repo || rest.length > 0) return undefined;
2745
2746 return {
2747 provider: "github",
2748 owner,
2749 repo,
2750 releaseType: updateChannel === "nightly" ? "prerelease" : "release",
2751 ...(updateChannel === "nightly" ? { channel: "nightly" as const } : {}),
2752 };
2753 });
2754
2755 export function resolveDesktopUpdateChannel(version: string): "latest" | "nightly" {
2756 return /-nightly\.\d{8}\.\d+$/.test(version) ? "nightly" : "latest";
2757 }
2758
2759 export function isDesktopPreviewVersion(version: string): boolean {
2760 return /-pr\./.test(version) || /-preview\.\d{8}\.\d+$/.test(version);
2761 }
2762
2763 export function resolveDesktopWebAssetBrand(version: string): WebAssetBrand {
2764 return resolveWebAssetBrandForChannel(resolveDesktopUpdateChannel(version));
2765 }
2766
2767 export function resolveDesktopBuildIconAssets(version: string): DesktopBuildIconAssets {
2768 if (resolveDesktopUpdateChannel(version) === "nightly") {
2769 return {
2770 macIconPng: BRAND_ASSET_PATHS.nightlyMacIconPng,
2771 linuxIconPng: BRAND_ASSET_PATHS.nightlyLinuxIconPng,
2772 windowsIconIco: BRAND_ASSET_PATHS.nightlyWindowsIconIco,
2773 };
2774 }
2775
2776 return {
2777 macIconPng: BRAND_ASSET_PATHS.productionMacIconPng,
2778 linuxIconPng: BRAND_ASSET_PATHS.productionLinuxIconPng,
2779 windowsIconIco: BRAND_ASSET_PATHS.productionWindowsIconIco,
2780 };
2781 }
2782
2783 export function resolveMockUpdateServerUrl(mockUpdateServerPort: number | undefined): string {
2784 return `http://localhost:${mockUpdateServerPort ?? 3000}`;
2785 }
2786
2787 // electron-builder reads user-agent syntax (pnpm/version), not packageManager syntax (pnpm@version).
2788 export function resolvePackageManagerUserAgent(packageManager: string): string {
2789 const trimmed = packageManager.trim();
2790 const versionSeparator = trimmed.lastIndexOf("@");
2791 if (versionSeparator <= 0 || versionSeparator === trimmed.length - 1) {
2792 return trimmed;
2793 }
2794
2795 return `${trimmed.slice(0, versionSeparator)}/${trimmed.slice(versionSeparator + 1)}`;
2796 }
2797
2798 export function resolveDesktopProductName(version: string): string {
2799 return resolveDesktopUpdateChannel(version) === "nightly"
2800 ? "T3 Code (Nightly)"
2801 : (desktopPackageJson.productName ?? "T3 Code");
2802 }
2803
2804 export const createBuildConfig = Effect.fn("createBuildConfig")(function* (
2805 platform: typeof BuildPlatform.Type,
2806 target: string,
2807 version: string,
2808 signed: boolean,
2809 mockUpdates: boolean,
2810 mockUpdateServerPort: number | undefined,
2811 macPasskeySigning:
2812 | {
2813 readonly entitlementsPath: string;
2814 readonly provisioningProfilePath: string;
2815 }
2816 | undefined,
2817 wslRuntimeBundled = false,
2818 arch?: typeof BuildArch.Type,
2819 ) {
2820 const buildConfig: Record<string, unknown> = {
2821 afterPack: (yield* Path.Path).join(yield* RepoRoot, "scripts/prepare-server-compile-cache.cjs"),
2822 appId: DESKTOP_APP_ID,
2823 productName: resolveDesktopProductName(version),
2824 artifactName: "T3-Code-${version}-${arch}.${ext}",
2825 electronLanguages: [...DESKTOP_ELECTRON_LANGUAGES],
2826 files: [
2827 ...DESKTOP_FILE_EXCLUSIONS,
2828 ...(platform === "mac"
2829 ? resolveMacFileExclusions(arch)
2830 : platform === "linux"
2831 ? LINUX_FILE_EXCLUSIONS
2832 : []),
2833 ],
2834 directories: {
2835 buildResources: "apps/desktop/resources",
2836 },
2837 // Disable smart unpack so native packages' JS/metadata stay archived and avoid slowing NSIS with loose files.
2838 ...(platform === "win"
2839 ? { asar: { smartUnpack: false }, asarUnpack: [WINDOWS_NATIVE_ASAR_UNPACK_GLOB] }
2840 : { asarUnpack: ["**/node_modules/@transcribe-cpp/**/*.{dylib,so,so.*}"] }),
2841 extraResources: [
2842 ...DESKTOP_EXTRA_RESOURCES,
2843 ...(platform === "linux" ? LINUX_CAPTURE_EXTRA_RESOURCES : []),
2844 ...(platform === "linux" ? LINUX_BROWSER_SECRET_EXTRA_RESOURCES : []),
2845 ...(platform === "mac" ? MAC_APPLE_SPEECH_EXTRA_RESOURCES : []),
2846 ...(platform === "win" ? WINDOWS_SERVER_EXTRA_RESOURCES : []),
2847 ...(platform === "win" && wslRuntimeBundled ? WSL_RUNTIME_EXTRA_RESOURCES : []),
2848 ],
2849 };
2850 const updateChannel = resolveDesktopUpdateChannel(version);
2851 // Missing publish config infers a GitHub feed from tokens; staging has no repository, so manifest generation would crash.
2852 buildConfig.publish = null;
2853 if (!isDesktopPreviewVersion(version)) {
2854 const publishConfig = yield* resolveGitHubPublishConfig(updateChannel);
2855 if (publishConfig) {
2856 buildConfig.publish = [publishConfig];
2857 } else if (mockUpdates) {
2858 buildConfig.publish = [
2859 {
2860 provider: "generic",
2861 url: resolveMockUpdateServerUrl(mockUpdateServerPort),
2862 },
2863 ];
2864 }
2865 }
2866
2867 if (platform === "mac") {
2868 const path = yield* Path.Path;
2869 const repoRoot = yield* RepoRoot;
2870 buildConfig.mac = {
2871 target: target === "dmg" ? [target, "zip"] : [target],
2872 icon: "icon.icns",
2873 category: "public.app-category.developer-tools",
2874 extendInfo: {
2875 // macOS 26 offers Messages/Mail codes in every text field unless opted out.
2876 NSAutoFillRequiresTextContentTypeForOneTimeCodeOnMac: true,
2877 NSLocalNetworkUsageDescription:
2878 "T3 Code connects to devices on your local network for remote environments and commands run by terminals and coding agents.",
2879 NSCalendarsUsageDescription:
2880 "Commands you run in T3 Code may need access to your calendars.",
2881 NSCalendarsFullAccessUsageDescription:
2882 "Commands you run in T3 Code may need to read and write your calendar events.",
2883 NSCalendarsWriteOnlyAccessUsageDescription:
2884 "Commands you run in T3 Code may need to add events to your calendars.",
2885 NSScreenCaptureUsageDescription:
2886 "T3 Code captures the active window when you use the window capture shortcut.",
2887 NSCameraUsageDescription:
2888 "T3 Code lets commands run by terminals and coding agents use the camera.",
2889 NSMicrophoneUsageDescription:
2890 "T3 Code lets commands run by terminals and coding agents use the microphone.",
2891 NSSpeechRecognitionUsageDescription:
2892 "T3 Code transcribes your dictation on this Mac when you choose Apple Speech.",
2893 // macOS lists an app under Default web browser only when it opens web
2894 // pages as documents as well as http and https links (see protocols).
2895 CFBundleDocumentTypes: [
2896 {
2897 CFBundleTypeName: "Web page",
2898 CFBundleTypeRole: "Viewer",
2899 LSHandlerRank: "Alternate",
2900 LSItemContentTypes: ["public.html", "public.xhtml"],
2901 },
2902 ],
2903 },
2904 protocols: [
2905 {
2906 name: "T3 Code",
2907 schemes: ["t3code", "t3code-dev"],
2908 },
2909 {
2910 name: "Web site URL",
2911 schemes: ["http", "https"],
2912 role: "Viewer",
2913 },
2914 ],
2915 ...(signed ? { sign: path.join(repoRoot, "scripts/sign-macos.ts") } : {}),
2916 ...(macPasskeySigning
2917 ? {
2918 entitlements: macPasskeySigning.entitlementsPath,
2919 provisioningProfile: macPasskeySigning.provisioningProfilePath,
2920 }
2921 : {}),
2922 };
2923 }
2924
2925 if (platform === "mac" && target === "dmg") {
2926 buildConfig.dmg = {
2927 // Finder caches DMG backgrounds by volume name; give each installer its own.
2928 title: `${resolveDesktopProductName(version)} ${version} Installer`,
2929 background: `dmg/dmg-background-${updateChannel}.png`,
2930 window: {
2931 width: 640,
2932 // DMG bounds include Finder's 32px title bar; keep that artwork strip clear.
2933 height: 432,
2934 },
2935 contents: [
2936 { x: 166, y: 214, type: "file" },
2937 { x: 474, y: 214, type: "link", path: "/Applications" },
2938 ],
2939 iconSize: 120,
2940 iconTextSize: 12,
2941 };
2942 }
2943
2944 if (platform === "linux") {
2945 // Pin the static AppImage runtime so hosts with only FUSE 3 do not need libfuse2.
2946 buildConfig.toolsets = { appimage: "1.0.3" };
2947 const path = yield* Path.Path;
2948 const repoRoot = yield* RepoRoot;
2949 buildConfig.afterPack = path.join(repoRoot, "scripts/linux-after-pack.ts");
2950 buildConfig.linux = {
2951 target: target === "AppImage" ? [target, "deb"] : [target],
2952 executableName: "t3code",
2953 icon: "icons",
2954 category: "Development",
2955 synopsis: "Desktop GUI for coding agents",
2956 maintainer: "T3 Tools <hello@t3.codes>",
2957 protocols: [
2958 {
2959 name: "T3 Code",
2960 schemes: ["t3code", "t3code-dev"],
2961 },
2962 ],
2963 desktop: {
2964 entry: {
2965 // Match Electron's WM_CLASS from setDesktopName so docks use this launcher.
2966 StartupWMClass: "com.t3tools.T3Code",
2967 },
2968 },
2969 };
2970 // electron-updater replaces an installed AppImage in place only when its name has no x.y.z version.
2971 if (buildConfig.publish) {
2972 buildConfig.appImage = {
2973 artifactName:
2974 updateChannel === "nightly" ? "T3-Code-Nightly-${arch}.${ext}" : "T3-Code-${arch}.${ext}",
2975 };
2976 }
2977 buildConfig.deb = {
2978 // FPM runs outside the staged app directory, so source paths must be absolute.
2979 fpm: [
2980 `${path.join(repoRoot, "apps/desktop/resources/linux/com.t3tools.t3code.metainfo.xml")}=/usr/share/metainfo/com.t3tools.t3code.metainfo.xml`,
2981 `${path.join(repoRoot, "LICENSE")}=/usr/share/doc/t3code/copyright`,
2982 ],
2983 // Debian 13 and Ubuntu 24.04 use 64-bit-time names; retain old-name fallbacks.
2984 depends: [
2985 "libasound2t64 | libasound2",
2986 "libatspi2.0-0t64 | libatspi2.0-0",
2987 "libgbm1",
2988 "libgtk-3-0t64 | libgtk-3-0",
2989 "libnotify4",
2990 "libnss3",
2991 "libsecret-1-0",
2992 "libuuid1",
2993 "libxss1",
2994 "libxtst6",
2995 "xdg-utils",
2996 ],
2997 };
2998 }
2999
3000 if (platform === "win") {
3001 buildConfig.npmRebuild = false;
3002 buildConfig.nsis = {
3003 differentialPackage: true,
3004 include: "apps/desktop/resources/installer.nsh",
3005 };
3006 const winConfig: Record<string, unknown> = {
3007 target: [target],
3008 icon: "icon.ico",
3009 // Smart App Control validates unpacked native libraries independently; sign them too.
3010 signExts: [".node", ".dll"],
3011 // Resource editing sets product icons even when code signing is disabled.
3012 signAndEditExecutable: true,
3013 };
3014 if (signed && (yield* HostProcess.Platform) === "win32") {
3015 winConfig.azureSignOptions = yield* AzureTrustedSigningOptionsConfig;
3016 } else if (signed) {
3017 const path = yield* Path.Path;
3018 const { publisherName } = yield* AzureTrustedSigningOptionsConfig;
3019 winConfig.signtoolOptions = {
3020 sign: yield* path.fromFileUrl(new URL("./lib/windows-jsign.ts", import.meta.url)),
3021 signingHashAlgorithms: ["sha256"],
3022 publisherName: [publisherName],
3023 };
3024 }
3025 buildConfig.win = winConfig;
3026 }
3027
3028 return buildConfig;
3029 });
3030
3031 const assertPlatformBuildResources = Effect.fn("assertPlatformBuildResources")(function* (
3032 platform: typeof BuildPlatform.Type,
3033 stageResourcesDir: string,
3034 iconAssets: DesktopBuildIconAssets,
3035 verbose: boolean,
3036 ) {
3037 if (platform === "mac") {
3038 yield* stageMacIcons(stageResourcesDir, iconAssets.macIconPng, verbose);
3039 return;
3040 }
3041
3042 if (platform === "linux") {
3043 yield* stageLinuxIcons(stageResourcesDir, iconAssets.linuxIconPng, verbose);
3044 return;
3045 }
3046
3047 if (platform === "win") {
3048 yield* stageWindowsIcons(stageResourcesDir, iconAssets.windowsIconIco);
3049 }
3050 });
3051
3052 // The digest verifies extraction and names the cache; hash the exact archive bytes that ship.
3053 export const stageWslRuntimeArchive = Effect.fn("stageWslRuntimeArchive")(function* (input: {
3054 readonly sourceArchivePath: string;
3055 readonly archivePath: string;
3056 readonly hashPath: string;
3057 }) {
3058 const fs = yield* FileSystem.FileSystem;
3059 const path = yield* Path.Path;
3060 const sourceExists = yield* fs
3061 .exists(input.sourceArchivePath)
3062 .pipe(Effect.orElseSucceed(() => false));
3063 if (!sourceExists) {
3064 return yield* new WslRuntimeArchiveMissingError({ archivePath: input.sourceArchivePath });
3065 }
3066 yield* fs.makeDirectory(path.dirname(input.archivePath), { recursive: true });
3067 yield* fs.copyFile(input.sourceArchivePath, input.archivePath);
3068 const hash = NodeCrypto.createHash("sha256");
3069 yield* fs
3070 .stream(input.archivePath)
3071 .pipe(Stream.runForEach((chunk) => Effect.sync(() => hash.update(chunk))));
3072 const digest = hash.digest("hex");
3073 yield* fs.writeFileString(input.hashPath, `${digest}\n`);
3074 yield* Effect.log(
3075 `[desktop-artifact] Staged WSL runtime archive at ${input.archivePath} (${digest}).`,
3076 );
3077 });
3078
3079 // Match cliArchiveStem without its circular import. WSL uses the Windows host's architecture.
3080 export const wslRuntimeArchiveStem = (version: string, arch: typeof BuildArch.Type): string =>
3081 `t3-${version}-linux-${arch}`;
3082
3083 export const parseWslRuntimeArchiveMembers = (listing: string): ReadonlyArray<string> =>
3084 listing
3085 .split(/\r?\n/)
3086 .map((member) => member.replace(/^\.\//, "").replace(/\/$/, ""))
3087 .filter((member) => member.length > 0);
3088
3089 export const packWindowsServerAsar = Effect.fn("packWindowsServerAsar")(function* (input: {
3090 readonly sourceDir: string;
3091 readonly asarPath: string;
3092 readonly arch: typeof BuildArch.Type;
3093 }) {
3094 const fs = yield* FileSystem.FileSystem;
3095 const path = yield* Path.Path;
3096 // Unpack/sign only Windows PE addons; packages also carry foreign prebuilds that Authenticode cannot sign.
3097 const unpackGlobs: string[] = [...WINDOWS_SERVER_ASAR_UNPACK_GLOBS];
3098 for (const entry of yield* fs.readDirectory(input.sourceDir, { recursive: true })) {
3099 if (!entry.endsWith(".node")) continue;
3100 const addonPath = path.join(input.sourceDir, entry);
3101 if ((yield* fs.stat(addonPath)).type !== "File") continue;
3102 const bytes = yield* fs.readFile(addonPath);
3103 if (bytes[0] !== 0x4d || bytes[1] !== 0x5a) continue;
3104 const posixPath = entry.split(path.sep).join("/");
3105 // Backslash escapes are path separators to minimatch on Windows.
3106 if (/[\\*?[\]{}(),]/.test(posixPath)) {
3107 return yield* new WindowsServerSidecarPackError({
3108 asarPath: input.asarPath,
3109 cause: new Error(`native addon path contains glob syntax: ${posixPath}`),
3110 });
3111 }
3112 unpackGlobs.push(`**/${posixPath}`);
3113 }
3114 yield* Effect.tryPromise({
3115 try: () =>
3116 createPackageWithOptions(input.sourceDir, input.asarPath, {
3117 dot: true,
3118 unpack: `{${unpackGlobs.join(",")}}`,
3119 // glob 13 (@electron/asar 4) resolves ignores against cwd; anchor them at the source.
3120 globOptions: {
3121 cwd: input.sourceDir,
3122 ignore: resolveWindowsServerAsarIgnoreGlobs(input.arch),
3123 },
3124 }),
3125 catch: (cause) => new WindowsServerSidecarPackError({ asarPath: input.asarPath, cause }),
3126 });
3127 const unpackedDirPath = `${input.asarPath}.unpacked`;
3128 if (!(yield* fs.exists(unpackedDirPath))) {
3129 return yield* new WindowsServerSidecarPackError({
3130 asarPath: input.asarPath,
3131 cause: new Error(`expected native binaries at ${unpackedDirPath}, but none were unpacked`),
3132 });
3133 }
3134 });
3135
3136 export const stageWindowsServerSidecar = Effect.fn("stageWindowsServerSidecar")(function* (input: {
3137 readonly stageRoot: string;
3138 readonly repoRoot: string;
3139 readonly serverDistDir: string;
3140 readonly arch: typeof BuildArch.Type;
3141 readonly appVersion: string;
3142 readonly runtimeExternalDependencies: Record<string, string>;
3143 readonly fffNodeVersion: string;
3144 readonly allowBuilds: Record<string, boolean>;
3145 readonly patchedDependencies: Record<string, string>;
3146 readonly overrides: Record<string, string>;
3147 readonly asarPath: string;
3148 readonly verbose: boolean;
3149 }) {
3150 const fs = yield* FileSystem.FileSystem;
3151 const path = yield* Path.Path;
3152
3153 const serverStageDir = path.join(input.stageRoot, "server");
3154 yield* fs.makeDirectory(path.join(serverStageDir, "apps/server"), { recursive: true });
3155 yield* fs.copy(input.serverDistDir, path.join(serverStageDir, "apps/server/dist"));
3156
3157 const sidecarDependencies = {
3158 ...input.runtimeExternalDependencies,
3159 ...resolveFffNativeDependencies("win", input.arch, input.fffNodeVersion),
3160 };
3161 const sidecarPatchedDependencies = createStagePatchedDependencies(
3162 input.patchedDependencies,
3163 sidecarDependencies,
3164 );
3165 const sidecarPackageJson = {
3166 name: "t3code-server",
3167 version: input.appVersion,
3168 private: true,
3169 packageManager: rootPackageJson.packageManager,
3170 dependencies: sidecarDependencies,
3171 };
3172 const sidecarPackageJsonString = yield* encodeJsonString(sidecarPackageJson);
3173 yield* fs.writeFileString(
3174 path.join(serverStageDir, "package.json"),
3175 `${sidecarPackageJsonString}\n`,
3176 );
3177 const sidecarWorkspaceConfig = {
3178 ...createStageWorkspaceConfig({
3179 platform: "win",
3180 arch: input.arch,
3181 allowBuilds: input.allowBuilds,
3182 patchedDependencies: sidecarPatchedDependencies,
3183 overrides: input.overrides,
3184 }),
3185 // server.asar cannot carry pnpm symlinks or junctions; install physical hoisted dependencies.
3186 nodeLinker: "hoisted" as const,
3187 };
3188 const sidecarWorkspaceConfigString = yield* encodeStageWorkspaceConfig(sidecarWorkspaceConfig);
3189 yield* fs.writeFileString(
3190 path.join(serverStageDir, "pnpm-workspace.yaml"),
3191 sidecarWorkspaceConfigString,
3192 );
3193 if (Object.keys(sidecarPatchedDependencies).length > 0) {
3194 yield* fs.copy(path.join(input.repoRoot, "patches"), path.join(serverStageDir, "patches"));
3195 }
3196
3197 yield* Effect.log("[desktop-artifact] Installing server sidecar runtime externals...");
3198 const installCommand = yield* resolveSpawnCommand("vp", [...STAGE_INSTALL_ARGS]);
3199 yield* runCommand(
3200 ChildProcess.make(installCommand.command, installCommand.args, {
3201 cwd: serverStageDir,
3202 shell: installCommand.shell,
3203 }),
3204 { label: "vp install --prod (server sidecar)", verbose: input.verbose },
3205 );
3206
3207 yield* Effect.log("[desktop-artifact] Packing server.asar...");
3208 yield* fs.makeDirectory(path.dirname(input.asarPath), { recursive: true });
3209 yield* packWindowsServerAsar({
3210 sourceDir: serverStageDir,
3211 asarPath: input.asarPath,
3212 arch: input.arch,
3213 });
3214 const packedStat = yield* fs.stat(input.asarPath);
3215 yield* Effect.log(
3216 `[desktop-artifact] Packed server.asar (${String(packedStat.size)} bytes) + unpacked natives.`,
3217 );
3218 });
3219
3220 function collectUnpackedAsarFiles(
3221 directory: DirectoryRecord,
3222 parentPath = "",
3223 output: string[] = [],
3224 ): readonly string[] {
3225 for (const [name, entry] of Object.entries(directory.files)) {
3226 const entryPath = parentPath.length === 0 ? name : `${parentPath}/${name}`;
3227 if ("files" in entry) {
3228 collectUnpackedAsarFiles(entry, entryPath, output);
3229 } else if (entry.unpacked) {
3230 output.push(entryPath);
3231 }
3232 }
3233 return output;
3234 }
3235
3236 const countPayloadFiles = Effect.fn("desktopArtifact.countPayloadFiles")(function* (root: string) {
3237 const fs = yield* FileSystem.FileSystem;
3238 const path = yield* Path.Path;
3239 const pendingDirectories = [root];
3240 let count = 0;
3241
3242 while (pendingDirectories.length > 0) {
3243 const directory = pendingDirectories.pop();
3244 if (directory === undefined) break;
3245 const entries = yield* fs.readDirectory(directory);
3246 for (const entry of entries) {
3247 const entryPath = path.join(directory, entry);
3248 const stat = yield* fs.stat(entryPath);
3249 if (stat.type === "Directory") {
3250 pendingDirectories.push(entryPath);
3251 } else if (stat.type === "File") {
3252 count += 1;
3253 }
3254 }
3255 }
3256
3257 return count;
3258 });
3259
3260 export const verifyWindowsPrimaryFffNativeLoad = Effect.fn(
3261 "desktopArtifact.verifyWindowsPrimaryFffNativeLoad",
3262 )(function* (input: {
3263 readonly packagedAppDir: string;
3264 readonly asarPath: string;
3265 readonly appExecutableName: string;
3266 readonly targetArch: typeof BuildArch.Type;
3267 readonly verbose: boolean;
3268 }) {
3269 const hostPlatform = yield* HostProcess.Platform;
3270 const hostArchitecture = yield* HostProcess.Architecture;
3271 const fs = yield* FileSystem.FileSystem;
3272 const path = yield* Path.Path;
3273 const executablePath = path.join(input.packagedAppDir, input.appExecutableName);
3274 const executableStat = yield* fs.stat(executablePath).pipe(Effect.orElseSucceed(() => null));
3275 if (executableStat?.type !== "File") {
3276 return yield* new WindowsPrimaryNativeProbeError({
3277 executablePath,
3278 exitCode: -1,
3279 output: "The unpacked application does not contain its expected primary executable.",
3280 });
3281 }
3282 if (hostPlatform !== "win32" || hostArchitecture !== input.targetArch) return;
3283
3284 const probeRoot = yield* fs.makeTempDirectoryScoped({
3285 prefix: "t3code-windows-primary-native-probe-",
3286 });
3287 const fffEntryPath = path.join(input.asarPath, "node_modules/@ff-labs/fff-node/dist/index.js");
3288 const probeEnv = { ...process.env };
3289 delete probeEnv.ELECTRON_NO_ASAR;
3290 delete probeEnv.NODE_OPTIONS;
3291
3292 yield* runCommand(
3293 ChildProcess.make(
3294 executablePath,
3295 [
3296 "--no-global-search-paths",
3297 "--input-type=module",
3298 "--eval",
3299 WINDOWS_PRIMARY_FFF_PROBE_SOURCE,
3300 fffEntryPath,
3301 probeRoot,
3302 ],
3303 {
3304 cwd: input.packagedAppDir,
3305 stdout: "pipe",
3306 stderr: "pipe",
3307 env: {
3308 ...probeEnv,
3309 ELECTRON_RUN_AS_NODE: "1",
3310 NODE_PATH: "",
3311 },
3312 },
3313 ),
3314 {
3315 label: "Windows primary fff native-load probe",
3316 verbose: input.verbose,
3317 },
3318 ).pipe(
3319 Effect.timeout(WINDOWS_PRIMARY_NATIVE_PROBE_TIMEOUT),
3320 Effect.catchTags({
3321 TimeoutError: () =>
3322 Effect.fail(
3323 new WindowsPrimaryNativeProbeError({
3324 executablePath,
3325 exitCode: -1,
3326 output: `The native-load probe did not finish within ${Duration.toSeconds(WINDOWS_PRIMARY_NATIVE_PROBE_TIMEOUT)}s.`,
3327 }),
3328 ),
3329 BuildCommandFailedError: (error) =>
3330 Effect.fail(
3331 new WindowsPrimaryNativeProbeError({
3332 executablePath,
3333 exitCode: error.exitCode,
3334 output: `${error.stderrTail ?? ""}${error.stdoutTail ?? ""}`.trim(),
3335 }),
3336 ),
3337 }),
3338 );
3339 });
3340
3341 /**
3342 * The fff probe needs a host of the target's platform and architecture; the
3343 * bundle self-check needs a Windows host. A cross build defers both to
3344 * scripts/verify-windows-desktop-artifact.ts.
3345 */
3346 export const verifyWindowsPackagedRuntime = Effect.fn(
3347 "desktopArtifact.verifyWindowsPackagedRuntime",
3348 )(function* (input: {
3349 readonly packagedAppDir: string;
3350 readonly appExecutableName: string;
3351 readonly targetArch: typeof BuildArch.Type;
3352 readonly verbose: boolean;
3353 }) {
3354 const path = yield* Path.Path;
3355 const asarPath = path.join(input.packagedAppDir, "resources", WINDOWS_SERVER_ASAR_RESOURCE);
3356 yield* verifyWindowsPrimaryFffNativeLoad({ ...input, asarPath });
3357 const hostPlatform = yield* HostProcess.Platform;
3358 if (hostPlatform !== "win32") {
3359 yield* Effect.log(
3360 `[desktop-artifact] Skipped the bundle self-check on a ${hostPlatform} host.`,
3361 );
3362 return;
3363 }
3364 yield* verifyPackagedBundleIsSelfContained({ asarPath, verbose: input.verbose });
3365 });
3366
3367 export const validateWindowsPackagedPayload = Effect.fn(
3368 "desktopArtifact.validateWindowsPackagedPayload",
3369 )(function* (input: {
3370 readonly stageDistDir: string;
3371 readonly appExecutableName: string;
3372 readonly targetArch: typeof BuildArch.Type;
3373 readonly appVersion: string;
3374 readonly expectWslRuntime?: boolean;
3375 readonly fileLimit?: number;
3376 readonly verbose?: boolean;
3377 }) {
3378 const fs = yield* FileSystem.FileSystem;
3379 const path = yield* Path.Path;
3380 const fileLimit = input.fileLimit ?? WINDOWS_PACKAGED_PAYLOAD_FILE_LIMIT;
3381 const isFile = (filePath: string) =>
3382 fs.stat(filePath).pipe(
3383 Effect.map((stat) => stat.type === "File"),
3384 Effect.orElseSucceed(() => false),
3385 );
3386 const stageEntries = yield* fs.readDirectory(input.stageDistDir);
3387 let packagedAppDir: string | undefined;
3388
3389 for (const entry of stageEntries) {
3390 if (!entry.endsWith("-unpacked")) continue;
3391 const candidate = path.join(input.stageDistDir, entry);
3392 const stat = yield* fs.stat(candidate).pipe(Effect.orElseSucceed(() => null));
3393 if (stat?.type === "Directory") {
3394 packagedAppDir = candidate;
3395 break;
3396 }
3397 }
3398
3399 if (packagedAppDir === undefined) {
3400 return yield* new WindowsPackagedPayloadValidationError({
3401 reason: "packaged-app-missing",
3402 packagedAppDir: path.join(input.stageDistDir, "win-unpacked"),
3403 });
3404 }
3405
3406 const resourcesDir = path.join(packagedAppDir, "resources");
3407 const asarPath = path.join(resourcesDir, WINDOWS_SERVER_ASAR_RESOURCE);
3408 if (!(yield* fs.exists(asarPath).pipe(Effect.orElseSucceed(() => false)))) {
3409 return yield* new WindowsPackagedPayloadValidationError({
3410 reason: "sidecar-missing",
3411 packagedAppDir,
3412 missingFiles: [WINDOWS_SERVER_ASAR_RESOURCE],
3413 });
3414 }
3415
3416 const unpackedFiles = yield* Effect.try({
3417 try: () => {
3418 // @electron/asar requires host separators even for archive entry names.
3419 statFile(asarPath, path.join("apps", "server", "dist", "bin.mjs"));
3420 return [...collectUnpackedAsarFiles(getRawHeader(asarPath).header)].sort();
3421 },
3422 catch: (cause) =>
3423 new WindowsPackagedPayloadValidationError({
3424 reason: "sidecar-invalid",
3425 packagedAppDir,
3426 cause,
3427 }),
3428 });
3429 if (unpackedFiles.length === 0) {
3430 return yield* new WindowsPackagedPayloadValidationError({
3431 reason: "sidecar-invalid",
3432 packagedAppDir,
3433 cause: new Error("server.asar does not declare any unpacked native files"),
3434 });
3435 }
3436
3437 const missingFiles: string[] = [];
3438 for (const unpackedFile of unpackedFiles) {
3439 const unpackedPath = path.join(
3440 resourcesDir,
3441 `${WINDOWS_SERVER_ASAR_RESOURCE}.unpacked`,
3442 ...unpackedFile.split("/"),
3443 );
3444 if (!(yield* isFile(unpackedPath))) {
3445 missingFiles.push(`${WINDOWS_SERVER_ASAR_RESOURCE}.unpacked/${unpackedFile}`);
3446 }
3447 }
3448 if (missingFiles.length > 0) {
3449 return yield* new WindowsPackagedPayloadValidationError({
3450 reason: "unpacked-native-missing",
3451 packagedAppDir,
3452 missingFiles,
3453 });
3454 }
3455
3456 const resourceMonitorPath = path.join(
3457 resourcesDir,
3458 "resource-monitor",
3459 resourceMonitorExecutableName("win"),
3460 );
3461 if (!(yield* isFile(resourceMonitorPath))) {
3462 return yield* new WindowsPackagedPayloadValidationError({
3463 reason: "resource-monitor-missing",
3464 packagedAppDir,
3465 missingFiles: ["resource-monitor/t3-resource-monitor.exe"],
3466 });
3467 }
3468
3469 const wslArchivePath = path.join(resourcesDir, WSL_RUNTIME_ARCHIVE_NAME);
3470 const wslArchiveHashPath = path.join(resourcesDir, WSL_RUNTIME_ARCHIVE_HASH_NAME);
3471 const [hasWslArchive, hasWslArchiveHash] = yield* Effect.all([
3472 isFile(wslArchivePath),
3473 isFile(wslArchiveHashPath),
3474 ]);
3475 if (input.expectWslRuntime === true && (!hasWslArchive || !hasWslArchiveHash)) {
3476 return yield* new WindowsPackagedPayloadValidationError({
3477 reason: "wsl-runtime-missing",
3478 packagedAppDir,
3479 missingFiles: [
3480 ...(hasWslArchive ? [] : [WSL_RUNTIME_ARCHIVE_NAME]),
3481 ...(hasWslArchiveHash ? [] : [WSL_RUNTIME_ARCHIVE_HASH_NAME]),
3482 ],
3483 });
3484 }
3485 if (hasWslArchive !== hasWslArchiveHash) {
3486 return yield* new WindowsPackagedPayloadValidationError({
3487 reason: "wsl-runtime-missing",
3488 packagedAppDir,
3489 missingFiles: [hasWslArchive ? WSL_RUNTIME_ARCHIVE_HASH_NAME : WSL_RUNTIME_ARCHIVE_NAME],
3490 });
3491 }
3492 if (hasWslArchive && hasWslArchiveHash) {
3493 const invalidWslRuntime = (cause: unknown) =>
3494 new WindowsPackagedPayloadValidationError({
3495 reason: "wsl-runtime-invalid",
3496 packagedAppDir,
3497 cause,
3498 });
3499 const recordedHash = yield* fs
3500 .readFileString(wslArchiveHashPath)
3501 .pipe(Effect.mapError(invalidWslRuntime));
3502 const expectedHash = recordedHash.trim().toLowerCase();
3503 if (!/^[0-9a-f]{64}$/.test(expectedHash)) {
3504 return yield* invalidWslRuntime(new Error("invalid WSL runtime SHA-256 sidecar"));
3505 }
3506 const archiveHash = NodeCrypto.createHash("sha256");
3507 yield* fs.stream(wslArchivePath).pipe(
3508 Stream.runForEach((chunk) => Effect.sync(() => archiveHash.update(chunk))),
3509 Effect.mapError(invalidWslRuntime),
3510 );
3511 const actualHash = archiveHash.digest("hex");
3512 if (actualHash !== expectedHash) {
3513 return yield* invalidWslRuntime(
3514 new Error(`WSL runtime SHA-256 mismatch: expected ${expectedHash}, got ${actualHash}`),
3515 );
3516 }
3517
3518 const listing = yield* spawnAndCollectOutput(
3519 ChildProcess.make("tar", ["-tzf", WSL_RUNTIME_ARCHIVE_NAME], {
3520 cwd: resourcesDir,
3521 stdin: "ignore",
3522 stdout: "pipe",
3523 stderr: "pipe",
3524 }),
3525 ).pipe(Effect.mapError(invalidWslRuntime));
3526 if (listing.exitCode !== 0) {
3527 return yield* invalidWslRuntime(
3528 new Error(`tar could not list WSL runtime archive: ${listing.stderr.trim()}`),
3529 );
3530 }
3531 const members = parseWslRuntimeArchiveMembers(listing.stdout);
3532 // The WSL installer finds t3 under the archive's single stem-named directory.
3533 const stem = wslRuntimeArchiveStem(input.appVersion, input.targetArch);
3534 const topLevel = new Set(members.map((member) => member.split("/")[0]));
3535 if (topLevel.size !== 1 || !topLevel.has(stem)) {
3536 return yield* invalidWslRuntime(
3537 new Error(
3538 `WSL runtime archive must contain a single top-level directory ${stem}, found ${[...topLevel].join(", ") || "nothing"}`,
3539 ),
3540 );
3541 }
3542 const requiredMembers = [`${stem}/t3`, `${stem}/client`, `${stem}/node_modules`];
3543 const missingMembers = requiredMembers.filter((member) => !members.includes(member));
3544 const ptyCandidates = [
3545 `${stem}/node_modules/node-pty/build/Release/pty.node`,
3546 `${stem}/node_modules/node-pty/prebuilds/linux-${input.targetArch}/pty.node`,
3547 ];
3548 if (!ptyCandidates.some((member) => members.includes(member))) {
3549 missingMembers.push(...ptyCandidates);
3550 }
3551 if (missingMembers.length > 0) {
3552 return yield* new WindowsPackagedPayloadValidationError({
3553 reason: "wsl-runtime-invalid",
3554 packagedAppDir,
3555 missingFiles: missingMembers,
3556 cause: new Error("WSL runtime archive is not a Linux CLI release archive"),
3557 });
3558 }
3559 const bundleEntry = members.find((member) => member.endsWith("/bin.mjs"));
3560 if (bundleEntry !== undefined) {
3561 return yield* invalidWslRuntime(
3562 new Error(`WSL runtime archive contains a server bundle entry ${bundleEntry}`),
3563 );
3564 }
3565 }
3566
3567 const fileCount = yield* countPayloadFiles(packagedAppDir);
3568 if (fileCount > fileLimit) {
3569 return yield* new WindowsPackagedPayloadValidationError({
3570 reason: "file-limit-exceeded",
3571 packagedAppDir,
3572 fileCount,
3573 fileLimit,
3574 });
3575 }
3576
3577 yield* verifyWindowsPackagedRuntime({
3578 packagedAppDir,
3579 appExecutableName: input.appExecutableName,
3580 targetArch: input.targetArch,
3581 verbose: input.verbose ?? false,
3582 });
3583
3584 yield* Effect.log(
3585 `[desktop-artifact] Validated Windows payload (${String(fileCount)} files, ${String(unpackedFiles.length)} sidecar natives).`,
3586 );
3587 return { packagedAppDir, fileCount, unpackedFiles } as const;
3588 });
3589
3590 export class MacPackagedAppMissingError extends Schema.TaggedError<MacPackagedAppMissingError>()(
3591 "MacPackagedAppMissingError",
3592 { stageDistDir: Schema.String },
3593 ) {
3594 override get message(): string {
3595 return `Expected electron-builder to leave a packaged .app with Contents/Resources/app.asar under ${this.stageDistDir}/mac*.`;
3596 }
3597 }
3598
3599 export const validateMacPackagedPayload = Effect.fn("desktopArtifact.validateMacPackagedPayload")(
3600 function* (input: { readonly stageDistDir: string; readonly verbose?: boolean }) {
3601 const fs = yield* FileSystem.FileSystem;
3602 const path = yield* Path.Path;
3603 const asarPaths: string[] = [];
3604 for (const entry of yield* fs.readDirectory(input.stageDistDir)) {
3605 if (!entry.startsWith("mac")) continue;
3606 const outputDir = path.join(input.stageDistDir, entry);
3607 const apps = yield* fs.readDirectory(outputDir).pipe(Effect.orElseSucceed(() => []));
3608 for (const app of apps) {
3609 if (app.endsWith(".app")) {
3610 asarPaths.push(path.join(outputDir, app, "Contents/Resources/app.asar"));
3611 }
3612 }
3613 }
3614 if (asarPaths.length === 0) {
3615 return yield* new MacPackagedAppMissingError({ stageDistDir: input.stageDistDir });
3616 }
3617 for (const asarPath of asarPaths) {
3618 yield* verifyPackagedBundleIsSelfContained({ asarPath, verbose: input.verbose ?? false });
3619 }
3620 yield* Effect.log(
3621 `[desktop-artifact] Validated macOS payload (${String(asarPaths.length)} app bundle(s)).`,
3622 );
3623 },
3624 );
3625
3626 export class LinuxPackagedAppMissingError extends Schema.TaggedError<LinuxPackagedAppMissingError>()(
3627 "LinuxPackagedAppMissingError",
3628 { stageDistDir: Schema.String },
3629 ) {
3630 override get message(): string {
3631 return `Expected electron-builder to leave resources/app.asar under ${this.stageDistDir}/linux*-unpacked.`;
3632 }
3633 }
3634
3635 export const validateLinuxPackagedPayload = Effect.fn(
3636 "desktopArtifact.validateLinuxPackagedPayload",
3637 )(function* (input: { readonly stageDistDir: string; readonly verbose?: boolean }) {
3638 const fs = yield* FileSystem.FileSystem;
3639 const path = yield* Path.Path;
3640 const asarPaths = (yield* fs.readDirectory(input.stageDistDir))
3641 .filter((entry) => entry.startsWith("linux") && entry.endsWith("-unpacked"))
3642 .map((entry) => path.join(input.stageDistDir, entry, "resources/app.asar"));
3643 if (asarPaths.length === 0) {
3644 return yield* new LinuxPackagedAppMissingError({ stageDistDir: input.stageDistDir });
3645 }
3646 for (const asarPath of asarPaths) {
3647 yield* verifyPackagedBundleIsSelfContained({ asarPath, verbose: input.verbose ?? false });
3648 }
3649 yield* Effect.log(
3650 `[desktop-artifact] Validated Linux payload (${String(asarPaths.length)} app bundle(s)).`,
3651 );
3652 });
3653
3654 const buildDesktopArtifactUnlocked = Effect.fn("buildDesktopArtifactUnlocked")(function* (
3655 options: ResolvedBuildOptions,
3656 ) {
3657 const repoRoot = yield* RepoRoot;
3658 const path = yield* Path.Path;
3659 const fs = yield* FileSystem.FileSystem;
3660 const hostPlatform = yield* HostProcess.Platform;
3661 if (hostPlatform === "linux" && options.platform === "linux") {
3662 yield* preflightLinuxDesktopBuild(options.arch);
3663 }
3664 if (hostPlatform === "darwin" && options.platform === "mac") {
3665 yield* preflightMacDesktopBuild(options.arch);
3666 }
3667 if (hostPlatform === "win32" && options.platform === "win") {
3668 yield* preflightWindowsDesktopBuild({
3669 arch: options.arch,
3670 bundlesWslRuntime: bundlesWslRuntime({
3671 platform: options.platform,
3672 runtimeArchivePath: options.wslRuntime,
3673 }),
3674 });
3675 }
3676 const workspaceConfig = yield* readWorkspaceConfig();
3677 const workspaceCatalog = workspaceConfig.catalog ?? {};
3678 const workspaceOverrides = workspaceConfig.overrides ?? {};
3679 const workspacePatchedDependencies = workspaceConfig.patchedDependencies ?? {};
3680 const workspaceAllowBuilds = workspaceConfig.allowBuilds ?? {};
3681
3682 const platformConfig = PLATFORM_CONFIG[options.platform];
3683 if (!platformConfig) {
3684 return yield* new UnsupportedDesktopBuildPlatformError({
3685 platform: options.platform,
3686 });
3687 }
3688
3689 const electronVersion = desktopPackageJson.dependencies.electron;
3690
3691 const serverDependencies = serverPackageJson.dependencies;
3692 if (!serverDependencies || Object.keys(serverDependencies).length === 0) {
3693 return yield* new MissingServerProductionDependenciesError({
3694 manifestPath: "apps/server/package.json",
3695 });
3696 }
3697
3698 const resolvedOverrides = yield* Effect.try({
3699 try: () => resolveCatalogDependencies(workspaceOverrides, workspaceCatalog, "apps/desktop"),
3700 catch: (cause) =>
3701 new DesktopBuildDependencyResolutionError({
3702 kind: "workspace-overrides",
3703 manifestPath: "pnpm-workspace.yaml",
3704 cause,
3705 }),
3706 });
3707
3708 const resolvedServerDependencies = yield* Effect.try({
3709 try: () => resolveCatalogDependencies(serverDependencies, workspaceCatalog, "apps/server"),
3710 catch: (cause) =>
3711 new DesktopBuildDependencyResolutionError({
3712 kind: "server-production",
3713 manifestPath: "apps/server/package.json",
3714 cause,
3715 }),
3716 });
3717 const resolvedServerRuntimeExternalDependencies = selectCliRuntimeExternalDependencies(
3718 resolvedServerDependencies,
3719 );
3720 const resolvedDesktopRuntimeDependencies = yield* Effect.try({
3721 try: () => resolveDesktopRuntimeDependencies(desktopPackageJson.dependencies, workspaceCatalog),
3722 catch: (cause) =>
3723 new DesktopBuildDependencyResolutionError({
3724 kind: "desktop-runtime",
3725 manifestPath: "apps/desktop/package.json",
3726 cause,
3727 }),
3728 });
3729
3730 const appVersion =
3731 options.version ?? resolveTaggedSourceVersion(repoRoot, serverPackageJson.version);
3732 const iconAssets = resolveDesktopBuildIconAssets(appVersion);
3733 const commitHash = yield* resolveGitCommitHash(repoRoot);
3734 const mkdir = options.keepStage ? fs.makeTempDirectory : fs.makeTempDirectoryScoped;
3735 const stageRoot = yield* mkdir({
3736 prefix: `t3code-desktop-${options.platform}-stage-`,
3737 });
3738
3739 const stageAppDir = path.join(stageRoot, "app");
3740 const stageResourcesDir = path.join(stageAppDir, "apps/desktop/resources");
3741 const distDirs = {
3742 desktopDist: path.join(repoRoot, "apps/desktop/dist-electron"),
3743 desktopResources: path.join(repoRoot, "apps/desktop/resources"),
3744 serverDist: path.join(repoRoot, "apps/server/dist"),
3745 };
3746 const bundledClientEntry = path.join(distDirs.serverDist, "client/index.html");
3747
3748 if (!options.skipBuild) {
3749 yield* Effect.log("[desktop-artifact] Building desktop/server/web artifacts...");
3750 yield* buildDesktopBundlesUnlocked(repoRoot, appVersion, options.verbose);
3751 }
3752
3753 const requiredBuildInputs = [
3754 { artifact: "desktop-dist", artifactPath: distDirs.desktopDist },
3755 { artifact: "desktop-resources", artifactPath: distDirs.desktopResources },
3756 { artifact: "server-dist", artifactPath: distDirs.serverDist },
3757 ] as const;
3758 for (const input of requiredBuildInputs) {
3759 if (!(yield* fs.exists(input.artifactPath))) {
3760 return yield* new MissingDesktopBuildInputError({
3761 ...input,
3762 buildCommand: "vp run build:desktop",
3763 });
3764 }
3765 }
3766
3767 // Inlined native loaders resolve relative to the bundle and can silently fall back to slower JS; reject them.
3768 {
3769 const chunkNames = (yield* fs.readDirectory(distDirs.serverDist)).filter((entry) =>
3770 entry.endsWith(".mjs"),
3771 );
3772 let totalRegions = 0;
3773 const inlined = new Set<string>();
3774 const inlinedPackages = new Set<string>();
3775 for (const chunkName of chunkNames) {
3776 const source = yield* fs.readFileString(path.join(distDirs.serverDist, chunkName));
3777 const scan = findInlinedExternalPackages(source);
3778 totalRegions += scan.regionCount;
3779 for (const name of scan.inlined) inlined.add(name);
3780 for (const name of scan.inlinedPackages) inlinedPackages.add(name);
3781 }
3782 if (inlined.size > 0) {
3783 return yield* new InlinedExternalPackageError({
3784 packages: [...inlined].sort(),
3785 });
3786 }
3787 // Zero regions means the marker scan failed, not that the bundle is clean.
3788 if (totalRegions === 0) {
3789 return yield* new InlinedExternalPackageError({
3790 packages: ["<no module regions found; the bundle scan needs updating>"],
3791 });
3792 }
3793 const nativeInlined: string[] = [];
3794 for (const name of [...inlinedPackages].sort()) {
3795 const packageDir = yield* findStorePackageDirectory(repoRoot, name);
3796 if (packageDir === null) continue;
3797 if (yield* hasNativeLoaderMarkers(packageDir)) nativeInlined.push(name);
3798 }
3799 if (nativeInlined.length > 0) {
3800 return yield* new InlinedNativePackageError({ packages: nativeInlined });
3801 }
3802
3803 if (!inlinedPackages.has(BUNDLE_SELF_CONTAINED_SENTINEL)) {
3804 return yield* new ExternalizedBundleError({
3805 sentinel: BUNDLE_SELF_CONTAINED_SENTINEL,
3806 inlinedPackageCount: inlinedPackages.size,
3807 });
3808 }
3809 }
3810
3811 if (!(yield* fs.exists(bundledClientEntry))) {
3812 return yield* new MissingDesktopBuildInputError({
3813 artifact: "bundled-server-client",
3814 artifactPath: bundledClientEntry,
3815 buildCommand: "vp run build:desktop",
3816 });
3817 }
3818
3819 const webAssetBrand = resolveDesktopWebAssetBrand(appVersion);
3820 yield* applyWebBrandAssets(webAssetBrand, "apps/server/dist/client");
3821 yield* Effect.log(`[desktop-artifact] Applied ${webAssetBrand} web client branding.`);
3822 yield* validateBundledClientAssets(path.dirname(bundledClientEntry));
3823
3824 yield* fs.makeDirectory(path.join(stageAppDir, "apps/desktop"), { recursive: true });
3825 if (options.platform !== "win") {
3826 yield* fs.makeDirectory(path.join(stageAppDir, "apps/server"), { recursive: true });
3827 }
3828
3829 yield* Effect.log("[desktop-artifact] Staging release app...");
3830 yield* fs.copy(distDirs.desktopDist, path.join(stageAppDir, "apps/desktop/dist-electron"));
3831 yield* fs.copy(distDirs.desktopResources, stageResourcesDir);
3832 if (options.platform === "linux") {
3833 const extensionDir = path.join(stageAppDir, "apps/desktop/gnome-extension");
3834 yield* fs.makeDirectory(extensionDir, { recursive: true });
3835 for (const file of gnomeCaptureBundle.files) {
3836 yield* fs.copyFile(
3837 path.join(repoRoot, "apps/desktop/gnome-extension", file),
3838 path.join(extensionDir, file),
3839 );
3840 }
3841 }
3842 if (options.platform === "mac" && options.target === "dmg") {
3843 yield* stageDesktopDmgBackground(
3844 stageResourcesDir,
3845 resolveDesktopUpdateChannel(appVersion),
3846 options.verbose,
3847 );
3848 }
3849 if (options.platform !== "win") {
3850 yield* fs.copy(distDirs.serverDist, path.join(stageAppDir, "apps/server/dist"));
3851 }
3852 yield* stageResourceMonitor({
3853 repoRoot,
3854 stageResourcesDir,
3855 platform: options.platform,
3856 arch: options.arch,
3857 verbose: options.verbose,
3858 });
3859 if (options.platform === "linux") {
3860 for (const backend of ["kde", "hyprland"] as const)
3861 yield* stageLinuxCaptureHelper({
3862 backend,
3863 repoRoot,
3864 stageResourcesDir,
3865 arch: options.arch,
3866 verbose: options.verbose,
3867 });
3868 }
3869 yield* stageBrowserSecret({
3870 repoRoot,
3871 stageResourcesDir,
3872 platform: options.platform,
3873 arch: options.arch,
3874 verbose: options.verbose,
3875 });
3876 yield* stageAppleSpeech({
3877 repoRoot,
3878 stageResourcesDir,
3879 platform: options.platform,
3880 arch: options.arch,
3881 verbose: options.verbose,
3882 });
3883
3884 yield* assertPlatformBuildResources(
3885 options.platform,
3886 stageResourcesDir,
3887 {
3888 macIconPng: path.join(repoRoot, iconAssets.macIconPng),
3889 linuxIconPng: path.join(repoRoot, iconAssets.linuxIconPng),
3890 windowsIconIco: path.join(repoRoot, iconAssets.windowsIconIco),
3891 },
3892 options.verbose,
3893 );
3894
3895 // electron-builder is filtering out stageResourcesDir directory in the AppImage for production
3896 const stageProdResourcesDir = path.join(stageAppDir, "apps/desktop/prod-resources");
3897 yield* fs.copy(stageResourcesDir, stageProdResourcesDir);
3898
3899 const configuredMacPasskeySigning =
3900 options.platform === "mac" && options.signed
3901 ? yield* Effect.try({
3902 try: () => resolveMacPasskeySigningConfiguration(loadRepoEnv({ repoRoot })),
3903 catch: MacPasskeySigningConfigurationResolutionError.fromCause,
3904 })
3905 : undefined;
3906 const macPasskeySigning = configuredMacPasskeySigning
3907 ? {
3908 ...configuredMacPasskeySigning,
3909 provisioningProfilePath: path.resolve(
3910 repoRoot,
3911 configuredMacPasskeySigning.provisioningProfilePath,
3912 ),
3913 }
3914 : undefined;
3915 const macEntitlementsPath = macPasskeySigning
3916 ? path.join(stageAppDir, "entitlements.mac.plist")
3917 : undefined;
3918 let macWebAuthn: MacWebAuthnEntitlements | undefined;
3919 if (macPasskeySigning && macEntitlementsPath) {
3920 if (!(yield* fs.exists(macPasskeySigning.provisioningProfilePath))) {
3921 return yield* new MacProvisioningProfileNotFoundError({
3922 provisioningProfilePath: macPasskeySigning.provisioningProfilePath,
3923 });
3924 }
3925 macWebAuthn = resolveMacWebAuthnEntitlements(
3926 yield* fs.readFileString(macPasskeySigning.provisioningProfilePath),
3927 macPasskeySigning,
3928 );
3929 yield* Effect.log(
3930 `[desktop-artifact] In-app browser passkeys: Touch ID ${macWebAuthn.touchIdKeychainAccessGroup ? "enabled" : "disabled"}, browser passkeys ${macWebAuthn.browserPasskeys ? "enabled" : "disabled"}.`,
3931 );
3932 yield* fs.writeFileString(
3933 macEntitlementsPath,
3934 renderMacPasskeyEntitlements(macPasskeySigning, macWebAuthn),
3935 );
3936 }
3937
3938 const stageDependencies =
3939 options.platform === "win"
3940 ? { ...resolvedDesktopRuntimeDependencies }
3941 : resolveMergedStageDependencies({
3942 platform: options.platform,
3943 serverDependencies: resolvedServerDependencies,
3944 desktopDependencies: resolvedDesktopRuntimeDependencies,
3945 arch: options.arch,
3946 fffNodeVersion: serverPackageJson.dependencies["@ff-labs/fff-node"],
3947 });
3948 const stagePatchedDependencies = createStagePatchedDependencies(
3949 workspacePatchedDependencies,
3950 stageDependencies,
3951 );
3952 const windowsServerAsarPath =
3953 options.platform === "win"
3954 ? path.join(stageAppDir, WINDOWS_SERVER_RESOURCE_SOURCE_DIR, WINDOWS_SERVER_ASAR_RESOURCE)
3955 : undefined;
3956 const stagePackageJson: StagePackageJson = {
3957 name: "t3code",
3958 version: appVersion,
3959 buildVersion: appVersion,
3960 t3codeCommitHash: commitHash,
3961 // Read by apps/desktop/src/preview/Passkeys.ts; must match the signed entitlements.
3962 ...(macWebAuthn ? { t3codeWebAuthn: macWebAuthn } : {}),
3963 private: true,
3964 packageManager: rootPackageJson.packageManager,
3965 description:
3966 "T3 Code is an open-source desktop app for coding agents. Work with your existing agent subscriptions, review code changes, and run commands in your projects. Connect from desktop, web, or mobile to continue working remotely.",
3967 license: "MIT",
3968 homepage: "https://t3.codes",
3969 author: "T3 Tools",
3970 main: "apps/desktop/dist-electron/boot.cjs",
3971 build: yield* createBuildConfig(
3972 options.platform,
3973 options.target,
3974 appVersion,
3975 options.signed,
3976 options.mockUpdates,
3977 options.mockUpdateServerPort,
3978 macPasskeySigning && macEntitlementsPath
3979 ? {
3980 entitlementsPath: macEntitlementsPath,
3981 provisioningProfilePath: macPasskeySigning.provisioningProfilePath,
3982 }
3983 : undefined,
3984 bundlesWslRuntime({ platform: options.platform, runtimeArchivePath: options.wslRuntime }),
3985 options.arch,
3986 ),
3987 dependencies: stageDependencies,
3988 devDependencies: {
3989 electron: electronVersion,
3990 },
3991 };
3992
3993 const stagePackageJsonString = yield* encodeJsonString(stagePackageJson);
3994 yield* fs.writeFileString(path.join(stageAppDir, "package.json"), `${stagePackageJsonString}\n`);
3995 const stageWorkspaceConfig = createStageWorkspaceConfig({
3996 platform: options.platform,
3997 arch: options.arch,
3998 allowBuilds: workspaceAllowBuilds,
3999 patchedDependencies: stagePatchedDependencies,
4000 overrides: resolvedOverrides,
4001 });
4002 const stageWorkspaceConfigString = yield* encodeStageWorkspaceConfig(stageWorkspaceConfig);
4003 yield* fs.writeFileString(
4004 path.join(stageAppDir, "pnpm-workspace.yaml"),
4005 stageWorkspaceConfigString,
4006 );
4007
4008 if (Object.keys(stagePatchedDependencies).length > 0) {
4009 yield* fs.copy(path.join(repoRoot, "patches"), path.join(stageAppDir, "patches"));
4010 }
4011
4012 yield* Effect.log("[desktop-artifact] Installing staged production dependencies...");
4013 const installCommand = yield* resolveSpawnCommand("vp", [...STAGE_INSTALL_ARGS]);
4014 yield* runCommand(
4015 ChildProcess.make(installCommand.command, installCommand.args, {
4016 cwd: stageAppDir,
4017 shell: installCommand.shell,
4018 }),
4019 { label: "vp install --prod", verbose: options.verbose },
4020 );
4021 yield* stageClerkPasskeyNativeBinaries(stageAppDir, options.platform, options.arch);
4022 yield* stageKeyringNativeBinaries(stageAppDir, options.platform, options.arch);
4023
4024 if (options.platform === "win" && windowsServerAsarPath) {
4025 yield* stageWindowsServerSidecar({
4026 stageRoot,
4027 repoRoot,
4028 serverDistDir: distDirs.serverDist,
4029 arch: options.arch,
4030 appVersion,
4031 runtimeExternalDependencies: resolvedServerRuntimeExternalDependencies,
4032 fffNodeVersion: serverPackageJson.dependencies["@ff-labs/fff-node"],
4033 allowBuilds: workspaceAllowBuilds,
4034 patchedDependencies: workspacePatchedDependencies,
4035 overrides: resolvedOverrides,
4036 asarPath: windowsServerAsarPath,
4037 verbose: options.verbose,
4038 });
4039 }
4040 yield* stageCursorSdkPlatformPackages(
4041 path.join(
4042 options.platform === "win" ? path.join(stageRoot, "server") : stageAppDir,
4043 "node_modules",
4044 ),
4045 path.join(stageProdResourcesDir, "cursor-sdk"),
4046 );
4047 if (
4048 options.wslRuntime !== undefined &&
4049 bundlesWslRuntime({ platform: options.platform, runtimeArchivePath: options.wslRuntime })
4050 ) {
4051 yield* stageWslRuntimeArchive({
4052 sourceArchivePath: options.wslRuntime,
4053 archivePath: path.join(stageAppDir, WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE.from),
4054 hashPath: path.join(stageAppDir, WSL_RUNTIME_ARCHIVE_HASH_EXTRA_RESOURCE.from),
4055 });
4056 }
4057
4058 // electron-builder treats empty signing variables as enabled; scrub them before spawning.
4059 const buildEnv: NodeJS.ProcessEnv = {
4060 ...process.env,
4061 };
4062 buildEnv.npm_config_user_agent = resolvePackageManagerUserAgent(rootPackageJson.packageManager);
4063 for (const [key, value] of Object.entries(buildEnv)) {
4064 if (value === "") {
4065 delete buildEnv[key];
4066 }
4067 }
4068 if (options.platform === "linux") {
4069 // fpm uses system xz through tar; threading cuts compression time on many-core runners.
4070 buildEnv.XZ_DEFAULTS = "-T0";
4071 }
4072 if (options.platform === "win") {
4073 // Windows signs only through Azure Trusted Signing. Off Windows,
4074 // electron-builder's signtool manager would read CSC_LINK (the macOS
4075 // certificate) as a Windows certificate.
4076 delete buildEnv.CSC_LINK;
4077 delete buildEnv.CSC_KEY_PASSWORD;
4078 }
4079 if (!options.signed) {
4080 buildEnv.CSC_IDENTITY_AUTO_DISCOVERY = "false";
4081 delete buildEnv.CSC_LINK;
4082 delete buildEnv.CSC_KEY_PASSWORD;
4083 delete buildEnv.APPLE_API_KEY;
4084 delete buildEnv.APPLE_API_KEY_ID;
4085 delete buildEnv.APPLE_API_ISSUER;
4086 }
4087
4088 if (hostPlatform === "win32") {
4089 const python = yield* resolvePythonForNodeGyp();
4090 if (python) {
4091 buildEnv.PYTHON = python;
4092 buildEnv.npm_config_python = python;
4093 }
4094 buildEnv.npm_config_msvs_version = buildEnv.npm_config_msvs_version ?? "2022";
4095 buildEnv.GYP_MSVS_VERSION = buildEnv.GYP_MSVS_VERSION ?? "2022";
4096 }
4097 if (options.verbose) {
4098 const debugNamespaces = [
4099 "electron-builder",
4100 "electron-builder:*",
4101 ...(options.platform === "mac" ? ["electron-osx-sign*", "electron-notarize*"] : []),
4102 ];
4103 buildEnv.DEBUG = [buildEnv.DEBUG, ...debugNamespaces].filter(Boolean).join(",");
4104 }
4105
4106 yield* Effect.log(
4107 `[desktop-artifact] Building ${options.platform}/${options.target} (arch=${options.arch}, version=${appVersion})...`,
4108 );
4109 const builderArgs = [
4110 "exec",
4111 "--filter",
4112 "@t3tools/desktop",
4113 "--",
4114 "electron-builder",
4115 "--projectDir",
4116 stageAppDir,
4117 platformConfig.cliFlag,
4118 `--${options.arch}`,
4119 "--publish",
4120 "never",
4121 ];
4122 const builderCommand = yield* resolveSpawnCommand("vp", builderArgs, { env: buildEnv });
4123 yield* runCommand(
4124 ChildProcess.make(builderCommand.command, builderCommand.args, {
4125 cwd: repoRoot,
4126 env: buildEnv,
4127 shell: builderCommand.shell,
4128 }),
4129 {
4130 label: `vp exec --filter @t3tools/desktop -- electron-builder --projectDir ${stageAppDir} ${platformConfig.cliFlag} --${options.arch} --publish never`,
4131 verbose: options.verbose,
4132 },
4133 );
4134
4135 const stageDistDir = path.join(stageAppDir, "dist");
4136 if (!(yield* fs.exists(stageDistDir))) {
4137 return yield* new DesktopBuildDistDirectoryMissingError({
4138 distPath: stageDistDir,
4139 platform: options.platform,
4140 arch: options.arch,
4141 });
4142 }
4143
4144 if (options.platform === "win") {
4145 yield* validateWindowsPackagedPayload({
4146 stageDistDir,
4147 appExecutableName: `${resolveDesktopProductName(appVersion)}.exe`,
4148 targetArch: options.arch,
4149 appVersion,
4150 expectWslRuntime: bundlesWslRuntime({
4151 platform: options.platform,
4152 runtimeArchivePath: options.wslRuntime,
4153 }),
4154 verbose: options.verbose,
4155 });
4156 }
4157 // The probe runs on the host Node, so a cross-arch build skips it.
4158 if (
4159 options.platform === "linux" &&
4160 hostPlatform === "linux" &&
4161 options.arch === (yield* HostProcess.Architecture)
4162 ) {
4163 yield* validateLinuxPackagedPayload({ stageDistDir, verbose: options.verbose });
4164 }
4165 // x64 builds on arm64 runners; the arm64 check covers the shared JS bundle.
4166 if (options.platform === "mac" && options.arch === "arm64" && hostPlatform === "darwin") {
4167 yield* validateMacPackagedPayload({ stageDistDir, verbose: options.verbose });
4168 }
4169
4170 const copiedArtifacts = yield* copyDesktopBuildArtifacts(
4171 stageDistDir,
4172 options.outputDir,
4173 options.target === "dir",
4174 );
4175
4176 if (copiedArtifacts.length === 0) {
4177 return yield* new DesktopBuildNoArtifactsProducedError({
4178 distPath: stageDistDir,
4179 platform: options.platform,
4180 arch: options.arch,
4181 });
4182 }
4183
4184 yield* Effect.log("[desktop-artifact] Done. Artifacts:").pipe(
4185 Effect.annotateLogs({ artifacts: copiedArtifacts }),
4186 );
4187 });
4188
4189 const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
4190 options: ResolvedBuildOptions,
4191 ) {
4192 const repoRoot = yield* RepoRoot;
4193 return yield* withDesktopBuildLock(repoRoot, buildDesktopArtifactUnlocked(options));
4194 });
4195
4196 export const copyDesktopBuildArtifacts = Effect.fn("copyDesktopBuildArtifacts")(function* (
4197 stageDistDir: string,
4198 outputDir: string,
4199 includeDirectories = false,
4200 ) {
4201 const fs = yield* FileSystem.FileSystem;
4202 const path = yield* Path.Path;
4203 const stageEntries = yield* fs.readDirectory(stageDistDir);
4204 yield* fs.makeDirectory(outputDir, { recursive: true });
4205
4206 const copiedArtifacts: string[] = [];
4207 for (const entry of stageEntries) {
4208 const from = path.join(stageDistDir, entry);
4209 const stat = yield* fs.stat(from).pipe(Effect.orElseSucceed(() => null));
4210 if (!stat || (stat.type !== "File" && !(includeDirectories && stat.type === "Directory")))
4211 continue;
4212
4213 const to = path.join(outputDir, entry);
4214 // Replace whatever a reused output dir already holds at this path. fs.cp refuses to
4215 // overwrite a directory with a file or a file with a directory, and only merges into
4216 // an existing directory, so a stale entry of either type must go first.
4217 yield* fs.remove(to, { recursive: true, force: true });
4218 yield* Effect.tryPromise({
4219 try: () =>
4220 NodeFSP.cp(from, to, {
4221 recursive: true,
4222 force: true,
4223 verbatimSymlinks: true,
4224 }),
4225 catch: (cause) => new DesktopBuildArtifactCopyError({ from, to, cause }),
4226 });
4227 copiedArtifacts.push(to);
4228 }
4229
4230 return copiedArtifacts;
4231 });
4232
4233 const buildDesktopArtifactCli = Command.make("build-desktop-artifact", {
4234 platform: Flag.Literals("platform", BuildPlatform.literals).pipe(
4235 Flag.withDescription("Build platform (env: T3CODE_DESKTOP_PLATFORM)."),
4236 Flag.optional,
4237 ),
4238 target: Flag.String("target").pipe(
4239 Flag.withDescription(
4240 "Artifact target, for example dmg/AppImage/nsis (env: T3CODE_DESKTOP_TARGET).",
4241 ),
4242 Flag.optional,
4243 ),
4244 arch: Flag.Literals("arch", BuildArch.literals).pipe(
4245 Flag.withDescription("Build arch, for example arm64/x64/universal (env: T3CODE_DESKTOP_ARCH)."),
4246 Flag.optional,
4247 ),
4248 buildVersion: Flag.String("build-version").pipe(
4249 Flag.withDescription(
4250 "Compiled bundle and desktop package version (env: T3CODE_DESKTOP_VERSION).",
4251 ),
4252 Flag.optional,
4253 ),
4254 outputDir: Flag.String("output-dir").pipe(
4255 Flag.withDescription("Output directory for artifacts (env: T3CODE_DESKTOP_OUTPUT_DIR)."),
4256 Flag.optional,
4257 ),
4258 skipBuild: Flag.Boolean("skip-build").pipe(
4259 Flag.withDescription(
4260 "Skip `vp run build:desktop` and use existing dist artifacts (env: T3CODE_DESKTOP_SKIP_BUILD).",
4261 ),
4262 Flag.optional,
4263 ),
4264 keepStage: Flag.Boolean("keep-stage").pipe(
4265 Flag.withDescription("Keep temporary staging files (env: T3CODE_DESKTOP_KEEP_STAGE)."),
4266 Flag.optional,
4267 ),
4268 signed: Flag.Boolean("signed").pipe(
4269 Flag.withDescription(
4270 "Enable signing/notarization discovery; Windows uses Azure Trusted Signing (env: T3CODE_DESKTOP_SIGNED).",
4271 ),
4272 Flag.optional,
4273 ),
4274 verbose: Flag.Boolean("verbose").pipe(
4275 Flag.withDescription("Stream subprocess stdout (env: T3CODE_DESKTOP_VERBOSE)."),
4276 Flag.optional,
4277 ),
4278 mockUpdates: Flag.Boolean("mock-updates").pipe(
4279 Flag.withDescription("Enable mock updates (env: T3CODE_DESKTOP_MOCK_UPDATES)."),
4280 Flag.optional,
4281 ),
4282 mockUpdateServerPort: Flag.Int("mock-update-server-port").pipe(
4283 Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
4284 Flag.withDescription("Mock update server port (env: T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT)."),
4285 Flag.optional,
4286 ),
4287 wslRuntime: Flag.String("wsl-runtime").pipe(
4288 Flag.withDescription(
4289 "Path to the Linux CLI release archive (t3-<version>-linux-x64.tar.gz) to embed as the WSL runtime of a Windows build (env: T3CODE_DESKTOP_WSL_RUNTIME).",
4290 ),
4291 Flag.optional,
4292 ),
4293 }).pipe(
4294 Command.withDescription("Build a desktop artifact for T3 Code."),
4295 Command.withHandler((input) => Effect.flatMap(resolveBuildOptions(input), buildDesktopArtifact)),
4296 );
4297
4298 const cliRuntimeLayer = Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer);
4299
4300 if (import.meta.main) {
4301 Command.run(buildDesktopArtifactCli, { version: "0.0.0" }).pipe(
4302 Effect.scoped,
4303 Effect.provide(cliRuntimeLayer),
4304 NodeRuntime.runMain,
4305 );
4306 }