TypeScript
fix(telemetry): honor opt-out for relay tracing (#14413)
Bilal Bayram23ce025f5834
diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.tsindex 999af3d90f2..47b342c47de 100644--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts@@ -41,6 +41,7 @@ import {getAppBranding,getLocalEnvironmentBootstraps,getLocalEnvironmentBearerToken,+ getRelayTelemetryEnabled,getSystemLocale,getWindowFullscreenState,openExternal,@@ -95,6 +96,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"yield* ipc.handleSync(takeLegacyLocalStorage);yield* ipc.handle(completeLegacyLocalStorage);yield* ipc.handleSync(getAppBranding);+ yield* ipc.handleSync(getRelayTelemetryEnabled);yield* ipc.handleSync(getSystemLocale);yield* ipc.handleSync(getWindowFullscreenState);yield* ipc.handleSync(getLocalEnvironmentBootstraps);diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.tsindex 5843f798ab2..9b11a2283a2 100644--- a/apps/desktop/src/ipc/channels.ts+++ b/apps/desktop/src/ipc/channels.ts@@ -30,6 +30,7 @@ export const CLI_COMMAND_GET_STATE_CHANNEL = "desktop:cli-command-get-state";export const CLI_COMMAND_INSTALL_CHANNEL = "desktop:cli-command-install";export const CLI_COMMAND_UNINSTALL_CHANNEL = "desktop:cli-command-uninstall";export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";+export const GET_RELAY_TELEMETRY_ENABLED_CHANNEL = "desktop:get-relay-telemetry-enabled";export const GET_SYSTEM_LOCALE_CHANNEL = "desktop:get-system-locale";export const GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL = "desktop:get-local-environment-bootstraps";export const GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL = "desktop:get-local-environment-enabled";diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.tsindex 97f5404e452..3459719e2f5 100644--- a/apps/desktop/src/ipc/methods/window.test.ts+++ b/apps/desktop/src/ipc/methods/window.test.ts@@ -27,6 +27,7 @@ import * as ElectronWindow from "../../electron/ElectronWindow.ts";import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";import {getLocalEnvironmentBootstraps,+ getRelayTelemetryEnabled,getWindowFullscreenState,pasteAsText,pickProjectFavicon,@@ -198,6 +199,25 @@ describe("getLocalEnvironmentBootstraps", () => {});});+describe("getRelayTelemetryEnabled", () => {+ it.effect("reads the desktop host opt-out before returning the renderer policy", () =>+ Effect.gen(function* () {+ assert.isFalse(+ yield* getRelayTelemetryEnabled.handler().pipe(+ Effect.provideService(HostProcess.Environment, {+ T3CODE_TELEMETRY_ENABLED: "false",+ }),+ ),+ );+ assert.isTrue(+ yield* getRelayTelemetryEnabled+ .handler()+ .pipe(Effect.provideService(HostProcess.Environment, {})),+ );+ }),+ );+});+describe("getWindowFullscreenState", () => {it.effect("reads the current native window state", () => {const window = { isFullScreen: () => true } as Electron.BrowserWindow;diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.tsindex a582dd578ab..9066cf6f1a6 100644--- a/apps/desktop/src/ipc/methods/window.ts+++ b/apps/desktop/src/ipc/methods/window.ts@@ -16,6 +16,7 @@ import {import { PROJECT_FAVICON_EXTENSIONS } from "@t3tools/shared/projectFavicon";import { resolveEditorCommand } from "@t3tools/shared/editor";import * as HostProcess from "@t3tools/shared/HostProcess";+import { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment";import * as FileSystem from "effect/FileSystem";import * as Path from "effect/Path";import * as Effect from "effect/Effect";@@ -71,6 +72,14 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({}),});+export const getRelayTelemetryEnabled = DesktopIpc.makeSyncIpcMethod({+ channel: IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL,+ result: Schema.Boolean,+ handler: Effect.fn("desktop.ipc.window.getRelayTelemetryEnabled")(function* () {+ return isRelayTracingEnabled(yield* HostProcess.Environment);+ }),+});+export const getSystemLocale = DesktopIpc.makeSyncIpcMethod({channel: IpcChannels.GET_SYSTEM_LOCALE_CHANNEL,result: Schema.String,diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex b57052f4d8a..bffa02d9ca4 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -82,6 +82,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {}return result as ReturnType<DesktopBridge["getAppBranding"]>;},+ getRelayTelemetryEnabled: () =>+ ipcRenderer.sendSync(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL) === true,getPathForFile: (file: File) => webUtils.getPathForFile(file),getClientPlatform: () => clientPlatform,setNotificationBadge: (badge) =>diff --git a/apps/server/src/cloud/publicConfig.test.ts b/apps/server/src/cloud/publicConfig.test.tsindex 02276e87d6d..31d8da62909 100644--- a/apps/server/src/cloud/publicConfig.test.ts+++ b/apps/server/src/cloud/publicConfig.test.ts@@ -180,3 +180,29 @@ it("resolves relay client tracing from runtime config with build-time fallback",null,);});++it("product opt-out disables relay tracing with either built-in or runtime credentials", () => {+ const fallback = {+ tracesUrl: "https://embedded.example.test/v1/traces",+ tracesDataset: "embedded-dataset",+ tracesToken: "embedded-token",+ };+ const env = {+ T3CODE_TELEMETRY_ENABLED: "false",+ T3CODE_OTEL_SDK_DISABLED: "false",+ };++ assert.equal(resolveRelayClientTracingConfig(env, fallback), null);+ assert.equal(+ resolveRelayClientTracingConfig(+ {+ ...env,+ T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: "https://runtime.example.test/v1/traces",+ T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: "runtime-dataset",+ T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: "runtime-token",+ },+ fallback,+ ),+ null,+ );+});diff --git a/apps/server/src/cloud/publicConfig.ts b/apps/server/src/cloud/publicConfig.tsindex eefb9719a9f..15594f1164e 100644--- a/apps/server/src/cloud/publicConfig.ts+++ b/apps/server/src/cloud/publicConfig.ts@@ -4,6 +4,7 @@ import {DEFAULT_HOSTED_APP_URL,} from "@t3tools/shared/connectAuth";import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";+import { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment";import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";import * as Config from "effect/Config";import * as ConfigProvider from "effect/ConfigProvider";@@ -85,6 +86,10 @@ export function resolveRelayClientTracingConfig(env: Readonly<Record<string, string | undefined>> = process.env,fallback = buildTimeRelayClientTracing,) {+ if (!isRelayTracingEnabled(env)) {+ return null;+ }+const tracesUrl = env.T3CODE_RELAY_CLIENT_OTLP_TRACES_URL?.trim() || fallback.tracesUrl;const tracesDataset =env.T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET?.trim() || fallback.tracesDataset;diff --git a/apps/web/src/cloud/publicConfig.ts b/apps/web/src/cloud/publicConfig.tsindex 8c3b9073e3b..13dd7fa53bb 100644--- a/apps/web/src/cloud/publicConfig.ts+++ b/apps/web/src/cloud/publicConfig.ts@@ -59,6 +59,13 @@ export function resolveCloudPublicConfig(): CloudPublicConfig {}export function resolveRelayTracingConfig() {+ // The relay exporter is created during module initialization, so this must be synchronous.+ if (+ typeof window !== "undefined" &&+ window.desktopBridge?.getRelayTelemetryEnabled?.() === false+ ) {+ return null;+ }const { relayTracing } = resolveCloudPublicConfig();return relayTracing.tracesUrl && relayTracing.tracesDataset && relayTracing.tracesToken? {diff --git a/apps/web/src/lib/runtime.test.ts b/apps/web/src/lib/runtime.test.tsindex 339ccf711a1..cfba341239f 100644--- a/apps/web/src/lib/runtime.test.ts+++ b/apps/web/src/lib/runtime.test.ts@@ -1,10 +1,16 @@-import { describe, expect, it } from "@effect/vitest";+import { afterEach, describe, expect, it, vi } from "@effect/vitest";+import { withRelayClientTracing } from "@t3tools/shared/relayTracing";import * as Effect from "effect/Effect";import * as Tracer from "effect/Tracer";import * as ClientTracer from "../observability/clientTracer";import { runtime } from "./runtime";+afterEach(() => {+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+});+describe("web runtime", () => {it("routes client spans to the exporter client tracing configured", async () => {const exported: Array<string> = [];@@ -26,3 +32,74 @@ describe("web runtime", () => {expect(exported).toEqual(["client.work"]);});});++describe("web runtime relay telemetry policy", () => {+ it.each([+ {+ surface: "desktop opt-out",+ desktopBridge: { getRelayTelemetryEnabled: () => false },+ exports: false,+ },+ {+ surface: "desktop enabled",+ desktopBridge: { getRelayTelemetryEnabled: () => true },+ exports: true,+ },+ { surface: "older desktop bridge", desktopBridge: {}, exports: true },+ {+ surface: "ordinary browser ignores host opt-out",+ desktopBridge: undefined,+ exports: true,+ },+ ])("applies $surface before the first relay span", async ({ desktopBridge, exports }) => {+ vi.resetModules();+ vi.stubEnv("T3CODE_TELEMETRY_ENABLED", "false");+ vi.stubEnv("T3CODE_OTEL_SDK_DISABLED", "true");+ vi.stubEnv("OTEL_SDK_DISABLED", "true");+ vi.stubEnv("VITE_RELAY_OTLP_TRACES_URL", "https://telemetry.example.test/v1/traces");+ vi.stubEnv("VITE_RELAY_OTLP_TRACES_DATASET", "relay-test");+ vi.stubEnv("VITE_RELAY_OTLP_TRACES_TOKEN", "test-token");+ vi.stubGlobal("window", { desktopBridge });+ const fetchFn = vi.fn<typeof fetch>(async () => new Response(null, { status: 202 }));+ vi.stubGlobal("fetch", fetchFn);+ // Re-import after setting runtime policy: static initialization creates the exporter layer.+ const { runtime: freshRuntime } = await import("./runtime");+ const { setDelegate } = await import("../observability/clientTracer");+ const userSpans: Array<string> = [];++ try {+ expect(+ await freshRuntime.runPromise(+ Effect.succeed("relay operation completed").pipe(+ Effect.withSpan("relay.first-operation"),+ withRelayClientTracing,+ ),+ ),+ ).toBe("relay operation completed");++ setDelegate(+ Tracer.make({+ span(options) {+ userSpans.push(options.name);+ return new Tracer.NativeSpan(options);+ },+ }),+ );+ await freshRuntime.runPromise(Effect.void.pipe(Effect.withSpan("user.work")));+ expect(userSpans).toEqual(["user.work"]);+ } finally {+ setDelegate(null);+ // Closing the runtime flushes the exporter without waiting for its batch timer.+ await freshRuntime.dispose();+ }++ if (exports) {+ expect(fetchFn).toHaveBeenCalledOnce();+ expect(String(fetchFn.mock.calls[0]?.[0])).toBe("https://telemetry.example.test/v1/traces");+ const payload = new TextDecoder().decode(fetchFn.mock.calls[0]?.[1]?.body as Uint8Array);+ expect(payload).toContain('"name":"relay.first-operation"');+ } else {+ expect(fetchFn).not.toHaveBeenCalled();+ }+ });+});diff --git a/docs/user/telemetry.md b/docs/user/telemetry.mdindex d25c04e186e..a25635faaaf 100644--- a/docs/user/telemetry.md+++ b/docs/user/telemetry.md@@ -9,10 +9,14 @@ available.Events do not include prompts, responses, file contents, authentication tokens, conversation IDs,raw provider events, or child-agent output. Child-agent token use is excluded from the totals.-To disable collection, set `T3CODE_TELEMETRY_ENABLED=false` in the server's environment before-starting it. This stops product events from being recorded or sent.+T3 Code also sends relay connection traces to Axiom to diagnose T3 Connect connectivity.-The desktop app reads the variable from your shell profile (for example `~/.zshrc`) on macOS and+To disable product events and relay tracing, set `T3CODE_TELEMETRY_ENABLED=false` in the server's+environment before starting it. Relay tracing also stops when `T3CODE_OTEL_SDK_DISABLED` or+`OTEL_SDK_DISABLED` turns OpenTelemetry export off. The web app in a browser, including one the+`t3` CLI opens, does not read these variables.++The desktop app reads `T3CODE_TELEMETRY_ENABLED` from your shell profile (for example `~/.zshrc`) on macOS andLinux, so export it there and restart the app. On Windows, set it as a user environment variable.## Export diagnostics to your own receiverdiff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.tsindex b8423e7ffdf..4cf76a56c37 100644--- a/packages/contracts/src/ipc.ts+++ b/packages/contracts/src/ipc.ts@@ -1027,6 +1027,7 @@ export type SystemSettingsPane = typeof SystemSettingsPaneSchema.Type;export interface DesktopBridge {getAppBranding: () => DesktopAppBranding | null;+ getRelayTelemetryEnabled?: () => boolean;getPathForFile?: (file: File) => string;getClientPlatform?: () => string;setNotificationBadge?: (badge: { count: number; image: string | null }) => Promise<void>;diff --git a/packages/shared/src/otelEnvironment.test.ts b/packages/shared/src/otelEnvironment.test.tsindex bec05cd4762..3c752e312f0 100644--- a/packages/shared/src/otelEnvironment.test.ts+++ b/packages/shared/src/otelEnvironment.test.ts@@ -508,3 +508,45 @@ describe("OtelEnvironment", () => {);});});++describe("isRelayTracingEnabled", () => {+ it("defaults on and respects the T3CODE SDK override of the standard kill switch", () => {+ assert.isTrue(OtelEnvironment.isRelayTracingEnabled({}));+ assert.isFalse(OtelEnvironment.isRelayTracingEnabled({ OTEL_SDK_DISABLED: "true" }));+ assert.isTrue(+ OtelEnvironment.isRelayTracingEnabled({+ OTEL_SDK_DISABLED: "true",+ T3CODE_OTEL_SDK_DISABLED: "false",+ }),+ );+ assert.isFalse(+ OtelEnvironment.isRelayTracingEnabled({+ OTEL_SDK_DISABLED: "false",+ T3CODE_OTEL_SDK_DISABLED: "true",+ }),+ );+ });++ it.effect("product opt-out beats SDK enable without disabling user-configured tracing", () =>+ Effect.gen(function* () {+ const env = {+ T3CODE_TELEMETRY_ENABLED: "false",+ T3CODE_OTEL_SDK_DISABLED: "false",+ OTEL_SDK_DISABLED: "true",+ OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: "https://user.example.test/v1/traces",+ };+ assert.isFalse(OtelEnvironment.isRelayTracingEnabled(env));++ const otel = yield* load(env);+ assert.isFalse(otel.disabled);+ assert.deepStrictEqual(+ otel.traces,+ OtelEnvironment.OtelSignal.Export({+ url: env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT,+ protocol: "http/protobuf",+ headers: undefined,+ }),+ );+ }),+ );+});diff --git a/packages/shared/src/otelEnvironment.ts b/packages/shared/src/otelEnvironment.tsindex 80b88fe42ca..bcbebe3e9bb 100644--- a/packages/shared/src/otelEnvironment.ts+++ b/packages/shared/src/otelEnvironment.ts@@ -246,7 +246,7 @@ const endpointSignal = (name: OtlpSignalName, own: Settings, generic: Settings):};};-export const load: Effect.Effect<OtelEnvironment> = Config.all({+const sdkFlags = {t3: flag("T3CODE_OTEL_SDK_DISABLED",T3CODE_TRUE,@@ -263,6 +263,10 @@ export const load: Effect.Effect<OtelEnvironment> = Config.all({(value) =>`OTEL_SDK_DISABLED=${value} was read as false; the OpenTelemetry specification recognizes only the string true, so use OTEL_SDK_DISABLED=true or T3CODE_OTEL_SDK_DISABLED to say it any other way`,),+};++export const load: Effect.Effect<OtelEnvironment> = Config.all({+ ...sdkFlags,resource: resourceAttributes,generic: settings("OTEL_EXPORTER_OTLP_"),traces: settings("OTEL_EXPORTER_OTLP_TRACES_"),@@ -311,6 +315,19 @@ export const load: Effect.Effect<OtelEnvironment> = Config.all({Effect.orDie,);+export const isRelayTracingEnabled = (env: Readonly<Record<string, string | undefined>>) =>+ Config.all({+ ...sdkFlags,+ telemetry: flag("T3CODE_TELEMETRY_ENABLED", T3CODE_TRUE, T3CODE_FALSE, String),+ }).pipe(+ Effect.map(+ ({ telemetry, t3, spec }) => telemetry.value !== false && !(t3.value ?? spec.value ?? false),+ ),+ Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnvRecord(env))),+ Effect.orDie,+ Effect.runSync,+ );+export type SignalName = "traces" | "metrics" | "logs";export interface SignalEndpoint {