@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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