Open History to see the last commit
1import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
5import * as Clock from "effect/Clock";
6import * as Console from "effect/Console";
7import * as Context from "effect/Context";
8import * as DateTime from "effect/DateTime";
9import * as Crypto from "effect/Crypto";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14import * as Random from "effect/Random";
15import * as Schema from "effect/Schema";
16import * as Stream from "effect/Stream";
17import { Argument, Command, Flag } from "effect/cli";
18import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
19import { ChildProcess, ChildProcessSpawner } from "effect/process";
20
21export type NativePlatform = "ios" | "android";
22const NativeClientRecord = Schema.Struct({ fingerprint: Schema.String, binary: Schema.String });
23const encodeRecord = Schema.encodeEffect(Schema.fromJsonString(NativeClientRecord));
24const decodeRecord = Schema.decodeUnknownEffect(Schema.fromJsonString(NativeClientRecord));
25const encodeOutput = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
26const isNotLink = Schema.is(Schema.Struct({ code: Schema.Literal("EINVAL") }));
27const decodeSimulators = Schema.decodeUnknownEffect(
28 Schema.fromJsonString(
29 Schema.Struct({
30 devices: Schema.Record(
31 Schema.String,
32 Schema.Array(
33 Schema.Struct({ udid: Schema.String, name: Schema.String, state: Schema.String }),
34 ),
35 ),
36 }),
37 ),
38);
39export type NativeClientRecord = typeof NativeClientRecord.Type;
40export type NativeClientStatus = "compatible" | "missing" | "unknown" | "stale";
41export class NativeClientError extends Schema.TaggedError<NativeClientError>()(
42 "NativeClientError",
43 { message: Schema.String },
44) {}
45
46export function clientStatus(
47 fingerprint: string,
48 binary: string | null,
49 record: NativeClientRecord | null,
50): NativeClientStatus {
51 if (binary === null) return "missing";
52 if (!record || record.binary !== binary) return "unknown";
53 return record.fingerprint === fingerprint ? "compatible" : "stale";
54}
55
56export type ArtifactSource = "local" | "remote" | "build";
57
58/** Keep native sources stable during ensure, as with a normal build; endpoint checks reject detected edits. */
59export const ensureClient = Effect.fn("ensureClient")(function* <E, R, E2, R2>(operations: {
60 fingerprint: Effect.Effect<string, E, R>;
61 installedBinary: Effect.Effect<string | null, E, R>;
62 readRecord: Effect.Effect<NativeClientRecord | null, E, R>;
63 install: (fingerprint: string) => Effect.Effect<ArtifactSource, E, R>;
64 saveRecord: (record: NativeClientRecord) => Effect.Effect<void, E2, R2>;
65}) {
66 const fingerprint = yield* operations.fingerprint;
67 const status = clientStatus(
68 fingerprint,
69 yield* operations.installedBinary,
70 yield* operations.readRecord,
71 );
72 if (status === "compatible") {
73 return { status, installed: false, fingerprint };
74 }
75 const source = yield* operations.install(fingerprint);
76 const binary = yield* operations.installedBinary;
77 if (binary === null)
78 return yield* new NativeClientError({
79 message: "Install finished but the development client is not on the device.",
80 });
81 yield* operations.saveRecord({ fingerprint, binary });
82 return { status: "compatible" as const, installed: true, source, fingerprint };
83});
84
85const digest = Effect.fn("nativeClient.digest")(function* (value: string | Uint8Array) {
86 const crypto = yield* Crypto.Crypto;
87 const bytes = yield* crypto.digest(
88 "SHA-256",
89 typeof value === "string" ? new TextEncoder().encode(value) : value,
90 );
91 return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
92});
93
94/** Hash fixed-size chunks to bound memory, including resources and symlink targets. */
95export const hashBundle = Effect.fn("hashBundle")(function* (root: string) {
96 const fs = yield* FileSystem.FileSystem;
97 const path = yield* Path.Path;
98 const entries: string[] = [];
99 const visit = Effect.fn("mobile-native-client.visit")(function* (
100 relative: string,
101 ): Effect.fn.Return<void, FileSystemError, FileSystem.FileSystem | Crypto.Crypto> {
102 const names = (yield* fs.readDirectory(path.join(root, relative))).sort((a, b) =>
103 a.localeCompare(b, "en"),
104 );
105 for (const name of names) {
106 const key = path.join(relative, name);
107 const absolute = path.join(root, key);
108 // FileSystem.stat follows links; readLink distinguishes them without following a cycle.
109 const link = yield* fs.readLink(absolute).pipe(
110 Effect.catchIf(
111 (error) => isNotLink(error.reason.cause),
112 () => Effect.succeed(null),
113 ),
114 );
115 if (link !== null) {
116 entries.push(`link:${key}:${link}`);
117 continue;
118 }
119 const info = yield* fs.stat(absolute);
120 if (info.type === "Directory") {
121 entries.push(`directory:${key}`);
122 yield* visit(key);
123 } else {
124 const chunks = yield* fs.stream(absolute, { chunkSize: 65536 }).pipe(
125 Stream.mapEffect((chunk) => digest(chunk)),
126 Stream.runCollect,
127 );
128 entries.push(`file:${key}:${yield* digest(chunks.join("\n"))}`);
129 }
130 }
131 });
132 yield* visit("");
133 return yield* digest(entries.map((entry) => `${entry.length}:${entry}`).join(""));
134});
135type FileSystemError = import("effect/PlatformError").PlatformError;
136
137const bundleId = "com.t3tools.t3code.dev";
138const roots = Effect.gen(function* () {
139 const path = yield* Path.Path;
140 const repo = yield* path.fromFileUrl(new URL("../", import.meta.url));
141 return { repo, mobile: path.join(repo, "apps/mobile") };
142});
143const collect = <E>(stream: Stream.Stream<Uint8Array, E>) =>
144 stream.pipe(
145 Stream.decodeText(),
146 Stream.runFold(
147 () => "",
148 (a, b) => a + b,
149 ),
150 );
151export const resolveAdb = Effect.gen(function* () {
152 if (yield* isCommandAvailable("adb")) return "adb";
153 const environment = yield* HostProcess.Environment;
154 const path = yield* Path.Path;
155 const executable = (yield* HostProcess.Platform) === "win32" ? "adb.exe" : "adb";
156 for (const sdk of [environment.ANDROID_SDK_ROOT, environment.ANDROID_HOME]) {
157 if (!sdk) continue;
158 const candidate = path.join(sdk, "platform-tools", executable);
159 if (yield* isCommandAvailable(candidate)) return candidate;
160 }
161 return yield* new NativeClientError({
162 message:
163 "adb was not found on PATH or in ANDROID_SDK_ROOT/ANDROID_HOME. Install Android SDK platform-tools.",
164 });
165});
166
167/** Build tool output goes to this file instead of the caller's terminal; null streams it. */
168const BuildLog = Context.Reference<string | null>("nativeClient/BuildLog", {
169 defaultValue: () => null,
170});
171
172const command = Effect.fn("nativeClient.command")(function* (
173 program: string,
174 args: string[],
175 inherit = false,
176 cwd?: string,
177) {
178 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
179 const environment = yield* HostProcess.Environment;
180 const log = inherit ? yield* BuildLog : null;
181 const spawn = yield* resolveSpawnCommand(program === "adb" ? yield* resolveAdb : program, args);
182 const child = yield* spawner.spawn(
183 ChildProcess.make(spawn.command, spawn.args, {
184 shell: spawn.shell,
185 cwd: cwd ?? (yield* roots).mobile,
186 env: {
187 ...environment,
188 APP_VARIANT: "development",
189 MOBILE_VERSION_POLICY: "appVersion",
190 T3CODE_IOS_PERSONAL_TEAM: "0",
191 CI: "1",
192 EXPO_NO_GIT_STATUS: "1",
193 // macOS tar otherwise adds AppleDouble entries that change the extracted bundle.
194 COPYFILE_DISABLE: "1",
195 },
196 stdin: "ignore",
197 stdout: inherit && !log ? "inherit" : "pipe",
198 stderr: inherit && !log ? "inherit" : "pipe",
199 }),
200 );
201 if (log) {
202 const fs = yield* FileSystem.FileSystem;
203 const append = <E>(stream: Stream.Stream<Uint8Array, E>) =>
204 stream.pipe(Stream.run(fs.sink(log, { flag: "a" })));
205 const [, , code] = yield* Effect.all(
206 [append(child.stdout), append(child.stderr), child.exitCode],
207 { concurrency: "unbounded" },
208 );
209 if (code === 0) return "";
210 const tail = (yield* fs.readFileString(log)).trimEnd().split("\n").slice(-40).join("\n");
211 return yield* new NativeClientError({
212 message: `${program} ${args[0]} failed (${code}). Last lines:\n${tail}\nFull log: ${log}`,
213 });
214 }
215 const [stdout, stderr, code] = yield* Effect.all(
216 [collect(child.stdout), collect(child.stderr), child.exitCode],
217 { concurrency: "unbounded" },
218 );
219 if (code !== 0)
220 return yield* new NativeClientError({
221 message: `${program} ${args[0]} failed (${code}): ${stderr || "see build output"}`,
222 });
223 return stdout.trim();
224}, Effect.scoped);
225
226const fingerprint = Effect.fn("nativeClient.fingerprint")(function* (platform: NativePlatform) {
227 const output = yield* command(yield* HostProcess.ExecutablePath, [
228 "--eval",
229 // Same hash on every machine: generated native projects and the config's `extra` (env-specific
230 // values a dev client reads from Metro) stay out, so a Mac and a Linux VM share builds.
231 `const f = require('expo/fingerprint'); f.createFingerprintAsync(process.cwd(), { platforms: [process.argv[1]], silent: true, ignorePaths: ['android/**', 'ios/**'], sourceSkips: f.DEFAULT_SOURCE_SKIPS | f.SourceSkips.ExpoConfigExtraSection }).then(fp => console.log('T3_NATIVE_FINGERPRINT=' + fp.hash)).catch(e => { console.error(e); process.exitCode = 1; });`,
232 platform,
233 ]);
234 const hash = output
235 .split("\n")
236 .find((line) => line.startsWith("T3_NATIVE_FINGERPRINT="))
237 ?.split("=")[1];
238 if (!hash || !/^[a-f0-9]{40,64}$/.test(hash))
239 return yield* new NativeClientError({ message: "Expo did not return a native fingerprint." });
240 return hash;
241});
242
243const runtimeName = (runtime: string) =>
244 runtime
245 .replace(/^com\.apple\.CoreSimulator\.SimRuntime\./, "")
246 .replace(/-(\d+)-(\d+)$/, " $1.$2");
247
248/** Validate the named device, or pick the only booted one; otherwise list exact commands to choose from. */
249const resolveDevice = Effect.fn("nativeClient.resolveDevice")(function* (
250 platform: NativePlatform,
251 requested: string | undefined,
252) {
253 const choose = (candidates: ReadonlyArray<{ id: string; label: string }>, problem: string) =>
254 new NativeClientError({
255 message: [
256 problem,
257 ...candidates.map(
258 ({ id, label }) => ` vp run mobile:install ${platform} ${id} # ${label}`,
259 ),
260 ].join("\n"),
261 });
262 if (platform === "ios") {
263 if ((yield* HostProcess.Platform) !== "darwin")
264 return yield* new NativeClientError({
265 message: "Run iOS installs on the Mac that hosts the simulator.",
266 });
267 // The shared iOS client is an arm64 simulator build; Intel simulators cannot run it.
268 if ((yield* HostProcess.Architecture) !== "arm64")
269 return yield* new NativeClientError({
270 message: "mobile:install needs an Apple silicon Mac. Use vp run ios:dev on Intel Macs.",
271 });
272 const listing = yield* decodeSimulators(
273 yield* command("xcrun", ["simctl", "list", "devices", "available", "--json"]),
274 );
275 const simulators = Object.entries(listing.devices).flatMap(([runtime, devices]) =>
276 devices.map((device) => ({ ...device, label: `${device.name} (${runtimeName(runtime)})` })),
277 );
278 const booted = simulators
279 .filter((simulator) => simulator.state === "Booted")
280 .map(({ udid, label }) => ({ id: udid, label }));
281 if (requested === undefined) {
282 if (booted.length === 1) return booted[0]!;
283 return yield* booted.length === 0
284 ? new NativeClientError({
285 message:
286 "No iOS simulator is booted. Open one with device_open, or boot one: xcrun simctl boot <udid>",
287 })
288 : choose(booted, "Several iOS simulators are booted. Pick one:");
289 }
290 const simulator = simulators.find((entry) => entry.udid === requested);
291 if (!simulator)
292 return yield* choose(booted, `No available iOS simulator with UDID ${requested}. Booted:`);
293 if (simulator.state !== "Booted")
294 return yield* new NativeClientError({
295 message: `Boot the selected simulator first: xcrun simctl boot ${requested}`,
296 });
297 return { id: simulator.udid, label: simulator.label };
298 }
299 const attached = (yield* command("adb", ["devices", "-l"]))
300 .split("\n")
301 .slice(1)
302 .map((line) => line.trim().split(/\s+/))
303 .filter((parts) => parts.length >= 2)
304 .map(([id, state, ...details]) => ({
305 id: id!,
306 state: state!,
307 label: details.find((detail) => detail.startsWith("model:"))?.slice(6) ?? id!,
308 }));
309 const ready = attached.filter((device) => device.state === "device");
310 const device =
311 requested === undefined ? ready : attached.filter((entry) => entry.id === requested);
312 if (requested === undefined && ready.length !== 1)
313 return yield* ready.length === 0
314 ? new NativeClientError({
315 message:
316 "No Android emulator or phone is connected. Open one with device_open, or start an emulator.",
317 })
318 : choose(ready, "Several Android devices are connected. Pick one:");
319 const selected = device[0];
320 if (!selected)
321 return yield* choose(ready, `Android device ${requested} is not connected. Ready:`);
322 if (selected.state === "unauthorized")
323 return yield* new NativeClientError({
324 message: `Unlock ${selected.label} and accept the USB debugging prompt, then run this again.`,
325 });
326 if (selected.state !== "device")
327 return yield* new NativeClientError({
328 message: `Android device ${selected.id} is ${selected.state}, not ready.`,
329 });
330 // Emulators report a generic model; their AVD name is what users recognize.
331 const avd = selected.id.startsWith("emulator-")
332 ? yield* command("adb", ["-s", selected.id, "emu", "avd", "name"]).pipe(
333 Effect.map((output) => output.split("\n")[0]?.trim()),
334 Effect.orElseSucceed(() => undefined),
335 )
336 : undefined;
337 return { id: selected.id, label: avd || selected.label };
338});
339
340export const installedBinary = Effect.fn("installedBinary")(function* (
341 platform: NativePlatform,
342 device: string,
343 run: typeof command = command,
344) {
345 if (platform === "ios") {
346 const apps = yield* run("xcrun", ["simctl", "listapps", device]);
347 if (!apps.includes(`"${bundleId}"`)) return null;
348 return yield* hashBundle(
349 yield* run("xcrun", ["simctl", "get_app_container", device, bundleId, "app"]),
350 );
351 }
352 const installed = yield* run("adb", ["-s", device, "shell", "pm", "list", "packages", bundleId]);
353 if (!installed.split("\n").some((line) => line.trim() === `package:${bundleId}`)) return null;
354 const packages = yield* run("adb", ["-s", device, "shell", "pm", "path", bundleId]);
355 const apks = packages
356 .split("\n")
357 .filter((line) => line.startsWith("package:"))
358 .map((line) => line.slice(8).trim())
359 .sort();
360 if (apks.length === 0) return null;
361 const hashes = yield* Effect.forEach(apks, (apk) =>
362 Effect.gen(function* () {
363 if (!/^\/[\w/+=.~-]+\.apk$/.test(apk))
364 return yield* new NativeClientError({ message: "Unexpected installed APK path." });
365 const hash = (yield* run("adb", ["-s", device, "shell", "sha256sum", apk])).split(/\s/)[0];
366 if (!hash || !/^[a-f0-9]{64}$/.test(hash))
367 return yield* new NativeClientError({ message: "Could not hash installed APK." });
368 return hash;
369 }),
370 );
371 return yield* digest(hashes.sort().join("\n"));
372});
373
374/** Preserve input-invalidated Gradle/.cxx caches; exclude app/build because its tasks omit inputs. Ignore cache failures. */
375export const prebuildAndroid = Effect.fn("nativeClient.prebuildAndroid")(function* <E, R>(
376 mobile: string,
377 prebuild: Effect.Effect<void, E, R>,
378) {
379 const fs = yield* FileSystem.FileSystem;
380 const path = yield* Path.Path;
381 const android = path.join(mobile, "android");
382 // Sibling renames stay on one filesystem; interrupted runs leave this gitignored cache for next-run cleanup.
383 const saved = path.join(mobile, ".android-cache");
384 const caches = [".gradle", "app/.cxx"];
385 const clear = fs.remove(saved, { recursive: true, force: true }).pipe(Effect.ignore);
386 const move = (from: string, to: string) =>
387 Effect.forEach(
388 caches,
389 (cache) =>
390 Effect.gen(function* () {
391 const source = path.join(from, cache);
392 const target = path.join(to, cache);
393 if (!(yield* fs.exists(source)) || (yield* fs.exists(target))) return;
394 yield* fs.makeDirectory(path.dirname(target), { recursive: true });
395 yield* fs.rename(source, target);
396 }).pipe(Effect.ignore),
397 { discard: true },
398 );
399 yield* Effect.acquireUseRelease(
400 clear.pipe(Effect.andThen(move(android, saved))),
401 () => prebuild,
402 () => move(saved, android).pipe(Effect.andThen(clear)),
403 );
404});
405
406const artifactNames = { ios: "T3CodeDev.app", android: "app-debug.apk" } as const;
407// R2 requires equal-sized parts and Workers cap request bodies at 100 MB.
408const partSize = 64 * 1024 * 1024;
409const RemoteCredentials = Schema.fromJsonString(
410 Schema.Record(Schema.String, Schema.Struct({ name: Schema.String, token: Schema.String })),
411);
412const decodeCredentials = Schema.decodeUnknownEffect(RemoteCredentials);
413const decodeEndpoint = Schema.decodeUnknownEffect(
414 Schema.fromJsonString(Schema.Struct({ endpoint: Schema.String })),
415);
416const decodeUpload = Schema.decodeUnknownEffect(
417 Schema.Union([
418 Schema.Struct({ exists: Schema.Literal(true) }),
419 Schema.Struct({ uploadId: Schema.String }),
420 ]),
421);
422const decodePart = Schema.decodeUnknownEffect(Schema.Struct({ etag: Schema.String }));
423const decodeEasBuilds = Schema.decodeUnknownEffect(
424 Schema.fromJsonString(
425 Schema.Array(Schema.Struct({ artifacts: Schema.Struct({ buildUrl: Schema.String }) })),
426 ),
427);
428
429interface RemoteCache {
430 readonly url: string;
431 readonly telemetry: string;
432 readonly name: string;
433 readonly token: string;
434}
435
436/** The shared task-cache login (infra/task-cache/install.sh) also authorizes native clients. */
437const remoteCache = Effect.fn("nativeClient.remoteCache")(
438 function* (home: string) {
439 const environment = yield* HostProcess.Environment;
440 if (environment.T3_NATIVE_CLIENT_CACHE === "off") return null;
441 const fs = yield* FileSystem.FileSystem;
442 const path = yield* Path.Path;
443 const { endpoint } = yield* decodeEndpoint(
444 yield* fs.readFileString(path.join((yield* roots).repo, ".task-cache.json")),
445 );
446 const credentials = yield* decodeCredentials(
447 yield* fs.readFileString(path.join(home, ".config/t3-task-cache/credentials.json")),
448 );
449 const login = credentials[endpoint];
450 if (!login) return null;
451 const base = endpoint.replace(/\/$/, "");
452 return {
453 url: `${base}/native-clients`,
454 telemetry: `${base}/telemetry`,
455 ...login,
456 } satisfies RemoteCache;
457 },
458 Effect.orElseSucceed(() => null),
459);
460
461const ReaderLogin = Schema.fromJsonString(
462 Schema.Struct({ name: Schema.String, token: Schema.String }),
463);
464
465/**
466 * A URL another machine can download `key` from. The header goes to that machine, so only a
467 * read-only login (`ci-reader`) is ever handed out, never a developer's writer token.
468 */
469const sharedSource = Effect.fn("nativeClient.sharedSource")(
470 function* (home: string, key: string) {
471 const remote = yield* remoteCache(home);
472 if (!remote) return null;
473 const fs = yield* FileSystem.FileSystem;
474 const path = yield* Path.Path;
475 const reader =
476 remote.name === "ci-reader"
477 ? remote
478 : yield* fs
479 .readFileString(path.join(home, ".config/t3-task-cache/ci-reader.json"))
480 .pipe(Effect.flatMap(Schema.decodeUnknownEffect(ReaderLogin)));
481 const basic = Buffer.from(`${reader.name}:${reader.token}`).toString("base64");
482 return { url: `${remote.url}/${key}`, header: `authorization:Basic ${basic}` };
483 },
484 Effect.orElseSucceed(() => null),
485);
486
487const authorized = (remote: RemoteCache, request: HttpClientRequest.HttpClientRequest) =>
488 request.pipe(HttpClientRequest.basicAuth(remote.name, remote.token));
489
490// Build duration lives beside the artifact so hits can report the time they saved.
491const sidecar = (directory: string) => `${directory}.json`;
492const decodeSidecar = Schema.decodeUnknownEffect(
493 Schema.fromJsonString(Schema.Struct({ buildMs: Schema.Number })),
494);
495const readBuildMs = (directory: string) =>
496 FileSystem.FileSystem.pipe(
497 Effect.flatMap((fs) => fs.readFileString(sidecar(directory))),
498 Effect.flatMap(decodeSidecar),
499 Effect.map(({ buildMs }) => buildMs),
500 Effect.orElseSucceed(() => 0),
501 );
502const writeBuildMs = (directory: string, buildMs: number) =>
503 FileSystem.FileSystem.pipe(
504 Effect.flatMap((fs) => fs.writeFileString(sidecar(directory), JSON.stringify({ buildMs }))),
505 Effect.ignore,
506 );
507
508/** Download into a sibling staging directory and publish only after the digest matches. */
509const download = Effect.fn("nativeClient.download")(function* (
510 remote: RemoteCache,
511 platform: NativePlatform,
512 key: string,
513 target: string,
514) {
515 const fs = yield* FileSystem.FileSystem;
516 const path = yield* Path.Path;
517 const client = yield* HttpClient.HttpClient;
518 const response = yield* client.execute(
519 authorized(remote, HttpClientRequest.get(`${remote.url}/${key}`)),
520 );
521 if (response.status === 404) return false;
522 yield* HttpClientResponse.filterStatusOk(response);
523 const expected = response.headers["x-t3-digest"] ?? "";
524 if (!/^[a-f0-9]{64}$/.test(expected))
525 return yield* new NativeClientError({ message: "Cached native client has no digest." });
526 yield* Console.error(`Downloading native client ${key} from the shared cache...`);
527 const staging = yield* fs.makeTempDirectory({
528 directory: path.dirname(target),
529 prefix: ".download-",
530 });
531 return yield* Effect.gen(function* () {
532 if (platform === "ios") {
533 const archive = `${staging}.tgz`;
534 yield* response.stream.pipe(
535 Stream.run(fs.sink(archive)),
536 Effect.andThen(command("tar", ["-xzf", archive, "-C", staging])),
537 Effect.ensuring(fs.remove(archive, { force: true }).pipe(Effect.ignore)),
538 );
539 } else {
540 yield* response.stream.pipe(Stream.run(fs.sink(path.join(staging, artifactNames.android))));
541 }
542 if ((yield* hashBundle(staging)) !== expected)
543 return yield* new NativeClientError({ message: "Cached native client failed verification." });
544 yield* publish(staging, target);
545 const buildMs = Number(response.headers["x-t3-build-ms"] ?? 0);
546 yield* writeBuildMs(target, Number.isSafeInteger(buildMs) ? buildMs : 0);
547 return true;
548 }).pipe(
549 Effect.ensuring(fs.remove(staging, { recursive: true, force: true }).pipe(Effect.ignore)),
550 );
551});
552
553/** Upload in fixed-size parts; any failure aborts the upload and leaves the cache unchanged. */
554const upload = Effect.fn("nativeClient.upload")(function* (
555 remote: RemoteCache,
556 platform: NativePlatform,
557 key: string,
558 artifact: string,
559) {
560 const fs = yield* FileSystem.FileSystem;
561 const path = yield* Path.Path;
562 const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
563 const created = yield* client
564 .execute(
565 authorized(remote, HttpClientRequest.post(`${remote.url}/${key}/uploads`)).pipe(
566 HttpClientRequest.setHeader("x-t3-digest", yield* hashBundle(artifact)),
567 HttpClientRequest.setHeader("x-t3-build-ms", String(yield* readBuildMs(artifact))),
568 ),
569 )
570 .pipe(
571 Effect.flatMap((response) => response.json),
572 Effect.flatMap(decodeUpload),
573 );
574 if ("exists" in created) return;
575 const uploadUrl = `${remote.url}/${key}/uploads/${encodeURIComponent(created.uploadId)}`;
576 yield* Console.error(`Uploading native client ${key} to the shared cache...`);
577 yield* Effect.gen(function* () {
578 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-native-upload-" });
579 const file =
580 platform === "ios"
581 ? path.join(directory, "client.tgz")
582 : path.join(artifact, artifactNames.android);
583 if (platform === "ios")
584 yield* command("tar", ["-czf", file, "-C", artifact, artifactNames.ios]);
585 const handle = yield* fs.open(file);
586 const parts: Array<{ partNumber: number; etag: string }> = [];
587 for (let partNumber = 1; ; partNumber++) {
588 const buffer = new Uint8Array(partSize);
589 let filled = 0;
590 while (filled < partSize) {
591 const read = Number(yield* handle.read(buffer.subarray(filled)));
592 if (read === 0) break;
593 filled += read;
594 }
595 if (filled === 0) break;
596 const { etag } = yield* client
597 .execute(
598 authorized(remote, HttpClientRequest.put(`${uploadUrl}/${partNumber}`)).pipe(
599 HttpClientRequest.bodyUint8Array(buffer.subarray(0, filled)),
600 ),
601 )
602 .pipe(
603 Effect.flatMap((response) => response.json),
604 Effect.flatMap(decodePart),
605 );
606 parts.push({ partNumber, etag });
607 if (filled < partSize) break;
608 }
609 yield* client.execute(
610 authorized(remote, HttpClientRequest.post(`${uploadUrl}/complete`)).pipe(
611 HttpClientRequest.bodyJsonUnsafe({ parts }),
612 ),
613 );
614 }).pipe(
615 Effect.scoped,
616 Effect.onError(() =>
617 client.execute(authorized(remote, HttpClientRequest.delete(uploadUrl))).pipe(Effect.ignore),
618 ),
619 );
620});
621
622const publish = Effect.fn("nativeClient.publish")(function* (staging: string, target: string) {
623 const fs = yield* FileSystem.FileSystem;
624 // A concurrent ensure may have published the same fingerprint first; either copy is valid.
625 if (yield* fs.exists(target)) return;
626 yield* fs.rename(staging, target);
627});
628
629const easCli = "eas-cli@25.3.0";
630
631/** Xcode builds iOS locally; without it (Linux, or a Mac with no Xcode) EAS builds in the cloud. */
632const hasXcode = Effect.gen(function* () {
633 if ((yield* HostProcess.Platform) !== "darwin") return false;
634 return yield* command("xcrun", ["--find", "xcodebuild"]).pipe(
635 Effect.as(true),
636 Effect.orElseSucceed(() => false),
637 );
638});
639
640/** Without Xcode, EAS builds the same simulator client from this checkout. */
641const buildIosOnEas = Effect.fn("nativeClient.buildIosOnEas")(function* (staging: string) {
642 const fs = yield* FileSystem.FileSystem;
643 const path = yield* Path.Path;
644 // Fail before any work when neither builder is available.
645 yield* command("npx", ["-y", easCli, "whoami"]).pipe(
646 Effect.mapError(
647 () =>
648 new NativeClientError({
649 message:
650 "iOS builds need Xcode on macOS, or an EAS login (`npx eas-cli login`, or EXPO_TOKEN) to build in the cloud.",
651 }),
652 ),
653 );
654 yield* Console.error("No Xcode here; building the iOS simulator client on EAS (10-30 min).");
655 const [build] = yield* decodeEasBuilds(
656 yield* command("npx", [
657 "-y",
658 easCli,
659 "build",
660 "--platform",
661 "ios",
662 "--profile",
663 "development-simulator",
664 "--non-interactive",
665 "--wait",
666 "--json",
667 ]),
668 );
669 if (!build) return yield* new NativeClientError({ message: "EAS returned no build." });
670 const archive = path.join(staging, "eas-build.tar.gz");
671 yield* command("curl", ["-fsSL", "--retry", "3", "-o", archive, build.artifacts.buildUrl]);
672 yield* command("tar", ["-xzf", archive, "-C", staging]);
673 yield* fs.remove(archive);
674 const app = (yield* fs.readDirectory(staging)).find((name) => name.endsWith(".app"));
675 if (!app) return yield* new NativeClientError({ message: "The EAS build archive has no .app." });
676 if (app !== artifactNames.ios)
677 yield* fs.rename(path.join(staging, app), path.join(staging, artifactNames.ios));
678});
679
680const build = Effect.fn("nativeClient.build")(function* (
681 platform: NativePlatform,
682 abi: string | null,
683 target: string,
684 expected: string,
685) {
686 const fs = yield* FileSystem.FileSystem;
687 const path = yield* Path.Path;
688 const { repo, mobile } = yield* roots;
689 const tracked = yield* command("git", ["ls-files", `apps/mobile/${platform}`], false, repo);
690 if (tracked)
691 return yield* new NativeClientError({
692 message: "Native directory contains tracked files; clean prebuild would overwrite them.",
693 });
694 const prebuild = command(
695 "vp",
696 ["exec", "expo", "prebuild", "--clean", "--platform", platform, "--no-install"],
697 true,
698 ).pipe(Effect.asVoid);
699 const onEas = platform === "ios" && !(yield* hasXcode);
700 if (platform === "android") yield* prebuildAndroid(mobile, prebuild);
701 else if (!onEas) yield* prebuild;
702 const staging = yield* fs.makeTempDirectory({
703 directory: path.dirname(target),
704 prefix: ".build-",
705 });
706 yield* Effect.gen(function* () {
707 if (onEas) {
708 yield* buildIosOnEas(staging);
709 } else if (platform === "ios") {
710 const output = yield* fs.makeTempDirectoryScoped({ prefix: "t3-native-client-" });
711 yield* command("pod", ["install"], true, path.join(mobile, "ios"));
712 // One device-independent arm64 simulator build installs on every iPhone and iPad simulator.
713 yield* command(
714 "xcrun",
715 [
716 "xcodebuild",
717 "-workspace",
718 path.join(mobile, "ios/T3CodeDev.xcworkspace"),
719 "-scheme",
720 "T3CodeDev",
721 "-configuration",
722 "Debug",
723 "-destination",
724 "generic/platform=iOS Simulator",
725 "-derivedDataPath",
726 output,
727 "ARCHS=arm64",
728 "ONLY_ACTIVE_ARCH=NO",
729 "build",
730 ],
731 true,
732 );
733 yield* command("ditto", [
734 path.join(output, "Build/Products/Debug-iphonesimulator", artifactNames.ios),
735 path.join(staging, artifactNames.ios),
736 ]);
737 } else {
738 const android = path.join(mobile, "android");
739 yield* command(
740 path.join(android, (yield* HostProcess.Platform) === "win32" ? "gradlew.bat" : "gradlew"),
741 ["app:assembleDebug", `-PreactNativeArchitectures=${abi}`],
742 true,
743 android,
744 );
745 yield* fs.copyFile(
746 path.join(android, "app/build/outputs/apk/debug", artifactNames.android),
747 path.join(staging, artifactNames.android),
748 );
749 }
750 // Native edits during the build would publish this binary under a fingerprint it doesn't match.
751 if ((yield* fingerprint(platform)) !== expected)
752 return yield* new NativeClientError({
753 message: "Native inputs changed during the build, so it was discarded. Run this again.",
754 });
755 yield* publish(staging, target);
756 }).pipe(
757 Effect.scoped,
758 Effect.ensuring(fs.remove(staging, { recursive: true, force: true }).pipe(Effect.ignore)),
759 );
760});
761
762/** Keep the newest few fingerprints per platform; each artifact is a few hundred megabytes. */
763const prune = Effect.fn("nativeClient.prune")(
764 function* (parent: string, keep: string) {
765 const fs = yield* FileSystem.FileSystem;
766 const path = yield* Path.Path;
767 const entries = yield* Effect.forEach(
768 (yield* fs.readDirectory(parent)).filter(
769 (name) => !name.startsWith(".") && !name.endsWith(".json"),
770 ),
771 (name) =>
772 fs.stat(path.join(parent, name)).pipe(
773 Effect.map((info) => ({
774 name,
775 modified: Option.getOrUndefined(info.mtime)?.getTime() ?? 0,
776 })),
777 ),
778 );
779 const stale = entries
780 .filter(({ name }) => name !== keep)
781 .sort((a, b) => b.modified - a.modified)
782 .slice(2);
783 yield* Effect.forEach(
784 stale,
785 ({ name }) =>
786 fs
787 .remove(path.join(parent, name), { recursive: true, force: true })
788 .pipe(Effect.andThen(fs.remove(sidecar(path.join(parent, name)), { force: true }))),
789 { discard: true },
790 );
791 },
792 (effect) => Effect.ignore(effect),
793);
794
795/** Local artifact, then the shared cache, then a build that is shared back when credentials allow. */
796export const resolveArtifact = Effect.fn("nativeClient.resolveArtifact")(function* (
797 home: string,
798 platform: NativePlatform,
799 abi: string | null,
800 fingerprint: string,
801) {
802 const fs = yield* FileSystem.FileSystem;
803 const path = yield* Path.Path;
804 const key = `${platform}/${abi ? `development-${abi}` : "development"}/${fingerprint}`;
805 const directory = path.join(home, ".cache/t3code/native-clients/artifacts", key);
806 const artifact = { directory, file: path.join(directory, artifactNames[platform]) };
807 if (yield* fs.exists(artifact.file)) {
808 yield* Console.error(`Using cached client ${key}.`);
809 // Pruning keeps the most recently used, so a client another checkout is installing stays.
810 const now = yield* Clock.currentTimeMillis;
811 yield* fs.utimes(directory, now / 1000, now / 1000).pipe(Effect.ignore);
812 return { ...artifact, source: "local" as const, buildMs: yield* readBuildMs(directory) };
813 }
814 yield* fs.makeDirectory(path.dirname(directory), { recursive: true });
815 const remote = yield* remoteCache(home);
816 if (remote) {
817 const downloaded = yield* download(remote, platform, key, directory).pipe(
818 Effect.catch((error) =>
819 Console.error(`Shared native client cache unavailable (${describe(error)}).`).pipe(
820 Effect.as(false),
821 ),
822 ),
823 );
824 if (downloaded) {
825 yield* prune(path.dirname(directory), fingerprint);
826 return { ...artifact, source: "remote" as const, buildMs: yield* readBuildMs(directory) };
827 }
828 }
829 const log = yield* BuildLog;
830 yield* Console.error(
831 `No cached client for ${key}. Building it once for every machine (5-15 min)${log ? `. Log: ${log}` : ""}`,
832 );
833 const started = yield* Clock.currentTimeMillis;
834 yield* build(platform, abi, directory, fingerprint);
835 yield* writeBuildMs(directory, (yield* Clock.currentTimeMillis) - started);
836 yield* prune(path.dirname(directory), fingerprint);
837 if (remote && (yield* HostProcess.Environment).T3_NATIVE_CLIENT_CACHE !== "read") {
838 yield* upload(remote, platform, key, directory).pipe(
839 Effect.catch((error) => Console.error(`Native client was not shared (${describe(error)}).`)),
840 );
841 }
842 return { ...artifact, source: "build" as const, buildMs: 0 };
843});
844
845const describe = (error: unknown) =>
846 typeof error === "object" &&
847 error !== null &&
848 "message" in error &&
849 typeof error.message === "string"
850 ? error.message
851 : String(error);
852
853const install = Effect.fn("nativeClient.install")(function* (
854 platform: NativePlatform,
855 device: string,
856 file: string,
857) {
858 if (platform === "ios") {
859 yield* command("xcrun", ["simctl", "install", device, file], true);
860 return;
861 }
862 yield* command("adb", ["-s", device, "install", "-r", "-d", file]).pipe(
863 Effect.catchTags({
864 NativeClientError: (error) =>
865 Effect.fail(
866 error.message.includes("INSTALL_FAILED_UPDATE_INCOMPATIBLE")
867 ? new NativeClientError({
868 message: `The installed client has a different signature. Remove it with adb -s ${device} uninstall ${bundleId} (this clears its pairings), then run ensure again.`,
869 })
870 : error,
871 ),
872 }),
873 );
874 // Emulators reach Metro through 10.0.2.2; a phone on USB needs the port forwarded.
875 if ((yield* command("adb", ["-s", device, "shell", "getprop", "ro.kernel.qemu"])) !== "1")
876 yield* command("adb", ["-s", device, "reverse", "tcp:8081", "tcp:8081"]).pipe(Effect.ignore);
877});
878
879const reportTelemetry = Effect.fn("nativeClient.reportTelemetry")(
880 function* (
881 home: string,
882 task: string,
883 source: "local" | "remote" | "executed" | "failed",
884 savedMs: number,
885 ) {
886 const remote = yield* remoteCache(home);
887 if (!remote) return;
888 const environment = yield* HostProcess.Environment;
889 const recordedAt = yield* Clock.currentTimeMillis;
890 // Same machine label as Vite task reports (infra/task-cache/src/telemetry.ts).
891 const fs = yield* FileSystem.FileSystem;
892 const machine = yield* fs.readFileString(`${home}/.agents/MACHINE`).pipe(
893 Effect.map((value) => value.trim()),
894 Effect.orElseSucceed(() => ""),
895 );
896 const host =
897 environment.T3_TASK_CACHE_HOST ||
898 machine ||
899 (environment.GITHUB_ACTIONS === "true"
900 ? `${environment.RUNNER_ENVIRONMENT || "github"}/${environment.RUNNER_OS}/${environment.RUNNER_ARCH}`
901 : yield* HostProcess.Hostname);
902 const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
903 yield* client.execute(
904 authorized(remote, HttpClientRequest.post(remote.telemetry)).pipe(
905 HttpClientRequest.bodyJsonUnsafe({
906 id: yield* digest(`${host}:${task}:${recordedAt}:${yield* Random.nextInt}`),
907 recordedAt,
908 host,
909 platform: yield* HostProcess.Platform,
910 arch: yield* HostProcess.Architecture,
911 ci: environment.CI === "true" || environment.CI === "1",
912 runId: environment.GITHUB_RUN_ID ?? "",
913 tasks: [{ package: "@t3tools/mobile", task, source, savedMs: Math.round(savedMs) }],
914 }),
915 ),
916 );
917 },
918 (effect) => effect.pipe(Effect.timeout("5 seconds"), Effect.ignore),
919);
920
921/**
922 * Install into an agent-device session the caller already opened (a device pool, a cloud
923 * provider, or a local device). A cache miss builds here, as for a local device: the device
924 * only runs the client.
925 */
926const installIntoSession = Effect.fn("nativeClient.installIntoSession")(function* (
927 home: string,
928 platform: NativePlatform,
929 session: string,
930 abi: string,
931 metro: string | undefined,
932) {
933 const started = yield* Clock.currentTimeMillis;
934 const path = yield* Path.Path;
935 const node = yield* HostProcess.ExecutablePath;
936 const agentDevice = path.join(
937 (yield* roots).repo,
938 "scripts/node_modules/agent-device/bin/agent-device.mjs",
939 );
940 // agent-device scopes session ownership to the workspace (working directory) it runs in.
941 const workspace = yield* HostProcess.WorkingDirectory;
942 const deviceAbi = platform === "android" ? abi : null;
943 const task = deviceAbi ? `native-client:android-${deviceAbi}` : `native-client:${platform}`;
944 const current = yield* fingerprint(platform);
945 const key = `${platform}/${deviceAbi ? `development-${deviceAbi}` : "development"}/${current}`;
946 const source = yield* sharedSource(home, key);
947 // The session's host downloads the client itself; uploading a 166 MB APK through a
948 // gateway from here takes minutes and can outlast the remote install timeout.
949 const downloadOnDevice = source
950 ? command(
951 node,
952 [
953 agentDevice,
954 "install-from-source",
955 source.url,
956 "--header",
957 source.header,
958 "--session",
959 session,
960 ],
961 true,
962 workspace,
963 ).pipe(
964 Effect.as(true),
965 Effect.catch((error) =>
966 Console.error(`The device could not download ${key} (${describe(error)}).`).pipe(
967 Effect.as(false),
968 ),
969 ),
970 )
971 : Effect.succeed(false);
972 const fetched = yield* downloadOnDevice;
973 const artifact = fetched
974 ? { source: "remote" as const, buildMs: 0 }
975 : yield* Effect.gen(function* () {
976 const local = yield* resolveArtifact(home, platform, deviceAbi, current).pipe(
977 Effect.tapError(() => reportTelemetry(home, task, "failed", 0)),
978 );
979 // A build just shared the client, so the device can fetch it now too.
980 if (local.source === "build" && (yield* downloadOnDevice)) return local;
981 yield* Console.error(`Installing into agent-device session ${session}...`);
982 yield* command(
983 node,
984 [agentDevice, "install", bundleId, local.file, "--session", session],
985 true,
986 workspace,
987 );
988 return local;
989 });
990 if (metro) {
991 const url = encodeURIComponent(metro);
992 yield* command(
993 node,
994 [
995 agentDevice,
996 "open",
997 bundleId,
998 `t3code-dev://expo-development-client/?url=${url}&disableOnboarding=1&disableFab=1&disableAutoLaunch=1`,
999 "--session",
1000 session,
1001 ],
1002 true,
1003 workspace,
1004 );
1005 }
1006 yield* reportTelemetry(
1007 home,
1008 task,
1009 artifact.source === "build" ? "executed" : artifact.source,
1010 artifact.buildMs,
1011 );
1012 const seconds = Math.round(((yield* Clock.currentTimeMillis) - started) / 1000);
1013 yield* Console.error(
1014 `Installed into session ${session} in ${seconds}s (${artifact.source}).${metro ? "" : " Open it with Metro: --metro http://<this-machine>:8081."}`,
1015 );
1016 yield* Console.log(
1017 yield* encodeOutput({
1018 status: "installed",
1019 source: artifact.source,
1020 fingerprint: current,
1021 session,
1022 seconds,
1023 }),
1024 );
1025});
1026
1027const main = Command.make(
1028 "mobile-native-client",
1029 {
1030 mode: Argument.Literals("mode", ["check", "ensure"]),
1031 platform: Argument.Literals("platform", ["ios", "android"]),
1032 device: Argument.String("device").pipe(Argument.optional),
1033 session: Flag.String("session").pipe(
1034 Flag.withDescription(
1035 "Install into this already-open agent-device session (a device pool, cloud, or remote host) instead of a local device.",
1036 ),
1037 Flag.optional,
1038 ),
1039 abi: Flag.Literals("abi", ["x86_64", "arm64-v8a"]).pipe(
1040 Flag.withDescription("Android ABI of the session's device (default x86_64)."),
1041 Flag.withDefault("x86_64" as const),
1042 ),
1043 metro: Flag.String("metro").pipe(
1044 Flag.withDescription("With --session, open the dev client against this Metro URL."),
1045 Flag.optional,
1046 ),
1047 prepare: Flag.Boolean("prepare").pipe(
1048 Flag.withDescription(
1049 "Fetch or build the client for this checkout without a device (Android: for --abi). Run it before leasing a device: a build can outlast the lease.",
1050 ),
1051 Flag.withDefault(false),
1052 ),
1053 },
1054 Effect.fn("nativeClient.main")(function* ({
1055 mode,
1056 platform,
1057 device: requested,
1058 session,
1059 abi: sessionAbi,
1060 metro,
1061 prepare,
1062 }) {
1063 const started = yield* Clock.currentTimeMillis;
1064 if (prepare) {
1065 if (mode !== "ensure" || Option.isSome(requested) || Option.isSome(session))
1066 return yield* new NativeClientError({
1067 message: "--prepare needs no device; use it with ensure and no device id or --session.",
1068 });
1069 const environment = yield* HostProcess.Environment;
1070 const home = environment.HOME ?? environment.USERPROFILE;
1071 if (!home)
1072 return yield* new NativeClientError({ message: "HOME or USERPROFILE must be set." });
1073 const current = yield* fingerprint(platform);
1074 const artifact = yield* resolveArtifact(
1075 home,
1076 platform,
1077 platform === "android" ? sessionAbi : null,
1078 current,
1079 );
1080 yield* Console.error(
1081 `Client ready for ${platform} (${artifact.source}); lease a device and install.`,
1082 );
1083 return yield* Console.log(
1084 yield* encodeOutput({ status: "ready", source: artifact.source, fingerprint: current }),
1085 );
1086 }
1087 if (Option.isSome(session)) {
1088 if (mode !== "ensure" || Option.isSome(requested))
1089 return yield* new NativeClientError({
1090 message:
1091 "--session installs into an agent-device session; use it with ensure and no device id.",
1092 });
1093 const environment = yield* HostProcess.Environment;
1094 const home = environment.HOME ?? environment.USERPROFILE;
1095 if (!home)
1096 return yield* new NativeClientError({ message: "HOME or USERPROFILE must be set." });
1097 return yield* installIntoSession(
1098 home,
1099 platform,
1100 session.value,
1101 sessionAbi,
1102 Option.getOrUndefined(metro),
1103 );
1104 }
1105 const target = yield* resolveDevice(platform, Option.getOrUndefined(requested));
1106 const device = target.id;
1107 yield* Console.error(`Device: ${target.label} (${device})`);
1108 const fs = yield* FileSystem.FileSystem;
1109 const path = yield* Path.Path;
1110 const environment = yield* HostProcess.Environment;
1111 const home = environment.HOME ?? environment.USERPROFILE;
1112 if (!home)
1113 return yield* new NativeClientError({
1114 message: "HOME or USERPROFILE must be set to store native client records.",
1115 });
1116 const cache = path.join(home, ".cache/t3code/native-clients");
1117 const recordPath = path.join(cache, platform, `${yield* digest(device)}.json`);
1118 // An iOS simulator build is arm64 for every device; an APK carries only the device's own ABI.
1119 const abi = Effect.gen(function* () {
1120 if (platform === "ios") return null;
1121 const value = yield* command("adb", ["-s", device, "shell", "getprop", "ro.product.cpu.abi"]);
1122 if (value !== "x86_64" && value !== "arm64-v8a")
1123 return yield* new NativeClientError({ message: `Unsupported Android ABI ${value}.` });
1124 return value;
1125 });
1126 let task = `native-client:${platform}`;
1127 let savedMs = 0;
1128 const operations = {
1129 fingerprint: fingerprint(platform),
1130 installedBinary: installedBinary(platform, device),
1131 readRecord: fs.readFileString(recordPath).pipe(
1132 Effect.flatMap(decodeRecord),
1133 Effect.catchTags({ SchemaError: () => Effect.succeed(null) }),
1134 Effect.catchIf(
1135 (error) => error.reason._tag === "NotFound",
1136 () => Effect.succeed(null),
1137 ),
1138 ),
1139 install: Effect.fn(function* (fingerprint: string) {
1140 const deviceAbi = yield* abi;
1141 if (deviceAbi) task = `native-client:android-${deviceAbi}`;
1142 const artifact = yield* resolveArtifact(home, platform, deviceAbi, fingerprint);
1143 savedMs = artifact.buildMs;
1144 yield* Console.error(`Installing on ${target.label}...`);
1145 yield* install(platform, device, artifact.file);
1146 return artifact.source;
1147 }),
1148 saveRecord: Effect.fn(function* (record: NativeClientRecord) {
1149 yield* fs.makeDirectory(path.dirname(recordPath), { recursive: true });
1150 yield* fs.writeFileString(recordPath, yield* encodeRecord(record));
1151 }),
1152 };
1153 if (mode === "check") {
1154 const current = yield* operations.fingerprint;
1155 const status = clientStatus(
1156 current,
1157 yield* operations.installedBinary,
1158 yield* operations.readRecord,
1159 );
1160 yield* Console.log(
1161 yield* encodeOutput({
1162 status,
1163 fingerprint: current,
1164 device,
1165 next:
1166 status === "compatible"
1167 ? "Start Metro with vp run dev:client"
1168 : `vp run mobile:install ${platform} ${device}`,
1169 }),
1170 );
1171 process.exitCode = status === "compatible" ? 0 : 2;
1172 return;
1173 }
1174 const logs = path.join(cache, "logs");
1175 yield* fs.makeDirectory(logs, { recursive: true });
1176 yield* prune(logs, "");
1177 const stamp = DateTime.formatIso(DateTime.makeUnsafe(started)).replaceAll(":", "-");
1178 const log = path.join(logs, `${stamp}-${platform}.log`);
1179 const result = yield* ensureClient(operations).pipe(
1180 Effect.provideService(BuildLog, environment.T3_NATIVE_CLIENT_VERBOSE === "1" ? null : log),
1181 Effect.tapError(() => reportTelemetry(home, task, "failed", 0)),
1182 );
1183 if (result.installed && result.source)
1184 yield* reportTelemetry(
1185 home,
1186 task,
1187 result.source === "build" ? "executed" : result.source,
1188 result.source === "build" ? 0 : savedMs,
1189 );
1190 const seconds = Math.round(((yield* Clock.currentTimeMillis) - started) / 1000);
1191 yield* Console.error(
1192 result.installed
1193 ? `Installed on ${target.label} in ${seconds}s (${result.source}). Next: start Metro with vp run dev:client.`
1194 : `${target.label} already has the client for this checkout. Next: start Metro with vp run dev:client.`,
1195 );
1196 yield* Console.log(yield* encodeOutput({ ...result, device, seconds }));
1197 }),
1198);
1199
1200if (import.meta.main) {
1201 Command.run(main, { version: "0.0.0" }).pipe(
1202 // Expected failures carry their next step; a stack trace only buries it.
1203 Effect.catchTags({
1204 NativeClientError: (error) =>
1205 Console.error(error.message).pipe(
1206 Effect.andThen(Effect.sync(() => (process.exitCode = 1))),
1207 ),
1208 }),
1209 Effect.scoped,
1210 Effect.provide([NodeServices.layer, FetchHttpClient.layer]),
1211 NodeRuntime.runMain,
1212 );
1213}