The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 03:00 UTC
feat(server): count which product features people use (#15921)
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Julius Marminge committed
Oct 18, 2026 at 18:27 UTC
9077e818d836ec6e9cc373d7469034cccc593a5a
6 files changed
+204
-3
apps/server/src/auth/RpcAuthorization.test.ts
+21
@@ -258,6 +258,27 @@ describe("RPC scope middleware", () => {
258
expect(handled).toEqual([]);
259
}).pipe(Effect.scoped),
260
);
261
+
262
+ it.effect("reports only authorized requests that succeed", () =>
263
+ Effect.gen(function* () {
264
+ const observed: Array<string> = [];
265
+ const client = yield* RpcTest.makeClient(group).pipe(
266
+ Effect.provide(
267
+ Layer.mergeAll(
268
+ group.toLayerHandler(WS_METHODS.serverProbe, () => Effect.succeed({})),
269
+ group.toLayerHandler(WS_METHODS.serverRetryResourceTelemetry, () => Effect.never),
270
+ RpcAuthorization.layer([AuthOrchestrationReadScope], (method) =>
271
+ Effect.sync(() => void observed.push(method)),
272
+ ),
273
+ ),
274
+ ),
275
+ );
276
+
277
+ yield* client[WS_METHODS.serverProbe]({});
278
+ yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe(Effect.flip);
279
+ expect(observed).toEqual([WS_METHODS.serverProbe]);
280
+ }).pipe(Effect.scoped),
281
+ );
282
});
283
284
describe("settings mutation authorization", () => {
apps/server/src/auth/RpcAuthorization.ts
+13
-2
@@ -267,11 +267,22 @@ const requiredScopesForRpcCall = (
267
return [requiredScopeForRpcMethod(method)];
268
};
269
270
-export const layer = (scopes: ReadonlyArray<AuthEnvironmentScope>) =>
270
+/**
271
+ * `onAuthorized` runs once after an authorized request succeeds; for a stream
272
+ * RPC, that is when the stream completes. Every RPC passes through here, so it
273
+ * is the one place to observe requests without wrapping each handler.
274
+ */
275
+export const layer = (
276
+ scopes: ReadonlyArray<AuthEnvironmentScope>,
277
+ onAuthorized?: (method: string, payload: unknown) => Effect.Effect<void>,
278
+) =>
279
Layer.succeed(RpcScopeAuthorization)((effect, { rpc, payload }) => {
280
const requiredScopes = requiredScopesForRpcCall(rpc._tag, payload);
281
const requiredScope = requiredScopes.find((scope) => !scopes.includes(scope));
274
- return requiredScope === undefined ? effect : Effect.fail(rpcAuthorizationError(requiredScope));
282
+ if (requiredScope !== undefined) return Effect.fail(rpcAuthorizationError(requiredScope));
283
+ return onAuthorized === undefined
284
+ ? effect
285
+ : Effect.tap(effect, () => onAuthorized(rpc._tag, payload));
286
});
287
288
/** Retrying can install or restart tools even though ordinary listing is readable. */
apps/server/src/telemetry/FeatureUsage.test.ts
new
+52
@@ -0,0 +1,52 @@
1
+import { CommandId, ORCHESTRATION_V2_WS_METHODS, ThreadId, WS_METHODS } from "@t3tools/contracts";
2
+import { expect, it } from "@effect/vitest";
3
+
4
+import { featureUsage } from "./FeatureUsage.ts";
5
+
6
+const dispatch = ORCHESTRATION_V2_WS_METHODS.dispatchCommand;
7
+const threadId = ThreadId.make("thread-private");
8
+const commandId = CommandId.make("command-private");
9
+
10
+it("names user commands with their closed-enum variant and nothing else", () => {
11
+ expect(
12
+ featureUsage(dispatch, {
13
+ type: "checkpoint.rollback",
14
+ commandId,
15
+ threadId,
16
+ scopeId: "scope-private",
17
+ checkpointId: "checkpoint-private",
18
+ restoreFiles: false,
19
+ }),
20
+ ).toEqual({ feature: "checkpoint.rollback", variant: "conversation_only" });
21
+ expect(
22
+ featureUsage(dispatch, {
23
+ type: "thread.runtime-mode.set",
24
+ commandId,
25
+ threadId,
26
+ runtimeMode: "full-access",
27
+ }),
28
+ ).toEqual({ feature: "thread.runtime_mode.set", variant: "full-access" });
29
+});
30
+
31
+it("ignores messages, housekeeping commands, and untracked RPCs", () => {
32
+ expect(featureUsage(dispatch, { type: "message.dispatch", text: "secret prompt" })).toBe(
33
+ undefined,
34
+ );
35
+ expect(featureUsage(dispatch, { type: "thread.visit", threadId })).toBe(undefined);
36
+ expect(featureUsage(WS_METHODS.terminalWrite, { data: "rm -rf" })).toBe(undefined);
37
+});
38
+
39
+it("reads RPC variants from enums, never from paths or text", () => {
40
+ expect(
41
+ featureUsage(WS_METHODS.shellOpenInEditor, { cwd: "/Users/someone/secret", editor: "cursor" }),
42
+ ).toEqual({ feature: "editor.open", variant: "cursor" });
43
+ expect(
44
+ featureUsage(ORCHESTRATION_V2_WS_METHODS.launchThread, {
45
+ title: "Private title",
46
+ workspaceStrategy: { type: "worktree", baseRef: "main", branch: "secret-branch" },
47
+ }),
48
+ ).toEqual({ feature: "thread.launch", variant: "worktree" });
49
+ expect(featureUsage(WS_METHODS.terminalOpen, { cwd: "/Users/someone/secret" })).toEqual({
50
+ feature: "terminal.open",
51
+ });
52
+});
apps/server/src/telemetry/FeatureUsage.ts
new
+93
@@ -0,0 +1,93 @@
1
+import {
2
+ ORCHESTRATION_V2_WS_METHODS,
3
+ type OrchestrationV2Command,
4
+ WS_METHODS,
5
+} from "@t3tools/contracts";
6
+
7
+export interface FeatureUsage {
8
+ readonly feature: string;
9
+ readonly variant?: string;
10
+}
11
+
12
+type Payload = Readonly<Record<string, unknown>>;
13
+
14
+const literal = (payload: Payload, key: string) =>
15
+ typeof payload[key] === "string" ? (payload[key] as string) : undefined;
16
+
17
+const use = (feature: string, variant?: string): FeatureUsage =>
18
+ variant === undefined ? { feature } : { feature, variant };
19
+
20
+/**
21
+ * User commands sent through `orchestration.dispatchCommand` that represent a
22
+ * feature choice. Housekeeping commands (visits, reorders, acknowledgements)
23
+ * and `message.dispatch`, which `client.turn.requested` already counts, are
24
+ * left out.
25
+ */
26
+const COMMAND_FEATURES: Partial<
27
+ Record<OrchestrationV2Command["type"], (command: Payload) => FeatureUsage>
28
+> = {
29
+ "checkpoint.rollback": (command) => ({
30
+ feature: "checkpoint.rollback",
31
+ variant: command.restoreFiles === false ? "conversation_only" : "with_files",
32
+ }),
33
+ "thread.fork": () => ({ feature: "thread.fork" }),
34
+ "thread.merge_back": () => ({ feature: "thread.merge_back" }),
35
+ "provider.switch": () => ({ feature: "provider.switch" }),
36
+ "thread.archive": () => ({ feature: "thread.archive" }),
37
+ "thread.snooze": () => ({ feature: "thread.snooze" }),
38
+ "thread.pin": () => ({ feature: "thread.pin" }),
39
+ "thread.settle": () => ({ feature: "thread.settle" }),
40
+ "thread.pull-request.link": () => ({ feature: "thread.pull_request.link" }),
41
+ "thread.pull-request.watch": () => ({ feature: "thread.pull_request.watch" }),
42
+ "thread.runtime-mode.set": (command) =>
43
+ use("thread.runtime_mode.set", literal(command, "runtimeMode")),
44
+ "thread.interaction-mode.set": (command) =>
45
+ use("thread.interaction_mode.set", literal(command, "interactionMode")),
46
+ "run.interrupt": () => ({ feature: "run.interrupt" }),
47
+ "queued-message.promote-to-steer": () => ({ feature: "queue.steer" }),
48
+ "queued-run.edit": () => ({ feature: "queue.edit" }),
49
+};
50
+
51
+/**
52
+ * RPCs that represent a user starting a feature. Variants come only from
53
+ * closed enums in the contracts, so no path, id, or free text can reach analytics.
54
+ */
55
+const METHOD_FEATURES: Readonly<Record<string, (payload: Payload) => FeatureUsage>> = {
56
+ [ORCHESTRATION_V2_WS_METHODS.launchThread]: (payload) => {
57
+ const strategy = payload.workspaceStrategy;
58
+ return use(
59
+ "thread.launch",
60
+ typeof strategy === "object" && strategy !== null
61
+ ? literal(strategy as Payload, "type")
62
+ : undefined,
63
+ );
64
+ },
65
+ [WS_METHODS.terminalOpen]: () => ({ feature: "terminal.open" }),
66
+ [WS_METHODS.previewOpen]: () => ({ feature: "preview.open" }),
67
+ [WS_METHODS.deviceOpen]: () => ({ feature: "device.open" }),
68
+ [WS_METHODS.shellOpenInEditor]: (payload) => use("editor.open", literal(payload, "editor")),
69
+ [WS_METHODS.vcsCreateWorktree]: () => ({ feature: "worktree.create" }),
70
+ [WS_METHODS.gitRunStackedAction]: (payload) =>
71
+ use("git.stacked_action", literal(payload, "action")),
72
+ [WS_METHODS.pullRequestsRunAction]: (payload) =>
73
+ use("pull_request.action", literal(payload, "action")),
74
+ [WS_METHODS.pullRequestsSubmitReview]: () => ({ feature: "pull_request.review" }),
75
+ [WS_METHODS.pullRequestsComment]: () => ({ feature: "pull_request.comment" }),
76
+ [WS_METHODS.scheduledTasksUpsert]: () => ({ feature: "scheduled_task.save" }),
77
+ [WS_METHODS.scheduledTasksRunNow]: () => ({ feature: "scheduled_task.run_now" }),
78
+ [WS_METHODS.agentSessionsImport]: () => ({ feature: "agent_session.import" }),
79
+ [WS_METHODS.projectCloneStart]: () => ({ feature: "project.clone" }),
80
+ [WS_METHODS.sourceControlPublishRepository]: () => ({ feature: "repository.publish" }),
81
+ [WS_METHODS.serverUpsertKeybinding]: () => ({ feature: "keybinding.customize" }),
82
+};
83
+
84
+/** The feature a WebSocket request uses, or undefined when it is not a tracked feature. */
85
+export function featureUsage(method: string, payload: unknown): FeatureUsage | undefined {
86
+ if (typeof payload !== "object" || payload === null) return undefined;
87
+ const input = payload as Payload;
88
+ if (method === ORCHESTRATION_V2_WS_METHODS.dispatchCommand) {
89
+ const type = literal(input, "type") as OrchestrationV2Command["type"] | undefined;
90
+ return type === undefined ? undefined : COMMAND_FEATURES[type]?.(input);
91
+ }
92
+ return METHOD_FEATURES[method]?.(input);
93
+}
apps/server/src/ws.ts
+19
-1
@@ -226,6 +226,7 @@ import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts
226
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
227
import * as HostResources from "./resourceTelemetry/HostResources.ts";
228
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
229
+import { featureUsage } from "./telemetry/FeatureUsage.ts";
230
import * as UsageService from "./usage/UsageService.ts";
231
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
232
import * as PullRequestService from "./pullRequest/PullRequestService.ts";
@@ -3130,7 +3131,24 @@ export const layer = Layer.unwrap(
3131
yield* RpcServer.make(ServerWsRpcGroup, WS_RPC_SERVER_OPTIONS).pipe(
3132
Effect.provideService(RpcServer.Protocol, withTerminalOutputWindow(protocol)),
3133
Effect.provide(
3133
- Layer.merge(RpcAuthorization.layer(session.scopes), rpcInstrumentationLayer),
3134
+ Layer.merge(
3135
+ RpcAuthorization.layer(session.scopes, (method, payload) => {
3136
+ // Anonymous product signal: the feature and its enum variant,
3137
+ // credited to the connecting client's surface only.
3138
+ const usage = featureUsage(method, payload);
3139
+ return usage === undefined
3140
+ ? Effect.void
3141
+ : analytics
3142
+ .record("feature.used", {
3143
+ ...usage,
3144
+ ...(clientAnalyticsProps.surface === undefined
3145
+ ? {}
3146
+ : { surface: clientAnalyticsProps.surface }),
3147
+ })
3148
+ .pipe(Effect.ignore);
3149
+ }),
3150
+ rpcInstrumentationLayer,
3151
+ ),
3152
),
3153
Effect.forkScoped,
3154
);
docs/internals/product-analytics.md
+6
@@ -41,6 +41,12 @@ Unknown counts stay absent. Partial usage contains valid observed counts but
41
cannot establish a whole-turn total. Keep these distinctions when changing token
42
normalization or building reports.
43
44
+`feature.used` counts WebSocket requests that start a feature, observed in the
45
+RPC authorization middleware after the request succeeds.
46
+[Feature mapping](../../apps/server/src/telemetry/FeatureUsage.ts) allowlists
47
+the methods and commands, and takes variants only from closed contract enums,
48
+so paths, ids, and text never reach analytics.
49
+
50
## Delivery
51
52
The server sends batches to the ingest endpoint at `ingest.t3.codes`, which archives