Skip to content

Commit c88e52c

Browse files
committed
Merge remote-tracking branch 'origin/main' into fix/rollback-provider-admission-main
2 parents 4a530b2 + dde3fdb commit c88e52c

552 files changed

Lines changed: 23948 additions & 2120 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/mobile-eas-production.yml‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,7 @@ jobs:
275275
--environment production \
276276
--platform ${{ inputs.platform }} \
277277
--message "$OTA_MESSAGE" \
278+
--emit-metadata \
278279
--non-interactive
279280
280281
# Reconcile each version separately because the major is in the fingerprint.
@@ -313,8 +314,11 @@ jobs:
313314
--environment production \
314315
--platform "$platform" \
315316
--message "$message" \
317+
--emit-metadata \
316318
--non-interactive; then
317319
echo ":white_check_mark: $platform/$profile: OTA published to production (fingerprint \`$hash\`)" >> "$GITHUB_STEP_SUMMARY"
320+
# The next target's export replaces dist; keep this one for the map upload.
321+
rm -rf "dist-$platform-$profile" && mv dist "dist-$platform-$profile"
318322
else
319323
failed=1
320324
echo ":x: $platform/$profile: OTA publish failed (fingerprint \`$hash\`)" >> "$GITHUB_STEP_SUMMARY"
@@ -354,3 +358,18 @@ jobs:
354358
fi
355359
done
356360
exit "$failed"
361+
362+
# Lets the relay symbolicate crash stacks from the updates published
363+
# above. A step of its own so the R2 credentials reach only this script,
364+
# not `eas update` and the dependencies it runs. Never fails the job.
365+
- name: Upload OTA source maps
366+
if: ${{ !cancelled() && steps.expo-token.outputs.present == 'true' }}
367+
working-directory: apps/mobile
368+
env:
369+
MOBILE_SOURCEMAPS_R2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }}
370+
run: |
371+
for dir in dist dist-*; do
372+
if [ -f "$dir/eas-update-metadata.json" ]; then
373+
node scripts/upload-sourcemaps.mts ota "$dir"
374+
fi
375+
done

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ Architecture and its constraints: `docs/internals/overview.md`. Glossary: `docs/
199199
options, and pass combinators as additional function-builder arguments.
200200
- Inferred types over annotations. `any` is the enemy.
201201
- Default to no comment. Write one only for a constraint, an external quirk, or an invariant the code can't show, in one line where you can and four at most. Don't restate names or signatures, narrate steps, record history, or explain the fix you just made; the PR carries that. `t3code/no-low-value-comments` enforces the length cap and the mechanical cases.
202-
- React effects are for synchronizing with something outside React. Derive in render and act in handlers instead of syncing state, but don't hide real lifecycle work in refs or stores to dodge one. The `t3code/react-effect-budget` lint rule holds each file to its count in `scripts/effect-budget.json`; a new effect states its reason with `// oxlint-disable-next-line t3code/react-effect-budget -- <why>`.
202+
- React effects are for synchronizing with something outside React. Derive in render and act in handlers instead of syncing state, but don't hide real lifecycle work in refs or stores to dodge one. The `t3code/no-unreasoned-state-sync` lint rule reports every effect; one that stays states its reason with `// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- <why>`.
203203
- Our users drive agents all day and notice a dropped frame, a lying spinner, and a stale label. No continuously repainting animations; they peg the GPU on high-refresh displays.
204204
- If a rule here fights the task in front of you, say so loudly and get a human sign-off before breaking it.
205205

‎apps/desktop/src/app/DesktopClerk.test.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ describe("DesktopClerk", () => {
156156
`setPath:userData:${userData}`,
157157
"requestSingleInstanceLock",
158158
"on:second-instance",
159+
"on:open-url",
159160
"createClerkBridge",
160161
]);
161162
},
@@ -200,14 +201,15 @@ describe("DesktopClerk", () => {
200201
},
201202
);
202203

203-
it.effect("delivers queued startup links and later links once in arrival order", () => {
204+
it.effect("delivers each queued startup link once, before later links", () => {
204205
storageMock.mockReturnValue(storageAdapter);
205206
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
206207
const listeners = new Map<string, (...args: unknown[]) => void>();
207208
const received: string[] = [];
208209
const first = "t3code://new?prompt=first";
209210
const second = "t3code://threads/env-1/thread-1";
210211
const later = "t3code://new?prompt=later";
212+
const launchPair = "t3code://pair?pairingUrl=https%3A%2F%2Fvps.example.com%2F%23token%3Dabc";
211213
const delivered = Promise.withResolvers<void>();
212214
const electronApp = {
213215
on: (name: string, listener: (...args: unknown[]) => void) =>
@@ -220,13 +222,14 @@ describe("DesktopClerk", () => {
220222
const clerk = yield* DesktopClerk.DesktopClerk;
221223
listeners.get("second-instance")?.({}, ["t3", first]);
222224
listeners.get("second-instance")?.({}, ["t3", second]);
225+
listeners.get("open-url")?.({ preventDefault: () => undefined }, launchPair);
223226
assert.deepEqual(received, []);
224227

225228
yield* clerk.configure;
226229
listeners.get("second-instance")!({}, ["t3", later]);
227230
yield* Effect.promise(() => delivered.promise);
228231

229-
assert.deepEqual(received, [first, second, later]);
232+
assert.deepEqual(received, [launchPair, first, second, later]);
230233
}).pipe(
231234
Effect.scoped,
232235
Effect.provide(layerDesktopClerk(true, [], "darwin", undefined, undefined, listeners)),
@@ -425,6 +428,7 @@ it.effect("hands web and app links to the renderer and leaves other links alone"
425428
}),
426429
} as unknown as ElectronApp.ElectronApp["Service"];
427430
const received: Array<string> = [];
431+
const pairLink = "t3code://pair?pairingUrl=https%3A%2F%2Fvps.example.com%2F%23token%3Dabc";
428432
yield* Effect.gen(function* () {
429433
const clerk = yield* DesktopClerk.DesktopClerk;
430434
yield* clerk.configure;
@@ -437,6 +441,8 @@ it.effect("hands web and app links to the renderer and leaves other links alone"
437441
assert.strictEqual(open("http://localhost:3000/"), 1);
438442
assert.strictEqual(open("t3code://new?prompt=hi"), 1);
439443
assert.strictEqual(open("t3code://threads/env-1/thread-1"), 1);
444+
assert.strictEqual(open(pairLink), 1);
445+
assert.strictEqual(open("t3code://pair"), 0);
440446
assert.strictEqual(open("mailto:[email protected]"), 0);
441447
assert.strictEqual(open("t3code://somewhere-else"), 0);
442448
yield* Effect.yieldNow;
@@ -445,6 +451,7 @@ it.effect("hands web and app links to the renderer and leaves other links alone"
445451
"http://localhost:3000/",
446452
"t3code://new?prompt=hi",
447453
"t3code://threads/env-1/thread-1",
454+
pairLink,
448455
]);
449456
}).pipe(
450457
Effect.provide(layerDesktopClerk(true, [], "darwin", undefined, undefined, listeners)),

‎apps/desktop/src/app/DesktopClerk.ts‎

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { receiveCodexAuthCallback, CodexAuthCallbackError } from "./CodexAuthCal
1313
import * as ElectronShell from "../electron/ElectronShell.ts";
1414
import { providerAuthReturnUrl } from "@t3tools/shared/providerAuthReturnUrl";
1515
import { promptLinkAppPath } from "@t3tools/shared/promptLinks";
16+
import { readPairingAppLink } from "@t3tools/shared/remote";
1617
import * as HostProcess from "@t3tools/shared/HostProcess";
1718
import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
1819
import * as ElectronApp from "../electron/ElectronApp.ts";
@@ -118,6 +119,15 @@ export const make = Effect.gen(function* () {
118119
yield* electronApp.on("second-instance", (_event: unknown, argv: readonly string[]) => {
119120
handleSecondInstance(argv);
120121
});
122+
// macOS hands a launch link to open-url, which can fire before configure runs.
123+
const pendingOpenUrls: Array<string> = [];
124+
let handleOpenUrl = (url: string) => {
125+
pendingOpenUrls.push(url);
126+
return true;
127+
};
128+
yield* electronApp.on("open-url", (event: { preventDefault: () => void }, url: string) => {
129+
if (handleOpenUrl(url)) event.preventDefault();
130+
});
121131

122132
yield* Effect.acquireRelease(
123133
Effect.try({
@@ -194,7 +204,8 @@ export const make = Effect.gen(function* () {
194204
return true;
195205
};
196206
const openAppLink = (value: string | undefined) => {
197-
if (!value || promptLinkAppPath(value) === null) return false;
207+
if (!value || (promptLinkAppPath(value) === null && readPairingAppLink(value) === null))
208+
return false;
198209
void runPromise(webLinks.receive(value));
199210
return true;
200211
};
@@ -205,15 +216,12 @@ export const make = Effect.gen(function* () {
205216
void runPromise(webLinks.receive(url));
206217
return true;
207218
};
208-
yield* electronApp.on("open-url", (event: { preventDefault: () => void }, url: string) => {
209-
if (
210-
startProviderAuthHandoff(url) ||
211-
resumeProviderAuth(url) ||
212-
openWebLink(url) ||
213-
openAppLink(url)
214-
)
215-
event.preventDefault();
216-
});
219+
handleOpenUrl = (url) =>
220+
startProviderAuthHandoff(url) ||
221+
resumeProviderAuth(url) ||
222+
openWebLink(url) ||
223+
openAppLink(url);
224+
for (const url of pendingOpenUrls.splice(0)) handleOpenUrl(url);
217225
yield* electronApp.on("open-file", (event: { preventDefault: () => void }, path: string) => {
218226
if (!DesktopWebLinks.isWebPageFile(path)) return;
219227
event.preventDefault();

‎apps/mobile/app.config.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ const runtimeVersionPolicy =
1717
const personalTeamBundleIdentifier = repoEnv.T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID?.trim();
1818
const IOS_BUNDLE_IDENTIFIER_PATTERN = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;
1919

20+
// Compiled into the native project. Without a relay, Observe's native side could dispatch to
21+
// Expo's own ingest before observe.ts turns it off; `.invalid` never resolves (RFC 6761).
22+
const observeEndpointUrl = repoEnv.T3CODE_RELAY_URL?.trim()
23+
? new URL("/v1/mobile/observe", repoEnv.T3CODE_RELAY_URL.trim()).toString()
24+
: "https://observe.invalid";
25+
2026
const fromRepoRoot = (relativePath: string) => `../../${relativePath}`;
2127
const androidAdaptiveForeground = "./assets/android-icon-foreground.png";
2228

@@ -450,6 +456,7 @@ const config: ExpoConfig = {
450456
},
451457
eas: {
452458
projectId: "d763fcb8-d37c-41ea-a773-b54a0ab4a454",
459+
observe: { endpointUrl: observeEndpointUrl },
453460
},
454461
},
455462
owner: "pingdotgg",
506 Bytes
Loading

‎apps/mobile/eas.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,8 @@
6666
"corepack": true,
6767
"env": {
6868
"APP_VARIANT": "production",
69-
"NODE_OPTIONS": "--max-old-space-size=4096"
69+
"NODE_OPTIONS": "--max-old-space-size=4096",
70+
"SOURCEMAP_FILE": "/tmp/t3code-ios-main.jsbundle.map"
7071
},
7172
"channel": "production",
7273
"environment": "production",

‎apps/mobile/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// Must stay first: the render counter wraps the DevTools hook before any React commit.
22
import "./src/features/development/render-counter-entry";
3+
// Next, so errors thrown while the rest of the app loads are recorded too.
4+
import "./src/features/observability/observe";
35
import { registerRootComponent } from "expo";
46
import "react-native-gesture-handler";
57
import { LogBox } from "react-native";

‎apps/mobile/package.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
"measure-renders": "node scripts/measure-renders.mts",
4747
"generate": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON scripts/generate-uniwind-themes.mts",
4848
"generate:highlights": "node scripts/generate-highlights.mts",
49+
"eas-build-on-success": "node scripts/upload-sourcemaps.mts build",
4950
"test": "vp test run --project unit --project react",
5051
"typecheck": "tsc --noEmit"
5152
},
@@ -103,6 +104,7 @@
103104
"expo-linking": "~58.0.13",
104105
"expo-network": "~58.0.3",
105106
"expo-notifications": "~58.1.5",
107+
"expo-observe": "~58.0.15",
106108
"expo-paste-input": "^0.1.15",
107109
"expo-quick-actions": "^6.0.2",
108110
"expo-secure-store": "~58.0.2",
@@ -145,6 +147,7 @@
145147
"@types/mdast": "^4.0.4",
146148
"@types/react": "catalog:",
147149
"@types/react-dom": "catalog:",
150+
"aws4fetch": "1.0.20",
148151
"babel-preset-expo": "~58.0.17",
149152
"jsdom": "^30.0.1",
150153
"tailwindcss": "^4.0.0",
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
import * as NodeFS from "node:fs";
2+
import * as NodePath from "node:path";
3+
import { mobileSourceMapKey, type MobilePlatform } from "@t3tools/shared/mobileSourceMaps";
4+
import { AwsClient } from "aws4fetch";
5+
6+
export interface SourceMapUpload {
7+
readonly key: string;
8+
readonly path: string;
9+
}
10+
11+
/** The `MOBILE_SOURCEMAPS_R2` secret: the relay stack's `mobileSourceMapsUploadCredentials`. */
12+
interface UploadCredentials {
13+
readonly endpoint: string;
14+
readonly bucketName: string;
15+
readonly accessKeyId: string;
16+
readonly secretAccessKey: string;
17+
}
18+
19+
const isPlatform = (value: unknown): value is MobilePlatform =>
20+
value === "ios" || value === "android";
21+
22+
const readJson = (path: string): unknown => JSON.parse(NodeFS.readFileSync(path, "utf8"));
23+
24+
const isRecord = (value: unknown): value is Record<string, unknown> =>
25+
typeof value === "object" && value !== null && !Array.isArray(value);
26+
27+
export function parseCredentials(value: string | undefined): UploadCredentials | undefined {
28+
if (!value?.trim()) return undefined;
29+
let parsed: unknown;
30+
try {
31+
parsed = JSON.parse(value);
32+
} catch {
33+
// JSON.parse's message quotes the input, which here is the secret.
34+
throw new Error("MOBILE_SOURCEMAPS_R2 is not valid JSON.");
35+
}
36+
if (!isRecord(parsed)) throw new Error("MOBILE_SOURCEMAPS_R2 is not a JSON object.");
37+
const { endpoint, bucketName, accessKeyId, secretAccessKey } = parsed;
38+
if (
39+
typeof endpoint !== "string" ||
40+
typeof bucketName !== "string" ||
41+
typeof accessKeyId !== "string" ||
42+
typeof secretAccessKey !== "string"
43+
) {
44+
throw new Error(
45+
"MOBILE_SOURCEMAPS_R2 needs endpoint, bucketName, accessKeyId and secretAccessKey.",
46+
);
47+
}
48+
return { endpoint, bucketName, accessKeyId, secretAccessKey };
49+
}
50+
51+
/** One map per update `eas update --emit-metadata` published, next to the bundle `metadata.json` names. */
52+
export function otaSourceMapUploads(distDir: string): ReadonlyArray<SourceMapUpload> {
53+
const metadata = readJson(NodePath.join(distDir, "metadata.json"));
54+
const easMetadata = readJson(NodePath.join(distDir, "eas-update-metadata.json"));
55+
const fileMetadata = isRecord(metadata) ? metadata.fileMetadata : undefined;
56+
const updates = isRecord(easMetadata) ? easMetadata.updates : undefined;
57+
if (!isRecord(fileMetadata) || !Array.isArray(updates)) {
58+
throw new Error(`${distDir} is missing Expo export or EAS update metadata.`);
59+
}
60+
return updates.flatMap((update): Array<SourceMapUpload> => {
61+
if (!isRecord(update) || !isPlatform(update.platform) || typeof update.id !== "string") {
62+
return [];
63+
}
64+
const platformFiles = fileMetadata[update.platform];
65+
const bundle = isRecord(platformFiles) ? platformFiles.bundle : undefined;
66+
if (typeof bundle !== "string") return [];
67+
return [
68+
{
69+
key: mobileSourceMapKey(update.platform, "ota", update.id),
70+
path: NodePath.join(distDir, `${bundle}.map`),
71+
},
72+
];
73+
});
74+
}
75+
76+
/** Android's Gradle plugin writes the map under the release variant; iOS to `SOURCEMAP_FILE` (eas.json). */
77+
export function buildSourceMapUpload(
78+
env: Readonly<Record<string, string | undefined>>,
79+
projectDir: string,
80+
): SourceMapUpload {
81+
const platform = env.EAS_BUILD_PLATFORM;
82+
const buildId = env.EAS_BUILD_ID;
83+
if (!isPlatform(platform) || !buildId) {
84+
throw new Error("EAS_BUILD_PLATFORM and EAS_BUILD_ID are only set on EAS Build.");
85+
}
86+
if (platform === "ios") {
87+
if (!env.SOURCEMAP_FILE) throw new Error("SOURCEMAP_FILE is not set for this iOS build.");
88+
return { key: mobileSourceMapKey("ios", "build", buildId), path: env.SOURCEMAP_FILE };
89+
}
90+
const variantsDir = NodePath.join(projectDir, "android/app/build/generated/sourcemaps/react");
91+
const variant = NodeFS.existsSync(variantsDir)
92+
? NodeFS.readdirSync(variantsDir).find((name) => /release$/iu.test(name))
93+
: undefined;
94+
if (!variant) throw new Error(`No release source map under ${variantsDir}.`);
95+
return {
96+
key: mobileSourceMapKey("android", "build", buildId),
97+
path: NodePath.join(variantsDir, variant, "index.android.bundle.map"),
98+
};
99+
}
100+
101+
/**
102+
* EAS writes the app's debug symbols next to the `.ipa`, so native frames in iOS crash
103+
* reports can be read with `atos`. Undefined when the build left none.
104+
*/
105+
export function buildDsymUpload(
106+
env: Readonly<Record<string, string | undefined>>,
107+
projectDir: string,
108+
): SourceMapUpload | undefined {
109+
if (env.EAS_BUILD_PLATFORM !== "ios" || !env.EAS_BUILD_ID) return undefined;
110+
const buildDir = NodePath.join(projectDir, "ios/build");
111+
const dsym = NodeFS.existsSync(buildDir)
112+
? NodeFS.readdirSync(buildDir).find((name) => name.endsWith(".app.dSYM.zip"))
113+
: undefined;
114+
if (!dsym) return undefined;
115+
return { key: `ios/dsym/${env.EAS_BUILD_ID}.zip`, path: NodePath.join(buildDir, dsym) };
116+
}
117+
118+
/** Only what the relay reads: source text stays out of the bucket, and the rest is dead weight. */
119+
function stripToMappings(text: string): string {
120+
const map: unknown = JSON.parse(text);
121+
if (!isRecord(map)) throw new Error("Source map is not a JSON object.");
122+
const { version, sources, sourceRoot, mappings } = map;
123+
return JSON.stringify({ version, sources, sourceRoot, mappings });
124+
}
125+
126+
export function uploadSourceMap(
127+
credentials: UploadCredentials,
128+
upload: SourceMapUpload,
129+
): Promise<number> {
130+
return putObject(
131+
credentials,
132+
upload.key,
133+
stripToMappings(NodeFS.readFileSync(upload.path, "utf8")),
134+
"application/json",
135+
);
136+
}
137+
138+
export function uploadDsym(credentials: UploadCredentials, upload: SourceMapUpload) {
139+
const body = new Uint8Array(NodeFS.readFileSync(upload.path));
140+
return putObject(credentials, upload.key, body, "application/zip");
141+
}
142+
143+
async function putObject(
144+
credentials: UploadCredentials,
145+
key: string,
146+
body: string | Uint8Array<ArrayBuffer>,
147+
contentType: string,
148+
): Promise<number> {
149+
const client = new AwsClient({
150+
accessKeyId: credentials.accessKeyId,
151+
secretAccessKey: credentials.secretAccessKey,
152+
service: "s3",
153+
region: "auto",
154+
});
155+
const url = `${credentials.endpoint.replace(/\/$/u, "")}/${credentials.bucketName}/${key}`;
156+
const response = await client.fetch(url, {
157+
method: "PUT",
158+
body,
159+
headers: { "content-type": contentType },
160+
});
161+
if (!response.ok) {
162+
throw new Error(`R2 answered ${response.status}: ${(await response.text()).slice(0, 500)}`);
163+
}
164+
return body.length;
165+
}

0 commit comments

Comments
 (0)