The best way to control Claude Code, Codex and more from any computer or phone
ci(mobile): dev clients build on Blacksmith, and mobile:install starts that build (#33617)
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Julius Marminge committed
Nov 9, 2026 at 17:52 UTC
83862afe7419f1d5812b8de98350c0c63cbd96b7
6 files changed
+573
-8
.agents/skills/test-t3-mobile/SKILL.md
+3
-2
@@ -36,8 +36,9 @@ vp run mobile:install <ios|android> <device-id>
36
37
This installs the dev client for the checkout's native fingerprint: from the
38
device, the local cache, or the shared cache in seconds, building once only
39
-when no machine has that fingerprint yet (5-15 minutes, logged to the file it
40
-names). The device id may be omitted when exactly one device is booted. It
39
+when no machine has that fingerprint yet: in the `Mobile Dev Client` workflow
40
+on Blacksmith when HEAD is pushed and `gh` may dispatch it (the command waits),
41
+otherwise here (5-15 minutes, logged to the file it names). The device id may be omitted when exactly one device is booted. It
42
prints one JSON line; on failure it names the next command. Mobile verification
43
includes that step unless the user prohibits it.
44
.github/workflows/mobile-dev-client.yml
new
+315
@@ -0,0 +1,315 @@
1
+name: Mobile Dev Client
2
+run-name: ${{ github.event_name == 'workflow_dispatch' && format('Dev client {0}{1} {2}', inputs.platform, inputs.platform == 'android' && format(' {0}', inputs.abi) || '', inputs.fingerprint) || '' }}
3
+
4
+# Builds the simulator and emulator development client for a commit's native
5
+# fingerprint and shares it through the native-client cache, the one
6
+# `vp run mobile:install` reads on every machine. Android builds with Gradle,
7
+# ccache, and pnpm state on a sticky disk; iOS builds on a macOS runner, so no
8
+# machine needs Xcode or an EAS build for it.
9
+#
10
+# - push to main: main's client is cached before anyone asks for it.
11
+# - workflow_dispatch: `mobile:install` starts this for the checkout's HEAD on a
12
+# cache miss, when the person running it may dispatch workflows here, and
13
+# waits for the client in the cache. The run name is how it finds its run.
14
+# - pull_request (this file or the script): builds without sharing, as a check.
15
+on:
16
+ push:
17
+ branches: [main]
18
+ paths:
19
+ - apps/mobile/**
20
+ - packages/client-runtime/**
21
+ - packages/contracts/**
22
+ - packages/shared/**
23
+ - assets/**
24
+ - patches/**
25
+ - scripts/mobile-native-client.ts
26
+ - package.json
27
+ - pnpm-lock.yaml
28
+ - pnpm-workspace.yaml
29
+ - .github/workflows/mobile-dev-client.yml
30
+ pull_request:
31
+ paths:
32
+ - .github/workflows/mobile-dev-client.yml
33
+ - scripts/mobile-native-client.ts
34
+ workflow_dispatch:
35
+ inputs:
36
+ ref:
37
+ description: Commit to build (default main)
38
+ required: false
39
+ type: string
40
+ platform:
41
+ description: Platform
42
+ required: true
43
+ default: android
44
+ type: choice
45
+ options: [android, ios]
46
+ abi:
47
+ description: Android ABI of the device
48
+ required: true
49
+ default: x86_64
50
+ type: choice
51
+ options: [x86_64, arm64-v8a]
52
+ fingerprint:
53
+ description: Native fingerprint the caller expects; the run fails when the commit's differs
54
+ required: false
55
+ type: string
56
+
57
+permissions:
58
+ contents: read
59
+
60
+jobs:
61
+ android:
62
+ name: Android ${{ matrix.abi }}
63
+ if: github.repository == 'pingdotgg/t3code' && (github.event_name != 'workflow_dispatch' || inputs.platform == 'android')
64
+ runs-on: blacksmith-32vcpu-ubuntu-2404
65
+ timeout-minutes: 45
66
+ strategy:
67
+ fail-fast: false
68
+ matrix:
69
+ # Pool emulators are x86_64; a dispatch builds the ABI it asks for.
70
+ abi: ${{ github.event_name == 'workflow_dispatch' && fromJSON(format('["{0}"]', inputs.abi)) || fromJSON('["x86_64"]') }}
71
+ concurrency:
72
+ # One run per client: a second request for the same fingerprint waits and finds it
73
+ # in the cache. A shared group would drop every waiting run but the newest.
74
+ group: mobile-dev-client-android-${{ matrix.abi }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || inputs.fingerprint || github.sha }}
75
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
76
+ env:
77
+ NODE_OPTIONS: --max-old-space-size=8192
78
+ ABI: ${{ matrix.abi }}
79
+ EXPECTED_FINGERPRINT: ${{ inputs.fingerprint }}
80
+ # A pull request checks that the build works: it builds even on a cache hit and shares nothing.
81
+ T3_NATIVE_CLIENT_CACHE: ${{ github.event_name == 'pull_request' && 'off' || '' }}
82
+ # Gradle and Xcode output goes to the job log, not a file on the runner.
83
+ T3_NATIVE_CLIENT_VERBOSE: "1"
84
+ steps:
85
+ - name: Checkout
86
+ uses: actions/checkout@v6
87
+ with:
88
+ ref: ${{ inputs.ref || github.sha }}
89
+
90
+ # A dispatch names any commit GitHub has, including a fork's. Only a commit that
91
+ # collaborators pushed here builds with the cache login and the shared disk.
92
+ - name: Check the commit belongs to this repository
93
+ if: github.event_name == 'workflow_dispatch'
94
+ env:
95
+ GH_TOKEN: ${{ github.token }}
96
+ run: |
97
+ sha="$(git rev-parse HEAD)"
98
+ if git ls-remote --heads origin | grep -q "^$sha"; then
99
+ exit 0
100
+ fi
101
+ status="$(gh api "repos/$GITHUB_REPOSITORY/compare/$sha...main" --jq .status || true)"
102
+ if [ "$status" = "ahead" ] || [ "$status" = "identical" ]; then
103
+ exit 0
104
+ fi
105
+ echo "::error::$sha is not the head of a branch in $GITHUB_REPOSITORY and not on main; build it locally."
106
+ exit 1
107
+
108
+ # The build runs dependency scripts; it gets no token. checkout keeps the token in a
109
+ # file under RUNNER_TEMP that .git/config includes, so both go. `persist-credentials:
110
+ # false` fails here: its cleanup runs `git submodule foreach`, which stops at the
111
+ # vendored gitlinks under .repos (no .gitmodules entry).
112
+ - name: Drop checkout credentials
113
+ run: |
114
+ git config --local --get-regexp '^includeif\..*\.path$' | while read -r key file; do
115
+ rm -f "$file"
116
+ git config --local --unset-all "$key"
117
+ done
118
+ git config --local --name-only --get-regexp '^http\..*\.extraheader$' | while read -r key; do
119
+ git config --local --unset-all "$key"
120
+ done
121
+ rm -f "$RUNNER_TEMP"/git-credentials-*.config
122
+ if git config --local --get-regexp 'extraheader|includeif' || ls "$RUNNER_TEMP"/git-credentials-*.config 2>/dev/null; then
123
+ echo "::error::checkout credentials are still present"
124
+ exit 1
125
+ fi
126
+
127
+ - name: Prepare build directories
128
+ run: |
129
+ cache="$HOME/.cache/t3-android-dev-client"
130
+ {
131
+ echo "GRADLE_USER_HOME=$cache/gradle"
132
+ echo "CCACHE_DIR=$cache/ccache"
133
+ echo "CCACHE_MAXSIZE=5G"
134
+ # Gradle installs the NDK fresh each run, so key on the compiler's version, not its mtime.
135
+ echo "CCACHE_COMPILERCHECK=%compiler% -v"
136
+ # The checkout path is the same on every run, so ccache keys stay stable.
137
+ echo "CCACHE_BASEDIR=$GITHUB_WORKSPACE"
138
+ # CMake (3.17+) reads these, and AGP passes Gradle's environment through.
139
+ echo "CMAKE_C_COMPILER_LAUNCHER=ccache"
140
+ echo "CMAKE_CXX_COMPILER_LAUNCHER=ccache"
141
+ } >> "$GITHUB_ENV"
142
+
143
+ # Pull requests build cold: their code must not write Gradle or ccache state that
144
+ # the runs holding the cache login restore.
145
+ - name: Mount build cache
146
+ if: github.event_name != 'pull_request'
147
+ uses: useblacksmith/stickydisk@v1
148
+ with:
149
+ key: ${{ github.repository }}-android-dev-client-${{ matrix.abi }}
150
+ path: ~/.cache/t3-android-dev-client
151
+
152
+ - name: Configure Gradle and ccache
153
+ run: |
154
+ mkdir -p "$GRADLE_USER_HOME" "$CCACHE_DIR"
155
+ # No daemon: nothing should hold the sticky disk open when it is committed.
156
+ printf 'org.gradle.caching=true\norg.gradle.daemon=false\n' > "$GRADLE_USER_HOME/gradle.properties"
157
+ sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources
158
+ sudo apt-get update -qq && sudo apt-get install -y -qq ccache
159
+ ccache --zero-stats
160
+
161
+ - name: Setup dependencies
162
+ uses: ./.github/actions/setup-ci-deps
163
+ with:
164
+ task-cache-read-token: ${{ secrets.T3_TASK_CACHE_READ_TOKEN }}
165
+ install-args: --filter=@t3tools/mobile... --filter=@t3tools/scripts...
166
+
167
+ - name: Setup Java
168
+ uses: actions/setup-java@v5
169
+ with:
170
+ distribution: temurin
171
+ java-version: 17
172
+
173
+ # Only this step's login can write to the cache; pull requests never get it.
174
+ # Only this login can write to the cache; pull requests never get it.
175
+ - id: login
176
+ name: Log in to the native client cache
177
+ if: github.event_name != 'pull_request'
178
+ env:
179
+ WRITE_TOKEN: ${{ secrets.T3_NATIVE_CLIENT_WRITE_TOKEN }}
180
+ run: |
181
+ if [ -z "$WRITE_TOKEN" ]; then
182
+ echo "::warning::T3_NATIVE_CLIENT_WRITE_TOKEN is not set; nothing can be shared, so nothing is built."
183
+ exit 0
184
+ fi
185
+ node --input-type=module <<'NODE'
186
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
187
+ import { homedir } from "node:os";
188
+ import { join } from "node:path";
189
+ const { endpoint } = JSON.parse(readFileSync(".task-cache.json", "utf8"));
190
+ const directory = join(homedir(), ".config/t3-task-cache");
191
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
192
+ writeFileSync(
193
+ join(directory, "credentials.json"),
194
+ JSON.stringify({ [endpoint]: { name: "ci-native-clients", token: process.env.WRITE_TOKEN } }),
195
+ { mode: 0o600 },
196
+ );
197
+ NODE
198
+ echo "T3_NATIVE_CLIENT_SHARE=required" >> "$GITHUB_ENV"
199
+ echo "ready=true" >> "$GITHUB_OUTPUT"
200
+
201
+ - name: Build and share
202
+ if: github.event_name == 'pull_request' || steps.login.outputs.ready == 'true'
203
+ shell: bash # pipefail: a failed build fails the step through tee
204
+ run: |
205
+ node scripts/mobile-native-client.ts ensure android --prepare --abi "$ABI" ${EXPECTED_FINGERPRINT:+--expect-fingerprint "$EXPECTED_FINGERPRINT"} | tee "$RUNNER_TEMP/dev-client.log"
206
+ result="$(tail -n 1 "$RUNNER_TEMP/dev-client.log")"
207
+ echo "### android dev client: \`$(jq -r '.source' <<<"$result")\` for fingerprint \`$(jq -r '.fingerprint' <<<"$result")\`" >> "$GITHUB_STEP_SUMMARY"
208
+
209
+ - name: Cache statistics
210
+ if: success() || failure()
211
+ continue-on-error: true
212
+ run: |
213
+ {
214
+ echo '```'
215
+ ccache --show-stats
216
+ echo '```'
217
+ } >> "$GITHUB_STEP_SUMMARY"
218
+
219
+ ios:
220
+ name: iOS simulator
221
+ if: github.repository == 'pingdotgg/t3code' && (github.event_name != 'workflow_dispatch' || inputs.platform == 'ios')
222
+ runs-on: blacksmith-12vcpu-macos-26
223
+ timeout-minutes: 60
224
+ concurrency:
225
+ group: mobile-dev-client-ios-${{ github.event_name == 'pull_request' && github.event.pull_request.number || inputs.fingerprint || github.sha }}
226
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
227
+ env:
228
+ NODE_OPTIONS: --max-old-space-size=8192
229
+ EXPECTED_FINGERPRINT: ${{ inputs.fingerprint }}
230
+ T3_NATIVE_CLIENT_CACHE: ${{ github.event_name == 'pull_request' && 'off' || '' }}
231
+ # Gradle and Xcode output goes to the job log, not a file on the runner.
232
+ T3_NATIVE_CLIENT_VERBOSE: "1"
233
+ steps:
234
+ - name: Checkout
235
+ uses: actions/checkout@v6
236
+ with:
237
+ ref: ${{ inputs.ref || github.sha }}
238
+
239
+ # A dispatch names any commit GitHub has, including a fork's. Only a commit that
240
+ # collaborators pushed here builds with the cache login and the shared disk.
241
+ - name: Check the commit belongs to this repository
242
+ if: github.event_name == 'workflow_dispatch'
243
+ env:
244
+ GH_TOKEN: ${{ github.token }}
245
+ run: |
246
+ sha="$(git rev-parse HEAD)"
247
+ if git ls-remote --heads origin | grep -q "^$sha"; then
248
+ exit 0
249
+ fi
250
+ status="$(gh api "repos/$GITHUB_REPOSITORY/compare/$sha...main" --jq .status || true)"
251
+ if [ "$status" = "ahead" ] || [ "$status" = "identical" ]; then
252
+ exit 0
253
+ fi
254
+ echo "::error::$sha is not the head of a branch in $GITHUB_REPOSITORY and not on main; build it locally."
255
+ exit 1
256
+
257
+ # The build runs dependency scripts; it gets no token. checkout keeps the token in a
258
+ # file under RUNNER_TEMP that .git/config includes, so both go. `persist-credentials:
259
+ # false` fails here: its cleanup runs `git submodule foreach`, which stops at the
260
+ # vendored gitlinks under .repos (no .gitmodules entry).
261
+ - name: Drop checkout credentials
262
+ run: |
263
+ git config --local --get-regexp '^includeif\..*\.path$' | while read -r key file; do
264
+ rm -f "$file"
265
+ git config --local --unset-all "$key"
266
+ done
267
+ git config --local --name-only --get-regexp '^http\..*\.extraheader$' | while read -r key; do
268
+ git config --local --unset-all "$key"
269
+ done
270
+ rm -f "$RUNNER_TEMP"/git-credentials-*.config
271
+ if git config --local --get-regexp 'extraheader|includeif' || ls "$RUNNER_TEMP"/git-credentials-*.config 2>/dev/null; then
272
+ echo "::error::checkout credentials are still present"
273
+ exit 1
274
+ fi
275
+
276
+ - name: Setup dependencies
277
+ uses: ./.github/actions/setup-ci-deps
278
+ with:
279
+ task-cache-read-token: ${{ secrets.T3_TASK_CACHE_READ_TOKEN }}
280
+ install-args: --filter=@t3tools/mobile... --filter=@t3tools/scripts...
281
+
282
+ # Only this login can write to the cache; pull requests never get it.
283
+ - id: login
284
+ name: Log in to the native client cache
285
+ if: github.event_name != 'pull_request'
286
+ env:
287
+ WRITE_TOKEN: ${{ secrets.T3_NATIVE_CLIENT_WRITE_TOKEN }}
288
+ run: |
289
+ if [ -z "$WRITE_TOKEN" ]; then
290
+ echo "::warning::T3_NATIVE_CLIENT_WRITE_TOKEN is not set; nothing can be shared, so nothing is built."
291
+ exit 0
292
+ fi
293
+ node --input-type=module <<'NODE'
294
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
295
+ import { homedir } from "node:os";
296
+ import { join } from "node:path";
297
+ const { endpoint } = JSON.parse(readFileSync(".task-cache.json", "utf8"));
298
+ const directory = join(homedir(), ".config/t3-task-cache");
299
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
300
+ writeFileSync(
301
+ join(directory, "credentials.json"),
302
+ JSON.stringify({ [endpoint]: { name: "ci-native-clients", token: process.env.WRITE_TOKEN } }),
303
+ { mode: 0o600 },
304
+ );
305
+ NODE
306
+ echo "T3_NATIVE_CLIENT_SHARE=required" >> "$GITHUB_ENV"
307
+ echo "ready=true" >> "$GITHUB_OUTPUT"
308
+
309
+ - name: Build and share
310
+ if: github.event_name == 'pull_request' || steps.login.outputs.ready == 'true'
311
+ shell: bash # pipefail: a failed build fails the step through tee
312
+ run: |
313
+ node scripts/mobile-native-client.ts ensure ios --prepare ${EXPECTED_FINGERPRINT:+--expect-fingerprint "$EXPECTED_FINGERPRINT"} | tee "$RUNNER_TEMP/dev-client.log"
314
+ result="$(tail -n 1 "$RUNNER_TEMP/dev-client.log")"
315
+ echo "### ios dev client: \`$(jq -r '.source' <<<"$result")\` for fingerprint \`$(jq -r '.fingerprint' <<<"$result")\`" >> "$GITHUB_STEP_SUMMARY"
apps/mobile/README.md
+5
-1
@@ -35,7 +35,11 @@ The device argument can be omitted when exactly one device is booted or connecte
35
compares this checkout's Expo fingerprint and the installed binary with its last install record,
36
and reuses a matching client. Otherwise it installs the build for that fingerprint from
37
`~/.cache/t3code/native-clients/artifacts`, then the shared task cache, and builds only when
38
-neither has it. One iOS simulator build serves every iPhone and iPad simulator, and one APK per
38
+neither has it. A build runs in the `Mobile Dev Client` workflow (Blacksmith runners with warm
39
+Gradle and ccache state, and a macOS runner for iOS) when `gh` may dispatch workflows on
40
+`pingdotgg/t3code` and HEAD is pushed; the helper waits for the client in the shared cache.
41
+Otherwise, or when HEAD lacks your native edits or `T3_NATIVE_CLIENT_BUILD=local` is set, it builds
42
+on this machine. Main's client is built there on every native change, so most checkouts hit. One iOS simulator build serves every iPhone and iPad simulator, and one APK per
43
ABI (x86_64 or arm64-v8a) serves every emulator and phone of that ABI. Build output goes to the
44
log file it prints (`T3_NATIVE_CLIENT_VERBOSE=1` streams it instead). Builds are shared back when
45
your task-cache login (`bash infra/task-cache/install.sh`) can write. `T3_NATIVE_CLIENT_CACHE=read`
infra/task-cache/README.md
+1
-1
@@ -53,7 +53,7 @@ The smoke check uploads a unique fixture, restores its output into a cold second
53
54
## Native clients
55
56
-`/projects/t3code/native-clients/<platform>/<variant>/<expo-fingerprint>` stores simulator and emulator development clients for `scripts/mobile-native-client.ts` in a separate `-native-clients` R2 bucket with 30-day retention. Unlike Vite Task entries, the Expo fingerprint is portable, so a client built on any Mac or Linux machine serves every other one. Readers download; writers upload through R2 multipart in 64 MB parts, because Workers cap request bodies. The uploader's bundle digest is stored as object metadata and checked by the client before it installs anything.
56
+`/projects/t3code/native-clients/<platform>/<variant>/<expo-fingerprint>` stores simulator and emulator development clients for `scripts/mobile-native-client.ts` in a separate `-native-clients` R2 bucket with 30-day retention. Unlike Vite Task entries, the Expo fingerprint is portable, so a client built on any Mac or Linux machine serves every other one. The `Mobile Dev Client` workflow builds them on Blacksmith and uploads as the writer `ci-native-clients` (`node infra/task-cache/scripts/manage.ts add-writer ci-native-clients`, deploy, then put the token from the file it writes in the repository secret `T3_NATIVE_CLIENT_WRITE_TOKEN`); without that secret the workflow builds nothing. Readers download; writers upload through R2 multipart in 64 MB parts, because Workers cap request bodies. The uploader's bundle digest is stored as object metadata and checked by the client before it installs anything.
57
58
## Current limits
59
scripts/mobile-native-client.test.ts
+67
-1
@@ -4,7 +4,12 @@ import * as Effect from "effect/Effect";
4
import * as FileSystem from "effect/FileSystem";
5
import * as Path from "effect/Path";
6
7
-import { NativeClientError, prebuildAndroid } from "./mobile-native-client.ts";
7
+import {
8
+ buildRunTitle,
9
+ NativeClientError,
10
+ prebuildAndroid,
11
+ remoteBuildState,
12
+} from "./mobile-native-client.ts";
13
14
const caches = [".gradle/history", "app/.cxx/object"];
15
@@ -61,3 +66,64 @@ it.layer(NodeServices.layer)("prebuildAndroid", (it) => {
66
}),
67
);
68
});
69
+
70
+it("finds a Blacksmith build by its run title and reads its state", () => {
71
+ const fingerprint = "a".repeat(40);
72
+ const title = buildRunTitle("android", "x86_64", fingerprint);
73
+ assert.strictEqual(title, `Dev client android x86_64 ${fingerprint}`);
74
+ assert.strictEqual(buildRunTitle("ios", null, fingerprint), `Dev client ios ${fingerprint}`);
75
+ const run = (
76
+ createdAt: string,
77
+ status: string,
78
+ conclusion: string | null,
79
+ displayTitle = title,
80
+ ) => ({
81
+ displayTitle,
82
+ status,
83
+ conclusion,
84
+ createdAt,
85
+ });
86
+ const since = Date.parse("2026-11-09T12:00:00Z");
87
+ assert.strictEqual(remoteBuildState([], title, since), "none");
88
+ // Another client's run, and a run from before this wait, say nothing about this build.
89
+ assert.strictEqual(
90
+ remoteBuildState(
91
+ [
92
+ run(
93
+ "2026-11-09T12:05:00Z",
94
+ "in_progress",
95
+ null,
96
+ buildRunTitle("android", "arm64-v8a", fingerprint),
97
+ ),
98
+ run("2026-11-09T11:00:00Z", "completed", "failure"),
99
+ ],
100
+ title,
101
+ since,
102
+ ),
103
+ "none",
104
+ );
105
+ assert.strictEqual(
106
+ remoteBuildState([run("2026-11-09T12:01:00Z", "queued", null)], title, since),
107
+ "running",
108
+ );
109
+ assert.strictEqual(
110
+ remoteBuildState([run("2026-11-09T12:01:00Z", "completed", "success")], title, since),
111
+ "succeeded",
112
+ );
113
+ // The newest run decides: a retry that is running outranks the failure before it.
114
+ assert.strictEqual(
115
+ remoteBuildState(
116
+ [
117
+ run("2026-11-09T12:01:00Z", "completed", "failure"),
118
+ run("2026-11-09T12:09:00Z", "in_progress", null),
119
+ ],
120
+ title,
121
+ since,
122
+ ),
123
+ "running",
124
+ );
125
+ assert.strictEqual(
126
+ remoteBuildState([run("2026-11-09T12:01:00Z", "completed", "cancelled")], title, since),
127
+ "failed",
128
+ );
129
+});
scripts/mobile-native-client.ts
+182
-3
@@ -793,7 +793,161 @@ const prune = Effect.fn("nativeClient.prune")(
793
(effect) => Effect.ignore(effect),
794
);
795
796
-/** Local artifact, then the shared cache, then a build that is shared back when credentials allow. */
796
+const buildWorkflow = "mobile-dev-client.yml";
797
+const WorkflowRun = Schema.Struct({
798
+ displayTitle: Schema.String,
799
+ status: Schema.String,
800
+ conclusion: Schema.NullOr(Schema.String),
801
+ createdAt: Schema.String,
802
+});
803
+const decodeWorkflowRuns = Schema.decodeUnknownEffect(
804
+ Schema.fromJsonString(Schema.Array(WorkflowRun)),
805
+);
806
+
807
+/** The workflow names each run after the client it builds, which is how a waiting machine finds it. */
808
+export const buildRunTitle = (platform: NativePlatform, abi: string | null, fingerprint: string) =>
809
+ `Dev client ${platform}${abi ? ` ${abi}` : ""} ${fingerprint}`;
810
+
811
+export type RemoteBuildState = "none" | "running" | "failed" | "succeeded";
812
+
813
+/** The newest run with this title that was created at or after `sinceMs`. */
814
+export const remoteBuildState = (
815
+ runs: ReadonlyArray<typeof WorkflowRun.Type>,
816
+ title: string,
817
+ sinceMs: number,
818
+): RemoteBuildState => {
819
+ const run = runs
820
+ .filter((run) => run.displayTitle === title && Date.parse(run.createdAt) >= sinceMs)
821
+ .sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt))[0];
822
+ if (!run) return "none";
823
+ if (run.status !== "completed") return "running";
824
+ return run.conclusion === "success" ? "succeeded" : "failed";
825
+};
826
+
827
+const remoteBuildPollMs = 20_000;
828
+const remoteBuildTimeoutMs = 25 * 60_000;
829
+/** A run this recent for the same client is joined instead of dispatching a second one. */
830
+const remoteBuildJoinMs = 30 * 60_000;
831
+
832
+/**
833
+ * Build the client for HEAD in the `mobile-dev-client.yml` workflow (Blacksmith runners with warm
834
+ * Gradle and ccache state) and download it from the shared cache. False means "build here
835
+ * instead": no `gh`, no permission to dispatch, HEAD not on GitHub, native edits that HEAD does
836
+ * not have (the workflow rejects a fingerprint it does not compute), or a failed run.
837
+ */
838
+const buildOnBlacksmith = Effect.fn("nativeClient.buildOnBlacksmith")(
839
+ function* (
840
+ remote: RemoteCache,
841
+ platform: NativePlatform,
842
+ abi: string | null,
843
+ fingerprint: string,
844
+ key: string,
845
+ directory: string,
846
+ ) {
847
+ const environment = yield* HostProcess.Environment;
848
+ // The workflow itself runs this script: it must build, never dispatch.
849
+ if (environment.GITHUB_ACTIONS === "true" || environment.T3_NATIVE_CLIENT_BUILD === "local")
850
+ return false;
851
+ if (!(yield* isCommandAvailable("gh"))) return false;
852
+ const repository = environment.T3_NATIVE_CLIENT_REPOSITORY ?? "pingdotgg/t3code";
853
+ const { repo } = yield* roots;
854
+ const sha = yield* command("git", ["rev-parse", "HEAD"], false, repo);
855
+ const pushed = yield* command(
856
+ "gh",
857
+ ["api", `repos/${repository}/commits/${sha}`, "--jq", ".sha"],
858
+ false,
859
+ repo,
860
+ ).pipe(
861
+ Effect.map((found) => found === sha),
862
+ Effect.orElseSucceed(() => false),
863
+ );
864
+ if (!pushed) {
865
+ yield* Console.error(`HEAD ${sha.slice(0, 10)} is not on GitHub yet; building here.`);
866
+ return false;
867
+ }
868
+ const title = buildRunTitle(platform, abi, fingerprint);
869
+ const state = (sinceMs: number) =>
870
+ command(
871
+ "gh",
872
+ [
873
+ "run",
874
+ "list",
875
+ "--repo",
876
+ repository,
877
+ "--workflow",
878
+ buildWorkflow,
879
+ "--event",
880
+ "workflow_dispatch",
881
+ "--limit",
882
+ "30",
883
+ "--json",
884
+ "displayTitle,status,conclusion,createdAt",
885
+ ],
886
+ false,
887
+ repo,
888
+ ).pipe(
889
+ Effect.flatMap(decodeWorkflowRuns),
890
+ Effect.map((runs) => remoteBuildState(runs, title, sinceMs)),
891
+ // A failed listing says nothing about the build; keep waiting on the cache.
892
+ Effect.orElseSucceed((): RemoteBuildState => "none"),
893
+ );
894
+ const started = yield* Clock.currentTimeMillis;
895
+ const joined = (yield* state(started - remoteBuildJoinMs)) === "running";
896
+ if (!joined) {
897
+ const dispatched = yield* command(
898
+ "gh",
899
+ [
900
+ "workflow",
901
+ "run",
902
+ buildWorkflow,
903
+ "--repo",
904
+ repository,
905
+ "--ref",
906
+ "main",
907
+ "-f",
908
+ `ref=${sha}`,
909
+ "-f",
910
+ `platform=${platform}`,
911
+ "-f",
912
+ `abi=${abi ?? "x86_64"}`,
913
+ "-f",
914
+ `fingerprint=${fingerprint}`,
915
+ ],
916
+ false,
917
+ repo,
918
+ ).pipe(
919
+ Effect.as(true),
920
+ Effect.orElseSucceed(() => false),
921
+ );
922
+ if (!dispatched) return false;
923
+ }
924
+ yield* Console.error(
925
+ `${joined ? "A Blacksmith build of" : "Building"} ${key} ${joined ? "is already running" : "on Blacksmith"}; waiting for it in the shared cache...`,
926
+ );
927
+ const since = joined ? started - remoteBuildJoinMs : started - 60_000;
928
+ const fetched = download(remote, platform, key, directory).pipe(
929
+ Effect.orElseSucceed(() => false),
930
+ );
931
+ while ((yield* Clock.currentTimeMillis) - started < remoteBuildTimeoutMs) {
932
+ yield* Effect.sleep(remoteBuildPollMs);
933
+ if (yield* fetched) return true;
934
+ const now = yield* state(since);
935
+ if (now === "failed" || (now === "succeeded" && !(yield* fetched))) {
936
+ yield* Console.error(
937
+ now === "failed"
938
+ ? "The Blacksmith build failed (or HEAD lacks this checkout's native edits); building here."
939
+ : "The Blacksmith run finished without sharing this client; building here.",
940
+ );
941
+ return false;
942
+ }
943
+ }
944
+ yield* Console.error("The Blacksmith build did not finish in time; building here.");
945
+ return false;
946
+ },
947
+ Effect.orElseSucceed(() => false),
948
+);
949
+
950
+/** 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. */
951
export const resolveArtifact = Effect.fn("nativeClient.resolveArtifact")(function* (
952
home: string,
953
platform: NativePlatform,
@@ -827,17 +981,31 @@ export const resolveArtifact = Effect.fn("nativeClient.resolveArtifact")(functio
981
return { ...artifact, source: "remote" as const, buildMs: yield* readBuildMs(directory) };
982
}
983
}
984
+ if (remote && (yield* buildOnBlacksmith(remote, platform, abi, fingerprint, key, directory))) {
985
+ yield* prune(path.dirname(directory), fingerprint);
986
+ return { ...artifact, source: "remote" as const, buildMs: yield* readBuildMs(directory) };
987
+ }
988
const log = yield* BuildLog;
989
yield* Console.error(
832
- `No cached client for ${key}. Building it once for every machine (5-15 min)${log ? `. Log: ${log}` : ""}`,
990
+ `No cached client for ${key}. Building it here once for every machine (5-15 min)${log ? `. Log: ${log}` : ""}`,
991
);
992
const started = yield* Clock.currentTimeMillis;
993
yield* build(platform, abi, directory, fingerprint);
994
yield* writeBuildMs(directory, (yield* Clock.currentTimeMillis) - started);
995
yield* prune(path.dirname(directory), fingerprint);
996
if (remote && (yield* HostProcess.Environment).T3_NATIVE_CLIENT_CACHE !== "read") {
997
+ // The Blacksmith workflow exists to share the client: there a failed upload fails the run.
998
+ const required = (yield* HostProcess.Environment).T3_NATIVE_CLIENT_SHARE === "required";
999
yield* upload(remote, platform, key, directory).pipe(
840
- Effect.catch((error) => Console.error(`Native client was not shared (${describe(error)}).`)),
1000
+ Effect.catch((error) =>
1001
+ required
1002
+ ? Effect.fail(
1003
+ new NativeClientError({
1004
+ message: `Native client was not shared (${describe(error)}).`,
1005
+ }),
1006
+ )
1007
+ : Console.error(`Native client was not shared (${describe(error)}).`),
1008
+ ),
1009
);
1010
}
1011
return { ...artifact, source: "build" as const, buildMs: 0 };
@@ -1051,6 +1219,12 @@ const main = Command.make(
1219
),
1220
Flag.withDefault(false),
1221
),
1222
+ expectFingerprint: Flag.String("expect-fingerprint").pipe(
1223
+ Flag.withDescription(
1224
+ "With --prepare, fail before building unless the checkout's native fingerprint is this one.",
1225
+ ),
1226
+ Flag.optional,
1227
+ ),
1228
},
1229
Effect.fn("nativeClient.main")(function* ({
1230
mode,
@@ -1060,6 +1234,7 @@ const main = Command.make(
1234
abi: sessionAbi,
1235
metro,
1236
prepare,
1237
+ expectFingerprint,
1238
}) {
1239
const started = yield* Clock.currentTimeMillis;
1240
if (prepare) {
@@ -1072,6 +1247,10 @@ const main = Command.make(
1247
if (!home)
1248
return yield* new NativeClientError({ message: "HOME or USERPROFILE must be set." });
1249
const current = yield* fingerprint(platform);
1250
+ if (Option.isSome(expectFingerprint) && expectFingerprint.value !== current)
1251
+ return yield* new NativeClientError({
1252
+ message: `This checkout's ${platform} fingerprint is ${current}, not the expected ${expectFingerprint.value}: the caller has native changes this commit does not.`,
1253
+ });
1254
const artifact = yield* resolveArtifact(
1255
home,
1256
platform,