Skip to content
TypeScript

feat(server): send telemetry through ingest.t3.codes (#15028)

Theo Browne28c32d20c3e2
diff --git a/.github/workflows/desktop-macos-preview.yml b/.github/workflows/desktop-macos-preview.yml
index 43b6c8220aa..6dcdd702c2d 100644
--- a/.github/workflows/desktop-macos-preview.yml
+++ b/.github/workflows/desktop-macos-preview.yml
@@ -78,7 +78,10 @@ jobs:
- name: Install browser secret helper build libraries
run: sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config
+ # desktop-macos-preview-publish.yml packages this bundle as the preview channel.
- name: Build JS bundle
+ env:
+ T3CODE_TELEMETRY_CHANNEL: ${{ github.repository == 'pingdotgg/t3code' && 'preview' || 'dev' }}
run: vp run build:desktop
# Same layout as release.yml's js-bundle so release-desktop.yml can
diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml
index 7c2bcc89bb1..08552d1cd53 100644
--- a/.github/workflows/release-desktop.yml
+++ b/.github/workflows/release-desktop.yml
@@ -501,6 +501,9 @@ jobs:
# the runner, and only exact versions have a dist directory. Keep in
# step with SEA_NODE_VERSION in apps/server/vite.config.ts.
VP_NODE_VERSION: "26.8.2"
+ # The executable bundles the server again, so it needs the same stamp
+ # as release.yml's JS bundle.
+ T3CODE_TELEMETRY_CHANNEL: ${{ github.repository == 'pingdotgg/t3code' && inputs.release_channel || 'dev' }}
run: node apps/server/scripts/cli.ts build-exe --verbose
- name: Import macOS signing certificate for the CLI archive
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 715edafee09..1173e99342d 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -525,7 +525,11 @@ jobs:
# Runs t3#build (which depends on @t3tools/web#build) and
# @t3tools/desktop#build, so apps/server/dist holds the server bundle
# plus the web client and apps/desktop/dist-electron the Electron main.
+ # The release channel is already stable, nightly, or preview. Builds in
+ # other repositories report "dev" telemetry.
- name: Build JS bundle
+ env:
+ T3CODE_TELEMETRY_CHANNEL: ${{ github.repository == 'pingdotgg/t3code' && needs.preflight.outputs.release_channel || 'dev' }}
run: vp run build:desktop
# Two paths under apps/ so the artifact root is apps/; consumers download
diff --git a/apps/server/src/telemetry/AnalyticsService.test.ts b/apps/server/src/telemetry/AnalyticsService.test.ts
index e7f5889a5b5..77b2088863b 100644
--- a/apps/server/src/telemetry/AnalyticsService.test.ts
+++ b/apps/server/src/telemetry/AnalyticsService.test.ts
@@ -1,6 +1,6 @@
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeServices from "@effect/platform-node/NodeServices";
-import { assert, it } from "@effect/vitest";
+import { assert, it, vi } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -8,6 +8,8 @@ import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import * as HttpClient from "effect/http/HttpClient";
import * as HttpClientError from "effect/http/HttpClientError";
+import * as HttpClientRequest from "effect/http/HttpClientRequest";
+import * as HttpClientResponse from "effect/http/HttpClientResponse";
import * as HttpServer from "effect/http/HttpServer";
import * as HttpServerRequest from "effect/http/HttpServerRequest";
import * as HttpServerResponse from "effect/http/HttpServerResponse";
@@ -52,27 +54,84 @@ interface RecordedBatchBody {
const SentBatch = Schema.fromJsonString(
Schema.Struct({
- batch: Schema.Array(Schema.Struct({ uuid: Schema.String })),
+ batch: Schema.Array(
+ Schema.Struct({
+ uuid: Schema.String,
+ properties: Schema.Struct({ telemetryChannel: Schema.String }),
+ }),
+ ),
}),
);
+const decodeSentBatch = Schema.decodeEffect(SentBatch);
+type SentEvent = (typeof SentBatch.Type)["batch"][number];
+type Respond = (
+ request: HttpClientRequest.HttpClientRequest,
+) => Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>;
+
+/** The connection drops after the endpoint read the batch, so it may be stored. */
+const connectionReset: Respond = (request) =>
+ Effect.fail(
+ new HttpClientError.HttpClientError({
+ reason: new HttpClientError.TransportError({ request, cause: "connection reset" }),
+ }),
+ );
-const layerAcceptThenFailClient = (batches: Array<ReadonlyArray<{ readonly uuid: string }>>) =>
- Layer.succeed(
- HttpClient.HttpClient,
- HttpClient.make((request) =>
+const respondWithStatus =
+ (status: number): Respond =>
+ (request) =>
+ Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null, { status })));
+
+/**
+ * Records 20 events, then lets ten minutes of background flushes run against
+ * a client that answers every send with `respond`. Returns the sent batches.
+ */
+const sendForTenMinutes = (respond: Respond) =>
+ Effect.gen(function* () {
+ const batches: Array<ReadonlyArray<SentEvent>> = [];
+ const client = HttpClient.make((request) =>
Effect.gen(function* () {
if (request.body._tag === "Uint8Array") {
- const body = yield* Schema.decodeEffect(SentBatch)(
- new TextDecoder().decode(request.body.body),
- ).pipe(Effect.orDie);
+ const body = yield* decodeSentBatch(new TextDecoder().decode(request.body.body)).pipe(
+ Effect.orDie,
+ );
batches.push(body.batch);
}
- return yield* new HttpClientError.HttpClientError({
- reason: new HttpClientError.TransportError({ request, cause: "connection reset" }),
- });
+ return yield* respond(request);
}),
- ),
- );
+ );
+ const runtimeLayer = AnalyticsService.layer.pipe(
+ Layer.provideMerge(
+ ServerConfig.ServerConfig.layerTest(process.cwd(), { prefix: "t3-telemetry-retry-" }),
+ ),
+ Layer.provide(
+ ConfigProvider.layer(
+ ConfigProvider.fromUnknown({
+ T3CODE_TELEMETRY_ENABLED: true,
+ T3CODE_POSTHOG_KEY: "phc_test_key",
+ T3CODE_POSTHOG_HOST: "http://localhost",
+ }),
+ ),
+ ),
+ Layer.provide(
+ Layer.mergeAll(
+ Layer.succeed(HostProcess.Platform, "win32"),
+ Layer.succeed(HostProcess.Architecture, "x64"),
+ Layer.succeed(HttpClient.HttpClient, client),
+ ),
+ ),
+ );
+
+ yield* Effect.gen(function* () {
+ const analytics = yield* AnalyticsService.AnalyticsService;
+ for (let index = 0; index < 20; index += 1) {
+ yield* analytics.record("test.retry", { index });
+ }
+ for (let second = 0; second < 600; second += 1) {
+ yield* TestClock.adjust("1 second");
+ }
+ }).pipe(Effect.provide(runtimeLayer));
+ return batches;
+ });
it("retryDelayMs doubles from 2s and stays under the 5 minute cap", () => {
assert.equal(AnalyticsService.retryDelayMs(1, 0), 1_000);
@@ -82,48 +141,46 @@ it("retryDelayMs doubles from 2s and stays under the 5 minute cap", () => {
});
it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
- it.effect("a batch that keeps failing is retried with backoff, then dropped", () =>
+ it.effect("a batch that keeps failing is retried with the same uuids, then dropped", () =>
Effect.gen(function* () {
- const batches: Array<ReadonlyArray<{ readonly uuid: string }>> = [];
- const layerRuntime = AnalyticsService.layer.pipe(
- Layer.provideMerge(
- ServerConfig.ServerConfig.layerTest(process.cwd(), { prefix: "t3-telemetry-retry-" }),
- ),
- Layer.provide(
- ConfigProvider.layer(
- ConfigProvider.fromUnknown({
- T3CODE_TELEMETRY_ENABLED: true,
- T3CODE_POSTHOG_KEY: "phc_test_key",
- T3CODE_POSTHOG_HOST: "http://localhost",
- }),
- ),
- ),
- Layer.provide(
- Layer.mergeAll(
- Layer.succeed(HostProcess.Platform, "win32"),
- Layer.succeed(HostProcess.Architecture, "x64"),
- layerAcceptThenFailClient(batches),
- ),
- ),
- );
-
- yield* Effect.gen(function* () {
- const analytics = yield* AnalyticsService.AnalyticsService;
- for (let index = 0; index < 20; index += 1) {
- yield* analytics.record("test.retry", { index });
- }
- for (let second = 0; second < 600; second += 1) {
- yield* TestClock.adjust("1 second");
- }
- }).pipe(Effect.provide(layerRuntime));
+ const failures = {
+ "connection reset": connectionReset,
+ "408": respondWithStatus(408),
+ "429": respondWithStatus(429),
+ "503": respondWithStatus(503),
+ };
+ for (const [failure, respond] of Object.entries(failures)) {
+ const batches = yield* sendForTenMinutes(respond);
+ assert.equal(batches.length, 5, failure);
+ const uuids = batches.map((batch) => batch.map((event) => event.uuid).join(","));
+ assert.equal(new Set(uuids).size, 1, `${failure}: every retry carries the same uuids`);
+ assert.equal(new Set(batches[0]?.map((event) => event.uuid)).size, 20, failure);
+ }
+ }),
+ );
- assert.equal(batches.length, 5);
- const uuids = batches.map((batch) => batch.map((event) => event.uuid).join(","));
- assert.equal(new Set(uuids).size, 1, "every retry carries the same uuids");
- assert.equal(new Set(batches[0]?.map((event) => event.uuid)).size, 20);
+ it.effect("a batch the endpoint rejects is dropped without a retry", () =>
+ Effect.gen(function* () {
+ for (const status of [400, 401, 413]) {
+ const batches = yield* sendForTenMinutes(respondWithStatus(status));
+ assert.equal(batches.length, 1, `status ${status}`);
+ }
}),
);
+ it.effect("events carry the build's telemetry channel, or dev when none is set", () =>
+ Effect.gen(function* () {
+ const channels = (batches: ReadonlyArray<ReadonlyArray<SentEvent>>) => [
+ ...new Set(batches.flat().map((event) => event.properties.telemetryChannel)),
+ ];
+ assert.deepEqual(channels(yield* sendForTenMinutes(respondWithStatus(204))), ["dev"]);
+
+ // Stands in for the value the bundler writes in at build time.
+ vi.stubGlobal("__T3CODE_TELEMETRY_CHANNEL__", "nightly");
+ assert.deepEqual(channels(yield* sendForTenMinutes(respondWithStatus(204))), ["nightly"]);
+ }).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllGlobals()))),
+ );
+
it.effect("flush drains all buffered events across multiple batches", () =>
Effect.gen(function* () {
const capturedRequests: Array<RecordedBatchRequest> = [];
diff --git a/apps/server/src/telemetry/AnalyticsService.ts b/apps/server/src/telemetry/AnalyticsService.ts
index db627fdb92d..59542498264 100644
--- a/apps/server/src/telemetry/AnalyticsService.ts
+++ b/apps/server/src/telemetry/AnalyticsService.ts
@@ -1,6 +1,7 @@
/**
- * Each event carries a uuid, so PostHog can tell a retried copy from a new
- * event.
+ * Events go to the T3 Code ingest endpoint, which keeps a copy and forwards
+ * them to PostHog. Each event carries a uuid, so PostHog can tell a retried
+ * copy from a new event.
*/
import * as HostProcess from "@t3tools/shared/HostProcess";
import type { ClientOs } from "@t3tools/contracts";
@@ -39,12 +40,26 @@ interface DeliveryState {
readonly retryAt: number;
}
-const FLUSH_INTERVAL_MS = 1_000;
+// The background flush checks for work at this interval, so a retry delay
+// shorter than it waits for the next check.
+const FLUSH_INTERVAL_MS = 10_000;
// A hung send would hold the flush lock, and with it the shutdown flush.
const SEND_TIMEOUT = "10 seconds";
const MAX_BATCH_ATTEMPTS = 5;
const RETRY_BASE_DELAY_MS = 2_000;
const RETRY_MAX_DELAY_MS = 300_000;
+// The endpoint answers these when the batch itself is wrong (bad body, wrong
+// api_key, too large), so sending it again cannot help. 408 and 429 are not
+// here because a later send can succeed.
+const REJECTED_BATCH_STATUSES = new Set([400, 401, 413]);
+
+/**
+ * Release channel of this build. Release workflows set it for
+ * pingdotgg/t3code builds (see apps/server/vite.config.ts); every other build
+ * reports "dev". It is separate from `__T3CODE_BUILD_CHANNEL__`, which names
+ * stable "latest" and preview "nightly" for the sign-in page.
+ */
+declare const __T3CODE_TELEMETRY_CHANNEL__: "stable" | "nightly" | "preview" | "dev" | undefined;
/** `random` is in [0, 1). */
export function retryDelayMs(failures: number, random: number): number {
@@ -57,7 +72,7 @@ const TelemetryEnvConfig = Config.all({
Config.withDefault("phc_XOWci4oZP4VvLiEyrFqkFjP4CZn55mjYYBMREK5Wd6m"),
),
posthogHost: Config.String("T3CODE_POSTHOG_HOST").pipe(
- Config.withDefault("https://us.i.posthog.com"),
+ Config.withDefault("https://ingest.t3.codes"),
),
enabled: Config.Boolean("T3CODE_TELEMETRY_ENABLED").pipe(Config.withDefault(true)),
flushBatchSize: Config.Number("T3CODE_TELEMETRY_FLUSH_BATCH_SIZE").pipe(Config.withDefault(20)),
@@ -120,6 +135,8 @@ export const make = Effect.gen(function* () {
// The background flush and the shutdown flush must not send the same batch at once.
const flushLock = yield* Semaphore.make(1);
const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
+ const telemetryChannel =
+ typeof __T3CODE_TELEMETRY_CHANNEL__ === "undefined" ? "dev" : __T3CODE_TELEMETRY_CHANNEL__;
const hostPlatform = yield* HostProcess.Platform;
const hostArchitecture = yield* HostProcess.Architecture;
@@ -173,6 +190,7 @@ export const make = Effect.gen(function* () {
wsl: Option.getOrUndefined(telemetryConfig.wslDistroName),
arch: hostArchitecture,
t3CodeVersion: packageJson.version,
+ telemetryChannel,
clientType,
serverOs: serverOsFromNodePlatform(hostPlatform),
serverArch: hostArchitecture,
@@ -197,6 +215,8 @@ export const make = Effect.gen(function* () {
return [nextBatch, current.slice(nextBatch.length)] as const;
});
+ // A rejected batch is dropped at once, but the next batch still waits for the
+ // backoff, so a wrong api_key does not send every batch as fast as it can.
const flush: AnalyticsService["Service"]["flush"] = Effect.gen(function* () {
while (true) {
const delivery = yield* Ref.get(deliveryRef);
@@ -214,20 +234,26 @@ export const make = Effect.gen(function* () {
const failures = delivery.failures + 1;
const batchAttempts = delivery.batchAttempts + 1;
const retryAt = (yield* Clock.currentTimeMillis) + retryDelayMs(failures, yield* Random.next);
- if (batchAttempts < MAX_BATCH_ATTEMPTS) {
+ const error = sent.failure;
+ const rejected =
+ error._tag === "HttpClientError" &&
+ error.reason._tag === "StatusCodeError" &&
+ REJECTED_BATCH_STATUSES.has(error.reason.response.status);
+ if (!rejected && batchAttempts < MAX_BATCH_ATTEMPTS) {
yield* Ref.set(deliveryRef, { failedBatch: batch, batchAttempts, failures, retryAt });
yield* Effect.logDebug("Failed to send telemetry batch; will retry", {
attempt: batchAttempts,
- cause: sent.failure,
+ cause: error,
});
return;
}
yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures, retryAt });
- yield* Effect.logWarning("Dropped telemetry batch after repeated send failures", {
- events: batch.length,
- attempts: batchAttempts,
- cause: sent.failure,
- });
+ yield* Effect.logWarning(
+ rejected
+ ? "Dropped telemetry batch the endpoint rejected"
+ : "Dropped telemetry batch after repeated send failures",
+ { events: batch.length, attempts: batchAttempts, cause: error },
+ );
return;
}
}).pipe(flushLock.withPermit);
diff --git a/apps/server/vite.config.ts b/apps/server/vite.config.ts
index a26e5afb061..5c6176b28c0 100644
--- a/apps/server/vite.config.ts
+++ b/apps/server/vite.config.ts
@@ -18,6 +18,16 @@ const repoEnv = loadRepoEnv();
const cliBuildChannel = /^[^-+]+-(?:nightly|preview)\./.test(packageJson.version)
? "nightly"
: "latest";
+// Sent with every analytics event. Release workflows set it for pingdotgg/t3code
+// builds only, so local builds and forks report "dev". A typo fails the build
+// instead of mislabeling events.
+const TELEMETRY_CHANNELS = ["stable", "nightly", "preview", "dev"];
+const telemetryChannel = process.env.T3CODE_TELEMETRY_CHANNEL?.trim() || "dev";
+if (!TELEMETRY_CHANNELS.includes(telemetryChannel)) {
+ throw new Error(
+ `T3CODE_TELEMETRY_CHANNEL must be one of ${TELEMETRY_CHANNELS.join(", ")}, got "${telemetryChannel}".`,
+ );
+}
// `build:exe` wraps the same bundle in a Node single-executable. tsdown's exe
// step refuses multi-chunk output and counts the sourcemap as a chunk, and the
@@ -93,6 +103,7 @@ export default mergeConfig(
},
define: {
__T3CODE_BUILD_CHANNEL__: JSON.stringify(cliBuildChannel),
+ __T3CODE_TELEMETRY_CHANNEL__: JSON.stringify(telemetryChannel),
__T3CODE_BUILD_RELAY_URL__: JSON.stringify(repoEnv.T3CODE_RELAY_URL?.trim() ?? ""),
__T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: JSON.stringify(
repoEnv.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ?? "",
diff --git a/docs/internals/product-analytics.md b/docs/internals/product-analytics.md
index e9123640a54..b07f99bdb2d 100644
--- a/docs/internals/product-analytics.md
+++ b/docs/internals/product-analytics.md
@@ -1,6 +1,6 @@
# Product analytics
-The server owns PostHog delivery, opt-out, and identity for every connected client.
+The server owns analytics delivery, opt-out, and identity for every connected client.
[Identity selection](../../apps/server/src/telemetry/Identify.ts) hashes an available
provider account ID, falling back to an installation-scoped ID. This identity can
span several clients; it does not identify a browser session. Clients do not load
@@ -43,10 +43,13 @@ normalization or building reports.
## Delivery
-A send can fail after PostHog has stored the batch, so every retry is a copy.
+The server sends batches to the ingest endpoint at `ingest.t3.codes`, which archives
+every event and forwards some of them to PostHog. A send can fail after the endpoint
+has stored the batch, so every retry is a copy.
[Delivery](../../apps/server/src/telemetry/AnalyticsService.ts) gives each event a
-uuid when it is recorded, backs off after a failed send, and drops a batch after a
-few tries. Without these limits, one stuck batch was sent every second for days.
+uuid when it is recorded (the endpoint rejects events without one), backs off after
+a failed send, and drops a batch after a few tries. Without these limits, one stuck
+batch was sent every second for days.
## Collection boundary
diff --git a/docs/user/telemetry.md b/docs/user/telemetry.md
index 61925062d3e..d25c04e186e 100644
--- a/docs/user/telemetry.md
+++ b/docs/user/telemetry.md
@@ -1,8 +1,10 @@
# Product usage data
-The T3 Code server sends product usage events to PostHog, associated with a hashed account or
-installation identifier. Events include the provider, model, reasoning effort, permission mode,
-turn result, duration, and main-agent token totals when available.
+The T3 Code server sends product usage events to T3 Code's own endpoint at `ingest.t3.codes`,
+associated with a hashed account or installation identifier. The endpoint keeps a copy of each
+event and forwards events to PostHog. Events include the provider, model, reasoning effort,
+permission mode, turn result, duration, release channel, and main-agent token totals when
+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.