Skip to content
TypeScript

feat(server): analytics records a stable install id and who owns each install (#21506)

Theo Brownee2875821820e
diff --git a/apps/mobile/src/connection/platform.ts b/apps/mobile/src/connection/platform.ts
index e8817de69ee..022eb496282 100644
--- a/apps/mobile/src/connection/platform.ts
+++ b/apps/mobile/src/connection/platform.ts
@@ -196,6 +196,10 @@ const layerCapabilities = Layer.effectContext(
bearerToken: Effect.succeed(Option.none()),
}),
),
+ // The relay device id already persists in secure storage; analytics only sends its hash.
+ Context.add(ClientCapabilities.AnalyticsDevice, {
+ id: storage.loadOrCreateAgentAwarenessDeviceId.pipe(Effect.option),
+ }),
Context.add(
ClientCapabilities.RelayDeviceIdentity,
ClientCapabilities.RelayDeviceIdentity.of({
diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts
index 251a5592eb9..b3bd302303f 100644
--- a/apps/server/src/mcp/toolkits/core.test.ts
+++ b/apps/server/src/mcp/toolkits/core.test.ts
@@ -483,6 +483,7 @@ it.effect("records the calling agent and the agent a tool acted on", () => {
properties: properties ?? {},
}).pipe(Effect.asVoid),
flush: Effect.void,
+ recordOwners: () => Effect.void,
}),
),
),
diff --git a/apps/server/src/provider/CodexChatGptAuth.test.ts b/apps/server/src/provider/CodexChatGptAuth.test.ts
index 859537b25cb..2ed528eb163 100644
--- a/apps/server/src/provider/CodexChatGptAuth.test.ts
+++ b/apps/server/src/provider/CodexChatGptAuth.test.ts
@@ -220,6 +220,7 @@ const makeHarnessFor = Effect.fnUntraced(function* (
analyticsEvents.push({ event, properties });
}),
flush: Effect.void,
+ recordOwners: () => Effect.void,
});
const auth = yield* makeCodexChatGptAuth({
instanceId,
diff --git a/apps/server/src/provider/CodexChatGptAuth.ts b/apps/server/src/provider/CodexChatGptAuth.ts
index a9bf5dbac74..8b9190c40d1 100644
--- a/apps/server/src/provider/CodexChatGptAuth.ts
+++ b/apps/server/src/provider/CodexChatGptAuth.ts
@@ -9,9 +9,11 @@ import {
type ProviderInstanceId,
} from "@t3tools/contracts";
import { codexCallbackUrl } from "@t3tools/shared/codexAuthHandoff";
+import { hashTelemetryId } from "@t3tools/shared/telemetryId";
import * as Clock from "effect/Clock";
import * as Cause from "effect/Cause";
import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
+import { openAiUserId } from "../telemetry/Identify.ts";
import * as Crypto from "effect/Crypto";
import * as Exit from "effect/Exit";
import { codexAuthCallbackPage, codexAuthReturnUrl } from "./CodexAuthCallbackPage.ts";
@@ -221,6 +223,18 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
saved.sessions.find((session) => session.clientId === saved.activeClientId),
),
),
+ // The OpenAI account is the person, so it marks who owns this install.
+ Effect.tap((credentials) => {
+ const userId = Option.flatMap(credentials, (saved) =>
+ Option.flatMap(Option.fromUndefinedOr(saved.idToken), openAiUserId),
+ );
+ return Option.isSome(userId) && Option.isSome(analytics)
+ ? analytics.value.recordOwners(
+ [{ source: "openai", ownerId: hashTelemetryId(userId.value) }],
+ "server",
+ )
+ : Effect.void;
+ }),
);
const writeSessions = (saved: typeof Sessions.Type) =>
encodeSessions(saved).pipe(
diff --git a/apps/server/src/serverRuntimeStartup.autoPull.test.ts b/apps/server/src/serverRuntimeStartup.autoPull.test.ts
index a919f6720fb..59f6b67f045 100644
--- a/apps/server/src/serverRuntimeStartup.autoPull.test.ts
+++ b/apps/server/src/serverRuntimeStartup.autoPull.test.ts
@@ -5,6 +5,7 @@ import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import { HttpServer } from "effect/http";
@@ -30,6 +31,7 @@ import { ServerActivation } from "./serverActivation.ts";
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
import * as ServerSettings from "./serverSettings.ts";
+import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
@@ -163,6 +165,9 @@ it.effect("parks automatic pull until activation without delaying command readin
),
}),
Layer.mock(AnalyticsService.AnalyticsService)({ record: () => Effect.void }),
+ // No provider logins or Connect link, so startup records no owners.
+ FileSystem.layerNoop({}),
+ Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }),
NodeCrypto.layer,
Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
Layer.mock(ExternalLauncher.ExternalLauncher)({}),
diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts
index dd679b30ac6..34ccf14a837 100644
--- a/apps/server/src/serverRuntimeStartup.test.ts
+++ b/apps/server/src/serverRuntimeStartup.test.ts
@@ -16,6 +16,7 @@ import { HttpServer } from "effect/http";
import * as NetAddress from "effect/net/NetAddress";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Ref from "effect/Ref";
@@ -44,6 +45,7 @@ import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
import { ServerActivation } from "./serverActivation.ts";
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerSettings from "./serverSettings.ts";
+import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
it("uses the canonical Codex model for auto-bootstrap", () => {
@@ -216,6 +218,9 @@ it.effect.each([
}),
Layer.mock(GitVcsDriver.GitVcsDriver)({}),
Layer.mock(AnalyticsService.AnalyticsService)({}),
+ // No provider logins or Connect link, so startup records no owners.
+ FileSystem.layerNoop({}),
+ Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }),
Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
Layer.mock(ExternalLauncher.ExternalLauncher)({}),
Layer.mock(HttpServer.HttpServer)({
diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts
index 75b86b84f6b..707f6d1d408 100644
--- a/apps/server/src/serverRuntimeStartup.ts
+++ b/apps/server/src/serverRuntimeStartup.ts
@@ -45,6 +45,7 @@ import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerSettings from "./serverSettings.ts";
import { forkParked, forkParkedFiber } from "./serverActivation.ts";
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
+import { getServerOwners } from "./telemetry/Identify.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import {
@@ -174,6 +175,7 @@ const recordStartupHeartbeat = Effect.gen(function* () {
threadCount,
projectCount,
});
+ yield* analytics.recordOwners(yield* getServerOwners, "server");
});
export const getAutoBootstrapThreadModelSelection = (): ModelSelection => ({
diff --git a/apps/server/src/telemetry/AnalyticsService.test.ts b/apps/server/src/telemetry/AnalyticsService.test.ts
index 77b2088863b..6a07d9decc6 100644
--- a/apps/server/src/telemetry/AnalyticsService.test.ts
+++ b/apps/server/src/telemetry/AnalyticsService.test.ts
@@ -16,7 +16,7 @@ import * as HttpServerResponse from "effect/http/HttpServerResponse";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as ServerConfig from "../config.ts";
-import { getTelemetryIdentifier } from "./Identify.ts";
+import { getTelemetryIdentity } from "./Identify.ts";
import * as AnalyticsService from "./AnalyticsService.ts";
interface RecordedBatchRequest {
@@ -57,7 +57,14 @@ const SentBatch = Schema.fromJsonString(
batch: Schema.Array(
Schema.Struct({
uuid: Schema.String,
- properties: Schema.Struct({ telemetryChannel: Schema.String }),
+ event: Schema.String,
+ distinct_id: Schema.String,
+ properties: Schema.Struct({
+ telemetryChannel: Schema.String,
+ installId: Schema.optionalKey(Schema.String),
+ ownerSource: Schema.optionalKey(Schema.String),
+ observedBy: Schema.optionalKey(Schema.String),
+ }),
}),
),
}),
@@ -81,11 +88,26 @@ const respondWithStatus =
(request) =>
Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null, { status })));
+const recordTwentyEvents = Effect.gen(function* () {
+ const analytics = yield* AnalyticsService.AnalyticsService;
+ for (let index = 0; index < 20; index += 1) {
+ yield* analytics.record("test.retry", { index });
+ }
+});
+
/**
- * Records 20 events, then lets ten minutes of background flushes run against
- * a client that answers every send with `respond`. Returns the sent batches.
+ * Runs `record` (20 events by default), 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) =>
+const sendForTenMinutes = (
+ respond: Respond,
+ record: Effect.Effect<
+ void,
+ never,
+ AnalyticsService.AnalyticsService | Effect.Services<typeof getTelemetryIdentity>
+ > = recordTwentyEvents,
+) =>
Effect.gen(function* () {
const batches: Array<ReadonlyArray<SentEvent>> = [];
const client = HttpClient.make((request) =>
@@ -122,10 +144,7 @@ const sendForTenMinutes = (respond: Respond) =>
);
yield* Effect.gen(function* () {
- const analytics = yield* AnalyticsService.AnalyticsService;
- for (let index = 0; index < 20; index += 1) {
- yield* analytics.record("test.retry", { index });
- }
+ yield* record;
for (let second = 0; second < 600; second += 1) {
yield* TestClock.adjust("1 second");
}
@@ -181,6 +200,71 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
}).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllGlobals()))),
);
+ it.effect("each owner is sent once per process, and every event carries the install id", () =>
+ Effect.gen(function* () {
+ let identity: Effect.Success<typeof getTelemetryIdentity> | null = null;
+ const batches = yield* sendForTenMinutes(
+ respondWithStatus(204),
+ Effect.gen(function* () {
+ identity = yield* getTelemetryIdentity;
+ const analytics = yield* AnalyticsService.AnalyticsService;
+ const connect = { source: "connect", ownerId: "a".repeat(64) } as const;
+ yield* analytics.recordOwners([connect, connect], "server");
+ yield* analytics.recordOwners(
+ [connect, { source: "device", ownerId: "b".repeat(64) }],
+ "client",
+ );
+ }),
+ );
+ const events = batches.flat();
+
+ assert.deepEqual(
+ events.map((event) => [
+ event.event,
+ event.properties.ownerSource,
+ event.properties.observedBy,
+ ]),
+ [
+ ["install.owner_observed", "connect", "server"],
+ ["install.owner_observed", "connect", "client"],
+ ["install.owner_observed", "device", "client"],
+ ],
+ );
+ const { distinctId, installId } = identity!;
+ assert.isString(installId);
+ assert.isTrue(
+ events.every(
+ (event) => event.distinct_id === distinctId && event.properties.installId === installId,
+ ),
+ );
+ }),
+ );
+
+ it.effect("client owner reports cannot use up the server's owner cap", () =>
+ Effect.gen(function* () {
+ const batches = yield* sendForTenMinutes(
+ respondWithStatus(204),
+ Effect.gen(function* () {
+ const analytics = yield* AnalyticsService.AnalyticsService;
+ yield* analytics.recordOwners(
+ Array.from({ length: 1_001 }, (_, index) => ({
+ source: "device" as const,
+ ownerId: index.toString(16).padStart(64, "0"),
+ })),
+ "client",
+ );
+ // The event buffer also holds 1,000, so send the client events first.
+ yield* analytics.flush;
+ yield* analytics.recordOwners([{ source: "connect", ownerId: "a".repeat(64) }], "server");
+ }),
+ );
+ const owners = batches.flat().map((event) => event.properties.observedBy);
+
+ assert.equal(owners.filter((observedBy) => observedBy === "client").length, 1_000);
+ assert.equal(owners.filter((observedBy) => observedBy === "server").length, 1);
+ }),
+ );
+
it.effect("flush drains all buffered events across multiple batches", () =>
Effect.gen(function* () {
const capturedRequests: Array<RecordedBatchRequest> = [];
@@ -227,8 +311,8 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
yield* Effect.gen(function* () {
yield* Layer.launch(layerBatchServer).pipe(Effect.forkScoped);
- const telemetryIdentifier = yield* getTelemetryIdentifier;
- assert.equal(telemetryIdentifier !== null, true);
+ const { distinctId } = yield* getTelemetryIdentity;
+ assert.equal(distinctId !== null, true);
const analytics = yield* AnalyticsService.AnalyticsService;
for (let index = 0; index < 45; index += 1) {
diff --git a/apps/server/src/telemetry/AnalyticsService.ts b/apps/server/src/telemetry/AnalyticsService.ts
index 59542498264..82226c44139 100644
--- a/apps/server/src/telemetry/AnalyticsService.ts
+++ b/apps/server/src/telemetry/AnalyticsService.ts
@@ -24,7 +24,7 @@ import * as HttpClientResponse from "effect/http/HttpClientResponse";
import packageJson from "../../package.json" with { type: "json" };
import * as ServerConfig from "../config.ts";
-import { getTelemetryIdentifier } from "./Identify.ts";
+import { getTelemetryIdentity, type TelemetryOwner } from "./Identify.ts";
interface BufferedAnalyticsEvent {
readonly uuid: string;
@@ -47,6 +47,10 @@ const FLUSH_INTERVAL_MS = 10_000;
const SEND_TIMEOUT = "10 seconds";
const MAX_BATCH_ATTEMPTS = 5;
const RETRY_BASE_DELAY_MS = 2_000;
+// Clients can report any number of owner ids; past this many per observer, new ones
+// are not sent. Each observer has its own cap, so client reports never crowd out the
+// server's own.
+const MAX_RECORDED_OWNERS = 1_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
@@ -91,6 +95,16 @@ export class AnalyticsService extends Context.Service<
) => Effect.Effect<void>;
readonly flush: Effect.Effect<void>;
+
+ /**
+ * Records `install.owner_observed` for each owner of this install that the
+ * server read itself or a connecting client reported. Each owner is sent once
+ * per server process, so reconnects and repeated reads are free.
+ */
+ readonly recordOwners: (
+ owners: ReadonlyArray<TelemetryOwner>,
+ observedBy: "server" | "client",
+ ) => Effect.Effect<void>;
}
>()("t3/telemetry/AnalyticsService") {
static readonly layerTest = Layer.succeed(
@@ -98,6 +112,7 @@ export class AnalyticsService extends Context.Service<
AnalyticsService.of({
record: () => Effect.void,
flush: Effect.void,
+ recordOwners: () => Effect.void,
}),
);
}
@@ -123,7 +138,7 @@ export const make = Effect.gen(function* () {
const telemetryConfig = yield* TelemetryEnvConfig;
const httpClient = yield* HttpClient.HttpClient;
const serverConfig = yield* ServerConfig.ServerConfig;
- const identifier = yield* getTelemetryIdentifier;
+ const { distinctId, installId } = yield* getTelemetryIdentity;
const crypto = yield* Crypto.Crypto;
const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);
const deliveryRef = yield* Ref.make<DeliveryState>({
@@ -132,6 +147,9 @@ export const make = Effect.gen(function* () {
failures: 0,
retryAt: 0,
});
+ const recordedOwnersRef = yield* Ref.make<
+ Readonly<Record<"server" | "client", ReadonlySet<string>>>
+ >({ server: new Set(), client: new Set() });
// 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";
@@ -175,16 +193,17 @@ export const make = Effect.gen(function* () {
const sendBatch = Effect.fn("AnalyticsService.sendBatch")(function* (
events: ReadonlyArray<BufferedAnalyticsEvent>,
) {
- if (!telemetryConfig.enabled || !identifier) return;
+ if (!telemetryConfig.enabled || !distinctId) return;
const payload = {
api_key: telemetryConfig.posthogKey,
batch: events.map((event) => ({
uuid: event.uuid,
event: event.event,
- distinct_id: identifier,
+ distinct_id: distinctId,
properties: {
...event.properties,
+ ...(installId === null ? {} : { installId }),
$process_person_profile: false,
platform: hostPlatform,
wsl: Option.getOrUndefined(telemetryConfig.wslDistroName),
@@ -267,7 +286,7 @@ export const make = Effect.gen(function* () {
const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")(
function* (event, properties) {
- if (!telemetryConfig.enabled || !identifier) return;
+ if (!telemetryConfig.enabled || !distinctId) return;
// Telemetry is best effort: an event without a uuid is not sent. The
// Node implementation throws (a defect) rather than failing, so catch both.
@@ -284,13 +303,36 @@ export const make = Effect.gen(function* () {
},
);
+ const recordOwners: AnalyticsService["Service"]["recordOwners"] = Effect.fn(
+ "AnalyticsService.recordOwners",
+ )((owners, observedBy) =>
+ Effect.forEach(
+ owners,
+ ({ source, ownerId }) =>
+ Ref.modify(recordedOwnersRef, (recorded) => {
+ const key = `${source}:${ownerId}`;
+ const seen = recorded[observedBy];
+ return seen.has(key) || seen.size >= MAX_RECORDED_OWNERS
+ ? [false, recorded]
+ : [true, { ...recorded, [observedBy]: new Set(seen).add(key) }];
+ }).pipe(
+ Effect.flatMap((isNew) =>
+ isNew
+ ? record("install.owner_observed", { ownerSource: source, ownerId, observedBy })
+ : Effect.void,
+ ),
+ ),
+ { discard: true },
+ ),
+ );
+
yield* Effect.forever(Effect.sleep(FLUSH_INTERVAL_MS).pipe(Effect.flatMap(() => flushWhenDue)), {
disableYield: true,
}).pipe(Effect.forkScoped);
yield* Effect.addFinalizer(() => flush);
- return AnalyticsService.of({ record, flush });
+ return AnalyticsService.of({ record, flush, recordOwners });
});
export const layer = Layer.effect(AnalyticsService, make);
diff --git a/apps/server/src/telemetry/DelegatedTaskAnalytics.test.ts b/apps/server/src/telemetry/DelegatedTaskAnalytics.test.ts
index aea7aec786c..11127e19c2d 100644
--- a/apps/server/src/telemetry/DelegatedTaskAnalytics.test.ts
+++ b/apps/server/src/telemetry/DelegatedTaskAnalytics.test.ts
@@ -92,6 +92,7 @@ it.effect("records each delegated task's final outcome once, without ids or prom
record: (event, properties) =>
Effect.sync(() => void recorded.push({ event, properties })),
flush: Effect.void,
+ recordOwners: () => Effect.void,
}),
),
),
diff --git a/apps/server/src/telemetry/Identify.test.ts b/apps/server/src/telemetry/Identify.test.ts
index b556499547a..fac476b15cc 100644
--- a/apps/server/src/telemetry/Identify.test.ts
+++ b/apps/server/src/telemetry/Identify.test.ts
@@ -10,6 +10,8 @@ import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
+import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
+import { CLOUD_LINKED_USER_ID } from "../cloud/config.ts";
import * as ServerConfig from "../config.ts";
import * as Identify from "./Identify.ts";
@@ -39,28 +41,76 @@ const findIdentityLog = (
errorTag: string,
) => logs.find((log) => log.annotations.source === source && log.annotations.errorTag === errorTag);
+const unsignedJwt = (claims: Readonly<Record<string, unknown>>) =>
+ ["e30", Buffer.from(JSON.stringify(claims)).toString("base64url"), "signature"].join(".");
+
+const layerIdentity = (prefix: string, logs?: CapturedLog[]) =>
+ Layer.provideMerge(
+ ServerSecretStore.layer,
+ ServerConfig.layerTest(process.cwd(), { prefix }),
+ ).pipe(
+ Layer.merge(
+ logs === undefined
+ ? Layer.empty
+ : Logger.layer([makeCaptureLogger(logs)], { mergeWithExisting: false }),
+ ),
+ );
+
+const writeHomeFile = Effect.fn("test.writeHomeFile")(function* (
+ homeDirectory: string,
+ relativePath: string,
+ contents: string,
+) {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const filePath = path.join(homeDirectory, relativePath);
+ yield* fileSystem.makeDirectory(path.dirname(filePath), { recursive: true });
+ yield* fileSystem.writeFileString(filePath, contents);
+ return filePath;
+});
+
it.layer(NodeServices.layer)("telemetry identity", (it) => {
- it.effect("uses the persisted anonymous id when provider identities are absent", () =>
+ it.effect("keeps the old distinct_id rule and a fixed install id as logins change", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
+ const homeDirectory = path.join(config.baseDir, "home");
const anonymousId = "persisted-anonymous-id";
-
yield* fileSystem.writeFileString(config.anonymousIdPath, anonymousId);
+ const installId = yield* sha256(anonymousId);
+ const identity = () => Identify.getTelemetryIdentityForHome(homeDirectory);
- const identifier = yield* Identify.getTelemetryIdentifierForHome(
- path.join(config.baseDir, "home"),
- );
+ assert.deepEqual(yield* identity(), { distinctId: installId, installId });
- assert.equal(identifier, yield* sha256(anonymousId));
- }).pipe(
- Effect.provide(
- ServerConfig.layerTest(process.cwd(), {
- prefix: "t3-telemetry-identify-anonymous-",
- }),
- ),
- ),
+ yield* writeHomeFile(homeDirectory, ".claude.json", `{"userID":"claude-machine"}`);
+ assert.deepEqual(yield* identity(), {
+ distinctId: yield* sha256("claude-machine"),
+ installId,
+ });
+
+ yield* writeHomeFile(homeDirectory, ".codex/auth.json", `{"auth_mode":"apikey"}`);
+ assert.equal((yield* identity()).distinctId, yield* sha256("claude-machine"));
+
+ yield* writeHomeFile(homeDirectory, ".codex/auth.json", `{"tokens":{"account_id":"ws-1"}}`);
+ assert.deepEqual(yield* identity(), { distinctId: yield* sha256("ws-1"), installId });
+ }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-install-"))),
+ );
+
+ it.effect("keeps a provider distinct_id when the install id cannot be saved", () =>
+ Effect.gen(function* () {
+ const config = yield* ServerConfig.ServerConfig;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const homeDirectory = path.join(config.baseDir, "home");
+ yield* fileSystem.makeDirectory(config.anonymousIdPath);
+ yield* writeHomeFile(homeDirectory, ".claude.json", `{"userID":"claude-machine"}`);
+
+ assert.deepEqual(yield* Identify.getTelemetryIdentityForHome(homeDirectory), {
+ distinctId: yield* sha256("claude-machine"),
+ installId: null,
+ });
+ }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-noinstall-"))),
);
it.effect("leaves no torn anonymous id behind when its write fails midway", () =>
@@ -87,19 +137,77 @@ it.layer(NodeServices.layer)("telemetry identity", (it) => {
),
});
- const identifier = yield* Identify.getTelemetryIdentifierForHome(
+ const identity = yield* Identify.getTelemetryIdentityForHome(
path.join(config.baseDir, "home"),
).pipe(Effect.provideService(FileSystem.FileSystem, tornWrites));
- assert.isNull(identifier);
+ assert.deepEqual(identity, { distinctId: null, installId: null });
assert.isFalse(yield* fileSystem.exists(config.anonymousIdPath));
- }).pipe(
- Effect.provide(
- ServerConfig.layerTest(process.cwd(), {
- prefix: "t3-telemetry-identify-torn-",
+ }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-torn-"))),
+ );
+
+ it.effect("does not overwrite the anonymous id path after a non-NotFound read failure", () => {
+ const logs: CapturedLog[] = [];
+
+ return Effect.gen(function* () {
+ const config = yield* ServerConfig.ServerConfig;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ yield* fileSystem.makeDirectory(config.anonymousIdPath);
+
+ const identity = yield* Identify.getTelemetryIdentityForHome(
+ path.join(config.baseDir, "home"),
+ );
+ assert.deepEqual(identity, { distinctId: null, installId: null });
+ assert.deepEqual(yield* fileSystem.readDirectory(config.anonymousIdPath), []);
+
+ const readLog = findIdentityLog(logs, "anonymous", "TelemetryIdentityReadError");
+ assert.equal(readLog?.annotations.filePath, config.anonymousIdPath);
+ assert.notEqual(readLog?.annotations.platformReason, "NotFound");
+ assert.notProperty(readLog?.annotations ?? {}, "cause");
+ assert.isUndefined(
+ findIdentityLog(logs, "anonymous", "TelemetryAnonymousIdPersistenceError"),
+ );
+ }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-read-", logs)));
+ });
+
+ it.effect("reads the Connect account and each provider account as owners", () =>
+ Effect.gen(function* () {
+ const config = yield* ServerConfig.ServerConfig;
+ const secrets = yield* ServerSecretStore.ServerSecretStore;
+ const path = yield* Path.Path;
+ const homeDirectory = path.join(config.baseDir, "home");
+ yield* secrets.set(CLOUD_LINKED_USER_ID, new TextEncoder().encode("user_connect"));
+ yield* writeHomeFile(
+ homeDirectory,
+ ".codex/auth.json",
+ JSON.stringify({
+ tokens: {
+ account_id: "team-workspace",
+ id_token: unsignedJwt({
+ sub: "google-oauth2|login-method",
+ "https://api.openai.com/auth": { user_id: "user-openai-person" },
+ }),
+ },
}),
- ),
- ),
+ );
+ yield* writeHomeFile(
+ homeDirectory,
+ ".claude.json",
+ JSON.stringify({
+ userID: "claude-machine",
+ oauthAccount: { accountUuid: "claude-person" },
+ }),
+ );
+
+ const owners = yield* Identify.getServerOwnersForHome(homeDirectory);
+
+ assert.deepEqual(owners, [
+ { source: "connect", ownerId: yield* sha256("user_connect") },
+ { source: "openai", ownerId: yield* sha256("user-openai-person") },
+ { source: "claude", ownerId: yield* sha256("claude-person") },
+ ]);
+ }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-owners-"))),
);
it.effect.each([
@@ -119,135 +227,60 @@ it.layer(NodeServices.layer)("telemetry identity", (it) => {
secret: "private-personal-access-token",
authJson: (secret: string) => `{"OPENAI_API_KEY":null,"personal_access_token":"${secret}"}`,
},
- ])("falls back quietly when Codex authenticates with $login", ({ secret, authJson }) => {
- const logs: CapturedLog[] = [];
- const logger = makeCaptureLogger(logs);
-
- return Effect.gen(function* () {
- const config = yield* ServerConfig.ServerConfig;
- const fileSystem = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const homeDirectory = path.join(config.baseDir, "home");
- const codexAuthPath = path.join(homeDirectory, ".codex", "auth.json");
- const anonymousId = "tokenless-codex-anonymous-id";
+ ])(
+ "adds no owner and logs nothing when Codex authenticates with $login",
+ ({ secret, authJson }) => {
+ const logs: CapturedLog[] = [];
- yield* fileSystem.makeDirectory(path.dirname(codexAuthPath), { recursive: true });
- yield* fileSystem.writeFileString(codexAuthPath, authJson(secret));
- yield* fileSystem.writeFileString(config.anonymousIdPath, anonymousId);
+ return Effect.gen(function* () {
+ const config = yield* ServerConfig.ServerConfig;
+ const path = yield* Path.Path;
+ const homeDirectory = path.join(config.baseDir, "home");
+ yield* writeHomeFile(homeDirectory, ".codex/auth.json", authJson(secret));
- const identifier = yield* Identify.getTelemetryIdentifierForHome(homeDirectory);
-
- assert.equal(identifier, yield* sha256(anonymousId));
- assert.isUndefined(findIdentityLog(logs, "codex", "TelemetryIdentityDecodeError"));
- assert.isUndefined(findIdentityLog(logs, "codex", "TelemetryIdentityReadError"));
- const allLogs = logs
- .map((log) =>
- [String(log.message), ...Object.values(log.annotations).map(String)].join("\n"),
- )
- .join("\n");
- assert.notInclude(allLogs, secret);
- }).pipe(
- Effect.provide(
- Layer.merge(
- ServerConfig.layerTest(process.cwd(), {
- prefix: "t3-telemetry-identify-tokenless-",
- }),
- Logger.layer([logger], { mergeWithExisting: false }),
- ),
- ),
- );
- });
-
- it.effect("logs structured decode context and falls back from malformed Codex auth", () => {
- const logs: CapturedLog[] = [];
- const logger = makeCaptureLogger(logs);
-
- return Effect.gen(function* () {
- const config = yield* ServerConfig.ServerConfig;
- const fileSystem = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const homeDirectory = path.join(config.baseDir, "home");
- const codexAuthPath = path.join(homeDirectory, ".codex", "auth.json");
- const anonymousId = "decode-fallback-anonymous-id";
- const privateAccessToken = "private-codex-access-token";
-
- yield* fileSystem.makeDirectory(path.dirname(codexAuthPath), { recursive: true });
- yield* fileSystem.writeFileString(
- codexAuthPath,
- `{"tokens":{"access_token":"${privateAccessToken}"}}`,
- );
- yield* fileSystem.writeFileString(config.anonymousIdPath, anonymousId);
-
- const identifier = yield* Identify.getTelemetryIdentifierForHome(homeDirectory);
-
- assert.equal(identifier, yield* sha256(anonymousId));
- const decodeLog = findIdentityLog(logs, "codex", "TelemetryIdentityDecodeError");
- assert.isDefined(decodeLog);
- assert.equal(
- decodeLog?.message,
- `Failed to decode codex telemetry identity at '${codexAuthPath}'.`,
- );
-
- assert.equal(decodeLog?.annotations.filePath, codexAuthPath);
- assert.equal(decodeLog?.annotations.causeKind, "schema");
- assert.notProperty(decodeLog?.annotations ?? {}, "cause");
- const errorStack = decodeLog?.annotations.errorStack;
- assert.isString(errorStack);
- assert.include(errorStack, "Failed to decode codex telemetry identity");
- const annotations = Object.values(decodeLog?.annotations ?? {})
- .map(String)
- .join("\n");
- assert.notInclude(annotations, privateAccessToken);
- }).pipe(
- Effect.provide(
- Layer.merge(
- ServerConfig.layerTest(process.cwd(), {
- prefix: "t3-telemetry-identify-decode-",
- }),
- Logger.layer([logger], { mergeWithExisting: false }),
- ),
- ),
- );
- });
-
- it.effect("does not overwrite the anonymous id path after a non-NotFound read failure", () => {
- const logs: CapturedLog[] = [];
- const logger = makeCaptureLogger(logs);
-
- return Effect.gen(function* () {
- const config = yield* ServerConfig.ServerConfig;
- const fileSystem = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const homeDirectory = path.join(config.baseDir, "home");
-
- yield* fileSystem.makeDirectory(config.anonymousIdPath);
+ assert.deepEqual(yield* Identify.getServerOwnersForHome(homeDirectory), []);
+ assert.deepEqual(logs, []);
+ }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-tokenless-", logs)));
+ },
+ );
- const identifier = yield* Identify.getTelemetryIdentifierForHome(homeDirectory);
+ it.effect(
+ "warns about malformed Codex auth without its tokens and keeps the other owners",
+ () => {
+ const logs: CapturedLog[] = [];
- assert.isNull(identifier);
- assert.deepEqual(yield* fileSystem.readDirectory(config.anonymousIdPath), []);
+ return Effect.gen(function* () {
+ const config = yield* ServerConfig.ServerConfig;
+ const path = yield* Path.Path;
+ const homeDirectory = path.join(config.baseDir, "home");
+ const privateAccessToken = "private-codex-access-token";
+ const codexAuthPath = yield* writeHomeFile(
+ homeDirectory,
+ ".codex/auth.json",
+ `{"tokens":{"access_token":"${privateAccessToken}"}}`,
+ );
+ yield* writeHomeFile(
+ homeDirectory,
+ ".claude.json",
+ `{"oauthAccount":{"accountUuid":"claude-person"}}`,
+ );
- const readLog = findIdentityLog(logs, "anonymous", "TelemetryIdentityReadError");
- assert.isDefined(readLog);
- assert.equal(readLog?.annotations.filePath, config.anonymousIdPath);
- assert.equal(readLog?.annotations.causeKind, "platform");
- assert.notEqual(readLog?.annotations.platformReason, "NotFound");
- assert.notProperty(readLog?.annotations ?? {}, "cause");
- const errorStack = readLog?.annotations.errorStack;
- assert.isString(errorStack);
- assert.include(errorStack, "Failed to read anonymous telemetry identity");
- assert.isUndefined(
- findIdentityLog(logs, "anonymous", "TelemetryAnonymousIdPersistenceError"),
- );
- }).pipe(
- Effect.provide(
- Layer.merge(
- ServerConfig.layerTest(process.cwd(), {
- prefix: "t3-telemetry-identify-read-",
- }),
- Logger.layer([logger], { mergeWithExisting: false }),
- ),
- ),
- );
- });
+ assert.deepEqual(yield* Identify.getServerOwnersForHome(homeDirectory), [
+ { source: "claude", ownerId: yield* sha256("claude-person") },
+ ]);
+ const decodeLog = findIdentityLog(logs, "codex", "TelemetryIdentityDecodeError");
+ assert.equal(
+ decodeLog?.message,
+ `Failed to decode codex telemetry identity at '${codexAuthPath}'.`,
+ );
+ assert.equal(decodeLog?.annotations.causeKind, "schema");
+ assert.notInclude(
+ Object.values(decodeLog?.annotations ?? {})
+ .map(String)
+ .join("\n"),
+ privateAccessToken,
+ );
+ }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-decode-", logs)));
+ },
+ );
});
diff --git a/apps/server/src/telemetry/Identify.ts b/apps/server/src/telemetry/Identify.ts
index 61c4d353591..05e657adbe3 100644
--- a/apps/server/src/telemetry/Identify.ts
+++ b/apps/server/src/telemetry/Identify.ts
@@ -1,33 +1,66 @@
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
-import * as Hex from "effect/encoding/Hex";
+import * as Base64Url from "effect/encoding/Base64Url";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
+import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
-import * as ServerConfig from "../config.ts";
import * as HostProcess from "@t3tools/shared/HostProcess";
+import { hashTelemetryId } from "@t3tools/shared/telemetryId";
+import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
+import { CLOUD_LINKED_USER_ID } from "../cloud/config.ts";
+import * as ServerConfig from "../config.ts";
/**
* Codex writes `tokens` only for ChatGPT logins and omits the key for API-key,
* agent-identity, and personal-access-token logins, so its absence is a
- * supported install and not a malformed file.
+ * supported install and not a malformed file. `account_id` is the ChatGPT
+ * workspace, which a whole Team shares; the `id_token` names the person.
*/
const CodexAuthJsonSchema = Schema.Struct({
tokens: Schema.optionalKey(
Schema.Struct({
account_id: Schema.String,
+ id_token: Schema.optionalKey(Schema.String),
}),
),
});
+/** `userID` is random per machine. `oauthAccount` is present only while Claude Code is logged in. */
const ClaudeJsonSchema = Schema.Struct({
- userID: Schema.String,
+ userID: Schema.optionalKey(Schema.String),
+ oauthAccount: Schema.optionalKey(
+ Schema.Struct({
+ accountUuid: Schema.optionalKey(Schema.String),
+ }),
+ ),
});
+// `sub` names the login method (`google-oauth2|…`), so one person can have several.
+// `user_id` (`user-…`) is the OpenAI account and is the same for every login.
+const IdTokenClaims = Schema.Struct({
+ "https://api.openai.com/auth": Schema.Struct({ user_id: Schema.NonEmptyString }),
+});
+const decodeIdTokenClaims = Schema.decodeUnknownOption(Schema.fromJsonString(IdTokenClaims));
+
+/**
+ * Who an install belongs to, from strongest to weakest. `connect` is the T3
+ * Connect account. `openai` and `claude` are provider accounts. `device` is a
+ * client device that connected.
+ */
+export const TelemetryOwnerSource = Schema.Literals(["connect", "openai", "claude", "device"]);
+export type TelemetryOwnerSource = typeof TelemetryOwnerSource.Type;
+
+export interface TelemetryOwner {
+ readonly source: TelemetryOwnerSource;
+ /** `hashTelemetryId` of the source's raw id. */
+ readonly ownerId: string;
+}
+
export const TelemetryIdentitySource = Schema.Literals(["codex", "claude", "anonymous"]);
export type TelemetryIdentitySource = typeof TelemetryIdentitySource.Type;
@@ -83,25 +116,11 @@ export class TelemetryAnonymousIdPersistenceError extends Schema.TaggedError<Tel
}
}
-export class TelemetryIdentityHashError extends Schema.TaggedError<TelemetryIdentityHashError>()(
- "TelemetryIdentityHashError",
- {
- source: TelemetryIdentitySource,
- algorithm: Schema.Literal("SHA-256"),
- cause: Schema.Defect(),
- },
-) {
- override get message(): string {
- return `Failed to hash ${this.source} telemetry identity with ${this.algorithm}.`;
- }
-}
-
type TelemetryIdentityError =
| TelemetryIdentityReadError
| TelemetryIdentityDecodeError
| TelemetryAnonymousIdGenerationError
- | TelemetryAnonymousIdPersistenceError
- | TelemetryIdentityHashError;
+ | TelemetryAnonymousIdPersistenceError;
const decodeCodexAuthJson = Schema.decodeEffect(Schema.fromJsonString(CodexAuthJsonSchema));
const decodeClaudeJson = Schema.decodeEffect(Schema.fromJsonString(ClaudeJsonSchema));
@@ -155,72 +174,48 @@ const readIdentityFile = (
}),
);
-const hash = (source: TelemetryIdentitySource, value: string) =>
- Crypto.Crypto.pipe(
- Effect.flatMap((crypto) => crypto.digest("SHA-256", new TextEncoder().encode(value))),
- Effect.map(Hex.encode),
- Effect.mapError(
- (cause) =>
- new TelemetryIdentityHashError({
- source,
- algorithm: "SHA-256",
- cause,
- }),
- ),
- );
+/**
+ * The OpenAI account id in a ChatGPT id_token, read without verifying it:
+ * analytics needs only a stable id. Codex CLI and T3's own sign-in both use it.
+ */
+export const openAiUserId = (idToken: string) => {
+ const payload = Base64Url.decodeString(idToken.split(".")[1] ?? "");
+ return Result.isSuccess(payload)
+ ? Option.map(
+ decodeIdTokenClaims(payload.success),
+ (claims) => claims["https://api.openai.com/auth"].user_id,
+ )
+ : Option.none<string>();
+};
-const getCodexAccountId = Effect.fn("TelemetryIdentity.getCodexAccountId")(function* (
- homeDirectory: string,
+const readJsonIdentityFile = Effect.fn("TelemetryIdentity.readJsonIdentityFile")(function* <A>(
+ source: "codex" | "claude",
+ filePath: string,
+ decode: (encoded: string) => Effect.Effect<A, Schema.SchemaError>,
) {
const fileSystem = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
-
- const authJsonPath = path.join(homeDirectory, ".codex", "auth.json");
- const encoded = yield* readIdentityFile(fileSystem, "codex", authJsonPath);
+ const encoded = yield* readIdentityFile(fileSystem, source, filePath);
if (Option.isNone(encoded)) {
- return Option.none<string>();
+ return Option.none<A>();
}
- const authJson = yield* decodeCodexAuthJson(encoded.value).pipe(
- Effect.mapError(
- (cause) =>
- new TelemetryIdentityDecodeError({
- source: "codex",
- filePath: authJsonPath,
- cause,
- }),
- ),
+ return yield* decode(encoded.value).pipe(
+ Effect.asSome,
+ Effect.mapError((cause) => new TelemetryIdentityDecodeError({ source, filePath, cause })),
);
-
- return authJson.tokens === undefined
- ? Option.none<string>()
- : Option.some(authJson.tokens.account_id);
});
-const getClaudeUserId = Effect.fn("TelemetryIdentity.getClaudeUserId")(function* (
- homeDirectory: string,
-) {
- const fileSystem = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
-
- const claudeJsonPath = path.join(homeDirectory, ".claude.json");
- const encoded = yield* readIdentityFile(fileSystem, "claude", claudeJsonPath);
- if (Option.isNone(encoded)) {
- return Option.none<string>();
- }
- const claudeJson = yield* decodeClaudeJson(encoded.value).pipe(
- Effect.mapError(
- (cause) =>
- new TelemetryIdentityDecodeError({
- source: "claude",
- filePath: claudeJsonPath,
- cause,
- }),
- ),
+// A missing or unreadable file only removes that owner; it never blocks the others.
+const skipOnError = <A, R>(
+ effect: Effect.Effect<
+ Option.Option<A>,
+ TelemetryIdentityReadError | TelemetryIdentityDecodeError,
+ R
+ >,
+) =>
+ effect.pipe(
+ Effect.catch((error) => logTelemetryIdentityError(error).pipe(Effect.as(Option.none<A>()))),
);
- return Option.some(claudeJson.userID);
-});
-
const upsertAnonymousId = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const { anonymousIdPath } = yield* ServerConfig.ServerConfig;
@@ -255,54 +250,97 @@ const upsertAnonymousId = Effect.gen(function* () {
return anonymousId;
});
-export const getTelemetryIdentifierForHome = Effect.fn("getTelemetryIdentifierForHome")(
- function* (homeDirectory: string) {
- const codexAccountId = yield* getCodexAccountId(homeDirectory).pipe(
- Effect.catchTags({
- TelemetryIdentityReadError: (error) =>
- logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
- TelemetryIdentityDecodeError: (error) =>
- logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
- }),
- );
- if (Option.isSome(codexAccountId)) {
- return yield* hash("codex", codexAccountId.value);
- }
-
- const claudeUserId = yield* getClaudeUserId(homeDirectory).pipe(
- Effect.catchTags({
- TelemetryIdentityReadError: (error) =>
- logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
- TelemetryIdentityDecodeError: (error) =>
- logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
- }),
- );
- if (Option.isSome(claudeUserId)) {
- return yield* hash("claude", claudeUserId.value);
- }
-
- const anonymousId = yield* upsertAnonymousId.pipe(
- Effect.asSome,
- Effect.catchTags({
- TelemetryIdentityReadError: (error) =>
- logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
- TelemetryAnonymousIdGenerationError: (error) =>
- logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
- TelemetryAnonymousIdPersistenceError: (error) =>
- logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),
- }),
- );
- if (Option.isSome(anonymousId)) {
- return yield* hash("anonymous", anonymousId.value);
- }
+const readProviderLogins = Effect.fn("TelemetryIdentity.readProviderLogins")(function* (
+ homeDirectory: string,
+) {
+ const path = yield* Path.Path;
+ const codexTokens = yield* readJsonIdentityFile(
+ "codex",
+ path.join(homeDirectory, ".codex", "auth.json"),
+ decodeCodexAuthJson,
+ ).pipe(
+ skipOnError,
+ Effect.map(Option.flatMap((authJson) => Option.fromUndefinedOr(authJson.tokens))),
+ );
+ const claudeJson = yield* readJsonIdentityFile(
+ "claude",
+ path.join(homeDirectory, ".claude.json"),
+ decodeClaudeJson,
+ ).pipe(skipOnError);
+ return { codexTokens, claudeJson };
+});
- return null;
- },
- Effect.tapError(logTelemetryIdentityError),
- Effect.orElseSucceed(() => null),
-);
+/**
+ * `distinctId` keeps the rule every earlier build used, so analytics stay
+ * continuous: the hashed Codex `account_id`, else the Claude machine `userID`,
+ * else the install's anonymous id. It can change when someone logs in, and a
+ * Codex Team shares one. `installId` is the hashed anonymous id, which never
+ * changes for an install; count installs and people with it.
+ *
+ * A null `distinctId` turns telemetry off. A missing file falls through quietly,
+ * and so does an API-key-only Codex auth.json. Only unreadable or malformed
+ * files warn.
+ */
+export const getTelemetryIdentityForHome = Effect.fn("getTelemetryIdentityForHome")(function* (
+ homeDirectory: string,
+) {
+ const { codexTokens, claudeJson } = yield* readProviderLogins(homeDirectory);
+ const installId = yield* upsertAnonymousId.pipe(
+ Effect.map(hashTelemetryId),
+ Effect.catch((error) => logTelemetryIdentityError(error).pipe(Effect.as(null))),
+ );
+ const providerId = Option.orElse(
+ Option.map(codexTokens, (tokens) => tokens.account_id),
+ () => Option.flatMap(claudeJson, (json) => Option.fromUndefinedOr(json.userID)),
+ );
+ return {
+ distinctId: Option.isSome(providerId) ? hashTelemetryId(providerId.value) : installId,
+ installId,
+ };
+});
-export const getTelemetryIdentifier = Effect.flatMap(
+export const getTelemetryIdentity = Effect.flatMap(
HostProcess.HomeDirectory,
- getTelemetryIdentifierForHome,
+ getTelemetryIdentityForHome,
);
+
+/**
+ * Owners the server can read without a client: the linked T3 Connect account
+ * and the provider logins under `homeDirectory`. Clients add `connect` and
+ * `device` owners when they connect.
+ */
+export const getServerOwnersForHome = Effect.fn("getServerOwnersForHome")(function* (
+ homeDirectory: string,
+) {
+ const secrets = yield* ServerSecretStore.ServerSecretStore;
+ const connectUser = yield* secrets.get(CLOUD_LINKED_USER_ID).pipe(
+ Effect.map(Option.map((bytes) => new TextDecoder().decode(bytes))),
+ Effect.catch((cause) =>
+ Effect.logWarning("Failed to read the linked T3 Connect account for telemetry", {
+ errorTag: cause._tag,
+ }).pipe(Effect.as(Option.none<string>())),
+ ),
+ );
+ const { codexTokens, claudeJson } = yield* readProviderLogins(homeDirectory);
+
+ const raw: ReadonlyArray<readonly [TelemetryOwnerSource, Option.Option<string>]> = [
+ ["connect", connectUser],
+ [
+ "openai",
+ Option.flatMap(codexTokens, (tokens) =>
+ Option.flatMap(Option.fromUndefinedOr(tokens.id_token), openAiUserId),
+ ),
+ ],
+ [
+ "claude",
+ Option.flatMap(claudeJson, (json) => Option.fromUndefinedOr(json.oauthAccount?.accountUuid)),
+ ],
+ ];
+ return raw.flatMap(([source, value]): ReadonlyArray<TelemetryOwner> =>
+ Option.isSome(value) && value.value.trim() !== ""
+ ? [{ source, ownerId: hashTelemetryId(value.value) }]
+ : [],
+ );
+});
+
+export const getServerOwners = Effect.flatMap(HostProcess.HomeDirectory, getServerOwnersForHome);
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 8eaa4bfad35..88b0be99046 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -224,6 +224,7 @@ import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
import * as HostResources from "./resourceTelemetry/HostResources.ts";
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
import { featureUsage } from "./telemetry/FeatureUsage.ts";
+import type { TelemetryOwner } from "./telemetry/Identify.ts";
import * as UsageService from "./usage/UsageService.ts";
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
import * as PullRequestService from "./pullRequest/PullRequestService.ts";
@@ -244,6 +245,7 @@ import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
import * as SessionStore from "./auth/SessionStore.ts";
import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
import * as RelayClient from "@t3tools/shared/relayClient";
+import { isTelemetryIdHash } from "@t3tools/shared/telemetryId";
import {
sameUsageLimitCommandCoverage,
withUsageLimitsCommands,
@@ -674,6 +676,28 @@ function readClientAnalyticsProps(request: HttpServerRequest.HttpServerRequest)
};
}
+/**
+ * Owners a connecting client reports: its hashed T3 Connect account and its
+ * hashed device id. Only hashes are accepted, so a raw id never reaches analytics.
+ */
+function readClientOwners(
+ request: HttpServerRequest.HttpServerRequest,
+): ReadonlyArray<TelemetryOwner> {
+ const url = HttpServerRequest.toURL(request);
+ if (Option.isNone(url)) {
+ return [];
+ }
+ const params = url.value.searchParams;
+ return (
+ [
+ ["connect", params.get("clientOwner")],
+ ["device", params.get("clientDevice")],
+ ] as const
+ ).flatMap(([source, ownerId]) =>
+ ownerId !== null && isTelemetryIdHash(ownerId) ? [{ source, ownerId }] : [],
+ );
+}
+
const canReplayPersistedRange = Effect.fnUntraced(function* (
afterSequence: number,
headSequence: number,
@@ -3124,6 +3148,7 @@ export const layer = Layer.unwrap(
const clientAnalyticsProps = readClientAnalyticsProps(request);
yield* sessions.recordClientConnection(session.sessionId, clientOrigin);
yield* analytics.record("client.connected", clientAnalyticsProps);
+ yield* analytics.recordOwners(readClientOwners(request), "client");
const rpcWebSocketHttpEffect = yield* Effect.gen(function* () {
const { protocol, httpEffect } = yield* RpcServer.makeProtocolWithHttpEffectWebsocket;
yield* RpcServer.make(ServerWsRpcGroup, WS_RPC_SERVER_OPTIONS).pipe(
diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts
index 1cbaaa163a6..dbc2e0ba70f 100644
--- a/apps/web/src/connection/platform.ts
+++ b/apps/web/src/connection/platform.ts
@@ -52,6 +52,7 @@ import {
import { clearComposerDraftsEnvironment } from "../composerDraftStore";
import { isHostedStaticApp } from "../hostedPairing";
import { isLocalEnvironmentDisabled } from "../localEnvironment";
+import { randomUUID } from "../lib/utils";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { acknowledgeRpcRequest, trackRpcRequestSent } from "../rpc/requestLatencyState";
import {
@@ -302,6 +303,19 @@ export const prepareDesktopSshEnvironment = Effect.fn("web.connectionPlatform.ss
},
);
+const ANALYTICS_DEVICE_ID_KEY = "t3code:analytics-device-id";
+
+// Lives as long as this browser profile's site data. Storage can be blocked, which only drops the id.
+const analyticsDevice = {
+ id: Effect.try(() => {
+ const existing = window.localStorage.getItem(ANALYTICS_DEVICE_ID_KEY);
+ if (existing) return existing;
+ const created = randomUUID();
+ window.localStorage.setItem(ANALYTICS_DEVICE_ID_KEY, created);
+ return created;
+ }).pipe(Effect.option),
+};
+
const layerCapabilities = Layer.effectContext(
Effect.sync(() => {
const presentation = ClientCapabilities.ClientPresentation.of({
@@ -391,6 +405,7 @@ const layerCapabilities = Layer.effectContext(
});
return Context.make(ClientCapabilities.CloudSession, cloudSession).pipe(
+ Context.add(ClientCapabilities.AnalyticsDevice, analyticsDevice),
Context.add(ClientCapabilities.PrimaryEnvironmentAuth, primaryAuth),
Context.add(ClientCapabilities.RelayDeviceIdentity, identity),
Context.add(ClientCapabilities.ClientPresentation, presentation),
diff --git a/docs/internals/product-analytics.md b/docs/internals/product-analytics.md
index 4d754c3eff0..023fe085a43 100644
--- a/docs/internals/product-analytics.md
+++ b/docs/internals/product-analytics.md
@@ -1,11 +1,36 @@
# Product analytics
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
-the PostHog browser SDK. Client-use events require an authenticated connection, so
-visiting the hosted app without connecting does not count as product use.
+Clients do not load the PostHog browser SDK. Client-use events require an
+authenticated connection, so visiting the hosted app without connecting does not
+count as product use.
+
+## Installs and owners
+
+`distinct_id` keeps the rule every build has used: the hashed Codex workspace,
+else the Claude machine id, else the install's anonymous id. It can change when
+someone logs in, and a Codex Team shares one, but keeping it means PostHog charts
+and history never break. Do not change it; add a field instead.
+
+Every event also carries `installId` when the server can save its state: the hash
+of a random id in the state directory, which never changes for the install. If
+that file cannot be written, events still go out under `distinct_id`, as before. Count installs
+with it. Who an install belongs to is a separate fact, sent as
+`install.owner_observed`. Owners are resolved at query time in our own store, so
+a rule can change and apply to all history.
+
+[Owner sources](../../apps/server/src/telemetry/Identify.ts), strongest first:
+T3 Connect, then the OpenAI and Claude person ids, then the client device. The
+server reports what it can read itself: the linked Connect account and provider
+logins. A connecting client reports its signed-in Connect account and its device,
+which links every environment opened from one phone, browser, or desktop. Use the
+OpenAI `user_id` claim, not the Codex `account_id` (the ChatGPT workspace, which a
+whole Team shares) or the token `sub` (one per login method). Two Connect accounts are never the same person, whatever
+weaker ids they share.
+
+Every id is SHA-256 hashed with [one helper](../../packages/shared/src/telemetryId.ts)
+on both sides, so a Connect account hashes the same on the client and the server.
+The server accepts only hashes from clients.
## Attribution boundaries
diff --git a/docs/user/telemetry.md b/docs/user/telemetry.md
index a25635faaaf..38d3ef0231a 100644
--- a/docs/user/telemetry.md
+++ b/docs/user/telemetry.md
@@ -1,7 +1,9 @@
# Product usage data
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
+associated with a hashed account or installation identifier. To count how many installations one person
+uses, the server also sends hashed account identifiers: your T3 Connect account, your OpenAI and
+Claude accounts when you are signed in, and a random identifier for each device that connects. 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.
diff --git a/packages/client-runtime/src/authorization/remote.test.ts b/packages/client-runtime/src/authorization/remote.test.ts
index 54290c469d8..0e56c0219d7 100644
--- a/packages/client-runtime/src/authorization/remote.test.ts
+++ b/packages/client-runtime/src/authorization/remote.test.ts
@@ -2,10 +2,12 @@ import { describe, expect, it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
+import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import { EnvironmentAuthInvalidError } from "@t3tools/contracts";
+import { hashTelemetryId } from "@t3tools/shared/telemetryId";
import {
appendClientConnectionParams,
bootstrapRemoteBearerSession,
@@ -18,6 +20,7 @@ import {
resolveRemoteWebSocketConnectionUrl,
} from "./remote.ts";
import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
+import * as ClientCapabilities from "../platform/capabilities.ts";
import * as RpcHttp from "../rpc/http.ts";
const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);
@@ -486,4 +489,37 @@ describe("remote environment authorization", () => {
);
}),
);
+
+ it.effect("names the signed-in Connect account and this device by hash only", () =>
+ Effect.gen(function* () {
+ const fetch = recordedFetch(
+ Response.json({ ticket: "ws-ticket", expiresAt: "2026-05-01T12:05:00.000Z" }),
+ );
+
+ const url = new URL(
+ yield* resolveRemoteWebSocketConnectionUrl({
+ wsBaseUrl: "wss://remote.example.com/",
+ httpBaseUrl: "https://remote.example.com/",
+ bearerToken: "bearer-token",
+ }).pipe(
+ provideRemoteHttp(fetch.fetchFn),
+ Effect.provideService(
+ ClientCapabilities.CloudSession,
+ ClientCapabilities.CloudSession.of({
+ identity: Effect.succeed(Option.some({ accountId: "user_connect" })),
+ clerkToken: Effect.succeed("clerk-token"),
+ }),
+ ),
+ Effect.provideService(ClientCapabilities.AnalyticsDevice, {
+ id: Effect.succeed(Option.some("device-1")),
+ }),
+ ),
+ );
+
+ expect(url.searchParams.get("clientOwner")).toBe(hashTelemetryId("user_connect"));
+ expect(url.searchParams.get("clientDevice")).toBe(hashTelemetryId("device-1"));
+ expect(url.toString()).not.toContain("user_connect");
+ expect(url.toString()).not.toContain("device-1");
+ }),
+ );
});
diff --git a/packages/client-runtime/src/authorization/remote.ts b/packages/client-runtime/src/authorization/remote.ts
index b80396602d4..0b815d9ac30 100644
--- a/packages/client-runtime/src/authorization/remote.ts
+++ b/packages/client-runtime/src/authorization/remote.ts
@@ -7,8 +7,11 @@ import {
type AuthEnvironmentScope,
} from "@t3tools/contracts";
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
+import { hashTelemetryId } from "@t3tools/shared/telemetryId";
import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
import { environmentEndpointUrl } from "../environment/endpoint.ts";
+import * as ClientCapabilities from "../platform/capabilities.ts";
import {
executeEnvironmentHttpRequest,
makeEnvironmentHttpApiGroupClient,
@@ -37,10 +40,31 @@ const clientMetadataTokenExchangeFields = (
};
};
+/** Hashes of who is connecting. Only hashes leave the client. */
+export interface ClientOwnerParams {
+ readonly connect?: string;
+ readonly device?: string;
+}
+
+/**
+ * Tells the environment, for analytics, which T3 Connect account and device
+ * are connecting, so it can count the environment as theirs.
+ */
+export const readClientOwnerParams = Effect.gen(function* () {
+ const session = yield* Effect.serviceOption(ClientCapabilities.CloudSession);
+ const account = Option.isSome(session) ? yield* session.value.identity : Option.none();
+ const device = yield* (yield* ClientCapabilities.AnalyticsDevice).id;
+ return {
+ ...(Option.isSome(account) ? { connect: hashTelemetryId(account.value.accountId) } : {}),
+ ...(Option.isSome(device) ? { device: hashTelemetryId(device.value) } : {}),
+ } satisfies ClientOwnerParams;
+});
+
export const appendClientConnectionParams = (
url: URL,
clientMetadata: AuthClientPresentationMetadata | undefined,
connectionMethod?: ClientConnectionMethod,
+ owners?: ClientOwnerParams,
): void => {
if (clientMetadata?.surface) {
url.searchParams.set("clientSurface", clientMetadata.surface);
@@ -79,6 +103,12 @@ export const appendClientConnectionParams = (
if (connectionMethod) {
url.searchParams.set("connectionMethod", connectionMethod);
}
+ if (owners?.connect) {
+ url.searchParams.set("clientOwner", owners.connect);
+ }
+ if (owners?.device) {
+ url.searchParams.set("clientDevice", owners.device);
+ }
};
export const exchangeRemoteDpopAccessToken = Effect.fn(
@@ -217,7 +247,12 @@ export const resolveRemoteWebSocketConnectionUrl = Effect.fn(
url.pathname = "/ws";
}
url.searchParams.set("wsTicket", issued.ticket);
- appendClientConnectionParams(url, input.clientMetadata, input.connectionMethod);
+ appendClientConnectionParams(
+ url,
+ input.clientMetadata,
+ input.connectionMethod,
+ yield* readClientOwnerParams,
+ );
return url.toString();
});
@@ -243,6 +278,11 @@ export const resolveRemoteDpopWebSocketConnectionUrl = Effect.fn(
url.pathname = "/ws";
}
url.searchParams.set("wsTicket", issued.ticket);
- appendClientConnectionParams(url, input.clientMetadata, input.connectionMethod);
+ appendClientConnectionParams(
+ url,
+ input.clientMetadata,
+ input.connectionMethod,
+ yield* readClientOwnerParams,
+ );
return url.toString();
});
diff --git a/packages/client-runtime/src/connection/resolver.ts b/packages/client-runtime/src/connection/resolver.ts
index 4e1a99a8af4..cfcf719d9bf 100644
--- a/packages/client-runtime/src/connection/resolver.ts
+++ b/packages/client-runtime/src/connection/resolver.ts
@@ -10,7 +10,11 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as HttpClient from "effect/http/HttpClient";
-import { appendClientConnectionParams } from "../authorization/remote.ts";
+import {
+ appendClientConnectionParams,
+ type ClientOwnerParams,
+ readClientOwnerParams,
+} from "../authorization/remote.ts";
import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
import * as ClientCapabilities from "../platform/capabilities.ts";
import {
@@ -74,12 +78,13 @@ const isBearerCredential = Schema.is(BearerConnectionCredential);
function primarySocketUrl(
target: PrimaryConnectionTarget,
clientMetadata: AuthClientPresentationMetadata | undefined,
+ owners: ClientOwnerParams,
): string {
const url = new URL(target.wsBaseUrl);
if (url.pathname === "" || url.pathname === "/") {
url.pathname = "/ws";
}
- appendClientConnectionParams(url, clientMetadata, "direct");
+ appendClientConnectionParams(url, clientMetadata, "direct", owners);
return url.toString();
}
@@ -97,7 +102,7 @@ const makePrimaryBroker = Effect.fn("clientRuntime.connection.broker.makePrimary
environmentId: target.environmentId,
label: target.label,
httpBaseUrl: target.httpBaseUrl,
- socketUrl: primarySocketUrl(target, presentation.metadata),
+ socketUrl: primarySocketUrl(target, presentation.metadata, yield* readClientOwnerParams),
httpAuthorization: null,
target,
} satisfies PreparedConnection;
diff --git a/packages/client-runtime/src/platform/capabilities.ts b/packages/client-runtime/src/platform/capabilities.ts
index 8ccc3541584..f05c835dda2 100644
--- a/packages/client-runtime/src/platform/capabilities.ts
+++ b/packages/client-runtime/src/platform/capabilities.ts
@@ -5,7 +5,7 @@ import {
EnvironmentId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
-import type * as Effect from "effect/Effect";
+import * as Effect from "effect/Effect";
import type * as Option from "effect/Option";
import type { ConnectionAttemptError } from "../connection/model.ts";
@@ -40,6 +40,17 @@ export class RelayDeviceIdentity extends Context.Service<
}
>()("@t3tools/client-runtime/platform/capabilities/RelayDeviceIdentity") {}
+/**
+ * A random id this client keeps across launches. Environments it connects to
+ * record its hash, so two environments opened from one device share an owner
+ * in analytics even when nobody is signed in.
+ */
+export class AnalyticsDevice extends Context.Reference<{
+ readonly id: Effect.Effect<Option.Option<string>>;
+}>("@t3tools/client-runtime/platform/capabilities/AnalyticsDevice", {
+ defaultValue: () => ({ id: Effect.succeedNone }),
+}) {}
+
export class ClientPresentation extends Context.Service<
ClientPresentation,
{
diff --git a/packages/shared/package.json b/packages/shared/package.json
index b90af1a9b2c..cd9137885a5 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -183,6 +183,10 @@
"types": "./src/dpopCommon.ts",
"import": "./src/dpopCommon.ts"
},
+ "./telemetryId": {
+ "types": "./src/telemetryId.ts",
+ "import": "./src/telemetryId.ts"
+ },
"./relayAuth": {
"types": "./src/relayAuth.ts",
"import": "./src/relayAuth.ts"
diff --git a/packages/shared/src/telemetryId.test.ts b/packages/shared/src/telemetryId.test.ts
new file mode 100644
index 00000000000..1a8e65eb745
--- /dev/null
+++ b/packages/shared/src/telemetryId.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { hashTelemetryId, isTelemetryIdHash } from "./telemetryId.ts";
+
+describe("telemetry ids", () => {
+ // The server hashes the linked Connect account and clients hash the signed-in
+ // one. Both must give plain SHA-256 hex, or the two never match.
+ it("is the SHA-256 hex digest of the id", () => {
+ expect(hashTelemetryId("user_connect")).toBe(
+ "7938265611170ce1ba814a67f5a51bcff2b9b46c5597da465e6f098f2217717a",
+ );
+ });
+
+ it("accepts only hashes, never a raw id", () => {
+ expect(isTelemetryIdHash(hashTelemetryId("user_connect"))).toBe(true);
+ expect(isTelemetryIdHash("user_connect")).toBe(false);
+ expect(isTelemetryIdHash(hashTelemetryId("x").toUpperCase())).toBe(false);
+ });
+});
diff --git a/packages/shared/src/telemetryId.ts b/packages/shared/src/telemetryId.ts
new file mode 100644
index 00000000000..833ee4fe6d9
--- /dev/null
+++ b/packages/shared/src/telemetryId.ts
@@ -0,0 +1,12 @@
+import { sha256 } from "@noble/hashes/sha2";
+import * as Hex from "effect/encoding/Hex";
+
+/**
+ * Hashes an identifier before it reaches analytics. Clients and the server both
+ * use it, so one Connect account gives the same owner id on every surface.
+ */
+export const hashTelemetryId = (value: string): string =>
+ Hex.encode(sha256(new TextEncoder().encode(value)));
+
+/** True for a `hashTelemetryId` result. The server accepts only this shape from clients. */
+export const isTelemetryIdHash = (value: string): boolean => /^[0-9a-f]{64}$/u.test(value);