@devries-cameron20 / t3code-1 / commits / b126312917
Fork 0

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

refactor(effect): trace relay and development tooling operations (#21997)

Julius Marminge committed Oct 19, 2026 at 18:31 UTC b12631291728c175c720f0cd660f3218cf2af236
15 files changed +957 -901
apps/server/scripts/record-codex-app-server-replay-fixture.ts
+128 -133
@@ -1110,7 +1110,7 @@ function recorderThreadConfigMetadata(scenario: ReplayScenario) {
1110 return keys.length === 0 ? {} : { recorderThreadConfigKeys: keys };
1111 }
1112
1113 -function makeRecorder({
1113 +const makeRecorder = Effect.fn("record-codex-app-server-replay-fixture.makeRecorder")(function* ({
1114 outPath,
1115 scenario,
1116 checkout,
@@ -1118,55 +1118,53 @@ function makeRecorder({
1118 readonly outPath: string;
1119 readonly scenario: ReplayScenario;
1120 readonly checkout: string;
1121 -}): Effect.Effect<Recorder, PlatformError.PlatformError, FileSystem.FileSystem> {
1122 - return Effect.gen(function* () {
1123 - const fs = yield* FileSystem.FileSystem;
1124 - let version = "unknown";
1125 - const records: Array<Record<string, unknown>> = [];
1126 - const setVersion = (nextVersion: string) =>
1127 - Effect.sync(() => {
1128 - version = nextVersion;
1129 - });
1130 - const writeRecord = (record: Record<string, unknown>) =>
1131 - Effect.sync(() => {
1132 - records.push(record);
1133 - });
1134 - const flush = () => {
1135 - const outputRecords = codexReplayRecordingOutputRecords(records, {
1136 - workspace: process.cwd(),
1137 - machine: {
1138 - home: NodeOS.homedir(),
1139 - hostname: NodeOS.hostname(),
1140 - checkout,
1141 - },
1142 - });
1143 - return fs.writeFileString(
1144 - outPath,
1145 - `${[
1146 - {
1147 - type: "transcript_start",
1148 - provider: "codex",
1149 - protocol: "codex.app-server",
1150 - version,
1151 - scenario: scenario.name,
1152 - metadata: {
1153 - source: "record-codex-app-server-replay-fixture",
1154 - fileName: scenario.fileName,
1155 - description: scenario.description,
1156 - model: scenarioModel(scenario),
1157 - ...recorderThreadConfigMetadata(scenario),
1158 - },
1121 +}): Effect.fn.Return<Recorder, PlatformError.PlatformError, FileSystem.FileSystem> {
1122 + const fs = yield* FileSystem.FileSystem;
1123 + let version = "unknown";
1124 + const records: Array<Record<string, unknown>> = [];
1125 + const setVersion = (nextVersion: string) =>
1126 + Effect.sync(() => {
1127 + version = nextVersion;
1128 + });
1129 + const writeRecord = (record: Record<string, unknown>) =>
1130 + Effect.sync(() => {
1131 + records.push(record);
1132 + });
1133 + const flush = () => {
1134 + const outputRecords = codexReplayRecordingOutputRecords(records, {
1135 + workspace: process.cwd(),
1136 + machine: {
1137 + home: NodeOS.homedir(),
1138 + hostname: NodeOS.hostname(),
1139 + checkout,
1140 + },
1141 + });
1142 + return fs.writeFileString(
1143 + outPath,
1144 + `${[
1145 + {
1146 + type: "transcript_start",
1147 + provider: "codex",
1148 + protocol: "codex.app-server",
1149 + version,
1150 + scenario: scenario.name,
1151 + metadata: {
1152 + source: "record-codex-app-server-replay-fixture",
1153 + fileName: scenario.fileName,
1154 + description: scenario.description,
1155 + model: scenarioModel(scenario),
1156 + ...recorderThreadConfigMetadata(scenario),
1157 },
1160 - ...outputRecords,
1161 - ]
1162 - .map((record) => JSON.stringify(record))
1163 - .join("\n")}\n`,
1164 - );
1165 - };
1158 + },
1159 + ...outputRecords,
1160 + ]
1161 + .map((record) => JSON.stringify(record))
1162 + .join("\n")}\n`,
1163 + );
1164 + };
1165
1167 - return { path: outPath, setVersion, writeRecord, flush };
1168 - });
1169 -}
1166 + return { path: outPath, setVersion, writeRecord, flush };
1167 +});
1168
1169 function layerCodex({ recorder }: { readonly recorder: Recorder }) {
1170 const clientRequestMethodById = new Map<string, string>();
@@ -1348,16 +1346,16 @@ function installReplayHandlers({
1346 );
1347 }
1348
1351 -function runReplaySession({
1352 - scenario,
1353 - run,
1354 - recorder,
1355 -}: {
1356 - readonly scenario: ReplayScenario;
1357 - readonly run: ReplayRun;
1358 - readonly recorder: Recorder;
1359 -}) {
1360 - return Effect.gen(function* () {
1349 +const runReplaySession = Effect.fn("record-codex-app-server-replay-fixture.runReplaySession")(
1350 + function* ({
1351 + scenario,
1352 + run,
1353 + recorder,
1354 + }: {
1355 + readonly scenario: ReplayScenario;
1356 + readonly run: ReplayRun;
1357 + readonly recorder: Recorder;
1358 + }) {
1359 const startedTurns = yield* makeReplayRecorderDeferredRegistry();
1360 const completedTurns = yield* makeReplayRecorderDeferredRegistry();
1361 const startedCommandExecutions = yield* makeReplayRecorderDeferredRegistry();
@@ -1397,73 +1395,72 @@ function runReplaySession({
1395 return client;
1396 });
1397
1400 - const runTurnStep = (
1398 + const runTurnStep = Effect.fn("record-codex-app-server-replay-fixture.runTurnStep")(function* (
1399 client: CodexClient.CodexAppServerClient["Service"],
1400 threadId: string,
1401 step: TurnReplayStep,
1404 - ) =>
1405 - Effect.gen(function* () {
1406 - const turnParams: TurnStartParams = {
1407 - approvalPolicy: "never",
1408 - sandboxPolicy: { type: "dangerFullAccess" },
1409 - cwd: process.cwd(),
1410 - model,
1411 - summary: "detailed",
1412 - approvalsReviewer: "user",
1413 - ...(run.interactionMode === "plan"
1414 - ? { collaborationMode: planCollaborationMode(model) }
1415 - : {}),
1416 - ...run.turnDefaults,
1417 - ...step.turnOverrides,
1418 - input: turnInput(step.prompt),
1419 - threadId,
1420 - };
1421 -
1422 - if (step.type === "steeredTurn") {
1423 - approvalGate = yield* Deferred.make<void>();
1424 - }
1402 + ) {
1403 + const turnParams: TurnStartParams = {
1404 + approvalPolicy: "never",
1405 + sandboxPolicy: { type: "dangerFullAccess" },
1406 + cwd: process.cwd(),
1407 + model,
1408 + summary: "detailed",
1409 + approvalsReviewer: "user",
1410 + ...(run.interactionMode === "plan"
1411 + ? { collaborationMode: planCollaborationMode(model) }
1412 + : {}),
1413 + ...run.turnDefaults,
1414 + ...step.turnOverrides,
1415 + input: turnInput(step.prompt),
1416 + threadId,
1417 + };
1418 +
1419 + if (step.type === "steeredTurn") {
1420 + approvalGate = yield* Deferred.make<void>();
1421 + }
1422
1426 - const turn = yield* client.request("turn/start", turnParams);
1427 - const turnId = getTurnId(turn);
1428 - const started = yield* getStarted(turnId);
1429 - yield* getCompletion(turnId);
1423 + const turn = yield* client.request("turn/start", turnParams);
1424 + const turnId = getTurnId(turn);
1425 + const started = yield* getStarted(turnId);
1426 + yield* getCompletion(turnId);
1427
1431 - if (step.type === "steeredTurn") {
1432 - yield* Deferred.await(started);
1433 - yield* client.request("turn/steer", {
1434 - expectedTurnId: turnId,
1435 - input: turnInput(step.steer),
1436 - threadId,
1437 - });
1438 - if (approvalGate) {
1439 - yield* Deferred.succeed(approvalGate, void 0);
1440 - approvalGate = undefined;
1441 - }
1428 + if (step.type === "steeredTurn") {
1429 + yield* Deferred.await(started);
1430 + yield* client.request("turn/steer", {
1431 + expectedTurnId: turnId,
1432 + input: turnInput(step.steer),
1433 + threadId,
1434 + });
1435 + if (approvalGate) {
1436 + yield* Deferred.succeed(approvalGate, void 0);
1437 + approvalGate = undefined;
1438 }
1439 + }
1440
1444 - if (step.type === "interruptedTurn") {
1445 - if (step.interruptAfterCommandExecutionStarted === true) {
1446 - const commandExecutionStarted = yield* getCommandExecutionStarted(turnId);
1447 - yield* Deferred.await(commandExecutionStarted);
1448 - } else {
1449 - yield* Effect.sleep(`${step.interruptAfterMs ?? 1_500} millis`);
1450 - }
1451 - yield* client.request("turn/interrupt", {
1441 + if (step.type === "interruptedTurn") {
1442 + if (step.interruptAfterCommandExecutionStarted === true) {
1443 + const commandExecutionStarted = yield* getCommandExecutionStarted(turnId);
1444 + yield* Deferred.await(commandExecutionStarted);
1445 + } else {
1446 + yield* Effect.sleep(`${step.interruptAfterMs ?? 1_500} millis`);
1447 + }
1448 + yield* client.request("turn/interrupt", {
1449 + threadId,
1450 + turnId,
1451 + });
1452 + for (const processId of runningCommandProcessIds.get(turnId)?.values() ?? []) {
1453 + yield* client.raw.request("thread/backgroundTerminals/terminate", {
1454 threadId,
1453 - turnId,
1455 + processId,
1456 });
1455 - for (const processId of runningCommandProcessIds.get(turnId)?.values() ?? []) {
1456 - yield* client.raw.request("thread/backgroundTerminals/terminate", {
1457 - threadId,
1458 - processId,
1459 - });
1460 - }
1457 }
1458 + }
1459
1463 - const completed = yield* getCompletion(turnId);
1464 - yield* Deferred.await(completed);
1465 - lastTurnIdByThread.set(threadId, turnId);
1466 - });
1460 + const completed = yield* getCompletion(turnId);
1461 + yield* Deferred.await(completed);
1462 + lastTurnIdByThread.set(threadId, turnId);
1463 + });
1464
1465 if (scenario.name === "provider_thread_resume") {
1466 const firstStep = run.steps[0];
@@ -1611,36 +1608,34 @@ function runReplaySession({
1608 }),
1609 ),
1610 );
1614 - });
1615 -}
1611 + },
1612 +);
1613
1617 -function runScenario({
1614 +const runScenario = Effect.fn("record-codex-app-server-replay-fixture.runScenario")(function* ({
1615 scenario,
1616 outPath,
1617 }: {
1618 readonly scenario: ReplayScenario;
1619 readonly outPath: string;
1620 }) {
1624 - return Effect.gen(function* () {
1625 - const fs = yield* FileSystem.FileSystem;
1626 - const path = yield* Path.Path;
1627 - const checkout = path.resolve(yield* path.fromFileUrl(new URL("../../..", import.meta.url)));
1628 - const recorder = yield* makeRecorder({ outPath, scenario, checkout });
1621 + const fs = yield* FileSystem.FileSystem;
1622 + const path = yield* Path.Path;
1623 + const checkout = path.resolve(yield* path.fromFileUrl(new URL("../../..", import.meta.url)));
1624 + const recorder = yield* makeRecorder({ outPath, scenario, checkout });
1625
1630 - yield* fs.makeDirectory(path.dirname(outPath), { recursive: true });
1631 - yield* Console.log(`Writing ${scenario.name} Codex replay events to ${recorder.path}`);
1626 + yield* fs.makeDirectory(path.dirname(outPath), { recursive: true });
1627 + yield* Console.log(`Writing ${scenario.name} Codex replay events to ${recorder.path}`);
1628
1633 - yield* Effect.forEach(scenario.runs, (run) => runReplaySession({ scenario, run, recorder }), {
1634 - concurrency: 1,
1635 - });
1629 + yield* Effect.forEach(scenario.runs, (run) => runReplaySession({ scenario, run, recorder }), {
1630 + concurrency: 1,
1631 + });
1632
1637 - yield* recorder.writeRecord({
1638 - type: "runtime_exit",
1639 - status: "success",
1640 - });
1641 - yield* recorder.flush();
1633 + yield* recorder.writeRecord({
1634 + type: "runtime_exit",
1635 + status: "success",
1636 });
1643 -}
1637 + yield* recorder.flush();
1638 +});
1639
1640 const program = Effect.gen(function* () {
1641 const path = yield* Path.Path;
infra/relay/src/hooks/HookForwarder.test.ts
+23
@@ -700,6 +700,29 @@ describe("HookForwarder", () => {
700 .find((span) => span.name === "relay.hooks.forward")
701 ?.attributes.has("relay.hook.upstream_outcome"),
702 ).toBe(false);
703 +
704 + for (const [holdWebhooksWhileOffline, inboxCapacity, outcome] of [
705 + [false, Infinity, "environment_unavailable"],
706 + [true, Infinity, "held"],
707 + [true, 0, "inbox_full"],
708 + ] as const) {
709 + spans.length = 0;
710 + yield* forward(
711 + makeHarness({
712 + links: [{ ...managedLink, holdWebhooksWhileOffline }],
713 + inboxCapacity,
714 + execute: (request) =>
715 + Effect.succeed(
716 + HttpClientResponse.fromWeb(request, new Response("", { status: 503 })),
717 + ),
718 + }),
719 + );
720 + expect(
721 + spans
722 + .find((span) => span.name === "relay.hooks.forward")
723 + ?.attributes.get("relay.hook.outcome"),
724 + ).toBe(outcome);
725 + }
726 }),
727 );
728
infra/relay/src/hooks/HookForwarder.ts
+42 -40
@@ -236,14 +236,14 @@ const make = Effect.gen(function* () {
236 const inbox = yield* HookInbox.HookInbox;
237 const crypto = yield* Crypto.Crypto;
238
239 - const signDeliveryProof = (input: {
240 - readonly environmentId: string;
241 - readonly deliveryId: string;
242 - readonly receivedAt: string;
243 - readonly hookId: string;
244 - readonly jti: string;
245 - }) =>
246 - Effect.gen(function* () {
239 + const signDeliveryProof = Effect.fn("HookForwarder.signDeliveryProof")(
240 + function* (input: {
241 + readonly environmentId: string;
242 + readonly deliveryId: string;
243 + readonly receivedAt: string;
244 + readonly hookId: string;
245 + readonly jti: string;
246 + }) {
247 const now = Math.floor((yield* Clock.currentTimeMillis) / 1_000);
248 return yield* signRelayJwt({
249 privateKey: Redacted.value(settings.cloudMintPrivateKey),
@@ -261,7 +261,9 @@ const make = Effect.gen(function* () {
261 hookId: input.hookId,
262 } satisfies RelayHookDeliveryProofPayload,
263 });
264 - }).pipe(Effect.orDie);
264 + },
265 + (effect, _input) => effect.pipe(Effect.orDie),
266 + );
267
268 const handle = Effect.fn("relay.hooks.forward")(function* (
269 request: HttpServerRequest.HttpServerRequest,
@@ -354,37 +356,37 @@ const make = Effect.gen(function* () {
356 headers: { ...forwardedHeaders(request.headers), [RELAY_HOOK_DELIVERY_HEADER]: proof },
357 body: body.success,
358 };
357 - const holdOrFail = (status: 503 | 504, error: string) =>
358 - Effect.gen(function* () {
359 - if (!endpoint.holdWhileOffline) {
360 - yield* outcome(error);
361 - return errorResponse(status, error);
362 - }
363 - const stored = yield* inbox
364 - .hold({
365 - endpointKey: parsed.endpointKey,
366 - baseUrl: endpoint.httpBaseUrl,
367 - hook,
368 - })
369 - .pipe(
370 - Effect.catch((cause) =>
371 - Effect.logWarning("Could not hold webhook request", {
372 - environmentId: endpoint.environmentId,
373 - errorTag: cause._tag,
374 - }).pipe(Effect.as(null)),
375 - ),
376 - );
377 - if (stored === null) {
378 - yield* outcome(error);
379 - return errorResponse(status, error);
380 - }
381 - if (!stored) {
382 - yield* outcome("inbox_full");
383 - return errorResponse(503, "inbox_full");
384 - }
385 - yield* outcome("held");
386 - return HttpServerResponse.jsonUnsafe({ queued: true }, { status: 202 });
387 - });
359 + // Keep offline outcomes on the enclosing relay.hooks.forward span.
360 + const holdOrFail = Effect.fnUntraced(function* (status: 503 | 504, error: string) {
361 + if (!endpoint.holdWhileOffline) {
362 + yield* outcome(error);
363 + return errorResponse(status, error);
364 + }
365 + const stored = yield* inbox
366 + .hold({
367 + endpointKey: parsed.endpointKey,
368 + baseUrl: endpoint.httpBaseUrl,
369 + hook,
370 + })
371 + .pipe(
372 + Effect.catch((cause) =>
373 + Effect.logWarning("Could not hold webhook request", {
374 + environmentId: endpoint.environmentId,
375 + errorTag: cause._tag,
376 + }).pipe(Effect.as(null)),
377 + ),
378 + );
379 + if (stored === null) {
380 + yield* outcome(error);
381 + return errorResponse(status, error);
382 + }
383 + if (!stored) {
384 + yield* outcome("inbox_full");
385 + return errorResponse(503, "inbox_full");
386 + }
387 + yield* outcome("held");
388 + return HttpServerResponse.jsonUnsafe({ queued: true }, { status: 202 });
389 + });
390
391 const upstream = yield* sendUpstream(endpoint.httpBaseUrl, hook).pipe(
392 Effect.provideService(HttpClient.HttpClient, httpClient),
infra/relay/src/hooks/HookInboxObject.ts
+20 -14
@@ -89,33 +89,39 @@ export const layer = HookInboxObject.make(
89 effect.pipe(Effect.provide(layerSql), Effect.orDie);
90 yield* run(HookInboxStore.migrate);
91
92 - const scheduleBy = (at: number) =>
93 - Effect.gen(function* () {
94 - const current = yield* state.storage.getAlarm();
95 - if (current === null || current > at) yield* state.storage.setAlarm(at);
96 - });
92 + const scheduleBy = Effect.fn("HookInboxObject.scheduleBy")(function* (at: number) {
93 + const current = yield* state.storage.getAlarm();
94 + if (current === null || current > at) yield* state.storage.setAlarm(at);
95 + });
96
97 + // withInboxSpan supplies each method's root span; avoid a second wrapper span.
98 return {
99 - hold: (hook: HookInboxStore.HeldHook, baseUrl: string) =>
100 - Effect.gen(function* () {
99 + hold: Effect.fnUntraced(
100 + function* (hook: HookInboxStore.HeldHook, baseUrl: string) {
101 const dueAt = yield* run(HookInboxStore.hold(hook, baseUrl));
102 yield* Effect.annotateCurrentSpan({ "relay.inbox.stored": dueAt !== null });
103 if (dueAt === null) return false;
104 yield* scheduleBy(dueAt);
105 return true;
106 - }).pipe(withInboxSpan("relay.inbox.hold", inboxId)),
107 - wake: (baseUrl: string) =>
108 - Effect.gen(function* () {
106 + },
107 + withInboxSpan("relay.inbox.hold", inboxId),
108 + ),
109 + wake: Effect.fnUntraced(
110 + function* (baseUrl: string) {
111 const pending = yield* run(HookInboxStore.wake(baseUrl));
112 yield* Effect.annotateCurrentSpan({ "relay.inbox.pending": pending });
113 if (pending) yield* state.storage.setAlarm(yield* Clock.currentTimeMillis);
114 return pending;
113 - }).pipe(withInboxSpan("relay.inbox.wake", inboxId)),
114 - clear: () =>
115 - Effect.gen(function* () {
115 + },
116 + withInboxSpan("relay.inbox.wake", inboxId),
117 + ),
118 + clear: Effect.fnUntraced(
119 + function* () {
120 yield* run(HookInboxStore.clear);
121 yield* state.storage.deleteAlarm();
118 - }).pipe(withInboxSpan("relay.inbox.clear", inboxId)),
122 + },
123 + withInboxSpan("relay.inbox.clear", inboxId),
124 + ),
125 alarm: () =>
126 run(HookInboxStore.deliverDue(deliver)).pipe(
127 // A wake during this run may already have asked for an earlier
infra/relay/src/hooks/HookInboxStore.test.ts
+30
@@ -8,6 +8,7 @@ import * as Effect from "effect/Effect";
8 import * as Fiber from "effect/Fiber";
9 import * as SqlClient from "effect/sql/SqlClient";
10 import * as TestClock from "effect/testing/TestClock";
11 +import * as Tracer from "effect/Tracer";
12
13 import * as HookInboxStore from "./HookInboxStore.ts";
14
@@ -44,6 +45,35 @@ const withInbox = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
45 );
46
47 describe("HookInboxStore", () => {
48 + it.effect.each(["delivered", "unreachable"] as const)(
49 + "keeps %s delivery results on the operation span",
50 + (outcome) =>
51 + withInbox(
52 + Effect.gen(function* () {
53 + yield* HookInboxStore.hold(yield* hook("traced"), BASE_URL);
54 + const spans: Array<Tracer.NativeSpan> = [];
55 + const tracer = Tracer.make({
56 + span(options) {
57 + const span = new Tracer.NativeSpan(options);
58 + spans.push(span);
59 + return span;
60 + },
61 + });
62 + yield* HookInboxStore.deliverDue(deliverer(() => outcome).send).pipe(
63 + Effect.withTracer(tracer),
64 + );
65 + const run = spans.find((span) => span.name === "HookInboxStore.deliverDue");
66 + expect(run?.attributes.get("relay.inbox.run_result")).toBe(
67 + outcome === "delivered" ? "drained" : "unreachable",
68 + );
69 + expect(run?.attributes.get("relay.inbox.sent")).toBe(1);
70 + expect(run?.attributes.get("relay.inbox.delivered")).toBe(
71 + outcome === "delivered" ? 1 : 0,
72 + );
73 + }),
74 + ),
75 + );
76 +
77 it.effect.each(["delivered", "busy", "unreachable"] as const)(
78 "stops a prefetched batch cleared during a %s send",
79 (outcome) =>
infra/relay/src/hooks/HookInboxStore.ts
+33 -32
@@ -132,19 +132,21 @@ export const migrate = Effect.gen(function* () {
132 `;
133 });
134
135 -const setTarget = (baseUrl: string, options: { readonly resetFailures: boolean }) =>
136 - Effect.gen(function* () {
137 - const sql = yield* SqlClient.SqlClient;
138 - yield* options.resetFailures
139 - ? sql`
135 +const setTarget = Effect.fn("HookInboxStore.setTarget")(function* (
136 + baseUrl: string,
137 + options: { readonly resetFailures: boolean },
138 +) {
139 + const sql = yield* SqlClient.SqlClient;
140 + yield* options.resetFailures
141 + ? sql`
142 INSERT INTO held_hooks_target (id, base_url) VALUES (1, ${baseUrl})
143 ON CONFLICT (id) DO UPDATE SET base_url = excluded.base_url, failures = 0
144 `
143 - : sql`
145 + : sql`
146 INSERT INTO held_hooks_target (id, base_url) VALUES (1, ${baseUrl})
147 ON CONFLICT (id) DO UPDATE SET base_url = excluded.base_url
148 `;
147 - });
149 +});
150
151 const readTarget = Effect.gen(function* () {
152 const sql = yield* SqlClient.SqlClient;
@@ -218,18 +220,17 @@ const backlogSize = Effect.gen(function* () {
220 return rows[0] ?? { count: 0, bytes: 0 };
221 });
222
221 -const refusalReason = (hook: HeldHook) =>
222 - Effect.gen(function* () {
223 - const sql = yield* SqlClient.SqlClient;
224 - const existing = yield* sql<{ readonly id: string }>`
223 +const refusalReason = Effect.fn("HookInboxStore.refusalReason")(function* (hook: HeldHook) {
224 + const sql = yield* SqlClient.SqlClient;
225 + const existing = yield* sql<{ readonly id: string }>`
226 SELECT id FROM held_hooks WHERE id = ${hook.id}
227 `;
227 - if (existing.length > 0) return "already_held";
228 - const backlog = yield* backlogSize;
229 - if (backlog.count >= HOOK_INBOX_MAX_REQUESTS) return "max_requests";
230 - if (backlog.bytes + hook.body.byteLength > HOOK_INBOX_MAX_BYTES) return "max_bytes";
231 - return "max_per_hook";
232 - });
228 + if (existing.length > 0) return "already_held";
229 + const backlog = yield* backlogSize;
230 + if (backlog.count >= HOOK_INBOX_MAX_REQUESTS) return "max_requests";
231 + if (backlog.bytes + hook.body.byteLength > HOOK_INBOX_MAX_BYTES) return "max_bytes";
232 + return "max_per_hook";
233 +});
234
235 export const wake = Effect.fn("HookInboxStore.wake")(function* (baseUrl: string) {
236 if (!(yield* hasPending)) return false;
@@ -277,22 +278,22 @@ export const deliverDue = Effect.fn("HookInboxStore.deliverDue")(function* <R>(
278 let longestWaitMs = 0;
279 const busyHooks = new Set<string>();
280
280 - const annotateRun = (result: string) =>
281 - Effect.gen(function* () {
282 - const backlog = yield* backlogSize;
283 - yield* Effect.annotateCurrentSpan({
284 - "relay.inbox.run_result": result,
285 - "relay.inbox.sent": sent,
286 - "relay.inbox.delivered": delivered,
287 - "relay.inbox.busy_hooks": busyHooks.size,
288 - "relay.inbox.expired": expired.length,
289 - "relay.inbox.unreadable": unreadable,
290 - "relay.inbox.consecutive_failures": failures,
291 - "relay.inbox.longest_wait_ms": longestWaitMs,
292 - "relay.inbox.held_count": backlog.count,
293 - "relay.inbox.held_bytes": backlog.bytes,
294 - });
281 + // Delivery results and counts belong to the enclosing deliverDue span.
282 + const annotateRun = Effect.fnUntraced(function* (result: string) {
283 + const backlog = yield* backlogSize;
284 + yield* Effect.annotateCurrentSpan({
285 + "relay.inbox.run_result": result,
286 + "relay.inbox.sent": sent,
287 + "relay.inbox.delivered": delivered,
288 + "relay.inbox.busy_hooks": busyHooks.size,
289 + "relay.inbox.expired": expired.length,
290 + "relay.inbox.unreadable": unreadable,
291 + "relay.inbox.consecutive_failures": failures,
292 + "relay.inbox.longest_wait_ms": longestWaitMs,
293 + "relay.inbox.held_count": backlog.count,
294 + "relay.inbox.held_bytes": backlog.bytes,
295 });
296 + });
297 const stillHeld = (seq: number) =>
298 sql<{ readonly seq: number }>`SELECT seq FROM held_hooks WHERE seq = ${seq}`.pipe(
299 Effect.map((rows) => rows.length > 0),
infra/relay/src/hooks/upstream.ts
+41 -39
@@ -73,43 +73,45 @@ const readCapped = (response: HttpClientResponse.HttpClientResponse) =>
73 * Sends a webhook request through the environment's tunnel. Fails when the
74 * environment cannot be reached, and succeeds with None on timeout.
75 */
76 -export const sendUpstream = (baseUrl: string, hook: UpstreamHook) =>
77 - Effect.gen(function* () {
78 - const httpClient = yield* HttpClient.HttpClient;
79 - const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
80 - // The environment's span joins this trace. Set by hand: the client span
81 - // that would propagate it is off, because it records the token in url.full.
82 - const parent = yield* Effect.currentSpan.pipe(Effect.option);
83 - const headers: Record<string, string> = {
84 - ...hook.headers,
85 - ...(Option.isSome(parent) ? HttpTraceContext.toHeaders(parent.value) : {}),
86 - [RELAY_DELIVERY_ID_HEADER]: hook.id,
87 - [RELAY_RECEIVED_AT_HEADER]: hook.receivedAt,
88 - };
89 - let request = HttpClientRequest.make(hook.method as "GET" | "POST" | "PUT" | "PATCH")(
90 - `${base}api/hooks/${hook.rawHookId}/${hook.rawToken}${hook.query ? `?${hook.query}` : ""}`,
91 - { headers },
92 - );
93 - if (HttpMethod.hasBody(request.method)) {
94 - request = HttpClientRequest.bodyUint8Array(request, hook.body, headers["content-type"]);
95 - }
96 - return yield* httpClient.execute(request).pipe(
97 - Effect.flatMap((response) =>
98 - readCapped(response).pipe(
99 - Effect.map((body): UpstreamResponse => {
100 - const outcome = response.headers["x-t3-hook-outcome"];
101 - return {
102 - status: response.status,
103 - contentType: response.headers["content-type"],
104 - outcome: outcome !== undefined && OUTCOME_PATTERN.test(outcome) ? outcome : undefined,
105 - body,
106 - };
107 - }),
108 - ),
76 +export const sendUpstream = Effect.fn("upstream.sendUpstream")(function* (
77 + baseUrl: string,
78 + hook: UpstreamHook,
79 +) {
80 + const httpClient = yield* HttpClient.HttpClient;
81 + const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
82 + // The environment's span joins this trace. Set by hand: the client span
83 + // that would propagate it is off, because it records the token in url.full.
84 + const parent = yield* Effect.currentSpan.pipe(Effect.option);
85 + const headers: Record<string, string> = {
86 + ...hook.headers,
87 + ...(Option.isSome(parent) ? HttpTraceContext.toHeaders(parent.value) : {}),
88 + [RELAY_DELIVERY_ID_HEADER]: hook.id,
89 + [RELAY_RECEIVED_AT_HEADER]: hook.receivedAt,
90 + };
91 + let request = HttpClientRequest.make(hook.method as "GET" | "POST" | "PUT" | "PATCH")(
92 + `${base}api/hooks/${hook.rawHookId}/${hook.rawToken}${hook.query ? `?${hook.query}` : ""}`,
93 + { headers },
94 + );
95 + if (HttpMethod.hasBody(request.method)) {
96 + request = HttpClientRequest.bodyUint8Array(request, hook.body, headers["content-type"]);
97 + }
98 + return yield* httpClient.execute(request).pipe(
99 + Effect.flatMap((response) =>
100 + readCapped(response).pipe(
101 + Effect.map((body): UpstreamResponse => {
102 + const outcome = response.headers["x-t3-hook-outcome"];
103 + return {
104 + status: response.status,
105 + contentType: response.headers["content-type"],
106 + outcome: outcome !== undefined && OUTCOME_PATTERN.test(outcome) ? outcome : undefined,
107 + body,
108 + };
109 + }),
110 ),
110 - withoutRedirects,
111 - // The client span would record url.full, which carries the token.
112 - Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
113 - Effect.timeoutOption(Duration.millis(RELAY_HOOK_UPSTREAM_TIMEOUT_MS)),
114 - );
115 - });
111 + ),
112 + withoutRedirects,
113 + // The client span would record url.full, which carries the token.
114 + Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
115 + Effect.timeoutOption(Duration.millis(RELAY_HOOK_UPSTREAM_TIMEOUT_MS)),
116 + );
117 +});
infra/relay/src/http/Api.ts
+39 -38
@@ -207,51 +207,51 @@ const relayRequestDeadline = <E, R>(
207
208 const SENDER_TRACE_HEADER = /^(traceparent|tracestate|b3|x-b3-.*)$/i;
209
210 -export const traceRelayHttpRequest = <E, R>(
210 +// The method-named server span is created below; this wrapper must not add another span.
211 +export const traceRelayHttpRequest = Effect.fnUntraced(function* <E, R>(
212 httpEffect: Effect.Effect<
213 HttpServerResponse.HttpServerResponse,
214 E,
215 HttpServerRequest.HttpServerRequest | R
216 >,
216 -) =>
217 - Effect.gen(function* () {
218 - const request = yield* HttpServerRequest.HttpServerRequest;
219 - const traced = appendRelayTraceContextResponseHeader.pipe(
220 - Effect.andThen(relayRequestDeadline(httpEffect)),
221 - );
222 - if (!isRelayHookPath(request.url)) {
223 - return yield* HttpMiddleware.tracer(traced).pipe(
224 - Effect.provideService(HttpMiddleware.TracerDisabledWhen, () => false),
225 - // HttpMiddleware finalizes its span on the dispatcher; do not close a request-scoped exporter first.
226 - Effect.ensuring(Effect.yieldNow),
227 - );
228 - }
229 - // Hook URLs carry a secret token: the tracer and deadline log see a redacted
230 - // request, while the route itself still receives the original. A webhook
231 - // sender's trace context is dropped, so it cannot pick the trace our relay
232 - // and environment spans land in.
233 - const redacted = request.modify({
234 - url: redactRelayHookUrl(request.url),
235 - headers: Headers.removeMany(
236 - request.headers,
237 - Object.keys(request.headers).filter((name) => SENDER_TRACE_HEADER.test(name)),
238 - ),
239 - });
240 - return yield* HttpMiddleware.tracer(
241 - appendRelayTraceContextResponseHeader.pipe(
242 - Effect.andThen(
243 - relayRequestDeadline(
244 - httpEffect.pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, request)),
245 - RELAY_HOOK_REQUEST_DEADLINE_MS,
246 - ),
247 - ),
248 - ),
249 - ).pipe(
250 - Effect.provideService(HttpServerRequest.HttpServerRequest, redacted),
217 +) {
218 + const request = yield* HttpServerRequest.HttpServerRequest;
219 + const traced = appendRelayTraceContextResponseHeader.pipe(
220 + Effect.andThen(relayRequestDeadline(httpEffect)),
221 + );
222 + if (!isRelayHookPath(request.url)) {
223 + return yield* HttpMiddleware.tracer(traced).pipe(
224 Effect.provideService(HttpMiddleware.TracerDisabledWhen, () => false),
225 + // HttpMiddleware finalizes its span on the dispatcher; do not close a request-scoped exporter first.
226 Effect.ensuring(Effect.yieldNow),
227 );
228 + }
229 + // Hook URLs carry a secret token: the tracer and deadline log see a redacted
230 + // request, while the route itself still receives the original. A webhook
231 + // sender's trace context is dropped, so it cannot pick the trace our relay
232 + // and environment spans land in.
233 + const redacted = request.modify({
234 + url: redactRelayHookUrl(request.url),
235 + headers: Headers.removeMany(
236 + request.headers,
237 + Object.keys(request.headers).filter((name) => SENDER_TRACE_HEADER.test(name)),
238 + ),
239 });
240 + return yield* HttpMiddleware.tracer(
241 + appendRelayTraceContextResponseHeader.pipe(
242 + Effect.andThen(
243 + relayRequestDeadline(
244 + httpEffect.pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, request)),
245 + RELAY_HOOK_REQUEST_DEADLINE_MS,
246 + ),
247 + ),
248 + ),
249 + ).pipe(
250 + Effect.provideService(HttpServerRequest.HttpServerRequest, redacted),
251 + Effect.provideService(HttpMiddleware.TracerDisabledWhen, () => false),
252 + Effect.ensuring(Effect.yieldNow),
253 + );
254 +});
255
256 const layerWebhookHeaderRedaction = Layer.effect(
257 Headers.CurrentRedactedNames,
@@ -1147,8 +1147,9 @@ export const layerServerApi = HttpApiBuilder.group(
1147 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
1148 const publishSignatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures;
1149 const heldHooks = yield* HeldHooks.HeldHooks;
1150 - const requireOwnEnvironment = (environmentId: string) =>
1151 - Effect.gen(function* () {
1150 + const requireOwnEnvironment =
1151 + /* Request instrumentation already owns the span; keep this helper in that context. */
1152 + Effect.fnUntraced(function* (environmentId: string) {
1153 const principal = yield* RelayEnvironmentPrincipal;
1154 if (principal.environmentId !== environmentId) {
1155 return yield* new HttpApiError.Unauthorized({});
scripts/build-cli-archive.ts
+8 -7
@@ -230,12 +230,12 @@ const stageRuntimeExternals = Effect.fn("stageRuntimeExternals")(function* (inpu
230 yield* removeNestedBinDirectories(fs, path, path.join(input.stageDir, "node_modules"));
231 });
232
233 -const removeNestedBinDirectories = (
234 - fs: FileSystem.FileSystem,
235 - path: Path.Path,
236 - root: string,
237 -): Effect.Effect<void, PlatformError.PlatformError> =>
238 - Effect.gen(function* () {
233 +const removeNestedBinDirectories = Effect.fn("build-cli-archive.removeNestedBinDirectories")(
234 + function* (
235 + fs: FileSystem.FileSystem,
236 + path: Path.Path,
237 + root: string,
238 + ): Effect.fn.Return<void, PlatformError.PlatformError> {
239 const entries = yield* fs.readDirectory(root).pipe(Effect.orElseSucceed(() => []));
240 for (const entry of entries) {
241 const child = path.join(root, entry);
@@ -248,7 +248,8 @@ const removeNestedBinDirectories = (
248 yield* removeNestedBinDirectories(fs, path, child);
249 }
250 }
251 - });
251 + },
252 +);
253
254 const stageWebClient = Effect.fn("stageWebClient")(function* (source: string, target: string) {
255 const fs = yield* FileSystem.FileSystem;
scripts/build-desktop-artifact.ts
+99 -95
@@ -2066,11 +2066,11 @@ export const copyDirectoryPreservingSymlinks = Effect.fn("copyDirectoryPreservin
2066 // probe cannot resolve through staging and Windows needs no symlink privilege.
2067 yield* fs.copy(source, destination);
2068
2069 - const restoreRelativeSymlinks = (
2070 - sourceDirectory: string,
2071 - destinationDirectory: string,
2072 - ): Effect.Effect<void, PlatformError | BundleNotSelfContainedError> =>
2073 - Effect.gen(function* () {
2069 + const restoreRelativeSymlinks = Effect.fn("build-desktop-artifact.restoreRelativeSymlinks")(
2070 + function* (
2071 + sourceDirectory: string,
2072 + destinationDirectory: string,
2073 + ): Effect.fn.Return<void, PlatformError | BundleNotSelfContainedError> {
2074 for (const entry of yield* fs.readDirectory(sourceDirectory)) {
2075 const sourceEntry = path.join(sourceDirectory, entry);
2076 const destinationEntry = path.join(destinationDirectory, entry);
@@ -2107,7 +2107,8 @@ export const copyDirectoryPreservingSymlinks = Effect.fn("copyDirectoryPreservin
2107 }
2108 }
2109 }
2110 - });
2110 + },
2111 + );
2112
2113 yield* restoreRelativeSymlinks(source, destination);
2114 },
@@ -2373,69 +2374,69 @@ export const stageBrowserSecret = Effect.fn("stageBrowserSecret")(function* (inp
2374 );
2375 });
2376
2376 -function generateMacIconSet(
2377 +const generateMacIconSet = Effect.fn("build-desktop-artifact.generateMacIconSet")(function* (
2378 sourcePng: string,
2379 targetIcns: string,
2380 tmpRoot: string,
2381 path: Path.Path,
2382 verbose: boolean,
2383 ) {
2383 - return Effect.gen(function* () {
2384 - const fs = yield* FileSystem.FileSystem;
2385 - const iconsetDir = path.join(tmpRoot, "icon.iconset");
2386 - yield* fs.makeDirectory(iconsetDir, { recursive: true });
2384 + const fs = yield* FileSystem.FileSystem;
2385 + const iconsetDir = path.join(tmpRoot, "icon.iconset");
2386 + yield* fs.makeDirectory(iconsetDir, { recursive: true });
2387
2388 - const iconSizes = [16, 32, 128, 256, 512] as const;
2389 - for (const size of iconSizes) {
2390 - yield* runCommand(
2391 - ChildProcess.make(
2392 - {},
2393 - )`sips -z ${size} ${size} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}.png`)}`,
2394 - { label: `sips icon ${size}x${size}`, verbose },
2395 - );
2388 + const iconSizes = [16, 32, 128, 256, 512] as const;
2389 + for (const size of iconSizes) {
2390 + yield* runCommand(
2391 + ChildProcess.make(
2392 + {},
2393 + )`sips -z ${size} ${size} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}.png`)}`,
2394 + { label: `sips icon ${size}x${size}`, verbose },
2395 + );
2396
2397 - const retinaSize = size * 2;
2398 - yield* runCommand(
2399 - ChildProcess.make(
2400 - {},
2401 - )`sips -z ${retinaSize} ${retinaSize} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}@2x.png`)}`,
2402 - { label: `sips icon ${size}x${size}@2x`, verbose },
2403 - );
2404 - }
2397 + const retinaSize = size * 2;
2398 + yield* runCommand(
2399 + ChildProcess.make(
2400 + {},
2401 + )`sips -z ${retinaSize} ${retinaSize} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}@2x.png`)}`,
2402 + { label: `sips icon ${size}x${size}@2x`, verbose },
2403 + );
2404 + }
2405
2406 - yield* runCommand(ChildProcess.make({})`iconutil -c icns ${iconsetDir} -o ${targetIcns}`, {
2407 - label: "iconutil icns",
2408 - verbose,
2409 - });
2406 + yield* runCommand(ChildProcess.make({})`iconutil -c icns ${iconsetDir} -o ${targetIcns}`, {
2407 + label: "iconutil icns",
2408 + verbose,
2409 });
2411 -}
2412 -
2413 -function stageMacIcons(stageResourcesDir: string, sourcePng: string, verbose: boolean) {
2414 - return Effect.gen(function* () {
2415 - const fs = yield* FileSystem.FileSystem;
2416 - const path = yield* Path.Path;
2417 - if (!(yield* fs.exists(sourcePng))) {
2418 - return yield* new DesktopIconSourceMissingError({
2419 - platform: "mac",
2420 - sourcePath: sourcePng,
2421 - });
2422 - }
2410 +});
2411
2424 - const tmpRoot = yield* fs.makeTempDirectoryScoped({
2425 - prefix: "t3code-icon-build-",
2412 +const stageMacIcons = Effect.fn("build-desktop-artifact.stageMacIcons")(function* (
2413 + stageResourcesDir: string,
2414 + sourcePng: string,
2415 + verbose: boolean,
2416 +) {
2417 + const fs = yield* FileSystem.FileSystem;
2418 + const path = yield* Path.Path;
2419 + if (!(yield* fs.exists(sourcePng))) {
2420 + return yield* new DesktopIconSourceMissingError({
2421 + platform: "mac",
2422 + sourcePath: sourcePng,
2423 });
2424 + }
2425
2428 - const iconPngPath = path.join(stageResourcesDir, "icon.png");
2429 - const iconIcnsPath = path.join(stageResourcesDir, "icon.icns");
2426 + const tmpRoot = yield* fs.makeTempDirectoryScoped({
2427 + prefix: "t3code-icon-build-",
2428 + });
2429
2431 - yield* runCommand(ChildProcess.make({})`sips -z 512 512 ${sourcePng} --out ${iconPngPath}`, {
2432 - label: "sips mac icon",
2433 - verbose,
2434 - });
2430 + const iconPngPath = path.join(stageResourcesDir, "icon.png");
2431 + const iconIcnsPath = path.join(stageResourcesDir, "icon.icns");
2432
2436 - yield* generateMacIconSet(sourcePng, iconIcnsPath, tmpRoot, path, verbose);
2433 + yield* runCommand(ChildProcess.make({})`sips -z 512 512 ${sourcePng} --out ${iconPngPath}`, {
2434 + label: "sips mac icon",
2435 + verbose,
2436 });
2438 -}
2437 +
2438 + yield* generateMacIconSet(sourcePng, iconIcnsPath, tmpRoot, path, verbose);
2439 +});
2440
2441 export const stageDesktopDmgBackground = Effect.fn("stageDesktopDmgBackground")(function* (
2442 stageResourcesDir: string,
@@ -2470,32 +2471,34 @@ export const stageDesktopDmgBackground = Effect.fn("stageDesktopDmgBackground")(
2471 }
2472 });
2473
2473 -function stageLinuxIcons(stageResourcesDir: string, sourcePng: string, verbose: boolean) {
2474 - return Effect.gen(function* () {
2475 - const fs = yield* FileSystem.FileSystem;
2476 - const path = yield* Path.Path;
2477 - if (!(yield* fs.exists(sourcePng))) {
2478 - return yield* new DesktopIconSourceMissingError({
2479 - platform: "linux",
2480 - sourcePath: sourcePng,
2481 - });
2482 - }
2474 +const stageLinuxIcons = Effect.fn("build-desktop-artifact.stageLinuxIcons")(function* (
2475 + stageResourcesDir: string,
2476 + sourcePng: string,
2477 + verbose: boolean,
2478 +) {
2479 + const fs = yield* FileSystem.FileSystem;
2480 + const path = yield* Path.Path;
2481 + if (!(yield* fs.exists(sourcePng))) {
2482 + return yield* new DesktopIconSourceMissingError({
2483 + platform: "linux",
2484 + sourcePath: sourcePng,
2485 + });
2486 + }
2487
2484 - const iconPath = path.join(stageResourcesDir, "icon.png");
2485 - yield* fs.copyFile(sourcePng, iconPath);
2488 + const iconPath = path.join(stageResourcesDir, "icon.png");
2489 + yield* fs.copyFile(sourcePng, iconPath);
2490
2487 - const iconsDir = path.join(stageResourcesDir, "icons");
2488 - yield* fs.makeDirectory(iconsDir, { recursive: true });
2489 - for (const iconSize of LINUX_ICON_SIZES) {
2490 - yield* stageLinuxIconSize(
2491 - sourcePng,
2492 - path.join(iconsDir, `${iconSize}x${iconSize}.png`),
2493 - iconSize,
2494 - verbose,
2495 - );
2496 - }
2497 - });
2498 -}
2491 + const iconsDir = path.join(stageResourcesDir, "icons");
2492 + yield* fs.makeDirectory(iconsDir, { recursive: true });
2493 + for (const iconSize of LINUX_ICON_SIZES) {
2494 + yield* stageLinuxIconSize(
2495 + sourcePng,
2496 + path.join(iconsDir, `${iconSize}x${iconSize}.png`),
2497 + iconSize,
2498 + verbose,
2499 + );
2500 + }
2501 +});
2502
2503 export function stageLinuxIconSize(
2504 sourcePng: string,
@@ -2531,24 +2534,25 @@ export function stageLinuxIconSize(
2534 );
2535 }
2536
2534 -function stageWindowsIcons(stageResourcesDir: string, sourceIco: string) {
2535 - return Effect.gen(function* () {
2536 - const fs = yield* FileSystem.FileSystem;
2537 - const path = yield* Path.Path;
2538 - if (!(yield* fs.exists(sourceIco))) {
2539 - return yield* new DesktopIconSourceMissingError({
2540 - platform: "win",
2541 - sourcePath: sourceIco,
2542 - });
2543 - }
2537 +const stageWindowsIcons = Effect.fn("build-desktop-artifact.stageWindowsIcons")(function* (
2538 + stageResourcesDir: string,
2539 + sourceIco: string,
2540 +) {
2541 + const fs = yield* FileSystem.FileSystem;
2542 + const path = yield* Path.Path;
2543 + if (!(yield* fs.exists(sourceIco))) {
2544 + return yield* new DesktopIconSourceMissingError({
2545 + platform: "win",
2546 + sourcePath: sourceIco,
2547 + });
2548 + }
2549
2545 - const iconPath = path.join(stageResourcesDir, "icon.ico");
2546 - yield* fs.copyFile(sourceIco, iconPath);
2547 - });
2548 -}
2550 + const iconPath = path.join(stageResourcesDir, "icon.ico");
2551 + yield* fs.copyFile(sourceIco, iconPath);
2552 +});
2553
2550 -function validateBundledClientAssets(clientDir: string) {
2551 - return Effect.gen(function* () {
2554 +const validateBundledClientAssets = Effect.fn("build-desktop-artifact.validateBundledClientAssets")(
2555 + function* (clientDir: string) {
2556 const fs = yield* FileSystem.FileSystem;
2557 const path = yield* Path.Path;
2558 const indexPath = path.join(clientDir, "index.html");
@@ -2580,8 +2584,8 @@ function validateBundledClientAssets(clientDir: string) {
2584 missingFiles: missing,
2585 });
2586 }
2583 - });
2584 -}
2587 + },
2588 +);
2589
2590 export function resolveDesktopRuntimeDependencies(
2591 dependencies: Record<string, string> | undefined,
scripts/dev-runner.ts
+366 -370
@@ -255,18 +255,18 @@ export function resolveOffset(config: {
255 return Effect.succeed({ offset: 0, source: "default ports" });
256 }
257
258 -function resolveBaseDir(baseDir: string | undefined): Effect.Effect<string, never, Path.Path> {
259 - return Effect.gen(function* () {
260 - const path = yield* Path.Path;
261 - const configured = baseDir?.trim();
262 -
263 - if (configured) {
264 - return path.resolve(configured);
265 - }
258 +const resolveBaseDir = Effect.fn("dev-runner.resolveBaseDir")(function* (
259 + baseDir: string | undefined,
260 +): Effect.fn.Return<string, never, Path.Path> {
261 + const path = yield* Path.Path;
262 + const configured = baseDir?.trim();
263 +
264 + if (configured) {
265 + return path.resolve(configured);
266 + }
267
267 - return yield* DEFAULT_T3_HOME;
268 - });
269 -}
268 + return yield* DEFAULT_T3_HOME;
269 +});
270
271 interface CreateDevRunnerEnvInput {
272 readonly mode: DevMode;
@@ -282,7 +282,7 @@ interface CreateDevRunnerEnvInput {
282 readonly devUrl: URL | undefined;
283 }
284
285 -export function createDevRunnerEnv({
285 +export const createDevRunnerEnv = Effect.fn("dev-runner.createDevRunnerEnv")(function* ({
286 mode,
287 baseEnv,
288 serverOffset,
@@ -294,111 +294,109 @@ export function createDevRunnerEnv({
294 host,
295 port,
296 devUrl,
297 -}: CreateDevRunnerEnvInput): Effect.Effect<NodeJS.ProcessEnv, never, Path.Path> {
298 - return Effect.gen(function* () {
299 - const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
300 - const webPort = BASE_WEB_PORT + webOffset;
301 - const configuredBaseDir = t3Home?.trim() || undefined;
302 - const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
303 - const isDesktopMode = mode === "dev:desktop";
304 -
305 - const output: NodeJS.ProcessEnv = {
306 - ...baseEnv,
307 - PORT: String(webPort),
308 - VITE_DEV_SERVER_URL:
309 - devUrl?.toString() ??
310 - `http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
311 - };
312 -
313 - if (configuredBaseDir !== undefined) {
314 - output.T3CODE_HOME = resolvedBaseDir;
315 - } else {
316 - delete output.T3CODE_HOME;
317 - }
297 +}: CreateDevRunnerEnvInput): Effect.fn.Return<NodeJS.ProcessEnv, never, Path.Path> {
298 + const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
299 + const webPort = BASE_WEB_PORT + webOffset;
300 + const configuredBaseDir = t3Home?.trim() || undefined;
301 + const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
302 + const isDesktopMode = mode === "dev:desktop";
303 +
304 + const output: NodeJS.ProcessEnv = {
305 + ...baseEnv,
306 + PORT: String(webPort),
307 + VITE_DEV_SERVER_URL:
308 + devUrl?.toString() ??
309 + `http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
310 + };
311
319 - // A dev-runner server is never launcher-managed. When the shell that runs
320 - // this script was itself spawned by the machine's managed t3 service (an
321 - // agent working inside T3 Code), these leak through and the child server
322 - // fails startup with "The service launcher started a different t3 version"
323 - // (serviceLauncherClient.ts resolveStartup).
324 - delete output.T3_SERVICE_LAUNCHER_CONTEXT;
325 - delete output.T3_BOOT_SERVICE_UNIT;
326 -
327 - if (!isDesktopMode) {
328 - output.T3CODE_PORT = String(serverPort);
329 - // HOST is Vite's own bind address, and the desktop branch below is the
330 - // only place we set it. An inherited one (an exported HOST, a container,
331 - // a `HOST=0.0.0.0 npm start` habit) would otherwise reach Vite and pin
332 - // its HMR socket to that address — see the `explicitHost` gate in
333 - // apps/web/vite.config.ts.
334 - delete output.HOST;
335 - if (mode === "dev" || mode === "dev:web") {
336 - // Browser dev is single-origin: everything (including /ws) is proxied
337 - // through Vite, so the client must resolve its backend from
338 - // window.location.origin rather than a baked-in localhost URL.
339 - delete output.VITE_HTTP_URL;
340 - delete output.VITE_WS_URL;
341 - // Deleting is not enough on its own: vite.config.ts calls loadRepoEnv,
342 - // which merges `.env`/`.env.local` *under* this env, so a developer
343 - // with either URL in their `.env` would get it back and silently lose
344 - // single-origin mode.
345 - output.T3CODE_SINGLE_ORIGIN_DEV = "1";
346 - } else {
347 - output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
348 - output.VITE_WS_URL = `ws://localhost:${serverPort}`;
349 - delete output.T3CODE_SINGLE_ORIGIN_DEV;
350 - }
312 + if (configuredBaseDir !== undefined) {
313 + output.T3CODE_HOME = resolvedBaseDir;
314 + } else {
315 + delete output.T3CODE_HOME;
316 + }
317 +
318 + // A dev-runner server is never launcher-managed. When the shell that runs
319 + // this script was itself spawned by the machine's managed t3 service (an
320 + // agent working inside T3 Code), these leak through and the child server
321 + // fails startup with "The service launcher started a different t3 version"
322 + // (serviceLauncherClient.ts resolveStartup).
323 + delete output.T3_SERVICE_LAUNCHER_CONTEXT;
324 + delete output.T3_BOOT_SERVICE_UNIT;
325 +
326 + if (!isDesktopMode) {
327 + output.T3CODE_PORT = String(serverPort);
328 + // HOST is Vite's own bind address, and the desktop branch below is the
329 + // only place we set it. An inherited one (an exported HOST, a container,
330 + // a `HOST=0.0.0.0 npm start` habit) would otherwise reach Vite and pin
331 + // its HMR socket to that address — see the `explicitHost` gate in
332 + // apps/web/vite.config.ts.
333 + delete output.HOST;
334 + if (mode === "dev" || mode === "dev:web") {
335 + // Browser dev is single-origin: everything (including /ws) is proxied
336 + // through Vite, so the client must resolve its backend from
337 + // window.location.origin rather than a baked-in localhost URL.
338 + delete output.VITE_HTTP_URL;
339 + delete output.VITE_WS_URL;
340 + // Deleting is not enough on its own: vite.config.ts calls loadRepoEnv,
341 + // which merges `.env`/`.env.local` *under* this env, so a developer
342 + // with either URL in their `.env` would get it back and silently lose
343 + // single-origin mode.
344 + output.T3CODE_SINGLE_ORIGIN_DEV = "1";
345 } else {
352 - output.T3CODE_PORT = String(serverPort);
353 - output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
354 - output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
355 - // Desktop pins the renderer to loopback on purpose; an ambient marker
356 - // must not make Vite drop those URLs.
346 + output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
347 + output.VITE_WS_URL = `ws://localhost:${serverPort}`;
348 delete output.T3CODE_SINGLE_ORIGIN_DEV;
358 - delete output.T3CODE_MODE;
359 - delete output.T3CODE_NO_BROWSER;
360 - delete output.T3CODE_HOST;
361 - delete output.T3CODE_DEV_AUTH_TOKEN;
349 }
350 + } else {
351 + output.T3CODE_PORT = String(serverPort);
352 + output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
353 + output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
354 + // Desktop pins the renderer to loopback on purpose; an ambient marker
355 + // must not make Vite drop those URLs.
356 + delete output.T3CODE_SINGLE_ORIGIN_DEV;
357 + delete output.T3CODE_MODE;
358 + delete output.T3CODE_NO_BROWSER;
359 + delete output.T3CODE_HOST;
360 + delete output.T3CODE_DEV_AUTH_TOKEN;
361 + }
362
364 - if (!isDesktopMode && host !== undefined) {
365 - output.T3CODE_HOST = host;
366 - }
363 + if (!isDesktopMode && host !== undefined) {
364 + output.T3CODE_HOST = host;
365 + }
366
368 - if (!isDesktopMode) {
369 - output.T3CODE_NO_BROWSER = browser === true ? "0" : "1";
370 - }
367 + if (!isDesktopMode) {
368 + output.T3CODE_NO_BROWSER = browser === true ? "0" : "1";
369 + }
370
372 - if (autoBootstrapProjectFromCwd !== undefined) {
373 - output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
374 - } else {
375 - delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
376 - }
371 + if (autoBootstrapProjectFromCwd !== undefined) {
372 + output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
373 + } else {
374 + delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
375 + }
376
378 - if (logWebSocketEvents !== undefined) {
379 - output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
380 - } else {
381 - delete output.T3CODE_LOG_WS_EVENTS;
382 - }
377 + if (logWebSocketEvents !== undefined) {
378 + output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
379 + } else {
380 + delete output.T3CODE_LOG_WS_EVENTS;
381 + }
382
384 - if (mode === "dev") {
385 - output.T3CODE_MODE = "web";
386 - delete output.T3CODE_DESKTOP_WS_URL;
387 - }
383 + if (mode === "dev") {
384 + output.T3CODE_MODE = "web";
385 + delete output.T3CODE_DESKTOP_WS_URL;
386 + }
387
389 - if (mode === "dev:server" || mode === "dev:web") {
390 - output.T3CODE_MODE = "web";
391 - delete output.T3CODE_DESKTOP_WS_URL;
392 - }
388 + if (mode === "dev:server" || mode === "dev:web") {
389 + output.T3CODE_MODE = "web";
390 + delete output.T3CODE_DESKTOP_WS_URL;
391 + }
392
394 - if (isDesktopMode) {
395 - output.HOST = DESKTOP_DEV_LOOPBACK_HOST;
396 - delete output.T3CODE_DESKTOP_WS_URL;
397 - }
393 + if (isDesktopMode) {
394 + output.HOST = DESKTOP_DEV_LOOPBACK_HOST;
395 + delete output.T3CODE_DESKTOP_WS_URL;
396 + }
397
399 - return output;
400 - });
401 -}
398 + return output;
399 +});
400
401 function portPairForOffset(offset: number): {
402 readonly serverPort: number;
@@ -410,12 +408,12 @@ function portPairForOffset(offset: number): {
408 };
409 }
410
413 -export function checkPortAvailabilityOnHosts<R>(
414 - port: number,
415 - hosts: ReadonlyArray<string>,
416 - canListenOnHost: (port: number, host: string) => Effect.Effect<boolean, never, R>,
417 -): Effect.Effect<boolean, never, R> {
418 - return Effect.gen(function* () {
411 +export const checkPortAvailabilityOnHosts = Effect.fn("dev-runner.checkPortAvailabilityOnHosts")(
412 + function* <R>(
413 + port: number,
414 + hosts: ReadonlyArray<string>,
415 + canListenOnHost: (port: number, host: string) => Effect.Effect<boolean, never, R>,
416 + ): Effect.fn.Return<boolean, never, R> {
417 for (const host of hosts) {
418 if (!(yield* canListenOnHost(port, host))) {
419 return false;
@@ -423,8 +421,8 @@ export function checkPortAvailabilityOnHosts<R>(
421 }
422
423 return true;
426 - });
427 -}
424 + },
425 +);
426
427 export function devPortProbeHosts(configuredHost: string | undefined): ReadonlyArray<string> {
428 const host = configuredHost?.trim();
@@ -454,61 +452,61 @@ interface FindFirstAvailableOffsetInput<R = NetService.NetService> {
452 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
453 }
454
457 -export function findFirstAvailableOffset<R = NetService.NetService>({
455 +export const findFirstAvailableOffset = Effect.fn("dev-runner.findFirstAvailableOffset")(function* <
456 + R = NetService.NetService,
457 +>({
458 startOffset,
459 requireServerPort,
460 requireWebPort,
461 checkPortAvailability,
462 -}: FindFirstAvailableOffsetInput<R>): Effect.Effect<number, DevRunnerPortExhaustedError, R> {
463 - return Effect.gen(function* () {
464 - const checkPort = (checkPortAvailability ??
465 - defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
466 -
467 - for (let candidate = startOffset; ; candidate += 1) {
468 - const { serverPort, webPort } = portPairForOffset(candidate);
469 - const serverPortOutOfRange = serverPort > MAX_PORT;
470 - const webPortOutOfRange = webPort > MAX_PORT;
471 -
472 - if (
473 - (requireServerPort && serverPortOutOfRange) ||
474 - (requireWebPort && webPortOutOfRange) ||
475 - (!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
476 - ) {
477 - break;
478 - }
462 +}: FindFirstAvailableOffsetInput<R>): Effect.fn.Return<number, DevRunnerPortExhaustedError, R> {
463 + const checkPort = (checkPortAvailability ??
464 + defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
465
480 - if (requireWebPort && !isBrowserAllowedPort(webPort)) {
481 - continue;
482 - }
466 + for (let candidate = startOffset; ; candidate += 1) {
467 + const { serverPort, webPort } = portPairForOffset(candidate);
468 + const serverPortOutOfRange = serverPort > MAX_PORT;
469 + const webPortOutOfRange = webPort > MAX_PORT;
470
484 - const checks: Array<Effect.Effect<boolean, never, R>> = [];
485 - if (requireServerPort) {
486 - checks.push(checkPort(serverPort, "server"));
487 - }
488 - if (requireWebPort) {
489 - checks.push(checkPort(webPort, "web"));
490 - }
471 + if (
472 + (requireServerPort && serverPortOutOfRange) ||
473 + (requireWebPort && webPortOutOfRange) ||
474 + (!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
475 + ) {
476 + break;
477 + }
478
492 - if (checks.length === 0) {
493 - return candidate;
494 - }
479 + if (requireWebPort && !isBrowserAllowedPort(webPort)) {
480 + continue;
481 + }
482
496 - const availability = yield* Effect.all(checks);
497 - if (availability.every(Boolean)) {
498 - return candidate;
499 - }
483 + const checks: Array<Effect.Effect<boolean, never, R>> = [];
484 + if (requireServerPort) {
485 + checks.push(checkPort(serverPort, "server"));
486 + }
487 + if (requireWebPort) {
488 + checks.push(checkPort(webPort, "web"));
489 }
490
502 - return yield* new DevRunnerPortExhaustedError({
503 - startOffset,
504 - requireServerPort,
505 - requireWebPort,
506 - baseServerPort: BASE_SERVER_PORT,
507 - baseWebPort: BASE_WEB_PORT,
508 - maximumPort: MAX_PORT,
509 - });
491 + if (checks.length === 0) {
492 + return candidate;
493 + }
494 +
495 + const availability = yield* Effect.all(checks);
496 + if (availability.every(Boolean)) {
497 + return candidate;
498 + }
499 + }
500 +
501 + return yield* new DevRunnerPortExhaustedError({
502 + startOffset,
503 + requireServerPort,
504 + requireWebPort,
505 + baseServerPort: BASE_SERVER_PORT,
506 + baseWebPort: BASE_WEB_PORT,
507 + maximumPort: MAX_PORT,
508 });
511 -}
509 +});
510
511 interface ResolveModePortOffsetsInput<R = NetService.NetService> {
512 readonly mode: DevMode;
@@ -518,59 +516,59 @@ interface ResolveModePortOffsetsInput<R = NetService.NetService> {
516 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
517 }
518
521 -export function resolveModePortOffsets<R = NetService.NetService>({
519 +export const resolveModePortOffsets = Effect.fn("dev-runner.resolveModePortOffsets")(function* <
520 + R = NetService.NetService,
521 +>({
522 mode,
523 startOffset,
524 hasExplicitServerPort,
525 hasExplicitDevUrl,
526 checkPortAvailability,
527 -}: ResolveModePortOffsetsInput<R>): Effect.Effect<
527 +}: ResolveModePortOffsetsInput<R>): Effect.fn.Return<
528 { readonly serverOffset: number; readonly webOffset: number },
529 DevRunnerPortExhaustedError,
530 R
531 > {
532 - return Effect.gen(function* () {
533 - const checkPort = (checkPortAvailability ??
534 - defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
535 -
536 - if (mode === "dev:web") {
537 - if (hasExplicitDevUrl) {
538 - return { serverOffset: startOffset, webOffset: startOffset };
539 - }
532 + const checkPort = (checkPortAvailability ??
533 + defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
534
541 - const webOffset = yield* findFirstAvailableOffset({
542 - startOffset,
543 - requireServerPort: false,
544 - requireWebPort: true,
545 - checkPortAvailability: checkPort,
546 - });
547 - return { serverOffset: startOffset, webOffset };
535 + if (mode === "dev:web") {
536 + if (hasExplicitDevUrl) {
537 + return { serverOffset: startOffset, webOffset: startOffset };
538 }
539
550 - if (mode === "dev:server") {
551 - if (hasExplicitServerPort) {
552 - return { serverOffset: startOffset, webOffset: startOffset };
553 - }
540 + const webOffset = yield* findFirstAvailableOffset({
541 + startOffset,
542 + requireServerPort: false,
543 + requireWebPort: true,
544 + checkPortAvailability: checkPort,
545 + });
546 + return { serverOffset: startOffset, webOffset };
547 + }
548
555 - const serverOffset = yield* findFirstAvailableOffset({
556 - startOffset,
557 - requireServerPort: true,
558 - requireWebPort: false,
559 - checkPortAvailability: checkPort,
560 - });
561 - return { serverOffset, webOffset: serverOffset };
549 + if (mode === "dev:server") {
550 + if (hasExplicitServerPort) {
551 + return { serverOffset: startOffset, webOffset: startOffset };
552 }
553
564 - const sharedOffset = yield* findFirstAvailableOffset({
554 + const serverOffset = yield* findFirstAvailableOffset({
555 startOffset,
566 - requireServerPort: !hasExplicitServerPort,
567 - requireWebPort: !hasExplicitDevUrl,
556 + requireServerPort: true,
557 + requireWebPort: false,
558 checkPortAvailability: checkPort,
559 });
560 + return { serverOffset, webOffset: serverOffset };
561 + }
562
571 - return { serverOffset: sharedOffset, webOffset: sharedOffset };
563 + const sharedOffset = yield* findFirstAvailableOffset({
564 + startOffset,
565 + requireServerPort: !hasExplicitServerPort,
566 + requireWebPort: !hasExplicitDevUrl,
567 + checkPortAvailability: checkPort,
568 });
573 -}
569 +
570 + return { serverOffset: sharedOffset, webOffset: sharedOffset };
571 +});
572
573 interface DevRunnerCliInput {
574 readonly mode: DevMode;
@@ -586,198 +584,196 @@ interface DevRunnerCliInput {
584 readonly runArgs: ReadonlyArray<string>;
585 }
586
589 -export function runDevRunnerWithInput(input: DevRunnerCliInput) {
590 - return Effect.gen(function* () {
591 - const { portOffset, devInstance } = yield* OffsetConfig.pipe(
592 - Effect.mapError(
593 - (cause) =>
594 - new DevRunnerConfigurationError({
595 - configKeys: ["T3CODE_PORT_OFFSET", "T3CODE_DEV_INSTANCE"],
596 - cause,
597 - }),
598 - ),
599 - );
587 +export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInput")(function* (
588 + input: DevRunnerCliInput,
589 +) {
590 + const { portOffset, devInstance } = yield* OffsetConfig.pipe(
591 + Effect.mapError(
592 + (cause) =>
593 + new DevRunnerConfigurationError({
594 + configKeys: ["T3CODE_PORT_OFFSET", "T3CODE_DEV_INSTANCE"],
595 + cause,
596 + }),
597 + ),
598 + );
599
601 - if (
602 - (input.mode === "dev" || input.mode === "dev:web") &&
603 - input.host !== undefined &&
604 - !isProxiableBindHost(input.host)
605 - ) {
606 - return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
607 - }
600 + if (
601 + (input.mode === "dev" || input.mode === "dev:web") &&
602 + input.host !== undefined &&
603 + !isProxiableBindHost(input.host)
604 + ) {
605 + return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
606 + }
607
609 - const worktreePath = yield* resolveGitWorktreePath(yield* HostProcess.WorkingDirectory);
608 + const worktreePath = yield* resolveGitWorktreePath(yield* HostProcess.WorkingDirectory);
609
611 - const { offset, source } = yield* resolveOffset({
612 - portOffset,
613 - devInstance,
614 - worktreePath,
615 - });
610 + const { offset, source } = yield* resolveOffset({
611 + portOffset,
612 + devInstance,
613 + worktreePath,
614 + });
615
617 - const { serverOffset, webOffset } = yield* resolveModePortOffsets({
618 - mode: input.mode,
619 - startOffset: offset,
620 - hasExplicitServerPort: input.port !== undefined,
621 - hasExplicitDevUrl: input.devUrl !== undefined,
622 - checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
623 - });
616 + const { serverOffset, webOffset } = yield* resolveModePortOffsets({
617 + mode: input.mode,
618 + startOffset: offset,
619 + hasExplicitServerPort: input.port !== undefined,
620 + hasExplicitDevUrl: input.devUrl !== undefined,
621 + checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
622 + });
623
625 - const hostEnvironment = yield* HostProcess.Environment;
626 - // A dev server started inside a worktree defaults to that worktree's own
627 - // (gitignored) `.t3` — see @t3tools/shared/devHome for why this must
628 - // outrank an ambient T3CODE_HOME. `--home-dir` still wins.
629 - const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcess.WorkingDirectory);
630 - // Trim before choosing: `--home-dir ""` is not a selection, and treating it
631 - // as one would skip the worktree default and land on the shared home —
632 - // exactly the outcome this precedence exists to prevent.
633 - const resolvedT3Home =
634 - (input.t3Home?.trim() || undefined) ??
635 - worktreeHome ??
636 - (hostEnvironment.T3CODE_HOME?.trim() || undefined);
637 - const env = yield* createDevRunnerEnv({
638 - mode: input.mode,
639 - baseEnv: hostEnvironment,
640 - serverOffset,
641 - webOffset,
642 - t3Home: resolvedT3Home,
643 - browser: input.browser,
644 - autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
645 - logWebSocketEvents: input.logWebSocketEvents,
646 - host: input.host,
647 - port: input.port,
648 - devUrl: input.devUrl,
649 - });
624 + const hostEnvironment = yield* HostProcess.Environment;
625 + // A dev server started inside a worktree defaults to that worktree's own
626 + // (gitignored) `.t3` — see @t3tools/shared/devHome for why this must
627 + // outrank an ambient T3CODE_HOME. `--home-dir` still wins.
628 + const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcess.WorkingDirectory);
629 + // Trim before choosing: `--home-dir ""` is not a selection, and treating it
630 + // as one would skip the worktree default and land on the shared home —
631 + // exactly the outcome this precedence exists to prevent.
632 + const resolvedT3Home =
633 + (input.t3Home?.trim() || undefined) ??
634 + worktreeHome ??
635 + (hostEnvironment.T3CODE_HOME?.trim() || undefined);
636 + const env = yield* createDevRunnerEnv({
637 + mode: input.mode,
638 + baseEnv: hostEnvironment,
639 + serverOffset,
640 + webOffset,
641 + t3Home: resolvedT3Home,
642 + browser: input.browser,
643 + autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
644 + logWebSocketEvents: input.logWebSocketEvents,
645 + host: input.host,
646 + port: input.port,
647 + devUrl: input.devUrl,
648 + });
649
651 - const selectionSuffix =
652 - serverOffset !== offset || webOffset !== offset
653 - ? ` selectedOffset(server=${serverOffset},web=${webOffset})`
654 - : "";
655 - const baseDir = env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME);
656 -
657 - yield* Effect.logInfo(
658 - `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
659 - );
660 -
661 - // Before the share block: --dry-run only resolves and prints. Sharing would
662 - // replace, then tear down, whatever mapping the port already had — a
663 - // surprising side effect from a command documented as inert.
664 - if (input.dryRun) {
665 - return;
666 - }
650 + const selectionSuffix =
651 + serverOffset !== offset || webOffset !== offset
652 + ? ` selectedOffset(server=${serverOffset},web=${webOffset})`
653 + : "";
654 + const baseDir = env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME);
655 +
656 + yield* Effect.logInfo(
657 + `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
658 + );
659
668 - const sharedWebPort = BASE_WEB_PORT + webOffset;
669 - if (input.share) {
670 - if (input.mode === "dev:server") {
671 - yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
672 - } else if (input.mode === "dev:desktop") {
673 - yield* Effect.logWarning(
674 - "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
675 - );
676 - } else {
677 - // acquireRelease, not share-then-addFinalizer: the mapping outlives this
678 - // process (and reboots), so the cleanup has to be registered atomically
679 - // with creating it. An interrupt landing in between would otherwise
680 - // leave a mapping pointing at a port nothing is listening on.
681 - const shared = yield* Effect.acquireRelease(
682 - shareDevServer({ webPort: sharedWebPort }),
683 - () =>
684 - unshareDevServer(sharedWebPort).pipe(
685 - Effect.flatMap((result) =>
686 - result.cleared
687 - ? Effect.void
688 - : Effect.logWarning(
689 - `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
690 - result.explanation ? `: ${result.explanation}` : ""
691 - }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,
692 - ),
693 - ),
694 - ),
695 - ).pipe(
696 - Effect.tapError((error: DevShareError) =>
697 - Effect.logWarning(
698 - `[dev-runner] could not share on the tailnet: ${error.message}${
699 - error.hint ? ` — ${error.hint}` : ""
700 - }`,
701 - ),
660 + // Before the share block: --dry-run only resolves and prints. Sharing would
661 + // replace, then tear down, whatever mapping the port already had — a
662 + // surprising side effect from a command documented as inert.
663 + if (input.dryRun) {
664 + return;
665 + }
666 +
667 + const sharedWebPort = BASE_WEB_PORT + webOffset;
668 + if (input.share) {
669 + if (input.mode === "dev:server") {
670 + yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
671 + } else if (input.mode === "dev:desktop") {
672 + yield* Effect.logWarning(
673 + "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
674 + );
675 + } else {
676 + // acquireRelease, not share-then-addFinalizer: the mapping outlives this
677 + // process (and reboots), so the cleanup has to be registered atomically
678 + // with creating it. An interrupt landing in between would otherwise
679 + // leave a mapping pointing at a port nothing is listening on.
680 + const shared = yield* Effect.acquireRelease(shareDevServer({ webPort: sharedWebPort }), () =>
681 + unshareDevServer(sharedWebPort).pipe(
682 + Effect.flatMap((result) =>
683 + result.cleared
684 + ? Effect.void
685 + : Effect.logWarning(
686 + `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
687 + result.explanation ? `: ${result.explanation}` : ""
688 + }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,
689 + ),
690 + ),
691 + ),
692 + ).pipe(
693 + Effect.tapError((error: DevShareError) =>
694 + Effect.logWarning(
695 + `[dev-runner] could not share on the tailnet: ${error.message}${
696 + error.hint ? ` — ${error.hint}` : ""
697 + }`,
698 ),
703 - Effect.option,
704 - Effect.map(Option.getOrUndefined),
705 - );
706 -
707 - if (shared) {
708 - // The app is reached from the tailnet origin. Vite already allows
709 - // *.ts.net hosts; the backend needs the origin for credentialed
710 - // requests that bypass the proxy (desktop renderer, direct calls).
711 - env.T3CODE_DEV_ALLOWED_ORIGINS = [
712 - env.T3CODE_DEV_ALLOWED_ORIGINS,
713 - new URL(shared.url).origin,
714 - ]
715 - .filter((entry) => entry && entry.length > 0)
716 - .join(",");
717 - if (input.devUrl === undefined) {
718 - env.VITE_DEV_SERVER_URL = shared.url;
719 - }
720 - // A shared origin serves a remote browser, where unbundled dev's
721 - // per-module requests each pay a tailnet round trip — a cold module
722 - // graph takes minutes to first paint. Bundled dev collapses that to a
723 - // few chunk requests.
724 - if (env.T3CODE_BUNDLED_DEV === undefined) {
725 - env.T3CODE_BUNDLED_DEV = "1";
726 - }
727 - yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
699 + ),
700 + Effect.option,
701 + Effect.map(Option.getOrUndefined),
702 + );
703 +
704 + if (shared) {
705 + // The app is reached from the tailnet origin. Vite already allows
706 + // *.ts.net hosts; the backend needs the origin for credentialed
707 + // requests that bypass the proxy (desktop renderer, direct calls).
708 + env.T3CODE_DEV_ALLOWED_ORIGINS = [
709 + env.T3CODE_DEV_ALLOWED_ORIGINS,
710 + new URL(shared.url).origin,
711 + ]
712 + .filter((entry) => entry && entry.length > 0)
713 + .join(",");
714 + if (input.devUrl === undefined) {
715 + env.VITE_DEV_SERVER_URL = shared.url;
716 }
717 + // A shared origin serves a remote browser, where unbundled dev's
718 + // per-module requests each pay a tailnet round trip — a cold module
719 + // graph takes minutes to first paint. Bundled dev collapses that to a
720 + // few chunk requests.
721 + if (env.T3CODE_BUNDLED_DEV === undefined) {
722 + env.T3CODE_BUNDLED_DEV = "1";
723 + }
724 + yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
725 }
726 }
727 + }
728
732 - const args = [...MODE_ARGS[input.mode], ...input.runArgs];
733 - const spawnCommand = yield* resolveSpawnCommand("vp", args, { env });
734 - const processContext = {
735 - mode: input.mode,
736 - executable: "vp" as const,
737 - argumentCount: args.length,
738 - shell: spawnCommand.shell,
739 - } as const;
740 - const child = yield* ChildProcess.make(spawnCommand.command, spawnCommand.args, {
741 - stdin: "inherit",
742 - stdout: "inherit",
743 - stderr: "inherit",
744 - env,
745 - extendEnv: false,
746 - shell: spawnCommand.shell,
747 - // Keep Vite+ in the same process group so terminal signals (Ctrl+C)
748 - // reach it directly. Effect defaults to detached: true on non-Windows,
749 - // which would put the runner in a new group and require manual forwarding.
750 - detached: false,
751 - forceKillAfter: "1500 millis",
752 - }).pipe(
753 - Effect.mapError(
754 - (cause) =>
755 - new DevRunnerProcessError({
756 - ...processContext,
757 - operation: "spawn",
758 - cause,
759 - }),
760 - ),
761 - );
762 -
763 - const exitCode = yield* child.exitCode.pipe(
764 - Effect.mapError(
765 - (cause) =>
766 - new DevRunnerProcessError({
767 - ...processContext,
768 - operation: "wait-for-exit",
769 - cause,
770 - }),
771 - ),
772 - );
773 - if (exitCode !== 0) {
774 - return yield* new DevRunnerProcessExitError({
775 - ...processContext,
776 - exitCode,
777 - });
778 - }
779 - });
780 -}
729 + const args = [...MODE_ARGS[input.mode], ...input.runArgs];
730 + const spawnCommand = yield* resolveSpawnCommand("vp", args, { env });
731 + const processContext = {
732 + mode: input.mode,
733 + executable: "vp" as const,
734 + argumentCount: args.length,
735 + shell: spawnCommand.shell,
736 + } as const;
737 + const child = yield* ChildProcess.make(spawnCommand.command, spawnCommand.args, {
738 + stdin: "inherit",
739 + stdout: "inherit",
740 + stderr: "inherit",
741 + env,
742 + extendEnv: false,
743 + shell: spawnCommand.shell,
744 + // Keep Vite+ in the same process group so terminal signals (Ctrl+C)
745 + // reach it directly. Effect defaults to detached: true on non-Windows,
746 + // which would put the runner in a new group and require manual forwarding.
747 + detached: false,
748 + forceKillAfter: "1500 millis",
749 + }).pipe(
750 + Effect.mapError(
751 + (cause) =>
752 + new DevRunnerProcessError({
753 + ...processContext,
754 + operation: "spawn",
755 + cause,
756 + }),
757 + ),
758 + );
759 +
760 + const exitCode = yield* child.exitCode.pipe(
761 + Effect.mapError(
762 + (cause) =>
763 + new DevRunnerProcessError({
764 + ...processContext,
765 + operation: "wait-for-exit",
766 + cause,
767 + }),
768 + ),
769 + );
770 + if (exitCode !== 0) {
771 + return yield* new DevRunnerProcessExitError({
772 + ...processContext,
773 + exitCode,
774 + });
775 + }
776 +});
777
778 const devRunnerCli = Command.make("dev-runner", {
779 mode: Argument.Literals("mode", DEV_RUNNER_MODES).pipe(
scripts/mobile-native-client.ts
+29 -30
@@ -96,40 +96,39 @@ export const hashBundle = Effect.fn("hashBundle")(function* (root: string) {
96 const fs = yield* FileSystem.FileSystem;
97 const path = yield* Path.Path;
98 const entries: string[] = [];
99 - const visit = (
99 + const visit = Effect.fn("mobile-native-client.visit")(function* (
100 relative: string,
101 - ): Effect.Effect<void, FileSystemError, FileSystem.FileSystem | Crypto.Crypto> =>
102 - Effect.gen(function* () {
103 - const names = (yield* fs.readDirectory(path.join(root, relative))).sort((a, b) =>
104 - a.localeCompare(b, "en"),
101 + ): Effect.fn.Return<void, FileSystemError, FileSystem.FileSystem | Crypto.Crypto> {
102 + const names = (yield* fs.readDirectory(path.join(root, relative))).sort((a, b) =>
103 + a.localeCompare(b, "en"),
104 + );
105 + for (const name of names) {
106 + const key = path.join(relative, name);
107 + const absolute = path.join(root, key);
108 + // FileSystem.stat follows links; readLink distinguishes them without following a cycle.
109 + const link = yield* fs.readLink(absolute).pipe(
110 + Effect.catchIf(
111 + (error) => isNotLink(error.reason.cause),
112 + () => Effect.succeed(null),
113 + ),
114 );
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 + if (link !== null) {
116 + entries.push(`link:${key}:${link}`);
117 + continue;
118 + }
119 + const info = yield* fs.stat(absolute);
120 + if (info.type === "Directory") {
121 + entries.push(`directory:${key}`);
122 + yield* visit(key);
123 + } else {
124 + const chunks = yield* fs.stream(absolute, { chunkSize: 65536 }).pipe(
125 + Stream.mapEffect((chunk) => digest(chunk)),
126 + Stream.runCollect,
127 );
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 - }
128 + entries.push(`file:${key}:${yield* digest(chunks.join("\n"))}`);
129 }
132 - });
130 + }
131 + });
132 yield* visit("");
133 return yield* digest(entries.map((entry) => `${entry.length}:${entry}`).join(""));
134 });
scripts/mobile-native-static-check.ts
+34 -36
@@ -170,62 +170,60 @@ export const runCommand = Effect.fn("runCommand")(function* (
170 }
171 });
172
173 -export function collectSources(
173 +export const collectSources = Effect.fn("mobile-native-static-check.collectSources")(function* (
174 directory: string,
175 root: string,
176 -): Effect.Effect<
176 +): Effect.fn.Return<
177 ReadonlyArray<string>,
178 NativeStaticCheckSourceDiscoveryError,
179 FileSystem.FileSystem | Path.Path
180 > {
181 - return Effect.gen(function* () {
182 - const fs = yield* FileSystem.FileSystem;
183 - const path = yield* Path.Path;
184 - const entries = yield* fs.readDirectory(directory).pipe(
181 + const fs = yield* FileSystem.FileSystem;
182 + const path = yield* Path.Path;
183 + const entries = yield* fs.readDirectory(directory).pipe(
184 + Effect.mapError(
185 + (cause) =>
186 + new NativeStaticCheckSourceDiscoveryError({
187 + operation: "read-directory",
188 + path: directory,
189 + cause,
190 + }),
191 + ),
192 + );
193 + const sources: Array<string> = [];
194 +
195 + for (const entry of entries) {
196 + const entryPath = path.join(directory, entry);
197 + const stat = yield* fs.stat(entryPath).pipe(
198 Effect.mapError(
199 (cause) =>
200 new NativeStaticCheckSourceDiscoveryError({
188 - operation: "read-directory",
189 - path: directory,
201 + operation: "stat-entry",
202 + path: entryPath,
203 cause,
204 }),
205 ),
206 );
194 - const sources: Array<string> = [];
195 -
196 - for (const entry of entries) {
197 - const entryPath = path.join(directory, entry);
198 - const stat = yield* fs.stat(entryPath).pipe(
199 - Effect.mapError(
200 - (cause) =>
201 - new NativeStaticCheckSourceDiscoveryError({
202 - operation: "stat-entry",
203 - path: entryPath,
204 - cause,
205 - }),
206 - ),
207 - );
208 -
209 - if (stat.type === "Directory") {
210 - const isGeneratedNativeProjectDirectory =
211 - directory === root && generatedNativeProjectDirectories.has(entry);
207
213 - if (excludedDirectories.has(entry) || isGeneratedNativeProjectDirectory) {
214 - continue;
215 - }
208 + if (stat.type === "Directory") {
209 + const isGeneratedNativeProjectDirectory =
210 + directory === root && generatedNativeProjectDirectories.has(entry);
211
217 - sources.push(...(yield* collectSources(entryPath, root)));
212 + if (excludedDirectories.has(entry) || isGeneratedNativeProjectDirectory) {
213 continue;
214 }
215
221 - if (stat.type === "File" && sourceExtensions.has(path.extname(entry))) {
222 - sources.push(entryPath);
223 - }
216 + sources.push(...(yield* collectSources(entryPath, root)));
217 + continue;
218 }
219
226 - return sources;
227 - });
228 -}
220 + if (stat.type === "File" && sourceExtensions.has(path.extname(entry))) {
221 + sources.push(entryPath);
222 + }
223 + }
224 +
225 + return sources;
226 +});
227
228 const runNativeStaticChecks = Effect.fn("runNativeStaticChecks")(function* () {
229 const path = yield* Path.Path;
scripts/mock-update-server.ts
+41 -38
@@ -32,32 +32,32 @@ const resolveMockUpdateServerConfig = Effect.gen(function* () {
32 } satisfies MockUpdateServerConfig;
33 });
34
35 -const isOutsideRoot = (rootRealPath: string, filePath: string) =>
36 - Effect.gen(function* () {
37 - const path = yield* Path.Path;
38 - const relativePath = path.relative(rootRealPath, filePath);
39 - return (
40 - relativePath === ".." || relativePath.startsWith("../") || relativePath.startsWith("..\\")
41 - );
42 - });
35 +const isOutsideRoot = Effect.fn("mock-update-server.isOutsideRoot")(function* (
36 + rootRealPath: string,
37 + filePath: string,
38 +) {
39 + const path = yield* Path.Path;
40 + const relativePath = path.relative(rootRealPath, filePath);
41 + return relativePath === ".." || relativePath.startsWith("../") || relativePath.startsWith("..\\");
42 +});
43
44 -const isWithinRoot = (rootRealPath: string, filePath: string) =>
45 - Effect.gen(function* () {
46 - const fileSystem = yield* FileSystem.FileSystem;
47 - const resolvedFilePath = yield* fileSystem.realPath(filePath).pipe(
48 - Effect.match({
49 - onFailure: () => undefined,
50 - onSuccess: (resolvedPath) => resolvedPath,
51 - }),
52 - );
44 +const isWithinRoot = Effect.fn("mock-update-server.isWithinRoot")(function* (
45 + rootRealPath: string,
46 + filePath: string,
47 +) {
48 + const fileSystem = yield* FileSystem.FileSystem;
49 + const resolvedFilePath = yield* fileSystem.realPath(filePath).pipe(
50 + Effect.match({
51 + onFailure: () => undefined,
52 + onSuccess: (resolvedPath) => resolvedPath,
53 + }),
54 + );
55
54 - return (
55 - resolvedFilePath !== undefined && !(yield* isOutsideRoot(rootRealPath, resolvedFilePath))
56 - );
57 - });
56 + return resolvedFilePath !== undefined && !(yield* isOutsideRoot(rootRealPath, resolvedFilePath));
57 +});
58
59 -const resolveRequestedFilePath = (rootRealPath: string, requestUrl: string | undefined) =>
60 - Effect.gen(function* () {
59 +const resolveRequestedFilePath = Effect.fn("mock-update-server.resolveRequestedFilePath")(
60 + function* (rootRealPath: string, requestUrl: string | undefined) {
61 const path = yield* Path.Path;
62 const rawPath = (requestUrl ?? "/").split("?", 1)[0] ?? "/";
63 const decodedPath = yield* Effect.try({
@@ -84,24 +84,27 @@ const resolveRequestedFilePath = (rootRealPath: string, requestUrl: string | und
84 );
85
86 return (yield* isOutsideRoot(rootRealPath, filePath)) ? undefined : filePath;
87 - });
87 + },
88 +);
89
89 -const isServableFile = (rootRealPath: string, filePath: string) =>
90 - Effect.gen(function* () {
91 - const fileSystem = yield* FileSystem.FileSystem;
92 - const stat = yield* fileSystem.stat(filePath).pipe(
93 - Effect.match({
94 - onFailure: () => undefined,
95 - onSuccess: (info) => info,
96 - }),
97 - );
90 +const isServableFile = Effect.fn("mock-update-server.isServableFile")(function* (
91 + rootRealPath: string,
92 + filePath: string,
93 +) {
94 + const fileSystem = yield* FileSystem.FileSystem;
95 + const stat = yield* fileSystem.stat(filePath).pipe(
96 + Effect.match({
97 + onFailure: () => undefined,
98 + onSuccess: (info) => info,
99 + }),
100 + );
101
99 - if (stat?.type !== "File") {
100 - return false;
101 - }
102 + if (stat?.type !== "File") {
103 + return false;
104 + }
105
103 - return yield* isWithinRoot(rootRealPath, filePath);
104 - });
106 + return yield* isWithinRoot(rootRealPath, filePath);
107 +});
108
109 export const makeMockUpdateRouteLayer = (rootRealPath: string) => {
110 return HttpRouter.add(
scripts/resolve-previous-release-tag.ts
+24 -29
@@ -192,44 +192,39 @@ const parseNightlyTag = (
192 };
193 };
194
195 -export const resolvePreviousReleaseTag = (
196 - channel: ReleaseChannel,
197 - currentTag: string,
198 - tags: ReadonlyArray<string>,
199 -) =>
200 - Effect.gen(function* () {
201 - if (channel === "stable") {
202 - const current = parseStableTag(currentTag);
203 - if (!current) {
204 - return yield* new InvalidReleaseTagError({ channel, currentTag });
205 - }
206 -
207 - const candidates = tags
208 - .map((tag) => ({ tag, parsed: parseStableTag(tag) }))
209 - .filter(
210 - (entry): entry is { tag: string; parsed: StableVersion } => entry.parsed !== undefined,
211 - )
212 - .filter((entry) => compareStableVersions(entry.parsed, current) < 0)
213 - .toSorted((left, right) => compareStableVersions(right.parsed, left.parsed));
214 -
215 - return candidates[0]?.tag;
216 - }
217 -
218 - const current = parseNightlyTag(currentTag, channel);
195 +export const resolvePreviousReleaseTag = Effect.fn(
196 + "resolve-previous-release-tag.resolvePreviousReleaseTag",
197 +)(function* (channel: ReleaseChannel, currentTag: string, tags: ReadonlyArray<string>) {
198 + if (channel === "stable") {
199 + const current = parseStableTag(currentTag);
200 if (!current) {
201 return yield* new InvalidReleaseTagError({ channel, currentTag });
202 }
203
204 const candidates = tags
224 - .map((tag) => ({ tag, parsed: parseNightlyTag(tag, channel) }))
205 + .map((tag) => ({ tag, parsed: parseStableTag(tag) }))
206 .filter(
226 - (entry): entry is { tag: string; parsed: NightlyVersion } => entry.parsed !== undefined,
207 + (entry): entry is { tag: string; parsed: StableVersion } => entry.parsed !== undefined,
208 )
228 - .filter((entry) => compareNightlyVersions(entry.parsed, current) < 0)
229 - .toSorted((left, right) => compareNightlyVersions(right.parsed, left.parsed));
209 + .filter((entry) => compareStableVersions(entry.parsed, current) < 0)
210 + .toSorted((left, right) => compareStableVersions(right.parsed, left.parsed));
211
212 return candidates[0]?.tag;
232 - });
213 + }
214 +
215 + const current = parseNightlyTag(currentTag, channel);
216 + if (!current) {
217 + return yield* new InvalidReleaseTagError({ channel, currentTag });
218 + }
219 +
220 + const candidates = tags
221 + .map((tag) => ({ tag, parsed: parseNightlyTag(tag, channel) }))
222 + .filter((entry): entry is { tag: string; parsed: NightlyVersion } => entry.parsed !== undefined)
223 + .filter((entry) => compareNightlyVersions(entry.parsed, current) < 0)
224 + .toSorted((left, right) => compareNightlyVersions(right.parsed, left.parsed));
225 +
226 + return candidates[0]?.tag;
227 +});
228
229 const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
230 stream.pipe(