Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 3b2742e93f Fix chat plan selector lint
Co-authored-by: Julius Marminge <[email protected]>
2026-06-09 16:29:47 +00:00
Cursor AgentandJulius Marminge 10d9ab45fc Refine chat plan thread id memoization
Co-authored-by: Julius Marminge <[email protected]>
2026-06-09 16:28:31 +00:00
Cursor AgentandJulius Marminge da6ac6b34e Optimize chat plan catalog selector
Co-authored-by: Julius Marminge <[email protected]>
2026-06-09 16:26:39 +00:00
Julius Marmingeandcodex 0e4a43519f [codex] Extract infrastructure, telemetry, and test tooling (#2994)
Co-authored-by: codex <[email protected]>
2026-06-07 20:21:47 -07:00
37 changed files with 989 additions and 410 deletions

No files matched your search

+5
View File
@@ -10,3 +10,8 @@
# 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,6 +161,11 @@ 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().relayUrl;
const relayUrl = resolveCloudPublicConfig().relay.url;
if (!relayUrl) {
logRegistrationDebug("relay registration skipped; relay config missing");
return null;
@@ -66,7 +66,9 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
}
export function CloudAuthProvider(props: { readonly children: ReactNode }) {
const { clerkPublishableKey: publishableKey, relayUrl } = resolveCloudPublicConfig();
const config = resolveCloudPublicConfig();
const publishableKey = config.clerk.publishableKey;
const relayUrl = config.relay.url;
useEffect(() => {
if (!publishableKey || !relayUrl) {
@@ -50,7 +50,7 @@ export function normalizeRelayBaseUrl(value: string | null | undefined): string
}
function readRelayUrl(): string | null {
return resolveCloudPublicConfig().relayUrl;
return resolveCloudPublicConfig().relay.url;
}
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
@@ -1,7 +1,6 @@
import { useAtomValue } from "@effect/atom-react";
import {
createManagedRelayQueryManager,
ManagedRelayClient,
managedRelaySessionAtom,
readManagedRelaySnapshotState,
} from "@t3tools/client-runtime";
@@ -9,23 +8,13 @@ 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 { mobileRuntime } from "../../lib/runtime";
import { mobileRuntimeContextLayer } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
const managedRelayAtomRuntime = Atom.runtime(
Layer.effect(
ManagedRelayClient,
mobileRuntime.contextEffect.pipe(
Effect.map((context) => Context.get(context, ManagedRelayClient)),
),
),
);
const managedRelayAtomRuntime = Atom.runtime(mobileRuntimeContextLayer);
export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime);
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { resolveCloudPublicConfig } from "./publicConfig";
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig";
vi.mock("expo-constants", () => ({
default: {
@@ -13,9 +13,18 @@ vi.mock("expo-constants", () => ({
describe("resolveCloudPublicConfig", () => {
it("returns no cloud configuration for an unconfigured build", () => {
expect(resolveCloudPublicConfig({})).toEqual({
clerkPublishableKey: null,
clerkJwtTemplate: null,
relayUrl: null,
clerk: {
publishableKey: null,
jwtTemplate: null,
},
relay: {
url: null,
},
observability: {
tracesUrl: null,
tracesDataset: null,
tracesToken: null,
},
});
});
@@ -24,11 +33,25 @@ 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({
clerkPublishableKey: "pk_test_example",
clerkJwtTemplate: "t3-relay",
relayUrl: "https://relay.example.test",
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",
},
});
});
@@ -39,9 +62,59 @@ describe("resolveCloudPublicConfig", () => {
relay: { url: "http://relay.example.test" },
}),
).toEqual({
clerkPublishableKey: "pk_test_example",
clerkJwtTemplate: "t3-relay",
relayUrl: null,
clerk: {
publishableKey: "pk_test_example",
jwtTemplate: "t3-relay",
},
relay: {
url: null,
},
observability: {
tracesUrl: null,
tracesDataset: null,
tracesToken: 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);
});
});
+69 -17
View File
@@ -2,40 +2,92 @@ 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 clerkPublishableKey: string | null;
readonly clerkJwtTemplate: string | null;
readonly relayUrl: string | null;
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;
};
}
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;
}
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;
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) {
return {
clerkPublishableKey: trimNonEmpty(clerk?.publishableKey),
clerkJwtTemplate: trimNonEmpty(clerk?.jwtTemplate),
relayUrl: normalizeSecureRelayUrl(trimNonEmpty(relay?.url) ?? ""),
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),
},
} satisfies CloudPublicConfig;
}
export function hasCloudPublicConfig(): boolean {
const config = resolveCloudPublicConfig();
return Boolean(config.clerkPublishableKey && config.clerkJwtTemplate && config.relayUrl);
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,
);
}
export function resolveRelayClerkTokenOptions() {
const { clerkJwtTemplate } = resolveCloudPublicConfig();
if (!clerkJwtTemplate) {
const { jwtTemplate } = resolveCloudPublicConfig().clerk;
if (!jwtTemplate) {
throw new Error("T3CODE_CLERK_JWT_TEMPLATE is not configured.");
}
return relayClerkTokenOptions(clerkJwtTemplate);
return relayClerkTokenOptions(jwtTemplate);
}
@@ -0,0 +1,52 @@
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");
}),
),
);
});
@@ -0,0 +1,60 @@
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",
});
+8 -7
View File
@@ -6,19 +6,20 @@ 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().relayUrl ?? "http://relay.invalid";
return resolveCloudPublicConfig().relay.url ?? "http://relay.invalid";
}
const mobileHttpClientLayer = remoteHttpClientLayer(fetch);
export const mobileRuntime = ManagedRuntime.make(
Layer.mergeAll(
mobileHttpClientLayer,
mobileCryptoLayer,
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
Layer.provide(Layer.mergeAll(mobileHttpClientLayer, mobileCryptoLayer)),
),
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
Layer.provideMerge(mobileCryptoLayer),
Layer.provideMerge(mobileHttpClientLayer),
Layer.provideMerge(mobileTracingLayer.pipe(Layer.provide(mobileHttpClientLayer))),
),
);
export const mobileRuntimeContextLayer = Layer.effectContext(mobileRuntime.contextEffect);
@@ -1,3 +1,4 @@
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";
@@ -18,6 +19,7 @@ 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(
+131 -121
View File
@@ -209,118 +209,131 @@ type EnvironmentUnavailableState = {
};
type ThreadPlanCatalogEntry = Pick<Thread, "id" | "proposedPlans">;
type ThreadPlanCatalogStoreState = ReturnType<typeof useStore.getState>;
interface ThreadPlanCatalogCacheEntry {
shell: object | null;
proposedPlanIds: readonly string[] | undefined;
proposedPlansById: Record<string, Thread["proposedPlans"][number]> | undefined;
entry: ThreadPlanCatalogEntry;
}
function createThreadPlanCatalogSelector(threadIds: readonly ThreadId[]) {
let previousThreadIds: readonly ThreadId[] = [];
let previousResult: ThreadPlanCatalogEntry[] = [];
let previousEntries = new Map<ThreadId, ThreadPlanCatalogCacheEntry>();
return (state: ThreadPlanCatalogStoreState): ThreadPlanCatalogEntry[] => {
const sameThreadIds =
previousThreadIds.length === threadIds.length &&
previousThreadIds.every((id, index) => id === threadIds[index]);
const nextEntries = new Map<ThreadId, ThreadPlanCatalogCacheEntry>();
const nextResult: ThreadPlanCatalogEntry[] = [];
let changed = !sameThreadIds;
for (const threadId of threadIds) {
let shell: object | undefined;
let proposedPlanIds: readonly string[] | undefined;
let proposedPlansById: Record<string, Thread["proposedPlans"][number]> | undefined;
for (const environmentState of Object.values(state.environmentStateById)) {
const matchedShell = environmentState.threadShellById[threadId];
if (!matchedShell) {
continue;
}
shell = matchedShell;
proposedPlanIds = environmentState.proposedPlanIdsByThreadId[threadId];
proposedPlansById = environmentState.proposedPlanByThreadId[threadId] as
| Record<string, Thread["proposedPlans"][number]>
| undefined;
break;
}
if (!shell) {
const previous = previousEntries.get(threadId);
if (
previous &&
previous.shell === null &&
previous.proposedPlanIds === undefined &&
previous.proposedPlansById === undefined
) {
nextEntries.set(threadId, previous);
continue;
}
changed = true;
nextEntries.set(threadId, {
shell: null,
proposedPlanIds: undefined,
proposedPlansById: undefined,
entry: { id: threadId, proposedPlans: EMPTY_PROPOSED_PLANS },
});
continue;
}
const previous = previousEntries.get(threadId);
if (
previous &&
previous.shell === shell &&
previous.proposedPlanIds === proposedPlanIds &&
previous.proposedPlansById === proposedPlansById
) {
nextEntries.set(threadId, previous);
nextResult.push(previous.entry);
continue;
}
changed = true;
const proposedPlans =
proposedPlanIds && proposedPlanIds.length > 0 && proposedPlansById
? proposedPlanIds.flatMap((planId) => {
const proposedPlan = proposedPlansById?.[planId];
return proposedPlan ? [proposedPlan] : [];
})
: EMPTY_PROPOSED_PLANS;
const entry = { id: threadId, proposedPlans };
nextEntries.set(threadId, {
shell,
proposedPlanIds,
proposedPlansById,
entry,
});
nextResult.push(entry);
}
if (!changed && previousResult.length === nextResult.length) {
return previousResult;
}
previousThreadIds = threadIds;
previousEntries = nextEntries;
previousResult = nextResult;
return nextResult;
};
}
function deriveThreadPlanCatalogThreadIds(input: {
activeThreadId: ThreadId | null;
sourceProposedPlanThreadId: ThreadId | null;
}): readonly ThreadId[] {
const threadIds: ThreadId[] = [];
if (input.activeThreadId) {
threadIds.push(input.activeThreadId);
}
if (
input.sourceProposedPlanThreadId &&
input.sourceProposedPlanThreadId !== input.activeThreadId
) {
threadIds.push(input.sourceProposedPlanThreadId);
}
return threadIds;
}
function useThreadPlanCatalog(threadIds: readonly ThreadId[]): ThreadPlanCatalogEntry[] {
return useStore(
useMemo(() => {
let previousThreadIds: readonly ThreadId[] = [];
let previousResult: ThreadPlanCatalogEntry[] = [];
let previousEntries = new Map<
ThreadId,
{
shell: object | null;
proposedPlanIds: readonly string[] | undefined;
proposedPlansById: Record<string, Thread["proposedPlans"][number]> | undefined;
entry: ThreadPlanCatalogEntry;
}
>();
return (state) => {
const sameThreadIds =
previousThreadIds.length === threadIds.length &&
previousThreadIds.every((id, index) => id === threadIds[index]);
const nextEntries = new Map<
ThreadId,
{
shell: object | null;
proposedPlanIds: readonly string[] | undefined;
proposedPlansById: Record<string, Thread["proposedPlans"][number]> | undefined;
entry: ThreadPlanCatalogEntry;
}
>();
const nextResult: ThreadPlanCatalogEntry[] = [];
let changed = !sameThreadIds;
for (const threadId of threadIds) {
let shell: object | undefined;
let proposedPlanIds: readonly string[] | undefined;
let proposedPlansById: Record<string, Thread["proposedPlans"][number]> | undefined;
for (const environmentState of Object.values(state.environmentStateById)) {
const matchedShell = environmentState.threadShellById[threadId];
if (!matchedShell) {
continue;
}
shell = matchedShell;
proposedPlanIds = environmentState.proposedPlanIdsByThreadId[threadId];
proposedPlansById = environmentState.proposedPlanByThreadId[threadId] as
| Record<string, Thread["proposedPlans"][number]>
| undefined;
break;
}
if (!shell) {
const previous = previousEntries.get(threadId);
if (
previous &&
previous.shell === null &&
previous.proposedPlanIds === undefined &&
previous.proposedPlansById === undefined
) {
nextEntries.set(threadId, previous);
continue;
}
changed = true;
nextEntries.set(threadId, {
shell: null,
proposedPlanIds: undefined,
proposedPlansById: undefined,
entry: { id: threadId, proposedPlans: EMPTY_PROPOSED_PLANS },
});
continue;
}
const previous = previousEntries.get(threadId);
if (
previous &&
previous.shell === shell &&
previous.proposedPlanIds === proposedPlanIds &&
previous.proposedPlansById === proposedPlansById
) {
nextEntries.set(threadId, previous);
nextResult.push(previous.entry);
continue;
}
changed = true;
const proposedPlans =
proposedPlanIds && proposedPlanIds.length > 0 && proposedPlansById
? proposedPlanIds.flatMap((planId) => {
const proposedPlan = proposedPlansById?.[planId];
return proposedPlan ? [proposedPlan] : [];
})
: EMPTY_PROPOSED_PLANS;
const entry = { id: threadId, proposedPlans };
nextEntries.set(threadId, {
shell,
proposedPlanIds,
proposedPlansById,
entry,
});
nextResult.push(entry);
}
if (!changed && previousResult.length === nextResult.length) {
return previousResult;
}
previousThreadIds = threadIds;
previousEntries = nextEntries;
previousResult = nextResult;
return nextResult;
};
}, [threadIds]),
const selectThreadPlanCatalog = useMemo(
() => createThreadPlanCatalogSelector(threadIds),
[threadIds],
);
return useStore(selectThreadPlanCatalog);
}
function formatOutgoingPrompt(params: {
@@ -1028,19 +1041,16 @@ export default function ChatView(props: ChatViewProps) {
return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey));
}, [draftThreadKeys, openTerminalThreadKeys, serverThreadKeys]);
const activeLatestTurn = activeThread?.latestTurn ?? null;
const threadPlanCatalog = useThreadPlanCatalog(
useMemo(() => {
const threadIds: ThreadId[] = [];
if (activeThread?.id) {
threadIds.push(activeThread.id);
}
const sourceThreadId = activeLatestTurn?.sourceProposedPlan?.threadId;
if (sourceThreadId && sourceThreadId !== activeThread?.id) {
threadIds.push(sourceThreadId);
}
return threadIds;
}, [activeLatestTurn?.sourceProposedPlan?.threadId, activeThread?.id]),
const sourceProposedPlanThreadId = activeLatestTurn?.sourceProposedPlan?.threadId ?? null;
const threadPlanCatalogThreadIds = useMemo(
() =>
deriveThreadPlanCatalogThreadIds({
activeThreadId,
sourceProposedPlanThreadId,
}),
[activeThreadId, sourceProposedPlanThreadId],
);
const threadPlanCatalog = useThreadPlanCatalog(threadPlanCatalogThreadIds);
useEffect(() => {
setMountedTerminalThreadKeys((currentThreadIds) => {
const nextThreadIds = reconcileMountedTerminalThreadIds({
@@ -1,8 +1,7 @@
import { scopeThreadRef } from "@t3tools/client-runtime";
import { ThreadId } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { useState } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { render } from "vitest-browser-react";
const SHARED_THREAD_ID = ThreadId.make("thread-shared");
@@ -27,8 +26,6 @@ const {
activeRunStackedActionDeferredRef,
activeDraftThreadRef,
hasServerThreadRef,
sourceControlDiscoveryRef,
vcsStatusRef,
invalidateSourceControlStateSpy,
refreshVcsStatusSpy,
runStackedActionSpy,
@@ -42,26 +39,6 @@ const {
activeRunStackedActionDeferredRef: { current: createDeferredPromise<never>() },
activeDraftThreadRef: { current: null as unknown },
hasServerThreadRef: { current: true },
sourceControlDiscoveryRef: { current: null as unknown },
vcsStatusRef: {
current: {
isRepo: true,
sourceControlProvider: {
kind: "github",
name: "GitHub",
baseUrl: "https://github.com",
},
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/toast-scope",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 1,
behindCount: 0,
pr: null,
},
},
invalidateSourceControlStateSpy: vi.fn(() => Promise.resolve()),
refreshVcsStatusSpy: vi.fn(() => Promise.resolve(null)),
runStackedActionSpy: vi.fn(() => activeRunStackedActionDeferredRef.current.promise),
@@ -87,10 +64,6 @@ vi.mock("~/editorPreferences", () => ({
openInPreferredEditor: vi.fn(),
}));
vi.mock("~/lib/sourceControlDiscoveryState", () => ({
useSourceControlDiscovery: vi.fn(() => sourceControlDiscoveryRef.current),
}));
vi.mock("~/lib/sourceControlActions", () => ({
invalidateSourceControlState: invalidateSourceControlStateSpy,
useGitStackedAction: vi.fn(() => ({
@@ -124,7 +97,23 @@ vi.mock("~/lib/vcsStatusState", () => ({
refreshVcsStatus: refreshVcsStatusSpy,
resetVcsStatusStateForTests: () => undefined,
useVcsStatus: vi.fn(() => ({
data: vcsStatusRef.current,
data: {
isRepo: true,
sourceControlProvider: {
kind: "github",
name: "GitHub",
baseUrl: "https://github.com",
},
hasPrimaryRemote: true,
isDefaultRef: false,
refName: BRANCH_NAME,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 1,
behindCount: 0,
pr: null,
},
error: null,
isPending: false,
})),
@@ -256,77 +245,6 @@ function findButtonByText(text: string): HTMLButtonElement | null {
) ?? null) as HTMLButtonElement | null;
}
function findRadioByText(text: string): HTMLElement | null {
return (Array.from(document.querySelectorAll('[role="radio"]')).find((radio) =>
radio.textContent?.includes(text),
) ?? null) as HTMLElement | null;
}
function setInputValue(input: HTMLInputElement, value: string) {
input.value = value;
input.dispatchEvent(new Event("input", { bubbles: true }));
}
function createDefaultVcsStatus() {
return {
isRepo: true,
sourceControlProvider: {
kind: "github",
name: "GitHub",
baseUrl: "https://github.com",
},
hasPrimaryRemote: true,
isDefaultRef: false,
refName: BRANCH_NAME,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 1,
behindCount: 0,
pr: null,
};
}
function createDefaultSourceControlDiscovery() {
return {
data: {
versionControlSystems: [],
sourceControlProviders: [
{
kind: "github",
label: "GitHub",
status: "available",
version: Option.some("2.85.0"),
installHint: "Install GitHub CLI.",
detail: Option.none(),
auth: {
status: "authenticated",
account: Option.some("octo"),
host: Option.some("github.com"),
detail: Option.none(),
},
},
{
kind: "gitlab",
label: "GitLab",
status: "available",
version: Option.some("19.0.0"),
installHint: "Install GitLab CLI.",
detail: Option.none(),
auth: {
status: "authenticated",
account: Option.some("tanuki"),
host: Option.some("gitlab.com"),
detail: Option.none(),
},
},
],
},
error: null,
isPending: false,
};
}
function Harness() {
const [activeThreadRef, setActiveThreadRef] = useState(
scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID),
@@ -346,19 +264,12 @@ function Harness() {
}
describe("GitActionsControl thread-scoped progress toast", () => {
beforeEach(() => {
vcsStatusRef.current = createDefaultVcsStatus();
sourceControlDiscoveryRef.current = createDefaultSourceControlDiscovery();
});
afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
activeRunStackedActionDeferredRef.current = createDeferredPromise<never>();
activeDraftThreadRef.current = null;
hasServerThreadRef.current = true;
vcsStatusRef.current = createDefaultVcsStatus();
sourceControlDiscoveryRef.current = createDefaultSourceControlDiscovery();
document.body.innerHTML = "";
});
@@ -424,58 +335,6 @@ describe("GitActionsControl thread-scoped progress toast", () => {
}
});
it("derives publish provider and repository defaults while preserving user edits", async () => {
vcsStatusRef.current = {
...createDefaultVcsStatus(),
hasPrimaryRemote: false,
hasUpstream: false,
aheadCount: 0,
};
const host = document.createElement("div");
document.body.append(host);
const screen = await render(
<GitActionsControl
gitCwd={GIT_CWD}
activeThreadRef={scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID)}
/>,
{ container: host },
);
try {
findButtonByText("Publish repository")?.click();
await Promise.resolve();
expect(document.querySelector('[role="dialog"]')?.textContent).toContain(
"Publish repository",
);
findButtonByText("Next")?.click();
await Promise.resolve();
const repositoryInput = document.querySelector<HTMLInputElement>("#publish-repository-path");
expect(repositoryInput?.value).toBe("octo/");
if (!repositoryInput) {
throw new Error("Repository input was not rendered.");
}
setInputValue(repositoryInput, "octo/demo");
expect(repositoryInput.value).toBe("octo/demo");
findButtonByText("Back")?.click();
await Promise.resolve();
findRadioByText("GitLab")?.click();
await Promise.resolve();
findButtonByText("Next")?.click();
await Promise.resolve();
expect(document.querySelector<HTMLInputElement>("#publish-repository-path")?.value).toBe(
"tanuki/",
);
} finally {
await screen.unmount();
host.remove();
}
});
it("debounces focus-driven git status refreshes", async () => {
vi.useFakeTimers();
+30 -17
View File
@@ -348,9 +348,8 @@ interface PublishRepositoryDialogProps {
function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
const navigate = useNavigate();
const sourceControlDiscovery = useSourceControlDiscovery();
const [requestedPublishProvider, setRequestedPublishProvider] =
useState<PublishProviderKind>("github");
const [publishRepositoryOverride, setPublishRepositoryOverride] = useState<string | null>(null);
const [publishProvider, setPublishProvider] = useState<PublishProviderKind>("github");
const [publishRepository, setPublishRepository] = useState("");
const [publishVisibility, setPublishVisibility] =
useState<SourceControlRepositoryVisibility>("private");
const [publishRemoteName, setPublishRemoteName] = useState("origin");
@@ -361,6 +360,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
const [publishResult, setPublishResult] = useState<SourceControlPublishRepositoryResult | null>(
null,
);
const [hasUserEditedPublishRepository, setHasUserEditedPublishRepository] = useState(false);
const sourceControlScope = useMemo(
() => ({
environmentId: props.environmentId,
@@ -395,13 +395,6 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
]),
) as Record<PublishProviderKind, { readonly ready: boolean; readonly hint: string | null }>;
}, [sourceControlDiscovery.data]);
const firstReadyPublishProvider = PUBLISH_PROVIDER_OPTIONS.find(
(option) => publishProviderReadiness[option.value].ready,
);
const publishProvider =
publishProviderReadiness[requestedPublishProvider].ready || !firstReadyPublishProvider
? requestedPublishProvider
: firstReadyPublishProvider.value;
const hasReadyPublishProvider = useMemo(
() => PUBLISH_PROVIDER_OPTIONS.some((option) => publishProviderReadiness[option.value].ready),
[publishProviderReadiness],
@@ -422,7 +415,6 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
const publishRepositoryPrefill = publishAccountByProvider[publishProvider]
? `${publishAccountByProvider[publishProvider]}/`
: "";
const publishRepository = publishRepositoryOverride ?? publishRepositoryPrefill;
const currentPublishProvider = publishProviderOption(publishProvider);
const publishHost = currentPublishProvider.host;
const publishPathPlaceholder = currentPublishProvider.pathPlaceholder;
@@ -434,6 +426,13 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
null,
] as const;
useEffect(() => {
if (!props.open || hasUserEditedPublishRepository) {
return;
}
setPublishRepository(publishRepositoryPrefill);
}, [hasUserEditedPublishRepository, props.open, publishRepositoryPrefill]);
const canSubmitPublishRepository = useMemo(() => {
if (!selectedPublishProviderReadiness.ready) return false;
if (publishRepositoryAction.isPending) return false;
@@ -444,6 +443,21 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
return owner.length > 0 && name.length > 0;
}, [publishRepository, publishRepositoryAction.isPending, selectedPublishProviderReadiness]);
useEffect(() => {
if (!props.open) {
return;
}
if (publishProviderReadiness[publishProvider].ready) {
return;
}
const firstReadyProvider = PUBLISH_PROVIDER_OPTIONS.find(
(option) => publishProviderReadiness[option.value].ready,
);
if (firstReadyProvider) {
setPublishProvider(firstReadyProvider.value);
}
}, [props.open, publishProvider, publishProviderReadiness]);
const submitPublishRepository = useCallback(() => {
if (!canSubmitPublishRepository) {
return;
@@ -485,7 +499,8 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
const resetState = useCallback(() => {
setPublishRemoteName("origin");
setPublishRepositoryOverride(null);
setPublishRepository("");
setHasUserEditedPublishRepository(false);
setPublishWizardStep(0);
setPublishAdvancedOpen(false);
setPublishError(null);
@@ -578,10 +593,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
</span>
<RadioGroup
value={publishProvider}
onValueChange={(value) => {
setRequestedPublishProvider(value as PublishProviderKind);
setPublishRepositoryOverride(null);
}}
onValueChange={(value) => setPublishProvider(value as PublishProviderKind)}
aria-labelledby="publish-provider-cards-label"
className="grid grid-cols-2 gap-2.5"
>
@@ -667,7 +679,8 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
name="publish-repository-path"
value={publishRepository}
onChange={(event) => {
setPublishRepositoryOverride(event.target.value);
setPublishRepository(event.target.value);
setHasUserEditedPublishRepository(true);
}}
onKeyDown={(event) => {
if (event.key === "Enter") {
+2
View File
@@ -4,6 +4,7 @@ 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,
@@ -28,6 +29,7 @@ const primaryHttpRuntime = ManagedRuntime.make(
Layer.mergeAll(
remoteHttpClientLayer((input, init) => globalThis.fetch(input, init)),
Layer.succeed(FetchHttpClient.RequestInit, primaryEnvironmentRequestInit),
httpHeaderRedactionLayer,
),
),
),
+5
View File
@@ -8,6 +8,7 @@ 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";
@@ -27,6 +28,7 @@ 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 {
@@ -37,6 +39,9 @@ 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,
};
}),
);
+52 -1
View File
@@ -1,6 +1,11 @@
import { describe, expect, it } from "vite-plus/test";
import { hasDeployChanges, reconcileRootEnvRelayUrl, serializeGithubOutput } from "./deploy.ts";
import {
hasDeployChanges,
reconcileRootEnvPublicConfig,
reconcileRootEnvRelayUrl,
serializeGithubOutput,
} from "./deploy.ts";
describe("hasDeployChanges", () => {
it("detects resource, binding, and deletion changes", () => {
@@ -51,6 +56,52 @@ 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(
+69 -20
View File
@@ -23,6 +23,7 @@ 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";
@@ -42,15 +43,49 @@ 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 {
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`;
return reconcileRootEnvPublicConfig(contents, {
relayUrl,
mobileTracingUrl: "",
mobileTracingDataset: "",
mobileTracingToken: "",
})
.split("\n")
.filter((line) => !line.startsWith("T3CODE_MOBILE_OTLP_TRACES_"))
.join("\n");
}
export function hasDeployChanges(plan: Plan.Plan): boolean {
@@ -68,7 +103,7 @@ export type RelayDeployResult = "applied" | "noop" | "dry-run" | "cancelled";
export interface RelayDeployOutcome {
readonly result: RelayDeployResult;
readonly changed: boolean;
readonly relayUrl: Option.Option<string>;
readonly publicConfig: Option.Option<RelayPublicConfig>;
}
export function serializeGithubOutput(entries: Readonly<Record<string, string | boolean>>): string {
@@ -106,15 +141,17 @@ const relayDeployStage = Config.nonEmptyString("stage").pipe(
),
);
const reconcileRootEnv = Effect.fn("relay.deploy.reconcileRootEnv")(function* (relayUrl: string) {
const reconcileRootEnv = Effect.fn("relay.deploy.reconcileRootEnv")(function* (
config: RelayPublicConfig,
) {
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, reconcileRootEnvRelayUrl(contents, relayUrl));
yield* Console.log(`Updated ${rootEnvPath} with T3CODE_RELAY_URL=${relayUrl}`);
yield* fs.writeFileString(rootEnvPath, reconcileRootEnvPublicConfig(contents, config));
yield* Console.log(`Updated ${rootEnvPath} with relay URL and mobile tracing configuration`);
});
const writeGithubOutput = Effect.fn("relay.deploy.writeGithubOutput")(function* (
@@ -127,7 +164,9 @@ const writeGithubOutput = Effect.fn("relay.deploy.writeGithubOutput")(function*
serializeGithubOutput({
changed: outcome.changed,
result: outcome.result,
...(Option.isSome(outcome.relayUrl) ? { relay_url: outcome.relayUrl.value } : {}),
...(Option.isSome(outcome.publicConfig)
? { relay_url: outcome.publicConfig.value.relayUrl }
: {}),
}),
{ flag: "a" },
);
@@ -160,7 +199,7 @@ const runRelayDeploy = Effect.fn("relay.deploy.run")(
return {
result: "dry-run",
changed,
relayUrl: Option.none<string>(),
publicConfig: Option.none<RelayPublicConfig>(),
} satisfies RelayDeployOutcome;
}
if (!options.yes && changed) {
@@ -175,20 +214,30 @@ const runRelayDeploy = Effect.fn("relay.deploy.run")(
return {
result: "cancelled",
changed,
relayUrl: Option.none<string>(),
publicConfig: Option.none<RelayPublicConfig>(),
} satisfies RelayDeployOutcome;
}
}
const output = yield* Apply.apply(plan).pipe(Effect.provide(stack.services));
if (output.url === undefined) {
if (
output.url === undefined ||
output.mobileTracingUrl === undefined ||
output.mobileTracingDataset === undefined ||
output.mobileTracingToken === undefined
) {
return yield* new RelayDeployError({
message: "Alchemy relay deploy output did not include a URL",
message: "Alchemy relay deploy output did not include complete public client config",
});
}
return {
result: changed ? "applied" : "noop",
changed,
relayUrl: Option.some(output.url),
publicConfig: Option.some({
relayUrl: output.url,
mobileTracingUrl: output.mobileTracingUrl,
mobileTracingDataset: output.mobileTracingDataset,
mobileTracingToken: Redacted.value(output.mobileTracingToken),
}),
} satisfies RelayDeployOutcome;
},
(effect, options, configProvider, stage) =>
@@ -216,8 +265,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.relayUrl)) {
yield* reconcileRootEnv(outcome.relayUrl.value);
if (Option.isSome(outcome.publicConfig)) {
yield* reconcileRootEnv(outcome.publicConfig.value);
}
if (options.githubOutput) {
yield* writeGithubOutput(outcome);
@@ -101,8 +101,13 @@ const make = Effect.gen(function* () {
"relay.mobile.device_id": input.deviceId,
"relay.operation": "replayForLiveActivityRegistration",
});
const activeStates = yield* rows.listForUser({ userId: input.userId });
const targets = yield* liveActivities.listTargets({ userId: input.userId });
const { activeStates, targets } = yield* Effect.all(
{
activeStates: rows.listForUser({ userId: input.userId }),
targets: liveActivities.listTargets({ userId: input.userId }),
},
{ concurrency: 2 },
);
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: 5,
originConnectionLimit: 20,
});
});
@@ -14,11 +14,13 @@ 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";
@@ -225,6 +227,58 @@ 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,11 +309,7 @@ const make = Effect.gen(function* () {
reason: "endpoint_provider_not_managed",
});
}
const allocation = yield* allocations.get({
userId: input.userId,
environmentId: input.link.environmentId,
});
if (!allocation) {
if (!input.allocation) {
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.link.environmentId,
operation: input.operation,
@@ -321,10 +317,10 @@ const make = Effect.gen(function* () {
});
}
const allocationAttributes = {
"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,
"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,
} as const;
if (!settings.managedEndpointBaseDomain) {
yield* Effect.annotateCurrentSpan(allocationAttributes);
@@ -335,9 +331,9 @@ const make = Effect.gen(function* () {
});
}
if (
allocation.readyAt === null ||
allocation.tunnelId === null ||
allocation.dnsRecordId === null
input.allocation.readyAt === null ||
input.allocation.tunnelId === null ||
input.allocation.dnsRecordId === null
) {
yield* Effect.annotateCurrentSpan(allocationAttributes);
return yield* new EnvironmentConnectNotAuthorized({
@@ -346,7 +342,9 @@ const make = Effect.gen(function* () {
reason: "managed_endpoint_allocation_not_ready",
});
}
if (!isManagedEndpointHostname(allocation.hostname, settings.managedEndpointBaseDomain)) {
if (
!isManagedEndpointHostname(input.allocation.hostname, settings.managedEndpointBaseDomain)
) {
yield* Effect.annotateCurrentSpan({
...allocationAttributes,
"relay.authorization.managed_endpoint_base_domain": settings.managedEndpointBaseDomain,
@@ -358,7 +356,7 @@ const make = Effect.gen(function* () {
});
}
const endpoint = ManagedEndpointAllocations.resolveReadyManagedEndpoint({
allocation,
allocation: input.allocation,
baseDomain: settings.managedEndpointBaseDomain,
});
if (
@@ -393,7 +391,13 @@ const make = Effect.gen(function* () {
"relay.environment_id": input.environmentId,
"relay.operation": "status",
});
const link = yield* links.getForUser(input);
const { link, allocation } = yield* Effect.all(
{
link: links.getForUser(input),
allocation: allocations.get(input),
},
{ concurrency: 2 },
);
if (!link) {
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.environmentId,
@@ -402,9 +406,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 });
@@ -518,7 +522,13 @@ const make = Effect.gen(function* () {
reason: "client_proof_key_thumbprint_missing",
});
}
const link = yield* links.getForUser(input);
const { link, allocation } = yield* Effect.all(
{
link: links.getForUser(input),
allocation: allocations.get(input),
},
{ concurrency: 2 },
);
if (!link) {
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.environmentId,
@@ -527,9 +537,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,6 +181,10 @@ 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",
},
}),
);
@@ -192,6 +196,8 @@ 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);
}),
+10 -13
View File
@@ -3,6 +3,7 @@ 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";
@@ -18,6 +19,7 @@ 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,
@@ -67,6 +69,7 @@ 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",
@@ -74,11 +77,7 @@ const relayCorsAllowedHeaders = [
"content-type",
"dpop",
] as const;
const relayCorsExposedHeaders = [
"traceparent",
"x-t3-relay-auth-failure",
"www-authenticate",
] as const;
const relayCorsExposedHeaders = ["traceparent", "www-authenticate"] as const;
const relayCorsHeaders = {
"access-control-allow-origin": "*",
@@ -176,7 +175,10 @@ export const traceRelayHttpRequestWith = <E, R, LayerError, LayerRequirements>(
HttpServerRequest.HttpServerRequest | R
>,
tracerLayer: Layer.Layer<never, LayerError, LayerRequirements>,
) => traceRelayHttpRequest(httpEffect).pipe(Effect.provide(tracerLayer));
) =>
traceRelayHttpRequest(httpEffect).pipe(
Effect.provide(Layer.merge(tracerLayer, httpHeaderRedactionLayer)),
);
export const withoutCapturedParentSpan = <A, E, R>(
effect: Effect.Effect<A, E, R>,
@@ -351,12 +353,7 @@ 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")),
@@ -602,7 +599,7 @@ export const tokenApi = HttpApiBuilder.group(
Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs),
);
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { minutes: 5 });
const expiresAt = DateTime.addDuration(now, RELAY_DPOP_ACCESS_TOKEN_TTL);
const jti = yield* crypto.randomUUIDv4.pipe(
Effect.catch(() => relayInternalErrorResponse("internal_error")),
);
@@ -620,7 +617,7 @@ export const tokenApi = HttpApiBuilder.group(
.pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))),
issued_token_type: RelayAccessTokenType,
token_type: "DPoP" as const,
expires_in: 300,
expires_in: Duration.toSeconds(RELAY_DPOP_ACCESS_TOKEN_TTL),
scope: encodeOAuthScope(requestedScopes),
};
}, mapRelayCommonApiErrors("invalid_dpop")),
+10 -2
View File
@@ -34,7 +34,7 @@ export const RelayObservability = Effect.gen(function* () {
useRetentionPeriod: true,
});
const ingestToken = yield* Axiom.ApiToken("RelayAxiomIngestToken", {
const workerIngestToken = yield* Axiom.ApiToken("RelayWorkerAxiomIngestToken", {
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,6 +42,14 @@ 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.",
@@ -49,7 +57,7 @@ export const RelayObservability = Effect.gen(function* () {
aplQuery: Output.map(traces.name, relayRecentSpansQuery),
});
return { traces, ingestToken } as const;
return { traces, workerIngestToken, mobileIngestToken } 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.ingestToken.token;
const axiomIngestToken = yield* observability.workerIngestToken.token;
const axiomTracesEndpoint = yield* observability.traces.otelTracesEndpoint;
const clerkSecretKey = yield* Config.redacted("CLERK_SECRET_KEY");
+2
View File
@@ -1,6 +1,7 @@
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: {
@@ -8,5 +9,6 @@ export default definePlugin({
},
rules: {
"no-inline-schema-compile": noInlineSchemaCompile,
"no-manual-effect-runtime-in-tests": noManualEffectRuntimeInTests,
},
});
@@ -0,0 +1,73 @@
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);
`,
);
@@ -0,0 +1,113 @@
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.`,
});
},
};
},
});
+9 -2
View File
@@ -48,6 +48,10 @@ 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(),
@@ -73,7 +77,10 @@ const spawnAndCollectOutput = Effect.fnUntraced(function* (command: ChildProcess
return { exitCode, stdout, stderr };
}, Effect.scoped);
export const createOxlintRuleHarness = (ruleName: string): RuleHarness => {
export const createOxlintRuleHarness = (
ruleName: string,
options: RuleHarnessOptions = {},
): RuleHarness => {
const [pluginName, shortRuleName] = ruleName.split("/");
const diagnosticRuleName =
pluginName && shortRuleName ? `${pluginName}\\(${shortRuleName}\\)` : ruleName;
@@ -84,7 +91,7 @@ export const createOxlintRuleHarness = (ruleName: string): RuleHarness => {
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, "fixture.ts");
const sourcePath = path.join(fixtureDir, options.filename ?? "fixture.ts");
const repoRoot = path.join(import.meta.dirname, "..", "..");
const oxlintBin = path.join(
repoRoot,
+5 -1
View File
@@ -15,6 +15,7 @@ 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";
@@ -111,7 +112,10 @@ export type RemoteEnvironmentAuthError =
export const remoteHttpClientLayer = (
fetchFn: typeof globalThis.fetch,
): Layer.Layer<HttpClient.HttpClient> =>
FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn)));
Layer.merge(
FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn))),
httpHeaderRedactionLayer,
);
const failRemoteRequest = (
requestUrl: string,
+4
View File
@@ -31,6 +31,10 @@
"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
@@ -0,0 +1,8 @@
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"]),
);
+22 -1
View File
@@ -27,6 +27,12 @@ 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", () => {
@@ -73,26 +79,41 @@ 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 only the configured aliases", () => {
it("projects canonical mobile tracing values to Expo public 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,6 +9,9 @@ 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>>;
@@ -57,6 +60,24 @@ 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,
}
: {}),
};
}
@@ -76,6 +97,21 @@ 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,6 +91,7 @@ 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.