Skip to content
TypeScript

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

Julius Marmingeb12631291728
diff --git a/apps/server/scripts/record-codex-app-server-replay-fixture.ts b/apps/server/scripts/record-codex-app-server-replay-fixture.ts
index b66e25ae9e7..f2287657167 100644
--- a/apps/server/scripts/record-codex-app-server-replay-fixture.ts
+++ b/apps/server/scripts/record-codex-app-server-replay-fixture.ts
@@ -1110,7 +1110,7 @@ function recorderThreadConfigMetadata(scenario: ReplayScenario) {
return keys.length === 0 ? {} : { recorderThreadConfigKeys: keys };
}
-function makeRecorder({
+const makeRecorder = Effect.fn("record-codex-app-server-replay-fixture.makeRecorder")(function* ({
outPath,
scenario,
checkout,
@@ -1118,55 +1118,53 @@ function makeRecorder({
readonly outPath: string;
readonly scenario: ReplayScenario;
readonly checkout: string;
-}): Effect.Effect<Recorder, PlatformError.PlatformError, FileSystem.FileSystem> {
- return Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- let version = "unknown";
- const records: Array<Record<string, unknown>> = [];
- const setVersion = (nextVersion: string) =>
- Effect.sync(() => {
- version = nextVersion;
- });
- const writeRecord = (record: Record<string, unknown>) =>
- Effect.sync(() => {
- records.push(record);
- });
- const flush = () => {
- const outputRecords = codexReplayRecordingOutputRecords(records, {
- workspace: process.cwd(),
- machine: {
- home: NodeOS.homedir(),
- hostname: NodeOS.hostname(),
- checkout,
- },
- });
- return fs.writeFileString(
- outPath,
- `${[
- {
- type: "transcript_start",
- provider: "codex",
- protocol: "codex.app-server",
- version,
- scenario: scenario.name,
- metadata: {
- source: "record-codex-app-server-replay-fixture",
- fileName: scenario.fileName,
- description: scenario.description,
- model: scenarioModel(scenario),
- ...recorderThreadConfigMetadata(scenario),
- },
+}): Effect.fn.Return<Recorder, PlatformError.PlatformError, FileSystem.FileSystem> {
+ const fs = yield* FileSystem.FileSystem;
+ let version = "unknown";
+ const records: Array<Record<string, unknown>> = [];
+ const setVersion = (nextVersion: string) =>
+ Effect.sync(() => {
+ version = nextVersion;
+ });
+ const writeRecord = (record: Record<string, unknown>) =>
+ Effect.sync(() => {
+ records.push(record);
+ });
+ const flush = () => {
+ const outputRecords = codexReplayRecordingOutputRecords(records, {
+ workspace: process.cwd(),
+ machine: {
+ home: NodeOS.homedir(),
+ hostname: NodeOS.hostname(),
+ checkout,
+ },
+ });
+ return fs.writeFileString(
+ outPath,
+ `${[
+ {
+ type: "transcript_start",
+ provider: "codex",
+ protocol: "codex.app-server",
+ version,
+ scenario: scenario.name,
+ metadata: {
+ source: "record-codex-app-server-replay-fixture",
+ fileName: scenario.fileName,
+ description: scenario.description,
+ model: scenarioModel(scenario),
+ ...recorderThreadConfigMetadata(scenario),
},
- ...outputRecords,
- ]
- .map((record) => JSON.stringify(record))
- .join("\n")}\n`,
- );
- };
+ },
+ ...outputRecords,
+ ]
+ .map((record) => JSON.stringify(record))
+ .join("\n")}\n`,
+ );
+ };
- return { path: outPath, setVersion, writeRecord, flush };
- });
-}
+ return { path: outPath, setVersion, writeRecord, flush };
+});
function layerCodex({ recorder }: { readonly recorder: Recorder }) {
const clientRequestMethodById = new Map<string, string>();
@@ -1348,16 +1346,16 @@ function installReplayHandlers({
);
}
-function runReplaySession({
- scenario,
- run,
- recorder,
-}: {
- readonly scenario: ReplayScenario;
- readonly run: ReplayRun;
- readonly recorder: Recorder;
-}) {
- return Effect.gen(function* () {
+const runReplaySession = Effect.fn("record-codex-app-server-replay-fixture.runReplaySession")(
+ function* ({
+ scenario,
+ run,
+ recorder,
+ }: {
+ readonly scenario: ReplayScenario;
+ readonly run: ReplayRun;
+ readonly recorder: Recorder;
+ }) {
const startedTurns = yield* makeReplayRecorderDeferredRegistry();
const completedTurns = yield* makeReplayRecorderDeferredRegistry();
const startedCommandExecutions = yield* makeReplayRecorderDeferredRegistry();
@@ -1397,73 +1395,72 @@ function runReplaySession({
return client;
});
- const runTurnStep = (
+ const runTurnStep = Effect.fn("record-codex-app-server-replay-fixture.runTurnStep")(function* (
client: CodexClient.CodexAppServerClient["Service"],
threadId: string,
step: TurnReplayStep,
- ) =>
- Effect.gen(function* () {
- const turnParams: TurnStartParams = {
- approvalPolicy: "never",
- sandboxPolicy: { type: "dangerFullAccess" },
- cwd: process.cwd(),
- model,
- summary: "detailed",
- approvalsReviewer: "user",
- ...(run.interactionMode === "plan"
- ? { collaborationMode: planCollaborationMode(model) }
- : {}),
- ...run.turnDefaults,
- ...step.turnOverrides,
- input: turnInput(step.prompt),
- threadId,
- };
-
- if (step.type === "steeredTurn") {
- approvalGate = yield* Deferred.make<void>();
- }
+ ) {
+ const turnParams: TurnStartParams = {
+ approvalPolicy: "never",
+ sandboxPolicy: { type: "dangerFullAccess" },
+ cwd: process.cwd(),
+ model,
+ summary: "detailed",
+ approvalsReviewer: "user",
+ ...(run.interactionMode === "plan"
+ ? { collaborationMode: planCollaborationMode(model) }
+ : {}),
+ ...run.turnDefaults,
+ ...step.turnOverrides,
+ input: turnInput(step.prompt),
+ threadId,
+ };
+
+ if (step.type === "steeredTurn") {
+ approvalGate = yield* Deferred.make<void>();
+ }
- const turn = yield* client.request("turn/start", turnParams);
- const turnId = getTurnId(turn);
- const started = yield* getStarted(turnId);
- yield* getCompletion(turnId);
+ const turn = yield* client.request("turn/start", turnParams);
+ const turnId = getTurnId(turn);
+ const started = yield* getStarted(turnId);
+ yield* getCompletion(turnId);
- if (step.type === "steeredTurn") {
- yield* Deferred.await(started);
- yield* client.request("turn/steer", {
- expectedTurnId: turnId,
- input: turnInput(step.steer),
- threadId,
- });
- if (approvalGate) {
- yield* Deferred.succeed(approvalGate, void 0);
- approvalGate = undefined;
- }
+ if (step.type === "steeredTurn") {
+ yield* Deferred.await(started);
+ yield* client.request("turn/steer", {
+ expectedTurnId: turnId,
+ input: turnInput(step.steer),
+ threadId,
+ });
+ if (approvalGate) {
+ yield* Deferred.succeed(approvalGate, void 0);
+ approvalGate = undefined;
}
+ }
- if (step.type === "interruptedTurn") {
- if (step.interruptAfterCommandExecutionStarted === true) {
- const commandExecutionStarted = yield* getCommandExecutionStarted(turnId);
- yield* Deferred.await(commandExecutionStarted);
- } else {
- yield* Effect.sleep(`${step.interruptAfterMs ?? 1_500} millis`);
- }
- yield* client.request("turn/interrupt", {
+ if (step.type === "interruptedTurn") {
+ if (step.interruptAfterCommandExecutionStarted === true) {
+ const commandExecutionStarted = yield* getCommandExecutionStarted(turnId);
+ yield* Deferred.await(commandExecutionStarted);
+ } else {
+ yield* Effect.sleep(`${step.interruptAfterMs ?? 1_500} millis`);
+ }
+ yield* client.request("turn/interrupt", {
+ threadId,
+ turnId,
+ });
+ for (const processId of runningCommandProcessIds.get(turnId)?.values() ?? []) {
+ yield* client.raw.request("thread/backgroundTerminals/terminate", {
threadId,
- turnId,
+ processId,
});
- for (const processId of runningCommandProcessIds.get(turnId)?.values() ?? []) {
- yield* client.raw.request("thread/backgroundTerminals/terminate", {
- threadId,
- processId,
- });
- }
}
+ }
- const completed = yield* getCompletion(turnId);
- yield* Deferred.await(completed);
- lastTurnIdByThread.set(threadId, turnId);
- });
+ const completed = yield* getCompletion(turnId);
+ yield* Deferred.await(completed);
+ lastTurnIdByThread.set(threadId, turnId);
+ });
if (scenario.name === "provider_thread_resume") {
const firstStep = run.steps[0];
@@ -1611,36 +1608,34 @@ function runReplaySession({
}),
),
);
- });
-}
+ },
+);
-function runScenario({
+const runScenario = Effect.fn("record-codex-app-server-replay-fixture.runScenario")(function* ({
scenario,
outPath,
}: {
readonly scenario: ReplayScenario;
readonly outPath: string;
}) {
- return Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const checkout = path.resolve(yield* path.fromFileUrl(new URL("../../..", import.meta.url)));
- const recorder = yield* makeRecorder({ outPath, scenario, checkout });
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const checkout = path.resolve(yield* path.fromFileUrl(new URL("../../..", import.meta.url)));
+ const recorder = yield* makeRecorder({ outPath, scenario, checkout });
- yield* fs.makeDirectory(path.dirname(outPath), { recursive: true });
- yield* Console.log(`Writing ${scenario.name} Codex replay events to ${recorder.path}`);
+ yield* fs.makeDirectory(path.dirname(outPath), { recursive: true });
+ yield* Console.log(`Writing ${scenario.name} Codex replay events to ${recorder.path}`);
- yield* Effect.forEach(scenario.runs, (run) => runReplaySession({ scenario, run, recorder }), {
- concurrency: 1,
- });
+ yield* Effect.forEach(scenario.runs, (run) => runReplaySession({ scenario, run, recorder }), {
+ concurrency: 1,
+ });
- yield* recorder.writeRecord({
- type: "runtime_exit",
- status: "success",
- });
- yield* recorder.flush();
+ yield* recorder.writeRecord({
+ type: "runtime_exit",
+ status: "success",
});
-}
+ yield* recorder.flush();
+});
const program = Effect.gen(function* () {
const path = yield* Path.Path;
diff --git a/infra/relay/src/hooks/HookForwarder.test.ts b/infra/relay/src/hooks/HookForwarder.test.ts
index 0da5bc219bb..c243127830f 100644
--- a/infra/relay/src/hooks/HookForwarder.test.ts
+++ b/infra/relay/src/hooks/HookForwarder.test.ts
@@ -700,6 +700,29 @@ describe("HookForwarder", () => {
.find((span) => span.name === "relay.hooks.forward")
?.attributes.has("relay.hook.upstream_outcome"),
).toBe(false);
+
+ for (const [holdWebhooksWhileOffline, inboxCapacity, outcome] of [
+ [false, Infinity, "environment_unavailable"],
+ [true, Infinity, "held"],
+ [true, 0, "inbox_full"],
+ ] as const) {
+ spans.length = 0;
+ yield* forward(
+ makeHarness({
+ links: [{ ...managedLink, holdWebhooksWhileOffline }],
+ inboxCapacity,
+ execute: (request) =>
+ Effect.succeed(
+ HttpClientResponse.fromWeb(request, new Response("", { status: 503 })),
+ ),
+ }),
+ );
+ expect(
+ spans
+ .find((span) => span.name === "relay.hooks.forward")
+ ?.attributes.get("relay.hook.outcome"),
+ ).toBe(outcome);
+ }
}),
);
diff --git a/infra/relay/src/hooks/HookForwarder.ts b/infra/relay/src/hooks/HookForwarder.ts
index 65bed83d758..2c13063cffd 100644
--- a/infra/relay/src/hooks/HookForwarder.ts
+++ b/infra/relay/src/hooks/HookForwarder.ts
@@ -236,14 +236,14 @@ const make = Effect.gen(function* () {
const inbox = yield* HookInbox.HookInbox;
const crypto = yield* Crypto.Crypto;
- const signDeliveryProof = (input: {
- readonly environmentId: string;
- readonly deliveryId: string;
- readonly receivedAt: string;
- readonly hookId: string;
- readonly jti: string;
- }) =>
- Effect.gen(function* () {
+ const signDeliveryProof = Effect.fn("HookForwarder.signDeliveryProof")(
+ function* (input: {
+ readonly environmentId: string;
+ readonly deliveryId: string;
+ readonly receivedAt: string;
+ readonly hookId: string;
+ readonly jti: string;
+ }) {
const now = Math.floor((yield* Clock.currentTimeMillis) / 1_000);
return yield* signRelayJwt({
privateKey: Redacted.value(settings.cloudMintPrivateKey),
@@ -261,7 +261,9 @@ const make = Effect.gen(function* () {
hookId: input.hookId,
} satisfies RelayHookDeliveryProofPayload,
});
- }).pipe(Effect.orDie);
+ },
+ (effect, _input) => effect.pipe(Effect.orDie),
+ );
const handle = Effect.fn("relay.hooks.forward")(function* (
request: HttpServerRequest.HttpServerRequest,
@@ -354,37 +356,37 @@ const make = Effect.gen(function* () {
headers: { ...forwardedHeaders(request.headers), [RELAY_HOOK_DELIVERY_HEADER]: proof },
body: body.success,
};
- const holdOrFail = (status: 503 | 504, error: string) =>
- Effect.gen(function* () {
- if (!endpoint.holdWhileOffline) {
- yield* outcome(error);
- return errorResponse(status, error);
- }
- const stored = yield* inbox
- .hold({
- endpointKey: parsed.endpointKey,
- baseUrl: endpoint.httpBaseUrl,
- hook,
- })
- .pipe(
- Effect.catch((cause) =>
- Effect.logWarning("Could not hold webhook request", {
- environmentId: endpoint.environmentId,
- errorTag: cause._tag,
- }).pipe(Effect.as(null)),
- ),
- );
- if (stored === null) {
- yield* outcome(error);
- return errorResponse(status, error);
- }
- if (!stored) {
- yield* outcome("inbox_full");
- return errorResponse(503, "inbox_full");
- }
- yield* outcome("held");
- return HttpServerResponse.jsonUnsafe({ queued: true }, { status: 202 });
- });
+ // Keep offline outcomes on the enclosing relay.hooks.forward span.
+ const holdOrFail = Effect.fnUntraced(function* (status: 503 | 504, error: string) {
+ if (!endpoint.holdWhileOffline) {
+ yield* outcome(error);
+ return errorResponse(status, error);
+ }
+ const stored = yield* inbox
+ .hold({
+ endpointKey: parsed.endpointKey,
+ baseUrl: endpoint.httpBaseUrl,
+ hook,
+ })
+ .pipe(
+ Effect.catch((cause) =>
+ Effect.logWarning("Could not hold webhook request", {
+ environmentId: endpoint.environmentId,
+ errorTag: cause._tag,
+ }).pipe(Effect.as(null)),
+ ),
+ );
+ if (stored === null) {
+ yield* outcome(error);
+ return errorResponse(status, error);
+ }
+ if (!stored) {
+ yield* outcome("inbox_full");
+ return errorResponse(503, "inbox_full");
+ }
+ yield* outcome("held");
+ return HttpServerResponse.jsonUnsafe({ queued: true }, { status: 202 });
+ });
const upstream = yield* sendUpstream(endpoint.httpBaseUrl, hook).pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
diff --git a/infra/relay/src/hooks/HookInboxObject.ts b/infra/relay/src/hooks/HookInboxObject.ts
index 2d1c8ef9768..409395eab0e 100644
--- a/infra/relay/src/hooks/HookInboxObject.ts
+++ b/infra/relay/src/hooks/HookInboxObject.ts
@@ -89,33 +89,39 @@ export const layer = HookInboxObject.make(
effect.pipe(Effect.provide(layerSql), Effect.orDie);
yield* run(HookInboxStore.migrate);
- const scheduleBy = (at: number) =>
- Effect.gen(function* () {
- const current = yield* state.storage.getAlarm();
- if (current === null || current > at) yield* state.storage.setAlarm(at);
- });
+ const scheduleBy = Effect.fn("HookInboxObject.scheduleBy")(function* (at: number) {
+ const current = yield* state.storage.getAlarm();
+ if (current === null || current > at) yield* state.storage.setAlarm(at);
+ });
+ // withInboxSpan supplies each method's root span; avoid a second wrapper span.
return {
- hold: (hook: HookInboxStore.HeldHook, baseUrl: string) =>
- Effect.gen(function* () {
+ hold: Effect.fnUntraced(
+ function* (hook: HookInboxStore.HeldHook, baseUrl: string) {
const dueAt = yield* run(HookInboxStore.hold(hook, baseUrl));
yield* Effect.annotateCurrentSpan({ "relay.inbox.stored": dueAt !== null });
if (dueAt === null) return false;
yield* scheduleBy(dueAt);
return true;
- }).pipe(withInboxSpan("relay.inbox.hold", inboxId)),
- wake: (baseUrl: string) =>
- Effect.gen(function* () {
+ },
+ withInboxSpan("relay.inbox.hold", inboxId),
+ ),
+ wake: Effect.fnUntraced(
+ function* (baseUrl: string) {
const pending = yield* run(HookInboxStore.wake(baseUrl));
yield* Effect.annotateCurrentSpan({ "relay.inbox.pending": pending });
if (pending) yield* state.storage.setAlarm(yield* Clock.currentTimeMillis);
return pending;
- }).pipe(withInboxSpan("relay.inbox.wake", inboxId)),
- clear: () =>
- Effect.gen(function* () {
+ },
+ withInboxSpan("relay.inbox.wake", inboxId),
+ ),
+ clear: Effect.fnUntraced(
+ function* () {
yield* run(HookInboxStore.clear);
yield* state.storage.deleteAlarm();
- }).pipe(withInboxSpan("relay.inbox.clear", inboxId)),
+ },
+ withInboxSpan("relay.inbox.clear", inboxId),
+ ),
alarm: () =>
run(HookInboxStore.deliverDue(deliver)).pipe(
// A wake during this run may already have asked for an earlier
diff --git a/infra/relay/src/hooks/HookInboxStore.test.ts b/infra/relay/src/hooks/HookInboxStore.test.ts
index f48a3aa3b07..4667b21db22 100644
--- a/infra/relay/src/hooks/HookInboxStore.test.ts
+++ b/infra/relay/src/hooks/HookInboxStore.test.ts
@@ -8,6 +8,7 @@ import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as SqlClient from "effect/sql/SqlClient";
import * as TestClock from "effect/testing/TestClock";
+import * as Tracer from "effect/Tracer";
import * as HookInboxStore from "./HookInboxStore.ts";
@@ -44,6 +45,35 @@ const withInbox = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
);
describe("HookInboxStore", () => {
+ it.effect.each(["delivered", "unreachable"] as const)(
+ "keeps %s delivery results on the operation span",
+ (outcome) =>
+ withInbox(
+ Effect.gen(function* () {
+ yield* HookInboxStore.hold(yield* hook("traced"), BASE_URL);
+ const spans: Array<Tracer.NativeSpan> = [];
+ const tracer = Tracer.make({
+ span(options) {
+ const span = new Tracer.NativeSpan(options);
+ spans.push(span);
+ return span;
+ },
+ });
+ yield* HookInboxStore.deliverDue(deliverer(() => outcome).send).pipe(
+ Effect.withTracer(tracer),
+ );
+ const run = spans.find((span) => span.name === "HookInboxStore.deliverDue");
+ expect(run?.attributes.get("relay.inbox.run_result")).toBe(
+ outcome === "delivered" ? "drained" : "unreachable",
+ );
+ expect(run?.attributes.get("relay.inbox.sent")).toBe(1);
+ expect(run?.attributes.get("relay.inbox.delivered")).toBe(
+ outcome === "delivered" ? 1 : 0,
+ );
+ }),
+ ),
+ );
+
it.effect.each(["delivered", "busy", "unreachable"] as const)(
"stops a prefetched batch cleared during a %s send",
(outcome) =>
diff --git a/infra/relay/src/hooks/HookInboxStore.ts b/infra/relay/src/hooks/HookInboxStore.ts
index 3edd2be17d6..aa7aa0d4e25 100644
--- a/infra/relay/src/hooks/HookInboxStore.ts
+++ b/infra/relay/src/hooks/HookInboxStore.ts
@@ -132,19 +132,21 @@ export const migrate = Effect.gen(function* () {
`;
});
-const setTarget = (baseUrl: string, options: { readonly resetFailures: boolean }) =>
- Effect.gen(function* () {
- const sql = yield* SqlClient.SqlClient;
- yield* options.resetFailures
- ? sql`
+const setTarget = Effect.fn("HookInboxStore.setTarget")(function* (
+ baseUrl: string,
+ options: { readonly resetFailures: boolean },
+) {
+ const sql = yield* SqlClient.SqlClient;
+ yield* options.resetFailures
+ ? sql`
INSERT INTO held_hooks_target (id, base_url) VALUES (1, ${baseUrl})
ON CONFLICT (id) DO UPDATE SET base_url = excluded.base_url, failures = 0
`
- : sql`
+ : sql`
INSERT INTO held_hooks_target (id, base_url) VALUES (1, ${baseUrl})
ON CONFLICT (id) DO UPDATE SET base_url = excluded.base_url
`;
- });
+});
const readTarget = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
@@ -218,18 +220,17 @@ const backlogSize = Effect.gen(function* () {
return rows[0] ?? { count: 0, bytes: 0 };
});
-const refusalReason = (hook: HeldHook) =>
- Effect.gen(function* () {
- const sql = yield* SqlClient.SqlClient;
- const existing = yield* sql<{ readonly id: string }>`
+const refusalReason = Effect.fn("HookInboxStore.refusalReason")(function* (hook: HeldHook) {
+ const sql = yield* SqlClient.SqlClient;
+ const existing = yield* sql<{ readonly id: string }>`
SELECT id FROM held_hooks WHERE id = ${hook.id}
`;
- if (existing.length > 0) return "already_held";
- const backlog = yield* backlogSize;
- if (backlog.count >= HOOK_INBOX_MAX_REQUESTS) return "max_requests";
- if (backlog.bytes + hook.body.byteLength > HOOK_INBOX_MAX_BYTES) return "max_bytes";
- return "max_per_hook";
- });
+ if (existing.length > 0) return "already_held";
+ const backlog = yield* backlogSize;
+ if (backlog.count >= HOOK_INBOX_MAX_REQUESTS) return "max_requests";
+ if (backlog.bytes + hook.body.byteLength > HOOK_INBOX_MAX_BYTES) return "max_bytes";
+ return "max_per_hook";
+});
export const wake = Effect.fn("HookInboxStore.wake")(function* (baseUrl: string) {
if (!(yield* hasPending)) return false;
@@ -277,22 +278,22 @@ export const deliverDue = Effect.fn("HookInboxStore.deliverDue")(function* <R>(
let longestWaitMs = 0;
const busyHooks = new Set<string>();
- const annotateRun = (result: string) =>
- Effect.gen(function* () {
- const backlog = yield* backlogSize;
- yield* Effect.annotateCurrentSpan({
- "relay.inbox.run_result": result,
- "relay.inbox.sent": sent,
- "relay.inbox.delivered": delivered,
- "relay.inbox.busy_hooks": busyHooks.size,
- "relay.inbox.expired": expired.length,
- "relay.inbox.unreadable": unreadable,
- "relay.inbox.consecutive_failures": failures,
- "relay.inbox.longest_wait_ms": longestWaitMs,
- "relay.inbox.held_count": backlog.count,
- "relay.inbox.held_bytes": backlog.bytes,
- });
+ // Delivery results and counts belong to the enclosing deliverDue span.
+ const annotateRun = Effect.fnUntraced(function* (result: string) {
+ const backlog = yield* backlogSize;
+ yield* Effect.annotateCurrentSpan({
+ "relay.inbox.run_result": result,
+ "relay.inbox.sent": sent,
+ "relay.inbox.delivered": delivered,
+ "relay.inbox.busy_hooks": busyHooks.size,
+ "relay.inbox.expired": expired.length,
+ "relay.inbox.unreadable": unreadable,
+ "relay.inbox.consecutive_failures": failures,
+ "relay.inbox.longest_wait_ms": longestWaitMs,
+ "relay.inbox.held_count": backlog.count,
+ "relay.inbox.held_bytes": backlog.bytes,
});
+ });
const stillHeld = (seq: number) =>
sql<{ readonly seq: number }>`SELECT seq FROM held_hooks WHERE seq = ${seq}`.pipe(
Effect.map((rows) => rows.length > 0),
diff --git a/infra/relay/src/hooks/upstream.ts b/infra/relay/src/hooks/upstream.ts
index 902cc3f3b80..a0d3a4780fc 100644
--- a/infra/relay/src/hooks/upstream.ts
+++ b/infra/relay/src/hooks/upstream.ts
@@ -73,43 +73,45 @@ const readCapped = (response: HttpClientResponse.HttpClientResponse) =>
* Sends a webhook request through the environment's tunnel. Fails when the
* environment cannot be reached, and succeeds with None on timeout.
*/
-export const sendUpstream = (baseUrl: string, hook: UpstreamHook) =>
- Effect.gen(function* () {
- const httpClient = yield* HttpClient.HttpClient;
- const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
- // The environment's span joins this trace. Set by hand: the client span
- // that would propagate it is off, because it records the token in url.full.
- const parent = yield* Effect.currentSpan.pipe(Effect.option);
- const headers: Record<string, string> = {
- ...hook.headers,
- ...(Option.isSome(parent) ? HttpTraceContext.toHeaders(parent.value) : {}),
- [RELAY_DELIVERY_ID_HEADER]: hook.id,
- [RELAY_RECEIVED_AT_HEADER]: hook.receivedAt,
- };
- let request = HttpClientRequest.make(hook.method as "GET" | "POST" | "PUT" | "PATCH")(
- `${base}api/hooks/${hook.rawHookId}/${hook.rawToken}${hook.query ? `?${hook.query}` : ""}`,
- { headers },
- );
- if (HttpMethod.hasBody(request.method)) {
- request = HttpClientRequest.bodyUint8Array(request, hook.body, headers["content-type"]);
- }
- return yield* httpClient.execute(request).pipe(
- Effect.flatMap((response) =>
- readCapped(response).pipe(
- Effect.map((body): UpstreamResponse => {
- const outcome = response.headers["x-t3-hook-outcome"];
- return {
- status: response.status,
- contentType: response.headers["content-type"],
- outcome: outcome !== undefined && OUTCOME_PATTERN.test(outcome) ? outcome : undefined,
- body,
- };
- }),
- ),
+export const sendUpstream = Effect.fn("upstream.sendUpstream")(function* (
+ baseUrl: string,
+ hook: UpstreamHook,
+) {
+ const httpClient = yield* HttpClient.HttpClient;
+ const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
+ // The environment's span joins this trace. Set by hand: the client span
+ // that would propagate it is off, because it records the token in url.full.
+ const parent = yield* Effect.currentSpan.pipe(Effect.option);
+ const headers: Record<string, string> = {
+ ...hook.headers,
+ ...(Option.isSome(parent) ? HttpTraceContext.toHeaders(parent.value) : {}),
+ [RELAY_DELIVERY_ID_HEADER]: hook.id,
+ [RELAY_RECEIVED_AT_HEADER]: hook.receivedAt,
+ };
+ let request = HttpClientRequest.make(hook.method as "GET" | "POST" | "PUT" | "PATCH")(
+ `${base}api/hooks/${hook.rawHookId}/${hook.rawToken}${hook.query ? `?${hook.query}` : ""}`,
+ { headers },
+ );
+ if (HttpMethod.hasBody(request.method)) {
+ request = HttpClientRequest.bodyUint8Array(request, hook.body, headers["content-type"]);
+ }
+ return yield* httpClient.execute(request).pipe(
+ Effect.flatMap((response) =>
+ readCapped(response).pipe(
+ Effect.map((body): UpstreamResponse => {
+ const outcome = response.headers["x-t3-hook-outcome"];
+ return {
+ status: response.status,
+ contentType: response.headers["content-type"],
+ outcome: outcome !== undefined && OUTCOME_PATTERN.test(outcome) ? outcome : undefined,
+ body,
+ };
+ }),
),
- withoutRedirects,
- // The client span would record url.full, which carries the token.
- Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
- Effect.timeoutOption(Duration.millis(RELAY_HOOK_UPSTREAM_TIMEOUT_MS)),
- );
- });
+ ),
+ withoutRedirects,
+ // The client span would record url.full, which carries the token.
+ Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
+ Effect.timeoutOption(Duration.millis(RELAY_HOOK_UPSTREAM_TIMEOUT_MS)),
+ );
+});
diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.ts
index 1db129ab834..49f3d33814c 100644
--- a/infra/relay/src/http/Api.ts
+++ b/infra/relay/src/http/Api.ts
@@ -207,51 +207,51 @@ const relayRequestDeadline = <E, R>(
const SENDER_TRACE_HEADER = /^(traceparent|tracestate|b3|x-b3-.*)$/i;
-export const traceRelayHttpRequest = <E, R>(
+// The method-named server span is created below; this wrapper must not add another span.
+export const traceRelayHttpRequest = Effect.fnUntraced(function* <E, R>(
httpEffect: Effect.Effect<
HttpServerResponse.HttpServerResponse,
E,
HttpServerRequest.HttpServerRequest | R
>,
-) =>
- Effect.gen(function* () {
- const request = yield* HttpServerRequest.HttpServerRequest;
- const traced = appendRelayTraceContextResponseHeader.pipe(
- Effect.andThen(relayRequestDeadline(httpEffect)),
- );
- if (!isRelayHookPath(request.url)) {
- return yield* HttpMiddleware.tracer(traced).pipe(
- Effect.provideService(HttpMiddleware.TracerDisabledWhen, () => false),
- // HttpMiddleware finalizes its span on the dispatcher; do not close a request-scoped exporter first.
- Effect.ensuring(Effect.yieldNow),
- );
- }
- // Hook URLs carry a secret token: the tracer and deadline log see a redacted
- // request, while the route itself still receives the original. A webhook
- // sender's trace context is dropped, so it cannot pick the trace our relay
- // and environment spans land in.
- const redacted = request.modify({
- url: redactRelayHookUrl(request.url),
- headers: Headers.removeMany(
- request.headers,
- Object.keys(request.headers).filter((name) => SENDER_TRACE_HEADER.test(name)),
- ),
- });
- return yield* HttpMiddleware.tracer(
- appendRelayTraceContextResponseHeader.pipe(
- Effect.andThen(
- relayRequestDeadline(
- httpEffect.pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, request)),
- RELAY_HOOK_REQUEST_DEADLINE_MS,
- ),
- ),
- ),
- ).pipe(
- Effect.provideService(HttpServerRequest.HttpServerRequest, redacted),
+) {
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ const traced = appendRelayTraceContextResponseHeader.pipe(
+ Effect.andThen(relayRequestDeadline(httpEffect)),
+ );
+ if (!isRelayHookPath(request.url)) {
+ return yield* HttpMiddleware.tracer(traced).pipe(
Effect.provideService(HttpMiddleware.TracerDisabledWhen, () => false),
+ // HttpMiddleware finalizes its span on the dispatcher; do not close a request-scoped exporter first.
Effect.ensuring(Effect.yieldNow),
);
+ }
+ // Hook URLs carry a secret token: the tracer and deadline log see a redacted
+ // request, while the route itself still receives the original. A webhook
+ // sender's trace context is dropped, so it cannot pick the trace our relay
+ // and environment spans land in.
+ const redacted = request.modify({
+ url: redactRelayHookUrl(request.url),
+ headers: Headers.removeMany(
+ request.headers,
+ Object.keys(request.headers).filter((name) => SENDER_TRACE_HEADER.test(name)),
+ ),
});
+ return yield* HttpMiddleware.tracer(
+ appendRelayTraceContextResponseHeader.pipe(
+ Effect.andThen(
+ relayRequestDeadline(
+ httpEffect.pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, request)),
+ RELAY_HOOK_REQUEST_DEADLINE_MS,
+ ),
+ ),
+ ),
+ ).pipe(
+ Effect.provideService(HttpServerRequest.HttpServerRequest, redacted),
+ Effect.provideService(HttpMiddleware.TracerDisabledWhen, () => false),
+ Effect.ensuring(Effect.yieldNow),
+ );
+});
const layerWebhookHeaderRedaction = Layer.effect(
Headers.CurrentRedactedNames,
@@ -1147,8 +1147,9 @@ export const layerServerApi = HttpApiBuilder.group(
const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
const publishSignatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures;
const heldHooks = yield* HeldHooks.HeldHooks;
- const requireOwnEnvironment = (environmentId: string) =>
- Effect.gen(function* () {
+ const requireOwnEnvironment =
+ /* Request instrumentation already owns the span; keep this helper in that context. */
+ Effect.fnUntraced(function* (environmentId: string) {
const principal = yield* RelayEnvironmentPrincipal;
if (principal.environmentId !== environmentId) {
return yield* new HttpApiError.Unauthorized({});
diff --git a/scripts/build-cli-archive.ts b/scripts/build-cli-archive.ts
index 25a53b73d7d..c5610687138 100644
--- a/scripts/build-cli-archive.ts
+++ b/scripts/build-cli-archive.ts
@@ -230,12 +230,12 @@ const stageRuntimeExternals = Effect.fn("stageRuntimeExternals")(function* (inpu
yield* removeNestedBinDirectories(fs, path, path.join(input.stageDir, "node_modules"));
});
-const removeNestedBinDirectories = (
- fs: FileSystem.FileSystem,
- path: Path.Path,
- root: string,
-): Effect.Effect<void, PlatformError.PlatformError> =>
- Effect.gen(function* () {
+const removeNestedBinDirectories = Effect.fn("build-cli-archive.removeNestedBinDirectories")(
+ function* (
+ fs: FileSystem.FileSystem,
+ path: Path.Path,
+ root: string,
+ ): Effect.fn.Return<void, PlatformError.PlatformError> {
const entries = yield* fs.readDirectory(root).pipe(Effect.orElseSucceed(() => []));
for (const entry of entries) {
const child = path.join(root, entry);
@@ -248,7 +248,8 @@ const removeNestedBinDirectories = (
yield* removeNestedBinDirectories(fs, path, child);
}
}
- });
+ },
+);
const stageWebClient = Effect.fn("stageWebClient")(function* (source: string, target: string) {
const fs = yield* FileSystem.FileSystem;
diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts
index 5688143ebc5..a8c535795cb 100644
--- a/scripts/build-desktop-artifact.ts
+++ b/scripts/build-desktop-artifact.ts
@@ -2066,11 +2066,11 @@ export const copyDirectoryPreservingSymlinks = Effect.fn("copyDirectoryPreservin
// probe cannot resolve through staging and Windows needs no symlink privilege.
yield* fs.copy(source, destination);
- const restoreRelativeSymlinks = (
- sourceDirectory: string,
- destinationDirectory: string,
- ): Effect.Effect<void, PlatformError | BundleNotSelfContainedError> =>
- Effect.gen(function* () {
+ const restoreRelativeSymlinks = Effect.fn("build-desktop-artifact.restoreRelativeSymlinks")(
+ function* (
+ sourceDirectory: string,
+ destinationDirectory: string,
+ ): Effect.fn.Return<void, PlatformError | BundleNotSelfContainedError> {
for (const entry of yield* fs.readDirectory(sourceDirectory)) {
const sourceEntry = path.join(sourceDirectory, entry);
const destinationEntry = path.join(destinationDirectory, entry);
@@ -2107,7 +2107,8 @@ export const copyDirectoryPreservingSymlinks = Effect.fn("copyDirectoryPreservin
}
}
}
- });
+ },
+ );
yield* restoreRelativeSymlinks(source, destination);
},
@@ -2373,69 +2374,69 @@ export const stageBrowserSecret = Effect.fn("stageBrowserSecret")(function* (inp
);
});
-function generateMacIconSet(
+const generateMacIconSet = Effect.fn("build-desktop-artifact.generateMacIconSet")(function* (
sourcePng: string,
targetIcns: string,
tmpRoot: string,
path: Path.Path,
verbose: boolean,
) {
- return Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const iconsetDir = path.join(tmpRoot, "icon.iconset");
- yield* fs.makeDirectory(iconsetDir, { recursive: true });
+ const fs = yield* FileSystem.FileSystem;
+ const iconsetDir = path.join(tmpRoot, "icon.iconset");
+ yield* fs.makeDirectory(iconsetDir, { recursive: true });
- const iconSizes = [16, 32, 128, 256, 512] as const;
- for (const size of iconSizes) {
- yield* runCommand(
- ChildProcess.make(
- {},
- )`sips -z ${size} ${size} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}.png`)}`,
- { label: `sips icon ${size}x${size}`, verbose },
- );
+ const iconSizes = [16, 32, 128, 256, 512] as const;
+ for (const size of iconSizes) {
+ yield* runCommand(
+ ChildProcess.make(
+ {},
+ )`sips -z ${size} ${size} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}.png`)}`,
+ { label: `sips icon ${size}x${size}`, verbose },
+ );
- const retinaSize = size * 2;
- yield* runCommand(
- ChildProcess.make(
- {},
- )`sips -z ${retinaSize} ${retinaSize} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}@2x.png`)}`,
- { label: `sips icon ${size}x${size}@2x`, verbose },
- );
- }
+ const retinaSize = size * 2;
+ yield* runCommand(
+ ChildProcess.make(
+ {},
+ )`sips -z ${retinaSize} ${retinaSize} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}@2x.png`)}`,
+ { label: `sips icon ${size}x${size}@2x`, verbose },
+ );
+ }
- yield* runCommand(ChildProcess.make({})`iconutil -c icns ${iconsetDir} -o ${targetIcns}`, {
- label: "iconutil icns",
- verbose,
- });
+ yield* runCommand(ChildProcess.make({})`iconutil -c icns ${iconsetDir} -o ${targetIcns}`, {
+ label: "iconutil icns",
+ verbose,
});
-}
-
-function stageMacIcons(stageResourcesDir: string, sourcePng: string, verbose: boolean) {
- return Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- if (!(yield* fs.exists(sourcePng))) {
- return yield* new DesktopIconSourceMissingError({
- platform: "mac",
- sourcePath: sourcePng,
- });
- }
+});
- const tmpRoot = yield* fs.makeTempDirectoryScoped({
- prefix: "t3code-icon-build-",
+const stageMacIcons = Effect.fn("build-desktop-artifact.stageMacIcons")(function* (
+ stageResourcesDir: string,
+ sourcePng: string,
+ verbose: boolean,
+) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ if (!(yield* fs.exists(sourcePng))) {
+ return yield* new DesktopIconSourceMissingError({
+ platform: "mac",
+ sourcePath: sourcePng,
});
+ }
- const iconPngPath = path.join(stageResourcesDir, "icon.png");
- const iconIcnsPath = path.join(stageResourcesDir, "icon.icns");
+ const tmpRoot = yield* fs.makeTempDirectoryScoped({
+ prefix: "t3code-icon-build-",
+ });
- yield* runCommand(ChildProcess.make({})`sips -z 512 512 ${sourcePng} --out ${iconPngPath}`, {
- label: "sips mac icon",
- verbose,
- });
+ const iconPngPath = path.join(stageResourcesDir, "icon.png");
+ const iconIcnsPath = path.join(stageResourcesDir, "icon.icns");
- yield* generateMacIconSet(sourcePng, iconIcnsPath, tmpRoot, path, verbose);
+ yield* runCommand(ChildProcess.make({})`sips -z 512 512 ${sourcePng} --out ${iconPngPath}`, {
+ label: "sips mac icon",
+ verbose,
});
-}
+
+ yield* generateMacIconSet(sourcePng, iconIcnsPath, tmpRoot, path, verbose);
+});
export const stageDesktopDmgBackground = Effect.fn("stageDesktopDmgBackground")(function* (
stageResourcesDir: string,
@@ -2470,32 +2471,34 @@ export const stageDesktopDmgBackground = Effect.fn("stageDesktopDmgBackground")(
}
});
-function stageLinuxIcons(stageResourcesDir: string, sourcePng: string, verbose: boolean) {
- return Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- if (!(yield* fs.exists(sourcePng))) {
- return yield* new DesktopIconSourceMissingError({
- platform: "linux",
- sourcePath: sourcePng,
- });
- }
+const stageLinuxIcons = Effect.fn("build-desktop-artifact.stageLinuxIcons")(function* (
+ stageResourcesDir: string,
+ sourcePng: string,
+ verbose: boolean,
+) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ if (!(yield* fs.exists(sourcePng))) {
+ return yield* new DesktopIconSourceMissingError({
+ platform: "linux",
+ sourcePath: sourcePng,
+ });
+ }
- const iconPath = path.join(stageResourcesDir, "icon.png");
- yield* fs.copyFile(sourcePng, iconPath);
+ const iconPath = path.join(stageResourcesDir, "icon.png");
+ yield* fs.copyFile(sourcePng, iconPath);
- const iconsDir = path.join(stageResourcesDir, "icons");
- yield* fs.makeDirectory(iconsDir, { recursive: true });
- for (const iconSize of LINUX_ICON_SIZES) {
- yield* stageLinuxIconSize(
- sourcePng,
- path.join(iconsDir, `${iconSize}x${iconSize}.png`),
- iconSize,
- verbose,
- );
- }
- });
-}
+ const iconsDir = path.join(stageResourcesDir, "icons");
+ yield* fs.makeDirectory(iconsDir, { recursive: true });
+ for (const iconSize of LINUX_ICON_SIZES) {
+ yield* stageLinuxIconSize(
+ sourcePng,
+ path.join(iconsDir, `${iconSize}x${iconSize}.png`),
+ iconSize,
+ verbose,
+ );
+ }
+});
export function stageLinuxIconSize(
sourcePng: string,
@@ -2531,24 +2534,25 @@ export function stageLinuxIconSize(
);
}
-function stageWindowsIcons(stageResourcesDir: string, sourceIco: string) {
- return Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- if (!(yield* fs.exists(sourceIco))) {
- return yield* new DesktopIconSourceMissingError({
- platform: "win",
- sourcePath: sourceIco,
- });
- }
+const stageWindowsIcons = Effect.fn("build-desktop-artifact.stageWindowsIcons")(function* (
+ stageResourcesDir: string,
+ sourceIco: string,
+) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ if (!(yield* fs.exists(sourceIco))) {
+ return yield* new DesktopIconSourceMissingError({
+ platform: "win",
+ sourcePath: sourceIco,
+ });
+ }
- const iconPath = path.join(stageResourcesDir, "icon.ico");
- yield* fs.copyFile(sourceIco, iconPath);
- });
-}
+ const iconPath = path.join(stageResourcesDir, "icon.ico");
+ yield* fs.copyFile(sourceIco, iconPath);
+});
-function validateBundledClientAssets(clientDir: string) {
- return Effect.gen(function* () {
+const validateBundledClientAssets = Effect.fn("build-desktop-artifact.validateBundledClientAssets")(
+ function* (clientDir: string) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const indexPath = path.join(clientDir, "index.html");
@@ -2580,8 +2584,8 @@ function validateBundledClientAssets(clientDir: string) {
missingFiles: missing,
});
}
- });
-}
+ },
+);
export function resolveDesktopRuntimeDependencies(
dependencies: Record<string, string> | undefined,
diff --git a/scripts/dev-runner.ts b/scripts/dev-runner.ts
index 31f521a96d8..efedef4b4f3 100644
--- a/scripts/dev-runner.ts
+++ b/scripts/dev-runner.ts
@@ -255,18 +255,18 @@ export function resolveOffset(config: {
return Effect.succeed({ offset: 0, source: "default ports" });
}
-function resolveBaseDir(baseDir: string | undefined): Effect.Effect<string, never, Path.Path> {
- return Effect.gen(function* () {
- const path = yield* Path.Path;
- const configured = baseDir?.trim();
-
- if (configured) {
- return path.resolve(configured);
- }
+const resolveBaseDir = Effect.fn("dev-runner.resolveBaseDir")(function* (
+ baseDir: string | undefined,
+): Effect.fn.Return<string, never, Path.Path> {
+ const path = yield* Path.Path;
+ const configured = baseDir?.trim();
+
+ if (configured) {
+ return path.resolve(configured);
+ }
- return yield* DEFAULT_T3_HOME;
- });
-}
+ return yield* DEFAULT_T3_HOME;
+});
interface CreateDevRunnerEnvInput {
readonly mode: DevMode;
@@ -282,7 +282,7 @@ interface CreateDevRunnerEnvInput {
readonly devUrl: URL | undefined;
}
-export function createDevRunnerEnv({
+export const createDevRunnerEnv = Effect.fn("dev-runner.createDevRunnerEnv")(function* ({
mode,
baseEnv,
serverOffset,
@@ -294,111 +294,109 @@ export function createDevRunnerEnv({
host,
port,
devUrl,
-}: CreateDevRunnerEnvInput): Effect.Effect<NodeJS.ProcessEnv, never, Path.Path> {
- return Effect.gen(function* () {
- const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
- const webPort = BASE_WEB_PORT + webOffset;
- const configuredBaseDir = t3Home?.trim() || undefined;
- const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
- const isDesktopMode = mode === "dev:desktop";
-
- const output: NodeJS.ProcessEnv = {
- ...baseEnv,
- PORT: String(webPort),
- VITE_DEV_SERVER_URL:
- devUrl?.toString() ??
- `http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
- };
-
- if (configuredBaseDir !== undefined) {
- output.T3CODE_HOME = resolvedBaseDir;
- } else {
- delete output.T3CODE_HOME;
- }
+}: CreateDevRunnerEnvInput): Effect.fn.Return<NodeJS.ProcessEnv, never, Path.Path> {
+ const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
+ const webPort = BASE_WEB_PORT + webOffset;
+ const configuredBaseDir = t3Home?.trim() || undefined;
+ const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
+ const isDesktopMode = mode === "dev:desktop";
+
+ const output: NodeJS.ProcessEnv = {
+ ...baseEnv,
+ PORT: String(webPort),
+ VITE_DEV_SERVER_URL:
+ devUrl?.toString() ??
+ `http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
+ };
- // A dev-runner server is never launcher-managed. When the shell that runs
- // this script was itself spawned by the machine's managed t3 service (an
- // agent working inside T3 Code), these leak through and the child server
- // fails startup with "The service launcher started a different t3 version"
- // (serviceLauncherClient.ts resolveStartup).
- delete output.T3_SERVICE_LAUNCHER_CONTEXT;
- delete output.T3_BOOT_SERVICE_UNIT;
-
- if (!isDesktopMode) {
- output.T3CODE_PORT = String(serverPort);
- // HOST is Vite's own bind address, and the desktop branch below is the
- // only place we set it. An inherited one (an exported HOST, a container,
- // a `HOST=0.0.0.0 npm start` habit) would otherwise reach Vite and pin
- // its HMR socket to that address — see the `explicitHost` gate in
- // apps/web/vite.config.ts.
- delete output.HOST;
- if (mode === "dev" || mode === "dev:web") {
- // Browser dev is single-origin: everything (including /ws) is proxied
- // through Vite, so the client must resolve its backend from
- // window.location.origin rather than a baked-in localhost URL.
- delete output.VITE_HTTP_URL;
- delete output.VITE_WS_URL;
- // Deleting is not enough on its own: vite.config.ts calls loadRepoEnv,
- // which merges `.env`/`.env.local` *under* this env, so a developer
- // with either URL in their `.env` would get it back and silently lose
- // single-origin mode.
- output.T3CODE_SINGLE_ORIGIN_DEV = "1";
- } else {
- output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
- output.VITE_WS_URL = `ws://localhost:${serverPort}`;
- delete output.T3CODE_SINGLE_ORIGIN_DEV;
- }
+ if (configuredBaseDir !== undefined) {
+ output.T3CODE_HOME = resolvedBaseDir;
+ } else {
+ delete output.T3CODE_HOME;
+ }
+
+ // A dev-runner server is never launcher-managed. When the shell that runs
+ // this script was itself spawned by the machine's managed t3 service (an
+ // agent working inside T3 Code), these leak through and the child server
+ // fails startup with "The service launcher started a different t3 version"
+ // (serviceLauncherClient.ts resolveStartup).
+ delete output.T3_SERVICE_LAUNCHER_CONTEXT;
+ delete output.T3_BOOT_SERVICE_UNIT;
+
+ if (!isDesktopMode) {
+ output.T3CODE_PORT = String(serverPort);
+ // HOST is Vite's own bind address, and the desktop branch below is the
+ // only place we set it. An inherited one (an exported HOST, a container,
+ // a `HOST=0.0.0.0 npm start` habit) would otherwise reach Vite and pin
+ // its HMR socket to that address — see the `explicitHost` gate in
+ // apps/web/vite.config.ts.
+ delete output.HOST;
+ if (mode === "dev" || mode === "dev:web") {
+ // Browser dev is single-origin: everything (including /ws) is proxied
+ // through Vite, so the client must resolve its backend from
+ // window.location.origin rather than a baked-in localhost URL.
+ delete output.VITE_HTTP_URL;
+ delete output.VITE_WS_URL;
+ // Deleting is not enough on its own: vite.config.ts calls loadRepoEnv,
+ // which merges `.env`/`.env.local` *under* this env, so a developer
+ // with either URL in their `.env` would get it back and silently lose
+ // single-origin mode.
+ output.T3CODE_SINGLE_ORIGIN_DEV = "1";
} else {
- output.T3CODE_PORT = String(serverPort);
- output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
- output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
- // Desktop pins the renderer to loopback on purpose; an ambient marker
- // must not make Vite drop those URLs.
+ output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
+ output.VITE_WS_URL = `ws://localhost:${serverPort}`;
delete output.T3CODE_SINGLE_ORIGIN_DEV;
- delete output.T3CODE_MODE;
- delete output.T3CODE_NO_BROWSER;
- delete output.T3CODE_HOST;
- delete output.T3CODE_DEV_AUTH_TOKEN;
}
+ } else {
+ output.T3CODE_PORT = String(serverPort);
+ output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
+ output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
+ // Desktop pins the renderer to loopback on purpose; an ambient marker
+ // must not make Vite drop those URLs.
+ delete output.T3CODE_SINGLE_ORIGIN_DEV;
+ delete output.T3CODE_MODE;
+ delete output.T3CODE_NO_BROWSER;
+ delete output.T3CODE_HOST;
+ delete output.T3CODE_DEV_AUTH_TOKEN;
+ }
- if (!isDesktopMode && host !== undefined) {
- output.T3CODE_HOST = host;
- }
+ if (!isDesktopMode && host !== undefined) {
+ output.T3CODE_HOST = host;
+ }
- if (!isDesktopMode) {
- output.T3CODE_NO_BROWSER = browser === true ? "0" : "1";
- }
+ if (!isDesktopMode) {
+ output.T3CODE_NO_BROWSER = browser === true ? "0" : "1";
+ }
- if (autoBootstrapProjectFromCwd !== undefined) {
- output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
- } else {
- delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
- }
+ if (autoBootstrapProjectFromCwd !== undefined) {
+ output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
+ } else {
+ delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
+ }
- if (logWebSocketEvents !== undefined) {
- output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
- } else {
- delete output.T3CODE_LOG_WS_EVENTS;
- }
+ if (logWebSocketEvents !== undefined) {
+ output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
+ } else {
+ delete output.T3CODE_LOG_WS_EVENTS;
+ }
- if (mode === "dev") {
- output.T3CODE_MODE = "web";
- delete output.T3CODE_DESKTOP_WS_URL;
- }
+ if (mode === "dev") {
+ output.T3CODE_MODE = "web";
+ delete output.T3CODE_DESKTOP_WS_URL;
+ }
- if (mode === "dev:server" || mode === "dev:web") {
- output.T3CODE_MODE = "web";
- delete output.T3CODE_DESKTOP_WS_URL;
- }
+ if (mode === "dev:server" || mode === "dev:web") {
+ output.T3CODE_MODE = "web";
+ delete output.T3CODE_DESKTOP_WS_URL;
+ }
- if (isDesktopMode) {
- output.HOST = DESKTOP_DEV_LOOPBACK_HOST;
- delete output.T3CODE_DESKTOP_WS_URL;
- }
+ if (isDesktopMode) {
+ output.HOST = DESKTOP_DEV_LOOPBACK_HOST;
+ delete output.T3CODE_DESKTOP_WS_URL;
+ }
- return output;
- });
-}
+ return output;
+});
function portPairForOffset(offset: number): {
readonly serverPort: number;
@@ -410,12 +408,12 @@ function portPairForOffset(offset: number): {
};
}
-export function checkPortAvailabilityOnHosts<R>(
- port: number,
- hosts: ReadonlyArray<string>,
- canListenOnHost: (port: number, host: string) => Effect.Effect<boolean, never, R>,
-): Effect.Effect<boolean, never, R> {
- return Effect.gen(function* () {
+export const checkPortAvailabilityOnHosts = Effect.fn("dev-runner.checkPortAvailabilityOnHosts")(
+ function* <R>(
+ port: number,
+ hosts: ReadonlyArray<string>,
+ canListenOnHost: (port: number, host: string) => Effect.Effect<boolean, never, R>,
+ ): Effect.fn.Return<boolean, never, R> {
for (const host of hosts) {
if (!(yield* canListenOnHost(port, host))) {
return false;
@@ -423,8 +421,8 @@ export function checkPortAvailabilityOnHosts<R>(
}
return true;
- });
-}
+ },
+);
export function devPortProbeHosts(configuredHost: string | undefined): ReadonlyArray<string> {
const host = configuredHost?.trim();
@@ -454,61 +452,61 @@ interface FindFirstAvailableOffsetInput<R = NetService.NetService> {
readonly checkPortAvailability?: PortAvailabilityCheck<R>;
}
-export function findFirstAvailableOffset<R = NetService.NetService>({
+export const findFirstAvailableOffset = Effect.fn("dev-runner.findFirstAvailableOffset")(function* <
+ R = NetService.NetService,
+>({
startOffset,
requireServerPort,
requireWebPort,
checkPortAvailability,
-}: FindFirstAvailableOffsetInput<R>): Effect.Effect<number, DevRunnerPortExhaustedError, R> {
- return Effect.gen(function* () {
- const checkPort = (checkPortAvailability ??
- defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
-
- for (let candidate = startOffset; ; candidate += 1) {
- const { serverPort, webPort } = portPairForOffset(candidate);
- const serverPortOutOfRange = serverPort > MAX_PORT;
- const webPortOutOfRange = webPort > MAX_PORT;
-
- if (
- (requireServerPort && serverPortOutOfRange) ||
- (requireWebPort && webPortOutOfRange) ||
- (!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
- ) {
- break;
- }
+}: FindFirstAvailableOffsetInput<R>): Effect.fn.Return<number, DevRunnerPortExhaustedError, R> {
+ const checkPort = (checkPortAvailability ??
+ defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
- if (requireWebPort && !isBrowserAllowedPort(webPort)) {
- continue;
- }
+ for (let candidate = startOffset; ; candidate += 1) {
+ const { serverPort, webPort } = portPairForOffset(candidate);
+ const serverPortOutOfRange = serverPort > MAX_PORT;
+ const webPortOutOfRange = webPort > MAX_PORT;
- const checks: Array<Effect.Effect<boolean, never, R>> = [];
- if (requireServerPort) {
- checks.push(checkPort(serverPort, "server"));
- }
- if (requireWebPort) {
- checks.push(checkPort(webPort, "web"));
- }
+ if (
+ (requireServerPort && serverPortOutOfRange) ||
+ (requireWebPort && webPortOutOfRange) ||
+ (!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
+ ) {
+ break;
+ }
- if (checks.length === 0) {
- return candidate;
- }
+ if (requireWebPort && !isBrowserAllowedPort(webPort)) {
+ continue;
+ }
- const availability = yield* Effect.all(checks);
- if (availability.every(Boolean)) {
- return candidate;
- }
+ const checks: Array<Effect.Effect<boolean, never, R>> = [];
+ if (requireServerPort) {
+ checks.push(checkPort(serverPort, "server"));
+ }
+ if (requireWebPort) {
+ checks.push(checkPort(webPort, "web"));
}
- return yield* new DevRunnerPortExhaustedError({
- startOffset,
- requireServerPort,
- requireWebPort,
- baseServerPort: BASE_SERVER_PORT,
- baseWebPort: BASE_WEB_PORT,
- maximumPort: MAX_PORT,
- });
+ if (checks.length === 0) {
+ return candidate;
+ }
+
+ const availability = yield* Effect.all(checks);
+ if (availability.every(Boolean)) {
+ return candidate;
+ }
+ }
+
+ return yield* new DevRunnerPortExhaustedError({
+ startOffset,
+ requireServerPort,
+ requireWebPort,
+ baseServerPort: BASE_SERVER_PORT,
+ baseWebPort: BASE_WEB_PORT,
+ maximumPort: MAX_PORT,
});
-}
+});
interface ResolveModePortOffsetsInput<R = NetService.NetService> {
readonly mode: DevMode;
@@ -518,59 +516,59 @@ interface ResolveModePortOffsetsInput<R = NetService.NetService> {
readonly checkPortAvailability?: PortAvailabilityCheck<R>;
}
-export function resolveModePortOffsets<R = NetService.NetService>({
+export const resolveModePortOffsets = Effect.fn("dev-runner.resolveModePortOffsets")(function* <
+ R = NetService.NetService,
+>({
mode,
startOffset,
hasExplicitServerPort,
hasExplicitDevUrl,
checkPortAvailability,
-}: ResolveModePortOffsetsInput<R>): Effect.Effect<
+}: ResolveModePortOffsetsInput<R>): Effect.fn.Return<
{ readonly serverOffset: number; readonly webOffset: number },
DevRunnerPortExhaustedError,
R
> {
- return Effect.gen(function* () {
- const checkPort = (checkPortAvailability ??
- defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
-
- if (mode === "dev:web") {
- if (hasExplicitDevUrl) {
- return { serverOffset: startOffset, webOffset: startOffset };
- }
+ const checkPort = (checkPortAvailability ??
+ defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
- const webOffset = yield* findFirstAvailableOffset({
- startOffset,
- requireServerPort: false,
- requireWebPort: true,
- checkPortAvailability: checkPort,
- });
- return { serverOffset: startOffset, webOffset };
+ if (mode === "dev:web") {
+ if (hasExplicitDevUrl) {
+ return { serverOffset: startOffset, webOffset: startOffset };
}
- if (mode === "dev:server") {
- if (hasExplicitServerPort) {
- return { serverOffset: startOffset, webOffset: startOffset };
- }
+ const webOffset = yield* findFirstAvailableOffset({
+ startOffset,
+ requireServerPort: false,
+ requireWebPort: true,
+ checkPortAvailability: checkPort,
+ });
+ return { serverOffset: startOffset, webOffset };
+ }
- const serverOffset = yield* findFirstAvailableOffset({
- startOffset,
- requireServerPort: true,
- requireWebPort: false,
- checkPortAvailability: checkPort,
- });
- return { serverOffset, webOffset: serverOffset };
+ if (mode === "dev:server") {
+ if (hasExplicitServerPort) {
+ return { serverOffset: startOffset, webOffset: startOffset };
}
- const sharedOffset = yield* findFirstAvailableOffset({
+ const serverOffset = yield* findFirstAvailableOffset({
startOffset,
- requireServerPort: !hasExplicitServerPort,
- requireWebPort: !hasExplicitDevUrl,
+ requireServerPort: true,
+ requireWebPort: false,
checkPortAvailability: checkPort,
});
+ return { serverOffset, webOffset: serverOffset };
+ }
- return { serverOffset: sharedOffset, webOffset: sharedOffset };
+ const sharedOffset = yield* findFirstAvailableOffset({
+ startOffset,
+ requireServerPort: !hasExplicitServerPort,
+ requireWebPort: !hasExplicitDevUrl,
+ checkPortAvailability: checkPort,
});
-}
+
+ return { serverOffset: sharedOffset, webOffset: sharedOffset };
+});
interface DevRunnerCliInput {
readonly mode: DevMode;
@@ -586,198 +584,196 @@ interface DevRunnerCliInput {
readonly runArgs: ReadonlyArray<string>;
}
-export function runDevRunnerWithInput(input: DevRunnerCliInput) {
- return Effect.gen(function* () {
- const { portOffset, devInstance } = yield* OffsetConfig.pipe(
- Effect.mapError(
- (cause) =>
- new DevRunnerConfigurationError({
- configKeys: ["T3CODE_PORT_OFFSET", "T3CODE_DEV_INSTANCE"],
- cause,
- }),
- ),
- );
+export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInput")(function* (
+ input: DevRunnerCliInput,
+) {
+ const { portOffset, devInstance } = yield* OffsetConfig.pipe(
+ Effect.mapError(
+ (cause) =>
+ new DevRunnerConfigurationError({
+ configKeys: ["T3CODE_PORT_OFFSET", "T3CODE_DEV_INSTANCE"],
+ cause,
+ }),
+ ),
+ );
- if (
- (input.mode === "dev" || input.mode === "dev:web") &&
- input.host !== undefined &&
- !isProxiableBindHost(input.host)
- ) {
- return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
- }
+ if (
+ (input.mode === "dev" || input.mode === "dev:web") &&
+ input.host !== undefined &&
+ !isProxiableBindHost(input.host)
+ ) {
+ return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
+ }
- const worktreePath = yield* resolveGitWorktreePath(yield* HostProcess.WorkingDirectory);
+ const worktreePath = yield* resolveGitWorktreePath(yield* HostProcess.WorkingDirectory);
- const { offset, source } = yield* resolveOffset({
- portOffset,
- devInstance,
- worktreePath,
- });
+ const { offset, source } = yield* resolveOffset({
+ portOffset,
+ devInstance,
+ worktreePath,
+ });
- const { serverOffset, webOffset } = yield* resolveModePortOffsets({
- mode: input.mode,
- startOffset: offset,
- hasExplicitServerPort: input.port !== undefined,
- hasExplicitDevUrl: input.devUrl !== undefined,
- checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
- });
+ const { serverOffset, webOffset } = yield* resolveModePortOffsets({
+ mode: input.mode,
+ startOffset: offset,
+ hasExplicitServerPort: input.port !== undefined,
+ hasExplicitDevUrl: input.devUrl !== undefined,
+ checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
+ });
- const hostEnvironment = yield* HostProcess.Environment;
- // A dev server started inside a worktree defaults to that worktree's own
- // (gitignored) `.t3` — see @t3tools/shared/devHome for why this must
- // outrank an ambient T3CODE_HOME. `--home-dir` still wins.
- const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcess.WorkingDirectory);
- // Trim before choosing: `--home-dir ""` is not a selection, and treating it
- // as one would skip the worktree default and land on the shared home —
- // exactly the outcome this precedence exists to prevent.
- const resolvedT3Home =
- (input.t3Home?.trim() || undefined) ??
- worktreeHome ??
- (hostEnvironment.T3CODE_HOME?.trim() || undefined);
- const env = yield* createDevRunnerEnv({
- mode: input.mode,
- baseEnv: hostEnvironment,
- serverOffset,
- webOffset,
- t3Home: resolvedT3Home,
- browser: input.browser,
- autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
- logWebSocketEvents: input.logWebSocketEvents,
- host: input.host,
- port: input.port,
- devUrl: input.devUrl,
- });
+ const hostEnvironment = yield* HostProcess.Environment;
+ // A dev server started inside a worktree defaults to that worktree's own
+ // (gitignored) `.t3` — see @t3tools/shared/devHome for why this must
+ // outrank an ambient T3CODE_HOME. `--home-dir` still wins.
+ const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcess.WorkingDirectory);
+ // Trim before choosing: `--home-dir ""` is not a selection, and treating it
+ // as one would skip the worktree default and land on the shared home —
+ // exactly the outcome this precedence exists to prevent.
+ const resolvedT3Home =
+ (input.t3Home?.trim() || undefined) ??
+ worktreeHome ??
+ (hostEnvironment.T3CODE_HOME?.trim() || undefined);
+ const env = yield* createDevRunnerEnv({
+ mode: input.mode,
+ baseEnv: hostEnvironment,
+ serverOffset,
+ webOffset,
+ t3Home: resolvedT3Home,
+ browser: input.browser,
+ autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
+ logWebSocketEvents: input.logWebSocketEvents,
+ host: input.host,
+ port: input.port,
+ devUrl: input.devUrl,
+ });
- const selectionSuffix =
- serverOffset !== offset || webOffset !== offset
- ? ` selectedOffset(server=${serverOffset},web=${webOffset})`
- : "";
- const baseDir = env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME);
-
- yield* Effect.logInfo(
- `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
- );
-
- // Before the share block: --dry-run only resolves and prints. Sharing would
- // replace, then tear down, whatever mapping the port already had — a
- // surprising side effect from a command documented as inert.
- if (input.dryRun) {
- return;
- }
+ const selectionSuffix =
+ serverOffset !== offset || webOffset !== offset
+ ? ` selectedOffset(server=${serverOffset},web=${webOffset})`
+ : "";
+ const baseDir = env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME);
+
+ yield* Effect.logInfo(
+ `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
+ );
- const sharedWebPort = BASE_WEB_PORT + webOffset;
- if (input.share) {
- if (input.mode === "dev:server") {
- yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
- } else if (input.mode === "dev:desktop") {
- yield* Effect.logWarning(
- "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
- );
- } else {
- // acquireRelease, not share-then-addFinalizer: the mapping outlives this
- // process (and reboots), so the cleanup has to be registered atomically
- // with creating it. An interrupt landing in between would otherwise
- // leave a mapping pointing at a port nothing is listening on.
- const shared = yield* Effect.acquireRelease(
- shareDevServer({ webPort: sharedWebPort }),
- () =>
- unshareDevServer(sharedWebPort).pipe(
- Effect.flatMap((result) =>
- result.cleared
- ? Effect.void
- : Effect.logWarning(
- `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
- result.explanation ? `: ${result.explanation}` : ""
- }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,
- ),
- ),
- ),
- ).pipe(
- Effect.tapError((error: DevShareError) =>
- Effect.logWarning(
- `[dev-runner] could not share on the tailnet: ${error.message}${
- error.hint ? ` — ${error.hint}` : ""
- }`,
- ),
+ // Before the share block: --dry-run only resolves and prints. Sharing would
+ // replace, then tear down, whatever mapping the port already had — a
+ // surprising side effect from a command documented as inert.
+ if (input.dryRun) {
+ return;
+ }
+
+ const sharedWebPort = BASE_WEB_PORT + webOffset;
+ if (input.share) {
+ if (input.mode === "dev:server") {
+ yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
+ } else if (input.mode === "dev:desktop") {
+ yield* Effect.logWarning(
+ "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
+ );
+ } else {
+ // acquireRelease, not share-then-addFinalizer: the mapping outlives this
+ // process (and reboots), so the cleanup has to be registered atomically
+ // with creating it. An interrupt landing in between would otherwise
+ // leave a mapping pointing at a port nothing is listening on.
+ const shared = yield* Effect.acquireRelease(shareDevServer({ webPort: sharedWebPort }), () =>
+ unshareDevServer(sharedWebPort).pipe(
+ Effect.flatMap((result) =>
+ result.cleared
+ ? Effect.void
+ : Effect.logWarning(
+ `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
+ result.explanation ? `: ${result.explanation}` : ""
+ }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,
+ ),
+ ),
+ ),
+ ).pipe(
+ Effect.tapError((error: DevShareError) =>
+ Effect.logWarning(
+ `[dev-runner] could not share on the tailnet: ${error.message}${
+ error.hint ? ` — ${error.hint}` : ""
+ }`,
),
- Effect.option,
- Effect.map(Option.getOrUndefined),
- );
-
- if (shared) {
- // The app is reached from the tailnet origin. Vite already allows
- // *.ts.net hosts; the backend needs the origin for credentialed
- // requests that bypass the proxy (desktop renderer, direct calls).
- env.T3CODE_DEV_ALLOWED_ORIGINS = [
- env.T3CODE_DEV_ALLOWED_ORIGINS,
- new URL(shared.url).origin,
- ]
- .filter((entry) => entry && entry.length > 0)
- .join(",");
- if (input.devUrl === undefined) {
- env.VITE_DEV_SERVER_URL = shared.url;
- }
- // A shared origin serves a remote browser, where unbundled dev's
- // per-module requests each pay a tailnet round trip — a cold module
- // graph takes minutes to first paint. Bundled dev collapses that to a
- // few chunk requests.
- if (env.T3CODE_BUNDLED_DEV === undefined) {
- env.T3CODE_BUNDLED_DEV = "1";
- }
- yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
+ ),
+ Effect.option,
+ Effect.map(Option.getOrUndefined),
+ );
+
+ if (shared) {
+ // The app is reached from the tailnet origin. Vite already allows
+ // *.ts.net hosts; the backend needs the origin for credentialed
+ // requests that bypass the proxy (desktop renderer, direct calls).
+ env.T3CODE_DEV_ALLOWED_ORIGINS = [
+ env.T3CODE_DEV_ALLOWED_ORIGINS,
+ new URL(shared.url).origin,
+ ]
+ .filter((entry) => entry && entry.length > 0)
+ .join(",");
+ if (input.devUrl === undefined) {
+ env.VITE_DEV_SERVER_URL = shared.url;
}
+ // A shared origin serves a remote browser, where unbundled dev's
+ // per-module requests each pay a tailnet round trip — a cold module
+ // graph takes minutes to first paint. Bundled dev collapses that to a
+ // few chunk requests.
+ if (env.T3CODE_BUNDLED_DEV === undefined) {
+ env.T3CODE_BUNDLED_DEV = "1";
+ }
+ yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
}
}
+ }
- const args = [...MODE_ARGS[input.mode], ...input.runArgs];
- const spawnCommand = yield* resolveSpawnCommand("vp", args, { env });
- const processContext = {
- mode: input.mode,
- executable: "vp" as const,
- argumentCount: args.length,
- shell: spawnCommand.shell,
- } as const;
- const child = yield* ChildProcess.make(spawnCommand.command, spawnCommand.args, {
- stdin: "inherit",
- stdout: "inherit",
- stderr: "inherit",
- env,
- extendEnv: false,
- shell: spawnCommand.shell,
- // Keep Vite+ in the same process group so terminal signals (Ctrl+C)
- // reach it directly. Effect defaults to detached: true on non-Windows,
- // which would put the runner in a new group and require manual forwarding.
- detached: false,
- forceKillAfter: "1500 millis",
- }).pipe(
- Effect.mapError(
- (cause) =>
- new DevRunnerProcessError({
- ...processContext,
- operation: "spawn",
- cause,
- }),
- ),
- );
-
- const exitCode = yield* child.exitCode.pipe(
- Effect.mapError(
- (cause) =>
- new DevRunnerProcessError({
- ...processContext,
- operation: "wait-for-exit",
- cause,
- }),
- ),
- );
- if (exitCode !== 0) {
- return yield* new DevRunnerProcessExitError({
- ...processContext,
- exitCode,
- });
- }
- });
-}
+ const args = [...MODE_ARGS[input.mode], ...input.runArgs];
+ const spawnCommand = yield* resolveSpawnCommand("vp", args, { env });
+ const processContext = {
+ mode: input.mode,
+ executable: "vp" as const,
+ argumentCount: args.length,
+ shell: spawnCommand.shell,
+ } as const;
+ const child = yield* ChildProcess.make(spawnCommand.command, spawnCommand.args, {
+ stdin: "inherit",
+ stdout: "inherit",
+ stderr: "inherit",
+ env,
+ extendEnv: false,
+ shell: spawnCommand.shell,
+ // Keep Vite+ in the same process group so terminal signals (Ctrl+C)
+ // reach it directly. Effect defaults to detached: true on non-Windows,
+ // which would put the runner in a new group and require manual forwarding.
+ detached: false,
+ forceKillAfter: "1500 millis",
+ }).pipe(
+ Effect.mapError(
+ (cause) =>
+ new DevRunnerProcessError({
+ ...processContext,
+ operation: "spawn",
+ cause,
+ }),
+ ),
+ );
+
+ const exitCode = yield* child.exitCode.pipe(
+ Effect.mapError(
+ (cause) =>
+ new DevRunnerProcessError({
+ ...processContext,
+ operation: "wait-for-exit",
+ cause,
+ }),
+ ),
+ );
+ if (exitCode !== 0) {
+ return yield* new DevRunnerProcessExitError({
+ ...processContext,
+ exitCode,
+ });
+ }
+});
const devRunnerCli = Command.make("dev-runner", {
mode: Argument.Literals("mode", DEV_RUNNER_MODES).pipe(
diff --git a/scripts/mobile-native-client.ts b/scripts/mobile-native-client.ts
index 7db1bd20031..e16a0af464e 100644
--- a/scripts/mobile-native-client.ts
+++ b/scripts/mobile-native-client.ts
@@ -96,40 +96,39 @@ export const hashBundle = Effect.fn("hashBundle")(function* (root: string) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const entries: string[] = [];
- const visit = (
+ const visit = Effect.fn("mobile-native-client.visit")(function* (
relative: string,
- ): Effect.Effect<void, FileSystemError, FileSystem.FileSystem | Crypto.Crypto> =>
- Effect.gen(function* () {
- const names = (yield* fs.readDirectory(path.join(root, relative))).sort((a, b) =>
- a.localeCompare(b, "en"),
+ ): Effect.fn.Return<void, FileSystemError, FileSystem.FileSystem | Crypto.Crypto> {
+ const names = (yield* fs.readDirectory(path.join(root, relative))).sort((a, b) =>
+ a.localeCompare(b, "en"),
+ );
+ for (const name of names) {
+ const key = path.join(relative, name);
+ const absolute = path.join(root, key);
+ // FileSystem.stat follows links; readLink distinguishes them without following a cycle.
+ const link = yield* fs.readLink(absolute).pipe(
+ Effect.catchIf(
+ (error) => isNotLink(error.reason.cause),
+ () => Effect.succeed(null),
+ ),
);
- for (const name of names) {
- const key = path.join(relative, name);
- const absolute = path.join(root, key);
- // FileSystem.stat follows links; readLink distinguishes them without following a cycle.
- const link = yield* fs.readLink(absolute).pipe(
- Effect.catchIf(
- (error) => isNotLink(error.reason.cause),
- () => Effect.succeed(null),
- ),
+ if (link !== null) {
+ entries.push(`link:${key}:${link}`);
+ continue;
+ }
+ const info = yield* fs.stat(absolute);
+ if (info.type === "Directory") {
+ entries.push(`directory:${key}`);
+ yield* visit(key);
+ } else {
+ const chunks = yield* fs.stream(absolute, { chunkSize: 65536 }).pipe(
+ Stream.mapEffect((chunk) => digest(chunk)),
+ Stream.runCollect,
);
- if (link !== null) {
- entries.push(`link:${key}:${link}`);
- continue;
- }
- const info = yield* fs.stat(absolute);
- if (info.type === "Directory") {
- entries.push(`directory:${key}`);
- yield* visit(key);
- } else {
- const chunks = yield* fs.stream(absolute, { chunkSize: 65536 }).pipe(
- Stream.mapEffect((chunk) => digest(chunk)),
- Stream.runCollect,
- );
- entries.push(`file:${key}:${yield* digest(chunks.join("\n"))}`);
- }
+ entries.push(`file:${key}:${yield* digest(chunks.join("\n"))}`);
}
- });
+ }
+ });
yield* visit("");
return yield* digest(entries.map((entry) => `${entry.length}:${entry}`).join(""));
});
diff --git a/scripts/mobile-native-static-check.ts b/scripts/mobile-native-static-check.ts
index 52b9a84078e..06d0b470a95 100644
--- a/scripts/mobile-native-static-check.ts
+++ b/scripts/mobile-native-static-check.ts
@@ -170,62 +170,60 @@ export const runCommand = Effect.fn("runCommand")(function* (
}
});
-export function collectSources(
+export const collectSources = Effect.fn("mobile-native-static-check.collectSources")(function* (
directory: string,
root: string,
-): Effect.Effect<
+): Effect.fn.Return<
ReadonlyArray<string>,
NativeStaticCheckSourceDiscoveryError,
FileSystem.FileSystem | Path.Path
> {
- return Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const entries = yield* fs.readDirectory(directory).pipe(
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const entries = yield* fs.readDirectory(directory).pipe(
+ Effect.mapError(
+ (cause) =>
+ new NativeStaticCheckSourceDiscoveryError({
+ operation: "read-directory",
+ path: directory,
+ cause,
+ }),
+ ),
+ );
+ const sources: Array<string> = [];
+
+ for (const entry of entries) {
+ const entryPath = path.join(directory, entry);
+ const stat = yield* fs.stat(entryPath).pipe(
Effect.mapError(
(cause) =>
new NativeStaticCheckSourceDiscoveryError({
- operation: "read-directory",
- path: directory,
+ operation: "stat-entry",
+ path: entryPath,
cause,
}),
),
);
- const sources: Array<string> = [];
-
- for (const entry of entries) {
- const entryPath = path.join(directory, entry);
- const stat = yield* fs.stat(entryPath).pipe(
- Effect.mapError(
- (cause) =>
- new NativeStaticCheckSourceDiscoveryError({
- operation: "stat-entry",
- path: entryPath,
- cause,
- }),
- ),
- );
-
- if (stat.type === "Directory") {
- const isGeneratedNativeProjectDirectory =
- directory === root && generatedNativeProjectDirectories.has(entry);
- if (excludedDirectories.has(entry) || isGeneratedNativeProjectDirectory) {
- continue;
- }
+ if (stat.type === "Directory") {
+ const isGeneratedNativeProjectDirectory =
+ directory === root && generatedNativeProjectDirectories.has(entry);
- sources.push(...(yield* collectSources(entryPath, root)));
+ if (excludedDirectories.has(entry) || isGeneratedNativeProjectDirectory) {
continue;
}
- if (stat.type === "File" && sourceExtensions.has(path.extname(entry))) {
- sources.push(entryPath);
- }
+ sources.push(...(yield* collectSources(entryPath, root)));
+ continue;
}
- return sources;
- });
-}
+ if (stat.type === "File" && sourceExtensions.has(path.extname(entry))) {
+ sources.push(entryPath);
+ }
+ }
+
+ return sources;
+});
const runNativeStaticChecks = Effect.fn("runNativeStaticChecks")(function* () {
const path = yield* Path.Path;
diff --git a/scripts/mock-update-server.ts b/scripts/mock-update-server.ts
index 687e0d7513c..ceb32f8f35c 100644
--- a/scripts/mock-update-server.ts
+++ b/scripts/mock-update-server.ts
@@ -32,32 +32,32 @@ const resolveMockUpdateServerConfig = Effect.gen(function* () {
} satisfies MockUpdateServerConfig;
});
-const isOutsideRoot = (rootRealPath: string, filePath: string) =>
- Effect.gen(function* () {
- const path = yield* Path.Path;
- const relativePath = path.relative(rootRealPath, filePath);
- return (
- relativePath === ".." || relativePath.startsWith("../") || relativePath.startsWith("..\\")
- );
- });
+const isOutsideRoot = Effect.fn("mock-update-server.isOutsideRoot")(function* (
+ rootRealPath: string,
+ filePath: string,
+) {
+ const path = yield* Path.Path;
+ const relativePath = path.relative(rootRealPath, filePath);
+ return relativePath === ".." || relativePath.startsWith("../") || relativePath.startsWith("..\\");
+});
-const isWithinRoot = (rootRealPath: string, filePath: string) =>
- Effect.gen(function* () {
- const fileSystem = yield* FileSystem.FileSystem;
- const resolvedFilePath = yield* fileSystem.realPath(filePath).pipe(
- Effect.match({
- onFailure: () => undefined,
- onSuccess: (resolvedPath) => resolvedPath,
- }),
- );
+const isWithinRoot = Effect.fn("mock-update-server.isWithinRoot")(function* (
+ rootRealPath: string,
+ filePath: string,
+) {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const resolvedFilePath = yield* fileSystem.realPath(filePath).pipe(
+ Effect.match({
+ onFailure: () => undefined,
+ onSuccess: (resolvedPath) => resolvedPath,
+ }),
+ );
- return (
- resolvedFilePath !== undefined && !(yield* isOutsideRoot(rootRealPath, resolvedFilePath))
- );
- });
+ return resolvedFilePath !== undefined && !(yield* isOutsideRoot(rootRealPath, resolvedFilePath));
+});
-const resolveRequestedFilePath = (rootRealPath: string, requestUrl: string | undefined) =>
- Effect.gen(function* () {
+const resolveRequestedFilePath = Effect.fn("mock-update-server.resolveRequestedFilePath")(
+ function* (rootRealPath: string, requestUrl: string | undefined) {
const path = yield* Path.Path;
const rawPath = (requestUrl ?? "/").split("?", 1)[0] ?? "/";
const decodedPath = yield* Effect.try({
@@ -84,24 +84,27 @@ const resolveRequestedFilePath = (rootRealPath: string, requestUrl: string | und
);
return (yield* isOutsideRoot(rootRealPath, filePath)) ? undefined : filePath;
- });
+ },
+);
-const isServableFile = (rootRealPath: string, filePath: string) =>
- Effect.gen(function* () {
- const fileSystem = yield* FileSystem.FileSystem;
- const stat = yield* fileSystem.stat(filePath).pipe(
- Effect.match({
- onFailure: () => undefined,
- onSuccess: (info) => info,
- }),
- );
+const isServableFile = Effect.fn("mock-update-server.isServableFile")(function* (
+ rootRealPath: string,
+ filePath: string,
+) {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const stat = yield* fileSystem.stat(filePath).pipe(
+ Effect.match({
+ onFailure: () => undefined,
+ onSuccess: (info) => info,
+ }),
+ );
- if (stat?.type !== "File") {
- return false;
- }
+ if (stat?.type !== "File") {
+ return false;
+ }
- return yield* isWithinRoot(rootRealPath, filePath);
- });
+ return yield* isWithinRoot(rootRealPath, filePath);
+});
export const makeMockUpdateRouteLayer = (rootRealPath: string) => {
return HttpRouter.add(
diff --git a/scripts/resolve-previous-release-tag.ts b/scripts/resolve-previous-release-tag.ts
index 58e6c3dcccf..6b53e031f9e 100644
--- a/scripts/resolve-previous-release-tag.ts
+++ b/scripts/resolve-previous-release-tag.ts
@@ -192,44 +192,39 @@ const parseNightlyTag = (
};
};
-export const resolvePreviousReleaseTag = (
- channel: ReleaseChannel,
- currentTag: string,
- tags: ReadonlyArray<string>,
-) =>
- Effect.gen(function* () {
- if (channel === "stable") {
- const current = parseStableTag(currentTag);
- if (!current) {
- return yield* new InvalidReleaseTagError({ channel, currentTag });
- }
-
- const candidates = tags
- .map((tag) => ({ tag, parsed: parseStableTag(tag) }))
- .filter(
- (entry): entry is { tag: string; parsed: StableVersion } => entry.parsed !== undefined,
- )
- .filter((entry) => compareStableVersions(entry.parsed, current) < 0)
- .toSorted((left, right) => compareStableVersions(right.parsed, left.parsed));
-
- return candidates[0]?.tag;
- }
-
- const current = parseNightlyTag(currentTag, channel);
+export const resolvePreviousReleaseTag = Effect.fn(
+ "resolve-previous-release-tag.resolvePreviousReleaseTag",
+)(function* (channel: ReleaseChannel, currentTag: string, tags: ReadonlyArray<string>) {
+ if (channel === "stable") {
+ const current = parseStableTag(currentTag);
if (!current) {
return yield* new InvalidReleaseTagError({ channel, currentTag });
}
const candidates = tags
- .map((tag) => ({ tag, parsed: parseNightlyTag(tag, channel) }))
+ .map((tag) => ({ tag, parsed: parseStableTag(tag) }))
.filter(
- (entry): entry is { tag: string; parsed: NightlyVersion } => entry.parsed !== undefined,
+ (entry): entry is { tag: string; parsed: StableVersion } => entry.parsed !== undefined,
)
- .filter((entry) => compareNightlyVersions(entry.parsed, current) < 0)
- .toSorted((left, right) => compareNightlyVersions(right.parsed, left.parsed));
+ .filter((entry) => compareStableVersions(entry.parsed, current) < 0)
+ .toSorted((left, right) => compareStableVersions(right.parsed, left.parsed));
return candidates[0]?.tag;
- });
+ }
+
+ const current = parseNightlyTag(currentTag, channel);
+ if (!current) {
+ return yield* new InvalidReleaseTagError({ channel, currentTag });
+ }
+
+ const candidates = tags
+ .map((tag) => ({ tag, parsed: parseNightlyTag(tag, channel) }))
+ .filter((entry): entry is { tag: string; parsed: NightlyVersion } => entry.parsed !== undefined)
+ .filter((entry) => compareNightlyVersions(entry.parsed, current) < 0)
+ .toSorted((left, right) => compareNightlyVersions(right.parsed, left.parsed));
+
+ return candidates[0]?.tag;
+});
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
stream.pipe(