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