Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

mobile-native-client.ts

1,066 lines41.9 KB

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";
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 }));
423​
424interface RemoteCache {
425 readonly url: string;
426 readonly telemetry: string;
427 readonly name: string;
428 readonly token: string;
430​
431/** The shared task-cache login (infra/task-cache/install.sh) also authorizes native clients. */
432const remoteCache = Effect.fn("nativeClient.remoteCache")(
433 function* (home: string) {
434 const environment = yield* HostProcess.Environment;
435 if (environment.T3_NATIVE_CLIENT_CACHE === "off") return null;
436 const fs = yield* FileSystem.FileSystem;
437 const path = yield* Path.Path;
438 const { endpoint } = yield* decodeEndpoint(
439 yield* fs.readFileString(path.join((yield* roots).repo, ".task-cache.json")),
440 );
441 const credentials = yield* decodeCredentials(
442 yield* fs.readFileString(path.join(home, ".config/t3-task-cache/credentials.json")),
443 );
444 const login = credentials[endpoint];
445 if (!login) return null;
446 const base = endpoint.replace(/\/$/, "");
447 return {
448 url: `${base}/native-clients`,
449 telemetry: `${base}/telemetry`,
450 ...login,
451 } satisfies RemoteCache;
452 },
453 Effect.orElseSucceed(() => null),
454);
455​
456const authorized = (remote: RemoteCache, request: HttpClientRequest.HttpClientRequest) =>
457 request.pipe(HttpClientRequest.basicAuth(remote.name, remote.token));
458​
459// Build duration lives beside the artifact so hits can report the time they saved.
460const sidecar = (directory: string) => `${directory}.json`;
461const decodeSidecar = Schema.decodeUnknownEffect(
462 Schema.fromJsonString(Schema.Struct({ buildMs: Schema.Number })),
463);
464const readBuildMs = (directory: string) =>
465 FileSystem.FileSystem.pipe(
466 Effect.flatMap((fs) => fs.readFileString(sidecar(directory))),
467 Effect.flatMap(decodeSidecar),
468 Effect.map(({ buildMs }) => buildMs),
469 Effect.orElseSucceed(() => 0),
470 );
471const writeBuildMs = (directory: string, buildMs: number) =>
472 FileSystem.FileSystem.pipe(
473 Effect.flatMap((fs) => fs.writeFileString(sidecar(directory), JSON.stringify({ buildMs }))),
474 Effect.ignore,
475 );
476​
477/** Download into a sibling staging directory and publish only after the digest matches. */
478const download = Effect.fn("nativeClient.download")(function* (
479 remote: RemoteCache,
480 platform: NativePlatform,
481 key: string,
482 target: string,
483) {
484 const fs = yield* FileSystem.FileSystem;
485 const path = yield* Path.Path;
486 const client = yield* HttpClient.HttpClient;
487 const response = yield* client.execute(
488 authorized(remote, HttpClientRequest.get(`${remote.url}/${key}`)),
489 );
490 if (response.status === 404) return false;
491 yield* HttpClientResponse.filterStatusOk(response);
492 const expected = response.headers["x-t3-digest"] ?? "";
493 if (!/^[a-f0-9]{64}$/.test(expected))
494 return yield* new NativeClientError({ message: "Cached native client has no digest." });
495 yield* Console.error(`Downloading native client ${key} from the shared cache...`);
496 const staging = yield* fs.makeTempDirectory({
497 directory: path.dirname(target),
498 prefix: ".download-",
499 });
500 return yield* Effect.gen(function* () {
501 if (platform === "ios") {
502 const archive = `${staging}.tgz`;
503 yield* response.stream.pipe(
504 Stream.run(fs.sink(archive)),
505 Effect.andThen(command("tar", ["-xzf", archive, "-C", staging])),
506 Effect.ensuring(fs.remove(archive, { force: true }).pipe(Effect.ignore)),
507 );
508 } else {
509 yield* response.stream.pipe(Stream.run(fs.sink(path.join(staging, artifactNames.android))));
510 }
511 if ((yield* hashBundle(staging)) !== expected)
512 return yield* new NativeClientError({ message: "Cached native client failed verification." });
513 yield* publish(staging, target);
514 const buildMs = Number(response.headers["x-t3-build-ms"] ?? 0);
515 yield* writeBuildMs(target, Number.isSafeInteger(buildMs) ? buildMs : 0);
516 return true;
517 }).pipe(
518 Effect.ensuring(fs.remove(staging, { recursive: true, force: true }).pipe(Effect.ignore)),
519 );
520});
521​
522/** Upload in fixed-size parts; any failure aborts the upload and leaves the cache unchanged. */
523const upload = Effect.fn("nativeClient.upload")(function* (
524 remote: RemoteCache,
525 platform: NativePlatform,
526 key: string,
527 artifact: string,
528) {
529 const fs = yield* FileSystem.FileSystem;
530 const path = yield* Path.Path;
531 const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
532 const created = yield* client
533 .execute(
534 authorized(remote, HttpClientRequest.post(`${remote.url}/${key}/uploads`)).pipe(
535 HttpClientRequest.setHeader("x-t3-digest", yield* hashBundle(artifact)),
536 HttpClientRequest.setHeader("x-t3-build-ms", String(yield* readBuildMs(artifact))),
537 ),
538 )
539 .pipe(
540 Effect.flatMap((response) => response.json),
541 Effect.flatMap(decodeUpload),
542 );
543 if ("exists" in created) return;
544 const uploadUrl = `${remote.url}/${key}/uploads/${encodeURIComponent(created.uploadId)}`;
545 yield* Console.error(`Uploading native client ${key} to the shared cache...`);
546 yield* Effect.gen(function* () {
547 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-native-upload-" });
548 const file =
549 platform === "ios"
550 ? path.join(directory, "client.tgz")
551 : path.join(artifact, artifactNames.android);
552 if (platform === "ios")
553 yield* command("tar", ["-czf", file, "-C", artifact, artifactNames.ios]);
554 const handle = yield* fs.open(file);
555 const parts: Array<{ partNumber: number; etag: string }> = [];
556 for (let partNumber = 1; ; partNumber++) {
557 const buffer = new Uint8Array(partSize);
558 let filled = 0;
559 while (filled < partSize) {
560 const read = Number(yield* handle.read(buffer.subarray(filled)));
561 if (read === 0) break;
562 filled += read;
563 }
564 if (filled === 0) break;
565 const { etag } = yield* client
566 .execute(
567 authorized(remote, HttpClientRequest.put(`${uploadUrl}/${partNumber}`)).pipe(
568 HttpClientRequest.bodyUint8Array(buffer.subarray(0, filled)),
569 ),
570 )
571 .pipe(
572 Effect.flatMap((response) => response.json),
573 Effect.flatMap(decodePart),
574 );
575 parts.push({ partNumber, etag });
576 if (filled < partSize) break;
577 }
578 yield* client.execute(
579 authorized(remote, HttpClientRequest.post(`${uploadUrl}/complete`)).pipe(
580 HttpClientRequest.bodyJsonUnsafe({ parts }),
581 ),
582 );
583 }).pipe(
584 Effect.scoped,
585 Effect.onError(() =>
586 client.execute(authorized(remote, HttpClientRequest.delete(uploadUrl))).pipe(Effect.ignore),
587 ),
588 );
589});
590​
591const publish = Effect.fn("nativeClient.publish")(function* (staging: string, target: string) {
592 const fs = yield* FileSystem.FileSystem;
593 // A concurrent ensure may have published the same fingerprint first; either copy is valid.
594 if (yield* fs.exists(target)) return;
595 yield* fs.rename(staging, target);
596});
597​
598const build = Effect.fn("nativeClient.build")(function* (
599 platform: NativePlatform,
600 abi: string | null,
601 target: string,
602 expected: string,
603) {
604 const fs = yield* FileSystem.FileSystem;
605 const path = yield* Path.Path;
606 const { repo, mobile } = yield* roots;
607 const tracked = yield* command("git", ["ls-files", `apps/mobile/${platform}`], false, repo);
608 if (tracked)
609 return yield* new NativeClientError({
610 message: "Native directory contains tracked files; clean prebuild would overwrite them.",
611 });
612 const prebuild = command(
613 "vp",
614 ["exec", "expo", "prebuild", "--clean", "--platform", platform, "--no-install"],
615 true,
616 ).pipe(Effect.asVoid);
617 yield* platform === "android" ? prebuildAndroid(mobile, prebuild) : prebuild;
618 const staging = yield* fs.makeTempDirectory({
619 directory: path.dirname(target),
620 prefix: ".build-",
621 });
622 yield* Effect.gen(function* () {
623 if (platform === "ios") {
624 const output = yield* fs.makeTempDirectoryScoped({ prefix: "t3-native-client-" });
625 yield* command("pod", ["install"], true, path.join(mobile, "ios"));
626 // One device-independent arm64 simulator build installs on every iPhone and iPad simulator.
627 yield* command(
628 "xcrun",
629 [
630 "xcodebuild",
631 "-workspace",
632 path.join(mobile, "ios/T3CodeDev.xcworkspace"),
633 "-scheme",
634 "T3CodeDev",
635 "-configuration",
636 "Debug",
637 "-destination",
638 "generic/platform=iOS Simulator",
639 "-derivedDataPath",
640 output,
641 "ARCHS=arm64",
642 "ONLY_ACTIVE_ARCH=NO",
643 "build",
644 ],
645 true,
646 );
647 yield* command("ditto", [
648 path.join(output, "Build/Products/Debug-iphonesimulator", artifactNames.ios),
649 path.join(staging, artifactNames.ios),
650 ]);
651 } else {
652 const android = path.join(mobile, "android");
653 yield* command(
654 path.join(android, (yield* HostProcess.Platform) === "win32" ? "gradlew.bat" : "gradlew"),
655 ["app:assembleDebug", `-PreactNativeArchitectures=${abi}`],
656 true,
657 android,
658 );
659 yield* fs.copyFile(
660 path.join(android, "app/build/outputs/apk/debug", artifactNames.android),
661 path.join(staging, artifactNames.android),
662 );
663 }
664 // Native edits during the build would publish this binary under a fingerprint it doesn't match.
665 if ((yield* fingerprint(platform)) !== expected)
666 return yield* new NativeClientError({
667 message: "Native inputs changed during the build, so it was discarded. Run this again.",
668 });
669 yield* publish(staging, target);
670 }).pipe(
671 Effect.scoped,
672 Effect.ensuring(fs.remove(staging, { recursive: true, force: true }).pipe(Effect.ignore)),
673 );
674});
675​
676/** Keep the newest few fingerprints per platform; each artifact is a few hundred megabytes. */
677const prune = Effect.fn("nativeClient.prune")(
678 function* (parent: string, keep: string) {
679 const fs = yield* FileSystem.FileSystem;
680 const path = yield* Path.Path;
681 const entries = yield* Effect.forEach(
682 (yield* fs.readDirectory(parent)).filter(
683 (name) => !name.startsWith(".") && !name.endsWith(".json"),
684 ),
685 (name) =>
686 fs.stat(path.join(parent, name)).pipe(
687 Effect.map((info) => ({
688 name,
689 modified: Option.getOrUndefined(info.mtime)?.getTime() ?? 0,
690 })),
691 ),
692 );
693 const stale = entries
694 .filter(({ name }) => name !== keep)
695 .sort((a, b) => b.modified - a.modified)
696 .slice(2);
697 yield* Effect.forEach(
698 stale,
699 ({ name }) =>
700 fs
701 .remove(path.join(parent, name), { recursive: true, force: true })
702 .pipe(Effect.andThen(fs.remove(sidecar(path.join(parent, name)), { force: true }))),
703 { discard: true },
704 );
705 },
706 (effect) => Effect.ignore(effect),
707);
708​
709/** Local artifact, then the shared cache, then a build that is shared back when credentials allow. */
710export const resolveArtifact = Effect.fn("nativeClient.resolveArtifact")(function* (
711 home: string,
712 platform: NativePlatform,
713 abi: string | null,
714 fingerprint: string,
715 allowBuild = true,
716) {
717 const fs = yield* FileSystem.FileSystem;
718 const path = yield* Path.Path;
719 const key = `${platform}/${abi ? `development-${abi}` : "development"}/${fingerprint}`;
720 const directory = path.join(home, ".cache/t3code/native-clients/artifacts", key);
721 const artifact = { directory, file: path.join(directory, artifactNames[platform]) };
722 if (yield* fs.exists(artifact.file)) {
723 yield* Console.error(`Using cached client ${key}.`);
724 // Pruning keeps the most recently used, so a client another checkout is installing stays.
725 const now = yield* Clock.currentTimeMillis;
726 yield* fs.utimes(directory, now / 1000, now / 1000).pipe(Effect.ignore);
727 return { ...artifact, source: "local" as const, buildMs: yield* readBuildMs(directory) };
728 }
729 yield* fs.makeDirectory(path.dirname(directory), { recursive: true });
730 const remote = yield* remoteCache(home);
731 if (remote) {
732 const downloaded = yield* download(remote, platform, key, directory).pipe(
733 Effect.catch((error) =>
734 Console.error(`Shared native client cache unavailable (${describe(error)}).`).pipe(
735 Effect.as(false),
736 ),
737 ),
738 );
739 if (downloaded) {
740 yield* prune(path.dirname(directory), fingerprint);
741 return { ...artifact, source: "remote" as const, buildMs: yield* readBuildMs(directory) };
742 }
743 }
744 if (!allowBuild)
745 return yield* new NativeClientError({
746 message: `No shared build of ${key} yet. Run \`vp run mobile:install ${platform}\` once on a machine with a local ${platform === "ios" ? "simulator" : "emulator"} of this checkout; it builds the client and shares it.`,
747 });
748 const log = yield* BuildLog;
749 yield* Console.error(
750 `No cached client for ${key}. Building it once for every machine (5-15 min)${log ? `. Log: ${log}` : ""}`,
751 );
752 const started = yield* Clock.currentTimeMillis;
753 yield* build(platform, abi, directory, fingerprint);
754 yield* writeBuildMs(directory, (yield* Clock.currentTimeMillis) - started);
755 yield* prune(path.dirname(directory), fingerprint);
756 if (remote && (yield* HostProcess.Environment).T3_NATIVE_CLIENT_CACHE !== "read") {
757 yield* upload(remote, platform, key, directory).pipe(
758 Effect.catch((error) => Console.error(`Native client was not shared (${describe(error)}).`)),
759 );
760 }
761 return { ...artifact, source: "build" as const, buildMs: 0 };
762});
763​
764const describe = (error: unknown) =>
765 typeof error === "object" &&
766 error !== null &&
767 "message" in error &&
768 typeof error.message === "string"
769 ? error.message
770 : String(error);
771​
772const install = Effect.fn("nativeClient.install")(function* (
773 platform: NativePlatform,
774 device: string,
775 file: string,
776) {
777 if (platform === "ios") {
778 yield* command("xcrun", ["simctl", "install", device, file], true);
779 return;
780 }
781 yield* command("adb", ["-s", device, "install", "-r", "-d", file]).pipe(
782 Effect.catchTags({
783 NativeClientError: (error) =>
784 Effect.fail(
785 error.message.includes("INSTALL_FAILED_UPDATE_INCOMPATIBLE")
786 ? new NativeClientError({
787 message: `The installed client has a different signature. Remove it with adb -s ${device} uninstall ${bundleId} (this clears its pairings), then run ensure again.`,
788 })
789 : error,
790 ),
791 }),
792 );
793 // Emulators reach Metro through 10.0.2.2; a phone on USB needs the port forwarded.
794 if ((yield* command("adb", ["-s", device, "shell", "getprop", "ro.kernel.qemu"])) !== "1")
795 yield* command("adb", ["-s", device, "reverse", "tcp:8081", "tcp:8081"]).pipe(Effect.ignore);
796});
797​
798const reportTelemetry = Effect.fn("nativeClient.reportTelemetry")(
799 function* (
800 home: string,
801 task: string,
802 source: "local" | "remote" | "executed" | "failed",
803 savedMs: number,
804 ) {
805 const remote = yield* remoteCache(home);
806 if (!remote) return;
807 const environment = yield* HostProcess.Environment;
808 const recordedAt = yield* Clock.currentTimeMillis;
809 // Same machine label as Vite task reports (infra/task-cache/src/telemetry.ts).
810 const fs = yield* FileSystem.FileSystem;
811 const machine = yield* fs.readFileString(`${home}/.agents/MACHINE`).pipe(
812 Effect.map((value) => value.trim()),
813 Effect.orElseSucceed(() => ""),
814 );
815 const host =
816 environment.T3_TASK_CACHE_HOST ||
817 machine ||
818 (environment.GITHUB_ACTIONS === "true"
819 ? `${environment.RUNNER_ENVIRONMENT || "github"}/${environment.RUNNER_OS}/${environment.RUNNER_ARCH}`
820 : yield* HostProcess.Hostname);
821 const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
822 yield* client.execute(
823 authorized(remote, HttpClientRequest.post(remote.telemetry)).pipe(
824 HttpClientRequest.bodyJsonUnsafe({
825 id: yield* digest(`${host}:${task}:${recordedAt}:${yield* Random.nextInt}`),
826 recordedAt,
827 host,
828 platform: yield* HostProcess.Platform,
829 arch: yield* HostProcess.Architecture,
830 ci: environment.CI === "true" || environment.CI === "1",
831 runId: environment.GITHUB_RUN_ID ?? "",
832 tasks: [{ package: "@t3tools/mobile", task, source, savedMs: Math.round(savedMs) }],
833 }),
834 ),
835 );
836 },
837 (effect) => effect.pipe(Effect.timeout("5 seconds"), Effect.ignore),
838);
839​
840/**
841 * Install into an agent-device session the caller already opened (a device pool, a cloud
842 * provider, or a local device), using the shared cache only; such hosts cannot build.
843 */
844const installIntoSession = Effect.fn("nativeClient.installIntoSession")(function* (
845 home: string,
846 platform: NativePlatform,
847 session: string,
848 abi: string,
849 metro: string | undefined,
850) {
851 const started = yield* Clock.currentTimeMillis;
852 const path = yield* Path.Path;
853 const node = yield* HostProcess.ExecutablePath;
854 const agentDevice = path.join(
855 (yield* roots).repo,
856 "scripts/node_modules/agent-device/bin/agent-device.mjs",
857 );
858 // agent-device scopes session ownership to the workspace (working directory) it runs in.
859 const workspace = yield* HostProcess.WorkingDirectory;
860 const deviceAbi = platform === "android" ? abi : null;
861 const task = deviceAbi ? `native-client:android-${deviceAbi}` : `native-client:${platform}`;
862 const current = yield* fingerprint(platform);
863 const artifact = yield* resolveArtifact(home, platform, deviceAbi, current, false).pipe(
864 Effect.tapError(() => reportTelemetry(home, task, "failed", 0)),
865 );
866 yield* Console.error(`Installing into agent-device session ${session}...`);
867 yield* command(
868 node,
869 [agentDevice, "install", bundleId, artifact.file, "--session", session],
870 true,
871 workspace,
872 );
873 if (metro) {
874 const url = encodeURIComponent(metro);
875 yield* command(
876 node,
877 [
878 agentDevice,
879 "open",
880 bundleId,
881 `t3code-dev://expo-development-client/?url=${url}&disableOnboarding=1&disableFab=1&disableAutoLaunch=1`,
882 "--session",
883 session,
884 ],
885 true,
886 workspace,
887 );
888 }
889 yield* reportTelemetry(
890 home,
891 task,
892 artifact.source === "build" ? "executed" : artifact.source,
893 artifact.buildMs,
894 );
895 const seconds = Math.round(((yield* Clock.currentTimeMillis) - started) / 1000);
896 yield* Console.error(
897 `Installed into session ${session} in ${seconds}s (${artifact.source}).${metro ? "" : " Open it with Metro: --metro http://<this-machine>:8081."}`,
898 );
899 yield* Console.log(
900 yield* encodeOutput({
901 status: "installed",
902 source: artifact.source,
903 fingerprint: current,
904 session,
905 seconds,
906 }),
907 );
908});
909​
910const main = Command.make(
911 "mobile-native-client",
912 {
913 mode: Argument.Literals("mode", ["check", "ensure"]),
914 platform: Argument.Literals("platform", ["ios", "android"]),
915 device: Argument.String("device").pipe(Argument.optional),
916 session: Flag.String("session").pipe(
917 Flag.withDescription(
918 "Install into this already-open agent-device session (a device pool, cloud, or remote host) instead of a local device.",
919 ),
920 Flag.optional,
921 ),
922 abi: Flag.Literals("abi", ["x86_64", "arm64-v8a"]).pipe(
923 Flag.withDescription("Android ABI of the session's device (default x86_64)."),
924 Flag.withDefault("x86_64" as const),
925 ),
926 metro: Flag.String("metro").pipe(
927 Flag.withDescription("With --session, open the dev client against this Metro URL."),
928 Flag.optional,
929 ),
930 },
931 Effect.fn("nativeClient.main")(function* ({
932 mode,
933 platform,
934 device: requested,
935 session,
936 abi: sessionAbi,
937 metro,
938 }) {
939 const started = yield* Clock.currentTimeMillis;
940 if (Option.isSome(session)) {
941 if (mode !== "ensure" || Option.isSome(requested))
942 return yield* new NativeClientError({
943 message:
944 "--session installs into an agent-device session; use it with ensure and no device id.",
945 });
946 const environment = yield* HostProcess.Environment;
947 const home = environment.HOME ?? environment.USERPROFILE;
948 if (!home)
949 return yield* new NativeClientError({ message: "HOME or USERPROFILE must be set." });
950 return yield* installIntoSession(
951 home,
952 platform,
953 session.value,
954 sessionAbi,
955 Option.getOrUndefined(metro),
956 );
957 }
958 const target = yield* resolveDevice(platform, Option.getOrUndefined(requested));
959 const device = target.id;
960 yield* Console.error(`Device: ${target.label} (${device})`);
961 const fs = yield* FileSystem.FileSystem;
962 const path = yield* Path.Path;
963 const environment = yield* HostProcess.Environment;
964 const home = environment.HOME ?? environment.USERPROFILE;
965 if (!home)
966 return yield* new NativeClientError({
967 message: "HOME or USERPROFILE must be set to store native client records.",
968 });
969 const cache = path.join(home, ".cache/t3code/native-clients");
970 const recordPath = path.join(cache, platform, `${yield* digest(device)}.json`);
971 // An iOS simulator build is arm64 for every device; an APK carries only the device's own ABI.
972 const abi = Effect.gen(function* () {
973 if (platform === "ios") return null;
974 const value = yield* command("adb", ["-s", device, "shell", "getprop", "ro.product.cpu.abi"]);
975 if (value !== "x86_64" && value !== "arm64-v8a")
976 return yield* new NativeClientError({ message: `Unsupported Android ABI ${value}.` });
977 return value;
978 });
979 let task = `native-client:${platform}`;
980 let savedMs = 0;
981 const operations = {
982 fingerprint: fingerprint(platform),
983 installedBinary: installedBinary(platform, device),
984 readRecord: fs.readFileString(recordPath).pipe(
985 Effect.flatMap(decodeRecord),
986 Effect.catchTags({ SchemaError: () => Effect.succeed(null) }),
987 Effect.catchIf(
988 (error) => error.reason._tag === "NotFound",
989 () => Effect.succeed(null),
990 ),
991 ),
992 install: Effect.fn(function* (fingerprint: string) {
993 const deviceAbi = yield* abi;
994 if (deviceAbi) task = `native-client:android-${deviceAbi}`;
995 const artifact = yield* resolveArtifact(home, platform, deviceAbi, fingerprint);
996 savedMs = artifact.buildMs;
997 yield* Console.error(`Installing on ${target.label}...`);
998 yield* install(platform, device, artifact.file);
999 return artifact.source;
1000 }),
1001 saveRecord: Effect.fn(function* (record: NativeClientRecord) {
1002 yield* fs.makeDirectory(path.dirname(recordPath), { recursive: true });
1003 yield* fs.writeFileString(recordPath, yield* encodeRecord(record));
1004 }),
1005 };
1006 if (mode === "check") {
1007 const current = yield* operations.fingerprint;
1008 const status = clientStatus(
1009 current,
1010 yield* operations.installedBinary,
1011 yield* operations.readRecord,
1012 );
1013 yield* Console.log(
1014 yield* encodeOutput({
1015 status,
1016 fingerprint: current,
1017 device,
1018 next:
1019 status === "compatible"
1020 ? "Start Metro with vp run dev:client"
1021 : `vp run mobile:install ${platform} ${device}`,
1022 }),
1023 );
1024 process.exitCode = status === "compatible" ? 0 : 2;
1025 return;
1027 const logs = path.join(cache, "logs");
1028 yield* fs.makeDirectory(logs, { recursive: true });
1029 yield* prune(logs, "");
1030 const stamp = DateTime.formatIso(DateTime.makeUnsafe(started)).replaceAll(":", "-");
1031 const log = path.join(logs, `${stamp}-${platform}.log`);
1032 const result = yield* ensureClient(operations).pipe(
1033 Effect.provideService(BuildLog, environment.T3_NATIVE_CLIENT_VERBOSE === "1" ? null : log),
1034 Effect.tapError(() => reportTelemetry(home, task, "failed", 0)),
1035 );
1036 if (result.installed && result.source)
1037 yield* reportTelemetry(
1038 home,
1039 task,
1040 result.source === "build" ? "executed" : result.source,
1041 result.source === "build" ? 0 : savedMs,
1042 );
1043 const seconds = Math.round(((yield* Clock.currentTimeMillis) - started) / 1000);
1044 yield* Console.error(
1045 result.installed
1046 ? `Installed on ${target.label} in ${seconds}s (${result.source}). Next: start Metro with vp run dev:client.`
1047 : `${target.label} already has the client for this checkout. Next: start Metro with vp run dev:client.`,
1048 );
1049 yield* Console.log(yield* encodeOutput({ ...result, device, seconds }));
1050 }),
1052​
1053if (import.meta.main) {
1054 Command.run(main, { version: "0.0.0" }).pipe(
1055 // Expected failures carry their next step; a stack trace only buries it.
1056 Effect.catchTags({
1057 NativeClientError: (error) =>
1058 Console.error(error.message).pipe(
1059 Effect.andThen(Effect.sync(() => (process.exitCode = 1))),
1060 ),
1061 }),
1062 Effect.scoped,
1063 Effect.provide([NodeServices.layer, FetchHttpClient.layer]),
1064 NodeRuntime.runMain,
1065 );