Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 53eea2ac5c Format chat timeline optimization
Co-authored-by: Julius Marminge <[email protected]>
2026-06-06 16:26:54 +00:00
Cursor AgentandJulius Marminge c897c0ee2e Optimize chat timeline render stability
Co-authored-by: Julius Marminge <[email protected]>
2026-06-06 16:20:37 +00:00
39 changed files with 191 additions and 1057 deletions

No files matched your search

-5
View File
@@ -10,8 +10,3 @@
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
# T3CODE_RELAY_URL=https://relay.example.com
# Public, ingest-only mobile OpenTelemetry configuration.
# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces
# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev
# T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-...
-5
View File
@@ -161,11 +161,6 @@ const config: ExpoConfig = {
publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,
},
observability: {
tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",
tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,
tracesToken: repoEnv.EXPO_PUBLIC_OTLP_TRACES_TOKEN ?? null,
},
eas: {
projectId: "d763fcb8-d37c-41ea-a773-b54a0ab4a454",
},
@@ -41,7 +41,7 @@ export function normalizeAgentAwarenessRelayBaseUrl(
}
function readRelayConfig(): { readonly url: string } | null {
const relayUrl = resolveCloudPublicConfig().relay.url;
const relayUrl = resolveCloudPublicConfig().relayUrl;
if (!relayUrl) {
logRegistrationDebug("relay registration skipped; relay config missing");
return null;
@@ -66,9 +66,7 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
}
export function CloudAuthProvider(props: { readonly children: ReactNode }) {
const config = resolveCloudPublicConfig();
const publishableKey = config.clerk.publishableKey;
const relayUrl = config.relay.url;
const { clerkPublishableKey: publishableKey, relayUrl } = resolveCloudPublicConfig();
useEffect(() => {
if (!publishableKey || !relayUrl) {
@@ -50,7 +50,7 @@ export function normalizeRelayBaseUrl(value: string | null | undefined): string
}
function readRelayUrl(): string | null {
return resolveCloudPublicConfig().relay.url;
return resolveCloudPublicConfig().relayUrl;
}
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
@@ -1,6 +1,7 @@
import { useAtomValue } from "@effect/atom-react";
import {
createManagedRelayQueryManager,
ManagedRelayClient,
managedRelaySessionAtom,
readManagedRelaySnapshotState,
} from "@t3tools/client-runtime";
@@ -8,13 +9,23 @@ import type {
RelayClientEnvironmentRecord,
RelayEnvironmentStatusResponse,
} from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback } from "react";
import { mobileRuntimeContextLayer } from "../../lib/runtime";
import { mobileRuntime } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
const managedRelayAtomRuntime = Atom.runtime(mobileRuntimeContextLayer);
const managedRelayAtomRuntime = Atom.runtime(
Layer.effect(
ManagedRelayClient,
mobileRuntime.contextEffect.pipe(
Effect.map((context) => Context.get(context, ManagedRelayClient)),
),
),
);
export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime);
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig";
import { resolveCloudPublicConfig } from "./publicConfig";
vi.mock("expo-constants", () => ({
default: {
@@ -13,18 +13,9 @@ vi.mock("expo-constants", () => ({
describe("resolveCloudPublicConfig", () => {
it("returns no cloud configuration for an unconfigured build", () => {
expect(resolveCloudPublicConfig({})).toEqual({
clerk: {
publishableKey: null,
jwtTemplate: null,
},
relay: {
url: null,
},
observability: {
tracesUrl: null,
tracesDataset: null,
tracesToken: null,
},
clerkPublishableKey: null,
clerkJwtTemplate: null,
relayUrl: null,
});
});
@@ -33,25 +24,11 @@ describe("resolveCloudPublicConfig", () => {
resolveCloudPublicConfig({
clerk: { publishableKey: " pk_test_example ", jwtTemplate: " t3-relay " },
relay: { url: " https://relay.example.test/// " },
observability: {
tracesUrl: " https://api.axiom.co/v1/traces ",
tracesDataset: " mobile-traces ",
tracesToken: " public-ingest-token ",
},
}),
).toEqual({
clerk: {
publishableKey: "pk_test_example",
jwtTemplate: "t3-relay",
},
relay: {
url: "https://relay.example.test",
},
observability: {
tracesUrl: "https://api.axiom.co/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
clerkPublishableKey: "pk_test_example",
clerkJwtTemplate: "t3-relay",
relayUrl: "https://relay.example.test",
});
});
@@ -62,59 +39,9 @@ describe("resolveCloudPublicConfig", () => {
relay: { url: "http://relay.example.test" },
}),
).toEqual({
clerk: {
publishableKey: "pk_test_example",
jwtTemplate: "t3-relay",
},
relay: {
url: null,
},
observability: {
tracesUrl: null,
tracesDataset: null,
tracesToken: null,
},
clerkPublishableKey: "pk_test_example",
clerkJwtTemplate: "t3-relay",
relayUrl: null,
});
});
it("rejects an insecure traces URL", () => {
expect(
resolveCloudPublicConfig({
observability: {
tracesUrl: "http://api.axiom.co/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
}).observability,
).toEqual({
tracesUrl: null,
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
});
});
it("keeps tracing disabled unless every public tracing value is configured", () => {
expect(hasMobileTracingPublicConfig(resolveCloudPublicConfig({}))).toBe(false);
expect(
hasMobileTracingPublicConfig(
resolveCloudPublicConfig({
observability: {
tracesUrl: "https://api.axiom.co/v1/traces",
tracesDataset: "mobile-traces",
},
}),
),
).toBe(false);
expect(
hasMobileTracingPublicConfig(
resolveCloudPublicConfig({
observability: {
tracesUrl: "https://api.axiom.co/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
}),
),
).toBe(true);
});
});
+17 -69
View File
@@ -2,92 +2,40 @@ import Constants from "expo-constants";
import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth";
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
type ExpoExtra = Readonly<Record<string, unknown>> | undefined;
export interface CloudPublicConfig {
readonly clerk: {
readonly publishableKey: string | null;
readonly jwtTemplate: string | null;
};
readonly relay: {
readonly url: string | null;
};
readonly observability: {
readonly tracesUrl: string | null;
readonly tracesDataset: string | null;
readonly tracesToken: string | null;
};
readonly clerkPublishableKey: string | null;
readonly clerkJwtTemplate: string | null;
readonly relayUrl: string | null;
}
type UntrustedSection<T> = {
readonly [Key in keyof T]?: unknown;
};
type ExpoExtra =
| {
readonly [Section in keyof CloudPublicConfig]?: UntrustedSection<CloudPublicConfig[Section]>;
}
| undefined;
function trimNonEmpty(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function normalizeSecureUrl(value: unknown): string | null {
const raw = trimNonEmpty(value);
if (raw === null) {
return null;
}
try {
const url = new URL(raw);
return url.protocol === "https:" ? url.toString() : null;
} catch {
return null;
}
}
export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig?.extra) {
const clerk = extra?.clerk as
| { readonly publishableKey?: unknown; readonly jwtTemplate?: unknown }
| undefined;
const relay = extra?.relay as { readonly url?: unknown } | undefined;
return {
clerk: {
publishableKey: trimNonEmpty(extra?.clerk?.publishableKey),
jwtTemplate: trimNonEmpty(extra?.clerk?.jwtTemplate),
},
relay: {
url: normalizeSecureRelayUrl(trimNonEmpty(extra?.relay?.url) ?? ""),
},
observability: {
tracesUrl: normalizeSecureUrl(extra?.observability?.tracesUrl),
tracesDataset: trimNonEmpty(extra?.observability?.tracesDataset),
tracesToken: trimNonEmpty(extra?.observability?.tracesToken),
},
clerkPublishableKey: trimNonEmpty(clerk?.publishableKey),
clerkJwtTemplate: trimNonEmpty(clerk?.jwtTemplate),
relayUrl: normalizeSecureRelayUrl(trimNonEmpty(relay?.url) ?? ""),
} satisfies CloudPublicConfig;
}
export function hasCloudPublicConfig(): boolean {
const config = resolveCloudPublicConfig();
return Boolean(config.clerk.publishableKey && config.clerk.jwtTemplate && config.relay.url);
}
type Configured<T> = {
readonly [Key in keyof T]: NonNullable<T[Key]>;
};
type MobileTracingPublicConfig = Omit<CloudPublicConfig, "observability"> & {
readonly observability: Configured<CloudPublicConfig["observability"]>;
};
export function hasMobileTracingPublicConfig(
config: CloudPublicConfig = resolveCloudPublicConfig(),
): config is MobileTracingPublicConfig {
return Boolean(
config.observability.tracesUrl &&
config.observability.tracesDataset &&
config.observability.tracesToken,
);
return Boolean(config.clerkPublishableKey && config.clerkJwtTemplate && config.relayUrl);
}
export function resolveRelayClerkTokenOptions() {
const { jwtTemplate } = resolveCloudPublicConfig().clerk;
if (!jwtTemplate) {
const { clerkJwtTemplate } = resolveCloudPublicConfig();
if (!clerkJwtTemplate) {
throw new Error("T3CODE_CLERK_JWT_TEMPLATE is not configured.");
}
return relayClerkTokenOptions(jwtTemplate);
return relayClerkTokenOptions(clerkJwtTemplate);
}
@@ -1,52 +0,0 @@
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { vi } from "vite-plus/test";
import { remoteHttpClientLayer } from "@t3tools/client-runtime";
import { makeMobileTracingLayer } from "./mobileTracing";
vi.mock("expo-constants", () => ({
default: {
expoConfig: {
extra: {},
},
},
}));
it.effect("exports spans through the scoped mobile OTLP layer", () => {
const fetchFn = vi.fn<typeof fetch>(async () => new Response(null, { status: 202 }));
const tracingLayer = makeMobileTracingLayer(
{
tracesUrl: "https://api.axiom.test/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
{
appVariant: "test",
serviceVersion: "1.2.3",
},
).pipe(Layer.provide(remoteHttpClientLayer(fetchFn)));
const tracedApplication = Layer.effectDiscard(
Effect.void.pipe(Effect.withSpan("mobile.test.span")),
).pipe(Layer.provide(tracingLayer));
return Effect.gen(function* () {
yield* Layer.build(tracedApplication);
expect(fetchFn).not.toHaveBeenCalled();
}).pipe(
Effect.scoped,
Effect.andThen(
Effect.sync(() => {
expect(fetchFn).toHaveBeenCalledOnce();
const [url, init] = fetchFn.mock.calls[0]!;
expect(String(url)).toBe("https://api.axiom.test/v1/traces");
expect(new Headers(init?.headers).get("authorization")).toBe("Bearer public-ingest-token");
expect(new Headers(init?.headers).get("x-axiom-dataset")).toBe("mobile-traces");
expect(new TextDecoder().decode(init?.body as Uint8Array)).toContain("mobile.test.span");
}),
),
);
});
@@ -1,60 +0,0 @@
import Constants from "expo-constants";
import * as Layer from "effect/Layer";
import type { HttpClient } from "effect/unstable/http";
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "../cloud/publicConfig";
export interface MobileTracingConfig {
readonly tracesUrl: string;
readonly tracesDataset: string;
readonly tracesToken: string;
}
export interface MobileTracingResource {
readonly serviceVersion?: string;
readonly appVariant: string;
}
export function resolveMobileTracingConfig(): MobileTracingConfig | null {
const config = resolveCloudPublicConfig();
if (!hasMobileTracingPublicConfig(config)) {
return null;
}
const { tracesUrl, tracesDataset, tracesToken } = config.observability;
return { tracesUrl, tracesDataset, tracesToken };
}
export function makeMobileTracingLayer(
config: MobileTracingConfig | null,
resource: MobileTracingResource,
): Layer.Layer<never, never, HttpClient.HttpClient> {
if (config === null) {
return Layer.empty;
}
return OtlpTracer.layer({
url: config.tracesUrl,
headers: {
Authorization: `Bearer ${config.tracesToken}`,
"X-Axiom-Dataset": config.tracesDataset,
},
resource: {
serviceName: "t3-mobile",
serviceVersion: resource.serviceVersion,
attributes: {
"service.runtime": "react-native",
"service.component": "mobile",
"deployment.environment.name": resource.appVariant,
},
},
}).pipe(Layer.provide(OtlpSerialization.layerJson));
}
export const mobileTracingLayer = makeMobileTracingLayer(resolveMobileTracingConfig(), {
serviceVersion: Constants.expoConfig?.version,
appVariant:
typeof Constants.expoConfig?.extra?.appVariant === "string"
? Constants.expoConfig.extra.appVariant
: "unknown",
});
+7 -8
View File
@@ -6,20 +6,19 @@ import { remoteHttpClientLayer } from "@t3tools/client-runtime";
import { mobileCryptoLayer } from "../features/cloud/dpop";
import { mobileManagedRelayClientLayer } from "../features/cloud/managedRelayLayer";
import { resolveCloudPublicConfig } from "../features/cloud/publicConfig";
import { mobileTracingLayer } from "../features/observability/mobileTracing";
function configuredRelayUrl(): string {
return resolveCloudPublicConfig().relay.url ?? "http://relay.invalid";
return resolveCloudPublicConfig().relayUrl ?? "http://relay.invalid";
}
const mobileHttpClientLayer = remoteHttpClientLayer(fetch);
export const mobileRuntime = ManagedRuntime.make(
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
Layer.provideMerge(mobileCryptoLayer),
Layer.provideMerge(mobileHttpClientLayer),
Layer.provideMerge(mobileTracingLayer.pipe(Layer.provide(mobileHttpClientLayer))),
Layer.mergeAll(
mobileHttpClientLayer,
mobileCryptoLayer,
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
Layer.provide(Layer.mergeAll(mobileHttpClientLayer, mobileCryptoLayer)),
),
),
);
export const mobileRuntimeContextLayer = Layer.effectContext(mobileRuntime.contextEffect);
@@ -1,4 +1,3 @@
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -19,7 +18,6 @@ export const ObservabilityLive = Layer.unwrap(
const traceReferencesLayer = Layer.mergeAll(
Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),
Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled),
httpHeaderRedactionLayer,
);
const tracerLayer = Layer.unwrap(
@@ -33,7 +33,6 @@ import {
EyeIcon,
GlobeIcon,
HammerIcon,
type LucideIcon,
SquarePenIcon,
TerminalIcon,
Undo2Icon,
@@ -104,6 +103,11 @@ interface TimelineRowActivityState {
isRevertingCheckpoint: boolean;
}
interface StableRowsSnapshot {
source: MessagesTimelineRow[];
state: StableMessagesTimelineRowsState;
}
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
const TimelineRowActivityCtx = createContext<TimelineRowActivityState>(null!);
const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
@@ -1008,19 +1012,34 @@ function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentConte
// so LegendList (and React) can skip re-rendering unchanged items.
// ---------------------------------------------------------------------------
function createStableRowsSnapshot(
rows: MessagesTimelineRow[],
previous?: StableMessagesTimelineRowsState,
): StableRowsSnapshot {
return {
source: rows,
state: computeStableMessagesTimelineRows(
rows,
previous ?? {
byId: new Map<string, MessagesTimelineRow>(),
result: [],
},
),
};
}
/** Returns a structurally-shared copy of `rows`: for each row whose content
* hasn't changed since last call, the previous object reference is reused. */
function useStableRows(rows: MessagesTimelineRow[]): MessagesTimelineRow[] {
const prevState = useRef<StableMessagesTimelineRowsState>({
byId: new Map<string, MessagesTimelineRow>(),
result: [],
});
const [snapshot, setSnapshot] = useState(() => createStableRowsSnapshot(rows));
return useMemo(() => {
const nextState = computeStableMessagesTimelineRows(rows, prevState.current);
prevState.current = nextState;
return nextState.result;
}, [rows]);
if (snapshot.source !== rows) {
const nextSnapshot = createStableRowsSnapshot(rows, snapshot.state);
setSnapshot(nextSnapshot);
return nextSnapshot.state.result;
}
return snapshot.state.result;
}
// ---------------------------------------------------------------------------
@@ -1072,32 +1091,17 @@ function formatMessageMeta(
return `${formatTimestamp(createdAt, timestampFormat)} • ${duration}`;
}
function workToneIcon(tone: TimelineWorkEntry["tone"]): {
icon: LucideIcon;
className: string;
} {
function workToneIconClass(tone: TimelineWorkEntry["tone"]): string {
if (tone === "error") {
return {
icon: CircleAlertIcon,
className: "text-foreground/92",
};
return "text-foreground/92";
}
if (tone === "thinking") {
return {
icon: BotIcon,
className: "text-foreground/92",
};
return "text-foreground/92";
}
if (tone === "info") {
return {
icon: CheckIcon,
className: "text-foreground/92",
};
return "text-foreground/92";
}
return {
icon: ZapIcon,
className: "text-foreground/92",
};
return "text-foreground/92";
}
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
@@ -1132,29 +1136,36 @@ function workEntryRawCommand(
return rawCommand === workEntry.command.trim() ? null : rawCommand;
}
function workEntryIcon(workEntry: TimelineWorkEntry): LucideIcon {
if (workEntry.requestKind === "command") return TerminalIcon;
if (workEntry.requestKind === "file-read") return EyeIcon;
if (workEntry.requestKind === "file-change") return SquarePenIcon;
function WorkToneIconGlyph({ tone }: { tone: TimelineWorkEntry["tone"] }) {
if (tone === "error") return <CircleAlertIcon className="size-3" />;
if (tone === "thinking") return <BotIcon className="size-3" />;
if (tone === "info") return <CheckIcon className="size-3" />;
return <ZapIcon className="size-3" />;
}
function WorkEntryIconGlyph({ workEntry }: { workEntry: TimelineWorkEntry }) {
if (workEntry.requestKind === "command") return <TerminalIcon className="size-3" />;
if (workEntry.requestKind === "file-read") return <EyeIcon className="size-3" />;
if (workEntry.requestKind === "file-change") return <SquarePenIcon className="size-3" />;
if (workEntry.itemType === "command_execution" || workEntry.command) {
return TerminalIcon;
return <TerminalIcon className="size-3" />;
}
if (workEntry.itemType === "file_change" || (workEntry.changedFiles?.length ?? 0) > 0) {
return SquarePenIcon;
return <SquarePenIcon className="size-3" />;
}
if (workEntry.itemType === "web_search") return GlobeIcon;
if (workEntry.itemType === "image_view") return EyeIcon;
if (workEntry.itemType === "web_search") return <GlobeIcon className="size-3" />;
if (workEntry.itemType === "image_view") return <EyeIcon className="size-3" />;
switch (workEntry.itemType) {
case "mcp_tool_call":
return WrenchIcon;
return <WrenchIcon className="size-3" />;
case "dynamic_tool_call":
case "collab_agent_tool_call":
return HammerIcon;
return <HammerIcon className="size-3" />;
}
return workToneIcon(workEntry.tone).icon;
return <WorkToneIconGlyph tone={workEntry.tone} />;
}
function capitalizePhrase(value: string): string {
@@ -1177,8 +1188,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
workspaceRoot: string | undefined;
}) {
const { workEntry, workspaceRoot } = props;
const iconConfig = workToneIcon(workEntry.tone);
const EntryIcon = workEntryIcon(workEntry);
const iconClassName = workToneIconClass(workEntry.tone);
const heading = toolWorkEntryHeading(workEntry);
const rawPreview = workEntryPreview(workEntry, workspaceRoot);
const preview =
@@ -1195,10 +1205,8 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
return (
<div className="rounded-lg px-1 py-1">
<div className="flex items-center gap-2 transition-[opacity,translate] duration-200">
<span
className={cn("flex size-5 shrink-0 items-center justify-center", iconConfig.className)}
>
<EntryIcon className="size-3" />
<span className={cn("flex size-5 shrink-0 items-center justify-center", iconClassName)}>
<WorkEntryIconGlyph workEntry={workEntry} />
</span>
<div className="min-w-0 flex-1 overflow-hidden">
{rawCommand ? (
-2
View File
@@ -4,7 +4,6 @@ import * as Layer from "effect/Layer";
import { FetchHttpClient } from "effect/unstable/http";
import { remoteHttpClientLayer } from "@t3tools/client-runtime";
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
import {
PrimaryEnvironmentHttpClient,
primaryEnvironmentHttpClientLive,
@@ -29,7 +28,6 @@ const primaryHttpRuntime = ManagedRuntime.make(
Layer.mergeAll(
remoteHttpClientLayer((input, init) => globalThis.fetch(input, init)),
Layer.succeed(FetchHttpClient.RequestInit, primaryEnvironmentRequestInit),
httpHeaderRedactionLayer,
),
),
),
-5
View File
@@ -8,7 +8,6 @@ import * as Layer from "effect/Layer";
import * as Planetscale from "alchemy/Planetscale";
import { PlanetscaleDatabase, RelayHyperdrive } from "./src/db.ts";
import { RelayObservability } from "./src/observability.ts";
import { ManagedEndpointZone, RelayApiZone } from "./src/zone.ts";
import Api from "./src/worker.ts";
@@ -28,7 +27,6 @@ export default Alchemy.Stack(
const hyperdrive = yield* RelayHyperdrive;
const managedEndpointZone = yield* ManagedEndpointZone.pipe(Effect.orDie);
const relayApiZone = yield* RelayApiZone.pipe(Effect.orDie);
const observability = yield* RelayObservability;
const api = yield* Api;
return {
@@ -39,9 +37,6 @@ export default Alchemy.Stack(
url: api.url,
relayApiZoneId: relayApiZone.zoneId,
managedEndpointZoneId: managedEndpointZone.zoneId,
mobileTracingUrl: observability.traces.otelTracesEndpoint,
mobileTracingDataset: observability.traces.name,
mobileTracingToken: observability.mobileIngestToken.token,
};
}),
);
+1 -52
View File
@@ -1,11 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import {
hasDeployChanges,
reconcileRootEnvPublicConfig,
reconcileRootEnvRelayUrl,
serializeGithubOutput,
} from "./deploy.ts";
import { hasDeployChanges, reconcileRootEnvRelayUrl, serializeGithubOutput } from "./deploy.ts";
describe("hasDeployChanges", () => {
it("detects resource, binding, and deletion changes", () => {
@@ -56,52 +51,6 @@ describe("reconcileRootEnvRelayUrl", () => {
});
});
describe("reconcileRootEnvPublicConfig", () => {
const config = {
relayUrl: "https://relay.example.test",
mobileTracingUrl: "https://api.axiom.co/v1/traces",
mobileTracingDataset: "t3-code-mobile-traces-dev",
mobileTracingToken: "xaat-public-ingest",
} as const;
it("adds the complete local client config", () => {
expect(reconcileRootEnvPublicConfig("", config)).toBe(
[
"T3CODE_RELAY_URL=https://relay.example.test",
"T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",
"T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev",
"T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-public-ingest",
"",
].join("\n"),
);
});
it("replaces stale values while preserving unrelated entries", () => {
expect(
reconcileRootEnvPublicConfig(
[
"T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_example",
"T3CODE_RELAY_URL=https://old.example.test",
"T3CODE_MOBILE_OTLP_TRACES_URL=https://old.example.test/v1/traces",
"T3CODE_MOBILE_OTLP_TRACES_DATASET=old-dataset",
"T3CODE_MOBILE_OTLP_TRACES_TOKEN=old-token",
"",
].join("\n"),
config,
),
).toBe(
[
"T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_example",
"T3CODE_RELAY_URL=https://relay.example.test",
"T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",
"T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev",
"T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-public-ingest",
"",
].join("\n"),
);
});
});
describe("serializeGithubOutput", () => {
it("serializes relay deploy metadata for GitHub Actions outputs", () => {
expect(
+20 -69
View File
@@ -23,7 +23,6 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Redacted from "effect/Redacted";
import { Command, Flag, Prompt } from "effect/unstable/cli";
import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";
@@ -43,49 +42,15 @@ export interface RelayDeployOptions {
readonly githubOutput: boolean;
}
export interface RelayPublicConfig {
readonly relayUrl: string;
readonly mobileTracingUrl: string;
readonly mobileTracingDataset: string;
readonly mobileTracingToken: string;
}
const publicConfigEnvEntries = (config: RelayPublicConfig) =>
({
T3CODE_RELAY_URL: config.relayUrl,
T3CODE_MOBILE_OTLP_TRACES_URL: config.mobileTracingUrl,
T3CODE_MOBILE_OTLP_TRACES_DATASET: config.mobileTracingDataset,
T3CODE_MOBILE_OTLP_TRACES_TOKEN: config.mobileTracingToken,
}) as const;
export function reconcileRootEnvPublicConfig(contents: string, config: RelayPublicConfig): string {
let next = contents;
for (const [name, value] of Object.entries(publicConfigEnvEntries(config))) {
const entry = `${name}=${value}`;
const pattern = new RegExp(`^${name}=.*$`, "mu");
if (pattern.test(next)) {
next = next.replace(pattern, entry);
continue;
}
if (!next) {
next = `${entry}\n`;
continue;
}
next = `${next}${next.endsWith("\n") ? "" : "\n"}${entry}\n`;
}
return next;
}
export function reconcileRootEnvRelayUrl(contents: string, relayUrl: string): string {
return reconcileRootEnvPublicConfig(contents, {
relayUrl,
mobileTracingUrl: "",
mobileTracingDataset: "",
mobileTracingToken: "",
})
.split("\n")
.filter((line) => !line.startsWith("T3CODE_MOBILE_OTLP_TRACES_"))
.join("\n");
const entry = `T3CODE_RELAY_URL=${relayUrl}`;
if (/^T3CODE_RELAY_URL=.*$/mu.test(contents)) {
return contents.replace(/^T3CODE_RELAY_URL=.*$/mu, entry);
}
if (!contents) {
return `${entry}\n`;
}
return `${contents}${contents.endsWith("\n") ? "" : "\n"}${entry}\n`;
}
export function hasDeployChanges(plan: Plan.Plan): boolean {
@@ -103,7 +68,7 @@ export type RelayDeployResult = "applied" | "noop" | "dry-run" | "cancelled";
export interface RelayDeployOutcome {
readonly result: RelayDeployResult;
readonly changed: boolean;
readonly publicConfig: Option.Option<RelayPublicConfig>;
readonly relayUrl: Option.Option<string>;
}
export function serializeGithubOutput(entries: Readonly<Record<string, string | boolean>>): string {
@@ -141,17 +106,15 @@ const relayDeployStage = Config.nonEmptyString("stage").pipe(
),
);
const reconcileRootEnv = Effect.fn("relay.deploy.reconcileRootEnv")(function* (
config: RelayPublicConfig,
) {
const reconcileRootEnv = Effect.fn("relay.deploy.reconcileRootEnv")(function* (relayUrl: string) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* repoRoot;
const rootEnvPath = path.join(root, ".env");
const contents = (yield* fs.exists(rootEnvPath)) ? yield* fs.readFileString(rootEnvPath) : "";
yield* fs.writeFileString(rootEnvPath, reconcileRootEnvPublicConfig(contents, config));
yield* Console.log(`Updated ${rootEnvPath} with relay URL and mobile tracing configuration`);
yield* fs.writeFileString(rootEnvPath, reconcileRootEnvRelayUrl(contents, relayUrl));
yield* Console.log(`Updated ${rootEnvPath} with T3CODE_RELAY_URL=${relayUrl}`);
});
const writeGithubOutput = Effect.fn("relay.deploy.writeGithubOutput")(function* (
@@ -164,9 +127,7 @@ const writeGithubOutput = Effect.fn("relay.deploy.writeGithubOutput")(function*
serializeGithubOutput({
changed: outcome.changed,
result: outcome.result,
...(Option.isSome(outcome.publicConfig)
? { relay_url: outcome.publicConfig.value.relayUrl }
: {}),
...(Option.isSome(outcome.relayUrl) ? { relay_url: outcome.relayUrl.value } : {}),
}),
{ flag: "a" },
);
@@ -199,7 +160,7 @@ const runRelayDeploy = Effect.fn("relay.deploy.run")(
return {
result: "dry-run",
changed,
publicConfig: Option.none<RelayPublicConfig>(),
relayUrl: Option.none<string>(),
} satisfies RelayDeployOutcome;
}
if (!options.yes && changed) {
@@ -214,30 +175,20 @@ const runRelayDeploy = Effect.fn("relay.deploy.run")(
return {
result: "cancelled",
changed,
publicConfig: Option.none<RelayPublicConfig>(),
relayUrl: Option.none<string>(),
} satisfies RelayDeployOutcome;
}
}
const output = yield* Apply.apply(plan).pipe(Effect.provide(stack.services));
if (
output.url === undefined ||
output.mobileTracingUrl === undefined ||
output.mobileTracingDataset === undefined ||
output.mobileTracingToken === undefined
) {
if (output.url === undefined) {
return yield* new RelayDeployError({
message: "Alchemy relay deploy output did not include complete public client config",
message: "Alchemy relay deploy output did not include a URL",
});
}
return {
result: changed ? "applied" : "noop",
changed,
publicConfig: Option.some({
relayUrl: output.url,
mobileTracingUrl: output.mobileTracingUrl,
mobileTracingDataset: output.mobileTracingDataset,
mobileTracingToken: Redacted.value(output.mobileTracingToken),
}),
relayUrl: Option.some(output.url),
} satisfies RelayDeployOutcome;
},
(effect, options, configProvider, stage) =>
@@ -265,8 +216,8 @@ export const deploy = Effect.fn("relay.deploy")(function* (options: RelayDeployO
);
const stage = Option.getOrElse(options.stage, () => configuredStage);
const outcome = yield* runRelayDeploy(options, configProvider, stage);
if (Option.isSome(outcome.publicConfig)) {
yield* reconcileRootEnv(outcome.publicConfig.value);
if (Option.isSome(outcome.relayUrl)) {
yield* reconcileRootEnv(outcome.relayUrl.value);
}
if (options.githubOutput) {
yield* writeGithubOutput(outcome);
@@ -101,13 +101,8 @@ const make = Effect.gen(function* () {
"relay.mobile.device_id": input.deviceId,
"relay.operation": "replayForLiveActivityRegistration",
});
const { activeStates, targets } = yield* Effect.all(
{
activeStates: rows.listForUser({ userId: input.userId }),
targets: liveActivities.listTargets({ userId: input.userId }),
},
{ concurrency: 2 },
);
const activeStates = yield* rows.listForUser({ userId: input.userId });
const targets = yield* liveActivities.listTargets({ userId: input.userId });
const target = targets.find((row) => row.device_id === input.deviceId) ?? null;
if (target === null) {
return null;
+1 -1
View File
@@ -63,6 +63,6 @@ export const RelayHyperdrive = Effect.gen(function* () {
caching: {
disabled: true,
},
originConnectionLimit: 20,
originConnectionLimit: 5,
});
});
@@ -14,13 +14,11 @@ import {
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import { RELAY_HEALTH_RESPONSE_TYP, RELAY_MINT_RESPONSE_TYP } from "@t3tools/shared/relayJwt";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
@@ -227,58 +225,6 @@ function makeLinks(
}
describe("EnvironmentConnector", () => {
it.effect("loads the environment link and managed allocation concurrently", () =>
Effect.gen(function* () {
const started = yield* Ref.make(0);
const bothStarted = yield* Deferred.make<void>();
const release = yield* Deferred.make<void>();
const waitForPeer = Effect.gen(function* () {
const count = yield* Ref.updateAndGet(started, (value) => value + 1);
if (count === 2) {
yield* Deferred.succeed(bothStarted, undefined);
}
yield* Deferred.await(release);
});
const links = makeLinks();
const allocations = makeAllocations();
const execute = (request: HttpClientRequest.HttpClientRequest) =>
Effect.sync(() => {
const healthRequest = decodeHealthRequestBody(requestBodyText(request));
return HttpClientResponse.fromWeb(
request,
Response.json(signHealthResponse(healthRequest), { status: 200 }),
);
});
const status = Effect.gen(function* () {
const connector = yield* EnvironmentConnector.EnvironmentConnector;
return yield* connector.status({
userId: "user_123",
environmentId: "env-connector-test" as never,
});
}).pipe(
Effect.provide(
connectorTestLayer(execute, {
links: {
...links,
getForUser: (input) => waitForPeer.pipe(Effect.andThen(links.getForUser(input))),
},
allocations: {
...allocations,
get: (input) => waitForPeer.pipe(Effect.andThen(allocations.get(input))),
},
}),
),
);
const fiber = yield* Effect.forkChild(status);
yield* Deferred.await(bothStarted);
yield* Deferred.succeed(release, undefined);
yield* Fiber.join(fiber);
expect(yield* Ref.get(started)).toBe(2);
}),
);
it.effect("checks linked environment health through the managed endpoint", () => {
const seenUrls: Array<string> = [];
const seenProofs: Array<RelayCloudEnvironmentHealthProofPayload> = [];
@@ -295,9 +295,9 @@ const make = Effect.gen(function* () {
);
const resolveManagedEndpoint = Effect.fn("relay.environment_connector.resolve_managed_endpoint")(
function* (input: {
readonly userId: string;
readonly operation: "connect" | "status";
readonly link: EnvironmentLinks.RelayLinkedEnvironmentRecord;
readonly allocation: ManagedEndpointAllocations.ManagedEndpointAllocation | null;
}) {
if (input.link.endpoint.providerKind !== "cloudflare_tunnel") {
yield* Effect.annotateCurrentSpan({
@@ -309,7 +309,11 @@ const make = Effect.gen(function* () {
reason: "endpoint_provider_not_managed",
});
}
if (!input.allocation) {
const allocation = yield* allocations.get({
userId: input.userId,
environmentId: input.link.environmentId,
});
if (!allocation) {
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.link.environmentId,
operation: input.operation,
@@ -317,10 +321,10 @@ const make = Effect.gen(function* () {
});
}
const allocationAttributes = {
"relay.authorization.allocation_hostname": input.allocation.hostname,
"relay.authorization.allocation_has_ready_at": input.allocation.readyAt !== null,
"relay.authorization.allocation_has_tunnel_id": input.allocation.tunnelId !== null,
"relay.authorization.allocation_has_dns_record_id": input.allocation.dnsRecordId !== null,
"relay.authorization.allocation_hostname": allocation.hostname,
"relay.authorization.allocation_has_ready_at": allocation.readyAt !== null,
"relay.authorization.allocation_has_tunnel_id": allocation.tunnelId !== null,
"relay.authorization.allocation_has_dns_record_id": allocation.dnsRecordId !== null,
} as const;
if (!settings.managedEndpointBaseDomain) {
yield* Effect.annotateCurrentSpan(allocationAttributes);
@@ -331,9 +335,9 @@ const make = Effect.gen(function* () {
});
}
if (
input.allocation.readyAt === null ||
input.allocation.tunnelId === null ||
input.allocation.dnsRecordId === null
allocation.readyAt === null ||
allocation.tunnelId === null ||
allocation.dnsRecordId === null
) {
yield* Effect.annotateCurrentSpan(allocationAttributes);
return yield* new EnvironmentConnectNotAuthorized({
@@ -342,9 +346,7 @@ const make = Effect.gen(function* () {
reason: "managed_endpoint_allocation_not_ready",
});
}
if (
!isManagedEndpointHostname(input.allocation.hostname, settings.managedEndpointBaseDomain)
) {
if (!isManagedEndpointHostname(allocation.hostname, settings.managedEndpointBaseDomain)) {
yield* Effect.annotateCurrentSpan({
...allocationAttributes,
"relay.authorization.managed_endpoint_base_domain": settings.managedEndpointBaseDomain,
@@ -356,7 +358,7 @@ const make = Effect.gen(function* () {
});
}
const endpoint = ManagedEndpointAllocations.resolveReadyManagedEndpoint({
allocation: input.allocation,
allocation,
baseDomain: settings.managedEndpointBaseDomain,
});
if (
@@ -391,13 +393,7 @@ const make = Effect.gen(function* () {
"relay.environment_id": input.environmentId,
"relay.operation": "status",
});
const { link, allocation } = yield* Effect.all(
{
link: links.getForUser(input),
allocation: allocations.get(input),
},
{ concurrency: 2 },
);
const link = yield* links.getForUser(input);
if (!link) {
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.environmentId,
@@ -406,9 +402,9 @@ const make = Effect.gen(function* () {
});
}
const endpoint = yield* resolveManagedEndpoint({
userId: input.userId,
operation: "status",
link,
allocation,
});
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { minutes: 2 });
@@ -522,13 +518,7 @@ const make = Effect.gen(function* () {
reason: "client_proof_key_thumbprint_missing",
});
}
const { link, allocation } = yield* Effect.all(
{
link: links.getForUser(input),
allocation: allocations.get(input),
},
{ concurrency: 2 },
);
const link = yield* links.getForUser(input);
if (!link) {
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.environmentId,
@@ -537,9 +527,9 @@ const make = Effect.gen(function* () {
});
}
const endpoint = yield* resolveManagedEndpoint({
userId: input.userId,
operation: "connect",
link,
allocation,
});
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { minutes: 2 });
-6
View File
@@ -181,10 +181,6 @@ describe("relay request tracing", () => {
const request = HttpServerRequest.fromWeb(
new Request("https://relay.test/v1/mobile/devices?client=mobile", {
method: "POST",
headers: {
authorization: "Bearer secret",
dpop: "signed-proof",
},
}),
);
@@ -196,8 +192,6 @@ describe("relay request tracing", () => {
expect(spans[0]?.kind).toBe("server");
expect(spans[0]?.attributes.get("url.path")).toBe("/v1/mobile/devices");
expect(spans[0]?.attributes.get("http.response.status_code")).toBe(204);
expect(spans[0]?.attributes.get("http.request.header.authorization")).toBe("<redacted>");
expect(spans[0]?.attributes.get("http.request.header.dpop")).toBe("<redacted>");
expect(Option.isNone(spans[0]!.parent)).toBe(true);
expect(Option.getOrUndefined(spans[1]!.parent)?.spanId).toBe(spans[0]?.spanId);
}),
+13 -10
View File
@@ -3,7 +3,6 @@ import { sql as drizzleSql } from "drizzle-orm";
import * as Crypto from "effect/Crypto";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Record from "effect/Record";
@@ -19,7 +18,6 @@ import * as HttpTraceContext from "effect/unstable/http/HttpTraceContext";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as HttpApiError from "effect/unstable/httpapi/HttpApiError";
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
import {
RelayApi,
@@ -69,7 +67,6 @@ import { withSpanAttributes } from "../observability.ts";
import { RelayDb } from "../db.ts";
const relayCorsAllowedMethods = ["GET", "POST", "DELETE", "OPTIONS"] as const;
const RELAY_DPOP_ACCESS_TOKEN_TTL = "30 minutes";
const relayCorsAllowedHeaders = [
"authorization",
"b3",
@@ -77,7 +74,11 @@ const relayCorsAllowedHeaders = [
"content-type",
"dpop",
] as const;
const relayCorsExposedHeaders = ["traceparent", "www-authenticate"] as const;
const relayCorsExposedHeaders = [
"traceparent",
"x-t3-relay-auth-failure",
"www-authenticate",
] as const;
const relayCorsHeaders = {
"access-control-allow-origin": "*",
@@ -175,10 +176,7 @@ export const traceRelayHttpRequestWith = <E, R, LayerError, LayerRequirements>(
HttpServerRequest.HttpServerRequest | R
>,
tracerLayer: Layer.Layer<never, LayerError, LayerRequirements>,
) =>
traceRelayHttpRequest(httpEffect).pipe(
Effect.provide(Layer.merge(tracerLayer, httpHeaderRedactionLayer)),
);
) => traceRelayHttpRequest(httpEffect).pipe(Effect.provide(tracerLayer));
export const withoutCapturedParentSpan = <A, E, R>(
effect: Effect.Effect<A, E, R>,
@@ -353,7 +351,12 @@ export const healthApi = HttpApiBuilder.group(
"health",
Effect.fn("relay.api.health")(
function* () {
const startedAt = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
yield* db.execute(drizzleSql`SELECT 1`);
const completedAt = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
yield* Effect.logInfo("relay health db probe completed", {
durationMs: completedAt - startedAt,
});
return { ok: true, service: "relay" as const };
},
Effect.catch(() => relayInternalErrorResponse("database_unavailable")),
@@ -599,7 +602,7 @@ export const tokenApi = HttpApiBuilder.group(
Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs),
);
const now = yield* DateTime.now;
const expiresAt = DateTime.addDuration(now, RELAY_DPOP_ACCESS_TOKEN_TTL);
const expiresAt = DateTime.add(now, { minutes: 5 });
const jti = yield* crypto.randomUUIDv4.pipe(
Effect.catch(() => relayInternalErrorResponse("internal_error")),
);
@@ -617,7 +620,7 @@ export const tokenApi = HttpApiBuilder.group(
.pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))),
issued_token_type: RelayAccessTokenType,
token_type: "DPoP" as const,
expires_in: Duration.toSeconds(RELAY_DPOP_ACCESS_TOKEN_TTL),
expires_in: 300,
scope: encodeOAuthScope(requestedScopes),
};
}, mapRelayCommonApiErrors("invalid_dpop")),
+2 -10
View File
@@ -34,7 +34,7 @@ export const RelayObservability = Effect.gen(function* () {
useRetentionPeriod: true,
});
const workerIngestToken = yield* Axiom.ApiToken("RelayWorkerAxiomIngestToken", {
const ingestToken = yield* Axiom.ApiToken("RelayAxiomIngestToken", {
name: relayResourceNameForStage("t3-code-relay-otel-ingest", stage),
description: "Owned by Alchemy. Scoped OTLP ingest token for relay HTTP spans.",
datasetCapabilities: Output.map(traces.name, (dataset) => ({
@@ -42,14 +42,6 @@ export const RelayObservability = Effect.gen(function* () {
})),
});
const mobileIngestToken = yield* Axiom.ApiToken("RelayMobileAxiomIngestToken", {
name: relayResourceNameForStage("t3-code-mobile-otel-ingest", stage),
description: "Owned by Alchemy. Scoped OTLP ingest token for T3 Code mobile spans.",
datasetCapabilities: Output.map(traces.name, (dataset) => ({
[dataset]: { ingest: ["create" as const] },
})),
});
yield* Axiom.View("RelayRecentSpansView", {
name: relayResourceNameForStage("t3-code-relay-recent-spans", stage),
description: "Recent relay HTTP request spans.",
@@ -57,7 +49,7 @@ export const RelayObservability = Effect.gen(function* () {
aplQuery: Output.map(traces.name, relayRecentSpansQuery),
});
return { traces, workerIngestToken, mobileIngestToken } as const;
return { traces, ingestToken } as const;
});
export const withSpanAttributes =
+1 -1
View File
@@ -129,7 +129,7 @@ export default class Api extends Cloudflare.Worker<Api>()(
const apnsDeliveryQueueSender = yield* Cloudflare.QueueBinding.bind(apnsDeliveryQueue);
const axiomDatasetName = yield* observability.traces.name;
const axiomIngestToken = yield* observability.workerIngestToken.token;
const axiomIngestToken = yield* observability.ingestToken.token;
const axiomTracesEndpoint = yield* observability.traces.otelTracesEndpoint;
const clerkSecretKey = yield* Config.redacted("CLERK_SECRET_KEY");
-2
View File
@@ -1,7 +1,6 @@
import { definePlugin } from "@oxlint/plugins";
import noInlineSchemaCompile from "./rules/no-inline-schema-compile.ts";
import noManualEffectRuntimeInTests from "./rules/no-manual-effect-runtime-in-tests.ts";
export default definePlugin({
meta: {
@@ -9,6 +8,5 @@ export default definePlugin({
},
rules: {
"no-inline-schema-compile": noInlineSchemaCompile,
"no-manual-effect-runtime-in-tests": noManualEffectRuntimeInTests,
},
});
@@ -1,73 +0,0 @@
import { assert, describe } from "@effect/vitest";
import { createOxlintRuleHarness } from "../test/utils.ts";
const rule = createOxlintRuleHarness("t3code/no-manual-effect-runtime-in-tests", {
filename: "fixture.test.ts",
});
describe("t3code/no-manual-effect-runtime-in-tests", () => {
rule.valid(
"allows @effect/vitest effect tests",
`
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
it.effect("runs an Effect", () => Effect.succeed("ok"));
`,
);
const runtimeMethods = [
"runCallback",
"runCallbackWith",
"runFork",
"runForkWith",
"runPromise",
"runPromiseExit",
"runPromiseExitWith",
"runPromiseWith",
"runSync",
"runSyncExit",
"runSyncExitWith",
"runSyncWith",
] as const;
for (const method of runtimeMethods) {
rule.invalid(
`reports Effect.${method}`,
`
import * as Effect from "effect/Effect";
test("runs an Effect", () => {
Effect.${method}(Effect.succeed("ok"));
});
`,
(output) => {
assert.match(output, /Use @effect\/vitest with it\.effect/);
},
);
}
rule.invalid(
"reports ManagedRuntime.make",
`
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
test("makes a runtime", () => {
ManagedRuntime.make(Layer.empty);
});
`,
);
});
const productionRule = createOxlintRuleHarness("t3code/no-manual-effect-runtime-in-tests");
productionRule.valid(
"allows production runtime boundaries",
`
import * as Effect from "effect/Effect";
export const main = () => Effect.runPromise(Effect.void);
`,
);
@@ -1,113 +0,0 @@
import { defineRule } from "@oxlint/plugins";
import * as Option from "effect/Option";
import { getPropertyName, isIdentifier, unwrapExpression } from "../utils.ts";
const TEST_FILE_PATTERN = /\.(?:test|spec)\.[cm]?[jt]sx?$/u;
const EFFECT_RUNTIME_METHODS = new Set([
"runCallback",
"runCallbackWith",
"runFork",
"runForkWith",
"runPromise",
"runPromiseExit",
"runPromiseExitWith",
"runPromiseWith",
"runSync",
"runSyncExit",
"runSyncExitWith",
"runSyncWith",
]);
// Existing manual runners are tracked as debt. The rule permits no net-new
// occurrences in these files, while unlisted test files must have zero.
const LEGACY_BASELINE = new Map<string, number>([
["apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts", 1],
["apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts", 2],
["apps/mobile/src/state/use-remote-environment-registry.test.ts", 2],
["apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts", 5],
["apps/server/src/orchestration/commandInvariants.test.ts", 6],
["apps/server/src/orchestration/Layers/CheckpointReactor.test.ts", 42],
["apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts", 5],
["apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts", 4],
["apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts", 70],
["apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts", 31],
["apps/server/src/orchestration/Layers/ThreadDeletionReactor.test.ts", 2],
["apps/server/src/orchestration/projector.test.ts", 20],
["apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts", 4],
["apps/server/src/provider/acp/CursorAcpSupport.test.ts", 1],
["apps/server/src/provider/Layers/ClaudeAdapter.test.ts", 2],
["apps/server/src/provider/Layers/CodexAdapter.test.ts", 1],
["apps/server/src/provider/Layers/CodexSessionRuntime.test.ts", 5],
["apps/server/src/provider/Layers/CursorAdapter.test.ts", 1],
["apps/server/src/provider/Layers/CursorProvider.test.ts", 4],
["apps/server/src/provider/Layers/ProviderService.test.ts", 2],
["apps/server/src/provider/Layers/ProviderSessionReaper.test.ts", 21],
["apps/server/src/relay/AgentAwarenessRelay.test.ts", 4],
["apps/server/src/server.test.ts", 1],
["apps/web/src/cloud/dpop.test.ts", 2],
["apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts", 1],
["oxlint-plugin-t3code/rules/no-manual-effect-runtime-in-tests.test.ts", 7],
["packages/client-runtime/src/managedRelayState.test.ts", 1],
["packages/client-runtime/src/wsTransport.test.ts", 2],
]);
const baselineFor = (filename: string): number => {
const normalized = filename.replaceAll("\\", "/");
for (const [suffix, count] of LEGACY_BASELINE) {
if (normalized.endsWith(suffix)) return count;
}
return 0;
};
const manualRunnerName = (callee: unknown): Option.Option<string> => {
const expression = unwrapExpression(callee);
if (Option.isNone(expression) || expression.value.type !== "MemberExpression") {
return Option.none();
}
const object = unwrapExpression(expression.value.object);
const property = getPropertyName(expression.value.property);
if (Option.isNone(property)) return Option.none();
if (isIdentifier(object, "Effect") && EFFECT_RUNTIME_METHODS.has(property.value)) {
return Option.some(`Effect.${property.value}`);
}
if (isIdentifier(object, "ManagedRuntime") && property.value === "make") {
return Option.some("ManagedRuntime.make");
}
return Option.none();
};
export default defineRule({
meta: {
type: "problem",
docs: {
description:
"Disallow manually creating or running Effect runtimes in tests; use @effect/vitest.",
},
},
create(context) {
if (!TEST_FILE_PATTERN.test(context.filename)) return {};
const allowedCount = baselineFor(context.filename);
let occurrenceCount = 0;
return {
CallExpression(node) {
const runner = manualRunnerName(node.callee);
if (Option.isNone(runner)) return;
occurrenceCount++;
if (occurrenceCount <= allowedCount) return;
context.report({
node: node.callee,
message: `Do not use ${runner.value} in tests. Use @effect/vitest with it.effect(...) and test layers instead.`,
});
},
};
},
});
+2 -9
View File
@@ -48,10 +48,6 @@ interface RuleHarness {
readonly invalid: (name: string, source: string, assertion?: (output: string) => void) => void;
}
interface RuleHarnessOptions {
readonly filename?: string;
}
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
stream.pipe(
Stream.decodeText(),
@@ -77,10 +73,7 @@ const spawnAndCollectOutput = Effect.fnUntraced(function* (command: ChildProcess
return { exitCode, stdout, stderr };
}, Effect.scoped);
export const createOxlintRuleHarness = (
ruleName: string,
options: RuleHarnessOptions = {},
): RuleHarness => {
export const createOxlintRuleHarness = (ruleName: string): RuleHarness => {
const [pluginName, shortRuleName] = ruleName.split("/");
const diagnosticRuleName =
pluginName && shortRuleName ? `${pluginName}\\(${shortRuleName}\\)` : ruleName;
@@ -91,7 +84,7 @@ export const createOxlintRuleHarness = (
const path = yield* Path.Path;
const fixtureDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-oxlint-" });
const configPath = path.join(fixtureDir, ".oxlintrc.json");
const sourcePath = path.join(fixtureDir, options.filename ?? "fixture.ts");
const sourcePath = path.join(fixtureDir, "fixture.ts");
const repoRoot = path.join(import.meta.dirname, "..", "..");
const oxlintBin = path.join(
repoRoot,
@@ -132,47 +132,6 @@ describe("createManagedRelayQueryManager", () => {
});
});
it("uses schema encoded status keys for equivalent environment inputs", async () => {
const getEnvironmentStatus = vi.fn(() =>
Effect.succeed({
environmentId: environment.environmentId,
endpoint: environment.endpoint,
status: "online" as const,
checkedAt: "2026-06-01T00:00:00.000Z",
}),
);
const manager = createManager({ getEnvironmentStatus });
const reorderedEnvironment = {
linkedAt: environment.linkedAt,
endpoint: {
providerKind: environment.endpoint.providerKind,
wsBaseUrl: environment.endpoint.wsBaseUrl,
httpBaseUrl: environment.endpoint.httpBaseUrl,
},
label: environment.label,
environmentId: environment.environmentId,
} satisfies RelayClientEnvironmentRecord;
setSession();
const atom = manager.environmentStatusAtom({ accountId: "account-1", environment });
registry.get(atom);
await vi.waitFor(() => expect(getEnvironmentStatus).toHaveBeenCalledTimes(1));
registry.get(
manager.environmentStatusAtom({
accountId: "account-1",
environment: reorderedEnvironment,
}),
);
expect(getEnvironmentStatus).toHaveBeenCalledTimes(1);
manager.refreshEnvironmentStatus(registry, {
accountId: "account-1",
environment: reorderedEnvironment,
});
await vi.waitFor(() => expect(getEnvironmentStatus).toHaveBeenCalledTimes(2));
});
it("rejects status responses for a different environment", async () => {
const mismatchedStatus = {
environmentId: EnvironmentId.make("environment-2"),
@@ -1,15 +1,15 @@
import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
import {
import type {
RelayClientEnvironmentRecord,
RelayEnvironmentStatusResponse,
} from "@t3tools/contracts/relay";
import {
RelayEnvironmentConnectScope,
RelayEnvironmentStatusScope,
type RelayClientEnvironmentRecord as RelayClientEnvironmentRecordType,
} from "@t3tools/contracts/relay";
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { AsyncResult, Atom, type AtomRegistry } from "effect/unstable/reactivity";
import { ManagedRelayClient } from "./managedRelay.ts";
@@ -37,16 +37,6 @@ export class ManagedRelaySnapshotError extends Data.TaggedError("ManagedRelaySna
readonly message: string;
}> {}
const EnvironmentStatusKey = Schema.Struct({
accountId: Schema.String,
environment: RelayClientEnvironmentRecord,
});
type EnvironmentStatusKey = typeof EnvironmentStatusKey.Type;
const EnvironmentStatusKeyJson = Schema.fromJsonString(EnvironmentStatusKey);
const encodeEnvironmentStatusKey = Schema.encodeSync(EnvironmentStatusKeyJson);
const decodeEnvironmentStatusKey = Schema.decodeSync(EnvironmentStatusKeyJson);
export const managedRelaySessionAtom = Atom.make<ManagedRelaySession | null>(null).pipe(
Atom.keepAlive,
Atom.withLabel("managed-relay:session"),
@@ -140,13 +130,19 @@ function requireClerkToken(
function statusKey(input: {
readonly accountId: string;
readonly environment: RelayClientEnvironmentRecordType;
readonly environment: RelayClientEnvironmentRecord;
}): string {
return encodeEnvironmentStatusKey(input);
return JSON.stringify(input);
}
function parseStatusKey(key: string): EnvironmentStatusKey {
return decodeEnvironmentStatusKey(key);
function parseStatusKey(key: string): {
readonly accountId: string;
readonly environment: RelayClientEnvironmentRecord;
} {
return JSON.parse(key) as {
readonly accountId: string;
readonly environment: RelayClientEnvironmentRecord;
};
}
function endpointMatches(
@@ -161,7 +157,7 @@ function endpointMatches(
}
function validateEnvironmentStatus(
environment: RelayClientEnvironmentRecordType,
environment: RelayClientEnvironmentRecord,
status: RelayEnvironmentStatusResponse,
): Effect.Effect<RelayEnvironmentStatusResponse, ManagedRelaySnapshotError> {
if (status.environmentId !== environment.environmentId) {
@@ -272,7 +268,7 @@ export function createManagedRelayQueryManager(
devicesAtom,
environmentStatusAtom: (input: {
readonly accountId: string;
readonly environment: RelayClientEnvironmentRecordType;
readonly environment: RelayClientEnvironmentRecord;
}) => environmentStatusAtom(statusKey(input)),
refreshEnvironments(registry: AtomRegistry.AtomRegistry, accountId: string): void {
registry.refresh(environmentsAtom(accountId));
@@ -284,7 +280,7 @@ export function createManagedRelayQueryManager(
registry: AtomRegistry.AtomRegistry,
input: {
readonly accountId: string;
readonly environment: RelayClientEnvironmentRecordType;
readonly environment: RelayClientEnvironmentRecord;
},
): void {
registry.refresh(environmentStatusAtom(statusKey(input)));
+1 -5
View File
@@ -15,7 +15,6 @@ import type {
EnvironmentScopeRequiredError,
} from "@t3tools/contracts";
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -112,10 +111,7 @@ export type RemoteEnvironmentAuthError =
export const remoteHttpClientLayer = (
fetchFn: typeof globalThis.fetch,
): Layer.Layer<HttpClient.HttpClient> =>
Layer.merge(
FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn))),
httpHeaderRedactionLayer,
);
FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn)));
const failRemoteRequest = (
requestUrl: string,
-4
View File
@@ -31,10 +31,6 @@
"types": "./src/observability.ts",
"import": "./src/observability.ts"
},
"./httpObservability": {
"types": "./src/httpObservability.ts",
"import": "./src/httpObservability.ts"
},
"./shell": {
"types": "./src/shell.ts",
"import": "./src/shell.ts"
-8
View File
@@ -1,8 +0,0 @@
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Headers from "effect/unstable/http/Headers";
export const httpHeaderRedactionLayer = Layer.effect(
Headers.CurrentRedactedNames,
Effect.map(Headers.CurrentRedactedNames, (names) => [...names, "dpop"]),
);
-101
View File
@@ -1,101 +0,0 @@
import * as NodeCrypto from "node:crypto";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import {
RelayJwtSignError,
RelayJwtVerifyError,
signRelayJwt,
verifyRelayJwt,
} from "./relayJwt.ts";
const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {
privateKeyEncoding: { format: "pem", type: "pkcs8" },
publicKeyEncoding: { format: "pem", type: "spki" },
});
const isRelayJwtSignError = Schema.is(RelayJwtSignError);
const isRelayJwtVerifyError = Schema.is(RelayJwtVerifyError);
describe("relayJwt", () => {
it.effect("signs and verifies relay JWTs", () =>
Effect.gen(function* () {
const token = yield* signRelayJwt({
privateKey: keyPair.privateKey,
typ: "test+jwt",
payload: {
iss: "https://relay.example.test",
aud: "https://relay.example.test",
sub: "user_123",
jti: "nonce-1",
iat: 100,
exp: 200,
},
});
const payload = yield* verifyRelayJwt({
publicKey: keyPair.publicKey,
token,
typ: "test+jwt",
issuer: "https://relay.example.test",
audience: "https://relay.example.test",
nowEpochSeconds: 150,
});
assert.equal(payload.sub, "user_123");
assert.equal(payload.jti, "nonce-1");
}),
);
it.effect("returns a structured sign error for invalid private key material", () =>
Effect.gen(function* () {
const error = yield* signRelayJwt({
privateKey: "not a pem",
typ: "test+jwt",
payload: {},
}).pipe(Effect.flip);
assert.equal(error._tag, "RelayJwtSignError");
assert.equal(error.typ, "test+jwt");
assert.equal(error.message, "Failed to sign relay JWT (test+jwt).");
assert.equal(isRelayJwtSignError(error), true);
}),
);
it.effect("returns a structured verify error with expected claim context", () =>
Effect.gen(function* () {
const token = yield* signRelayJwt({
privateKey: keyPair.privateKey,
typ: "test+jwt",
payload: {
iss: "https://relay.example.test",
aud: "https://relay.example.test",
sub: "user_123",
iat: 100,
exp: 200,
},
});
const error = yield* verifyRelayJwt({
publicKey: keyPair.publicKey,
token,
typ: "other+jwt",
issuer: "https://relay.example.test",
audience: "https://relay.example.test",
nowEpochSeconds: 150,
}).pipe(Effect.flip);
assert.equal(error._tag, "RelayJwtVerifyError");
if (error._tag !== "RelayJwtVerifyError") {
assert.fail(`Expected RelayJwtVerifyError, got ${error._tag}`);
}
assert.equal(error.typ, "other+jwt");
assert.equal(error.issuer, "https://relay.example.test");
assert.equal(error.audience, "https://relay.example.test");
assert.equal(error.message, "Failed to verify relay JWT (other+jwt).");
assert.equal(isRelayJwtVerifyError(error), true);
}),
);
});
+6 -37
View File
@@ -1,7 +1,7 @@
import { decodeJwt, importPKCS8, importSPKI, jwtVerify, SignJWT, type JWTPayload } from "jose";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
export const RELAY_LINK_PROOF_TYP = "t3-env-link+jwt";
export const RELAY_MINT_REQUEST_TYP = "t3-cloud-mint+jwt";
@@ -10,34 +10,9 @@ export const RELAY_MINT_RESPONSE_TYP = "t3-env-mint+jwt";
export const RELAY_HEALTH_RESPONSE_TYP = "t3-env-health+jwt";
export const RELAY_ACTIVITY_PUBLISH_TYP = "t3-env-activity+jwt";
export class RelayJwtSignError extends Schema.TaggedErrorClass<RelayJwtSignError>()(
"RelayJwtSignError",
{
typ: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to sign relay JWT (${this.typ}).`;
}
}
export class RelayJwtVerifyError extends Schema.TaggedErrorClass<RelayJwtVerifyError>()(
"RelayJwtVerifyError",
{
typ: Schema.String,
issuer: Schema.String,
audience: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to verify relay JWT (${this.typ}).`;
}
}
export const RelayJwtError = Schema.Union([RelayJwtSignError, RelayJwtVerifyError]);
export type RelayJwtError = typeof RelayJwtError.Type;
export class RelayJwtError extends Data.TaggedError("RelayJwtError")<{
readonly cause: unknown;
}> {}
export function normalizeRelayIssuer(value: string): string {
return value.trim().replace(/\/+$/gu, "");
@@ -63,7 +38,7 @@ export function signRelayJwt(input: {
.setProtectedHeader({ alg: "EdDSA", typ: input.typ })
.sign(key);
},
catch: (cause) => new RelayJwtSignError({ typ: input.typ, cause }),
catch: (cause) => new RelayJwtError({ cause }),
});
}
@@ -89,12 +64,6 @@ export function verifyRelayJwt(input: {
});
return verified.payload;
},
catch: (cause) =>
new RelayJwtVerifyError({
typ: input.typ,
issuer: input.issuer,
audience: input.audience,
cause,
}),
catch: (cause) => new RelayJwtError({ cause }),
});
}
+1 -22
View File
@@ -27,12 +27,6 @@ describe("loadRepoEnv", () => {
expect(env.EXPO_PUBLIC_CLERK_JWT_TEMPLATE).toBeUndefined();
expect(env.T3CODE_RELAY_URL).toBeUndefined();
expect(env.VITE_T3CODE_RELAY_URL).toBeUndefined();
expect(env.T3CODE_MOBILE_OTLP_TRACES_URL).toBeUndefined();
expect(env.T3CODE_MOBILE_OTLP_TRACES_DATASET).toBeUndefined();
expect(env.T3CODE_MOBILE_OTLP_TRACES_TOKEN).toBeUndefined();
expect(env.EXPO_PUBLIC_OTLP_TRACES_URL).toBeUndefined();
expect(env.EXPO_PUBLIC_OTLP_TRACES_DATASET).toBeUndefined();
expect(env.EXPO_PUBLIC_OTLP_TRACES_TOKEN).toBeUndefined();
});
it("applies process, root local, and root precedence in that order", () => {
@@ -79,41 +73,26 @@ describe("loadRepoEnv", () => {
VITE_CLERK_JWT_TEMPLATE: "template_legacy",
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_canonical",
VITE_T3CODE_RELAY_URL: "https://legacy.example.test",
EXPO_PUBLIC_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",
EXPO_PUBLIC_OTLP_TRACES_DATASET: "mobile-traces",
EXPO_PUBLIC_OTLP_TRACES_TOKEN: "mobile-token",
}),
).toEqual({
clerkPublishableKey: "pk_legacy",
clerkJwtTemplate: "template_legacy",
clerkCliOAuthClientId: "oauth_canonical",
relayUrl: "https://legacy.example.test",
mobileOtlpTracesUrl: "https://api.axiom.co/v1/traces",
mobileOtlpTracesDataset: "mobile-traces",
mobileOtlpTracesToken: "mobile-token",
});
});
it("projects canonical mobile tracing values to Expo public aliases", () => {
it("projects only the configured aliases", () => {
expect(
loadRepoEnv({
baseEnv: {
T3CODE_RELAY_URL: "https://relay.example.test",
T3CODE_MOBILE_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",
T3CODE_MOBILE_OTLP_TRACES_DATASET: "mobile-traces",
T3CODE_MOBILE_OTLP_TRACES_TOKEN: "mobile-token",
},
repoRoot: makeTemporaryDirectory(),
}),
).toEqual({
T3CODE_RELAY_URL: "https://relay.example.test",
VITE_T3CODE_RELAY_URL: "https://relay.example.test",
T3CODE_MOBILE_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",
T3CODE_MOBILE_OTLP_TRACES_DATASET: "mobile-traces",
T3CODE_MOBILE_OTLP_TRACES_TOKEN: "mobile-token",
EXPO_PUBLIC_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",
EXPO_PUBLIC_OTLP_TRACES_DATASET: "mobile-traces",
EXPO_PUBLIC_OTLP_TRACES_TOKEN: "mobile-token",
});
});
});
-36
View File
@@ -9,9 +9,6 @@ export interface T3CodePublicConfig {
readonly clerkJwtTemplate: string | undefined;
readonly clerkCliOAuthClientId: string | undefined;
readonly relayUrl: string | undefined;
readonly mobileOtlpTracesUrl: string | undefined;
readonly mobileOtlpTracesDataset: string | undefined;
readonly mobileOtlpTracesToken: string | undefined;
}
type Environment = Readonly<Record<string, string | undefined>>;
@@ -60,24 +57,6 @@ export function loadRepoEnv({
VITE_T3CODE_RELAY_URL: config.relayUrl,
}
: {}),
...(config.mobileOtlpTracesUrl
? {
T3CODE_MOBILE_OTLP_TRACES_URL: config.mobileOtlpTracesUrl,
EXPO_PUBLIC_OTLP_TRACES_URL: config.mobileOtlpTracesUrl,
}
: {}),
...(config.mobileOtlpTracesDataset
? {
T3CODE_MOBILE_OTLP_TRACES_DATASET: config.mobileOtlpTracesDataset,
EXPO_PUBLIC_OTLP_TRACES_DATASET: config.mobileOtlpTracesDataset,
}
: {}),
...(config.mobileOtlpTracesToken
? {
T3CODE_MOBILE_OTLP_TRACES_TOKEN: config.mobileOtlpTracesToken,
EXPO_PUBLIC_OTLP_TRACES_TOKEN: config.mobileOtlpTracesToken,
}
: {}),
};
}
@@ -97,21 +76,6 @@ export function resolvePublicConfig(...sources: readonly Environment[]): T3CodeP
),
clerkCliOAuthClientId: firstNonEmpty(sources, "T3CODE_CLERK_CLI_OAUTH_CLIENT_ID"),
relayUrl: firstNonEmpty(sources, "T3CODE_RELAY_URL", "VITE_T3CODE_RELAY_URL"),
mobileOtlpTracesUrl: firstNonEmpty(
sources,
"T3CODE_MOBILE_OTLP_TRACES_URL",
"EXPO_PUBLIC_OTLP_TRACES_URL",
),
mobileOtlpTracesDataset: firstNonEmpty(
sources,
"T3CODE_MOBILE_OTLP_TRACES_DATASET",
"EXPO_PUBLIC_OTLP_TRACES_DATASET",
),
mobileOtlpTracesToken: firstNonEmpty(
sources,
"T3CODE_MOBILE_OTLP_TRACES_TOKEN",
"EXPO_PUBLIC_OTLP_TRACES_TOKEN",
),
};
}
-1
View File
@@ -91,7 +91,6 @@ export default defineConfig({
"typescript/restrict-template-expressions": "off",
"typescript/unbound-method": "off",
"t3code/no-inline-schema-compile": "warn",
"t3code/no-manual-effect-runtime-in-tests": "error",
},
options: {
// Revisit once Oxlint's tsgolint path can integrate with @effect/tsgo diagnostics.