Skip to content
TypeScript

fix(server): analytics stop counting reconnects, retries, and dev servers (#24601)

Theo Browne8bcef34f16ca
diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
index 6259fd78db6..3b1a8ec1cec 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
@@ -1285,7 +1285,8 @@ it.effect("replays a thread.create receipt without changing the thread", () =>
const before = yield* projections.getThread(threadId);
const replayed = yield* orchestrator.dispatch(create);
assert.equal(replayed.sequence, original.sequence);
- assert.deepEqual(replayed, original);
+ // Marked so client analytics do not count the retry again.
+ assert.deepEqual(replayed, { ...original, replayed: true });
assert.deepEqual(yield* projections.getThread(threadId), before);
assert.equal(yield* orchestrator.getThreadEventSequence(threadId), original.sequence);
}).pipe(Effect.provide(layerTest)),
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 48972ce4cd4..351e804ac63 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -295,6 +295,8 @@ export type OrchestratorV2Error = typeof OrchestratorV2Error.Type;
export interface OrchestratorV2DispatchResult {
readonly sequence: number;
readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
+ /** The command id was already accepted; analytics skip it. */
+ readonly replayed?: true;
}
export interface OrchestratorV2Shape {
@@ -11791,6 +11793,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
return {
sequence: receipt.resultSequence,
storedEvents,
+ replayed: true,
} satisfies OrchestratorV2DispatchResult;
}
@@ -11863,9 +11866,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
if (plan.events.length === 0 && plan.effects.length === 0) {
// A settle that ended nothing still records its receipt: a replayed Stop
// effect then finds it instead of settling work that appeared since.
- const resultSequence = yield* Effect.gen(function* () {
+ const { resultSequence, inserted } = yield* Effect.gen(function* () {
const sequence = yield* eventSink.latestSequence({ threadId: commandThreadId(command) });
- yield* commandReceipts.insertIfAbsent({
+ const inserted = yield* commandReceipts.insertIfAbsent({
commandId: command.commandId,
threadId: commandThreadId(command),
commandType: command.type,
@@ -11874,7 +11877,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
status: "accepted",
error: null,
});
- return sequence;
+ return { resultSequence: sequence, inserted };
}).pipe(
Effect.mapError(
(cause) =>
@@ -11885,7 +11888,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}),
),
);
- return { sequence: resultSequence, storedEvents: [] } satisfies OrchestratorV2DispatchResult;
+ return {
+ sequence: resultSequence,
+ storedEvents: [],
+ ...(inserted ? {} : { replayed: true as const }),
+ } satisfies OrchestratorV2DispatchResult;
}
const acceptedAt = plan.events.at(-1)?.occurredAt ?? (yield* DateTime.now);
const committed = yield* eventSink
@@ -11936,6 +11943,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
return {
sequence: committed.receipt.resultSequence,
storedEvents: committed.storedEvents,
+ ...(committed.committed ? {} : { replayed: true as const }),
} satisfies OrchestratorV2DispatchResult;
});
diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts
index 849cedded92..f3b54f33f33 100644
--- a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts
@@ -233,6 +233,12 @@ it.effect("records accepted billed turn usage once without billing the context w
modelSelection,
runtimeMode: "full-access" as const,
interactionMode: "default" as const,
+ origin: {
+ createdBy: "agent" as const,
+ creationSource: "provider" as const,
+ scheduled: false,
+ subagent: true,
+ },
},
event: { type: "provider_turn.updated" as const, driver: CODEX_DRIVER, providerTurn },
};
@@ -271,6 +277,10 @@ it.effect("records accepted billed turn usage once without billing the context w
mixedModels: false,
runtimeMode: "full-access",
interactionMode: "default",
+ createdBy: "agent",
+ creationSource: "provider",
+ scheduled: false,
+ subagent: true,
durationMs: 120,
});
}).pipe(Effect.provide(layerTest.pipe(Layer.provide(layerAnalytics))));
diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts
index 8e916ab7931..47f34d35da9 100644
--- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts
+++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts
@@ -9,6 +9,8 @@ import {
type OrchestrationV2Subagent,
type OrchestrationV2ThreadProjection,
type ModelSelection,
+ type OrchestrationV2Actor,
+ type OrchestrationV2CreationSource,
type RuntimeMode,
type ProviderInteractionMode,
ProviderInstanceId,
@@ -77,6 +79,19 @@ export interface ProviderTurnAnalyticsContext {
readonly modelSelection: ModelSelection;
readonly runtimeMode?: RuntimeMode;
readonly interactionMode?: ProviderInteractionMode;
+ readonly origin?: ProviderTurnOrigin;
+}
+
+/**
+ * Where the run's starting message came from. Most turns start without a
+ * person (provider continuations, agent sends, delegated subagents), so
+ * reports need this to tell user turns apart.
+ */
+export interface ProviderTurnOrigin {
+ readonly createdBy: OrchestrationV2Actor;
+ readonly creationSource: OrchestrationV2CreationSource;
+ readonly scheduled: boolean;
+ readonly subagent: boolean;
}
export class ProviderTurnAnalytics extends Context.Reference<{
@@ -126,6 +141,7 @@ function providerTurnAnalyticsProperties(input: {
...(effort ? { effort } : {}),
...(input.context?.runtimeMode ? { runtimeMode: input.context.runtimeMode } : {}),
...(input.context?.interactionMode ? { interactionMode: input.context.interactionMode } : {}),
+ ...input.context?.origin,
...(input.providerTurn.startedAt && input.providerTurn.completedAt
? {
durationMs: Math.max(
diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts
index e7937f8a1fc..89d83941bd8 100644
--- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts
+++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts
@@ -50,6 +50,11 @@ import * as RunFinalizationService from "./RunFinalizationService.ts";
import * as TurnItemPositionStore from "./TurnItemPositionStore.ts";
const driver = ProviderDriverKind.make("codex");
+const rootAppThread = (id: ThreadId) =>
+ ({
+ id,
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: id },
+ }) as OrchestrationV2AppThread;
const layerTurnItemPositionsTest = Layer.mock(TurnItemPositionStore.TurnItemPositionStoreV2)({
allocate: () => Effect.succeed(1),
@@ -775,7 +780,7 @@ it.effect("rechecks run ownership immediately before calling the provider", () =
yield* runExecution.startRootRun({
commandId: CommandId.make("command:run-execution-start-guard"),
- appThread: { id: threadId } as OrchestrationV2AppThread,
+ appThread: rootAppThread(threadId),
providerSessionId,
session,
run,
@@ -830,7 +835,7 @@ it.effect("passes the thread's MCP app context to the provider under a safe key"
yield* runExecution.startRootRun({
commandId: CommandId.make("command:run-execution-app-context"),
- appThread: { id: threadId } as OrchestrationV2AppThread,
+ appThread: rootAppThread(threadId),
providerSessionId: ProviderSessionId.make("session:run-execution-app-context"),
session,
run: {
@@ -934,7 +939,7 @@ it.effect("fails the run when its ownership check cannot be read before calling
const runExecution = yield* RunExecutionService.RunExecutionServiceV2;
yield* runExecution.startRootRun({
commandId: CommandId.make("command:run-execution-start-guard-read"),
- appThread: { id: threadId } as OrchestrationV2AppThread,
+ appThread: rootAppThread(threadId),
providerSessionId: ProviderSessionId.make("session:run-execution-start-guard-read"),
session: {
events: Stream.never,
@@ -1029,7 +1034,7 @@ it.effect(
const attemptId = RunAttemptId.make(`attempt:compact-routing:${index}`);
yield* runExecution.startRootRun({
commandId: CommandId.make(`command:compact-routing:${index}`),
- appThread: { id: threadId } as OrchestrationV2AppThread,
+ appThread: rootAppThread(threadId),
providerSessionId: ProviderSessionId.make(`session:compact-routing:${index}`),
session: {
events: Stream.never,
@@ -1145,7 +1150,7 @@ it.effect("starts the provider when checkpoint baseline capture fails", () =>
const runExecution = yield* RunExecutionService.RunExecutionServiceV2;
yield* runExecution.startRootRun({
commandId: CommandId.make("command:run-execution-baseline-failure"),
- appThread: { id: threadId } as OrchestrationV2AppThread,
+ appThread: rootAppThread(threadId),
providerSessionId,
session: {
events: Stream.never,
@@ -1283,7 +1288,7 @@ it.effect.each(["failure", "interruption", "stale-attempt", "start-guard"] as co
const runExecution = yield* RunExecutionService.RunExecutionServiceV2;
yield* runExecution.startRootRun({
commandId: CommandId.make("command:run-execution-settings-failure"),
- appThread: { id: threadId } as OrchestrationV2AppThread,
+ appThread: rootAppThread(threadId),
providerSessionId,
session: {
events: Stream.never,
@@ -1399,6 +1404,7 @@ it.effect("ingests new member threads of an owned child after the root turn term
const subagentNodeId = NodeId.make("node:run-execution-late-child:subagent");
const childMessageIngested = yield* Deferred.make<void>();
const order = yield* Ref.make<ReadonlyArray<string>>([]);
+ const origins = yield* Ref.make<ReadonlyArray<readonly [string, unknown]>>([]);
const layerTest = RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
@@ -1424,6 +1430,11 @@ it.effect("ingests new member threads of an owned child after the root turn term
Layer.mock(ProviderEventIngestor.ProviderEventIngestorV2)({
ingestNormalized: (input) =>
Effect.gen(function* () {
+ const eventType = input.event.type;
+ yield* Ref.update(origins, (current) => [
+ ...current,
+ [eventType, input.analyticsContext?.origin] as const,
+ ]);
if (
input.event.type === "app_thread.created" &&
input.event.appThread.id === memberThreadId
@@ -1559,7 +1570,7 @@ it.effect("ingests new member threads of an owned child after the root turn term
const runExecution = yield* RunExecutionService.RunExecutionServiceV2;
yield* runExecution.startRootRun({
commandId: CommandId.make("command:run-execution-late-child"),
- appThread: { id: threadId } as OrchestrationV2AppThread,
+ appThread: rootAppThread(threadId),
providerSessionId,
session: {
events: Stream.fromIterable(events),
@@ -1612,6 +1623,19 @@ it.effect("ingests new member threads of an owned child after the root turn term
);
assert.isTrue(Option.isSome(observed), "child message was not ingested after root terminal");
assert.deepEqual(yield* Ref.get(order), ["root-finalized", "member-thread", "child-message"]);
+ // The run's message started the root; the parent agent started the child's turn.
+ const recorded = yield* Ref.get(origins);
+ assert.deepEqual(recorded[0], [
+ "app_thread.created",
+ { createdBy: "user", creationSource: "web", scheduled: false, subagent: false },
+ ]);
+ assert.deepEqual(
+ recorded.find(([type]) => type === "provider_turn.updated"),
+ [
+ "provider_turn.updated",
+ { createdBy: "agent", creationSource: "provider", scheduled: false, subagent: true },
+ ],
+ );
}),
);
@@ -1704,7 +1728,7 @@ it.effect("ends a nested native subagent and its thread when the root run is int
const runExecution = yield* RunExecutionService.RunExecutionServiceV2;
yield* runExecution.startRootRun({
commandId: CommandId.make(`command:${key}`),
- appThread: { id: threadId } as OrchestrationV2AppThread,
+ appThread: rootAppThread(threadId),
providerSessionId: ProviderSessionId.make(`session:${key}`),
session: {
events: Stream.fromIterable(events),
@@ -2031,7 +2055,7 @@ it.effect(
const runExecution = yield* RunExecutionService.RunExecutionServiceV2;
yield* runExecution.startRootRun({
commandId: CommandId.make("command:subagent-interrupt-cascade"),
- appThread: { id: ids.threadId } as OrchestrationV2AppThread,
+ appThread: rootAppThread(ids.threadId),
providerSessionId: ProviderSessionId.make("session:subagent-interrupt-cascade"),
session: {
events: Stream.empty,
@@ -2816,7 +2840,7 @@ function captureRootRunTermination(input: {
const runExecution = yield* RunExecutionService.RunExecutionServiceV2;
const start = runExecution.startRootRun({
commandId: CommandId.make(`command:${input.key}`),
- appThread: { id: ids.threadId } as OrchestrationV2AppThread,
+ appThread: rootAppThread(ids.threadId),
providerSessionId: ProviderSessionId.make(`session:${input.key}`),
session: {
events: Stream.empty,
@@ -3312,7 +3336,7 @@ function runBackgroundItemScenario(
const runExecution = yield* RunExecutionService.RunExecutionServiceV2;
yield* runExecution.startRootRun({
commandId: CommandId.make(`command:${key}`),
- appThread: { id: ids.threadId } as OrchestrationV2AppThread,
+ appThread: rootAppThread(ids.threadId),
providerSessionId: ProviderSessionId.make(`session:${key}`),
session: {
events: Stream.empty,
diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts
index 11ab94cefa6..f72c46a913f 100644
--- a/apps/server/src/orchestration-v2/RunExecutionService.ts
+++ b/apps/server/src/orchestration-v2/RunExecutionService.ts
@@ -97,6 +97,14 @@ function isSettledSubagentStatus(status: OrchestrationV2Subagent["status"]): boo
return !isOrchestrationV2WorkActive(status);
}
+/** A provider-native subagent's turns arrive on its parent's run, but the parent agent started them. */
+const NATIVE_SUBAGENT_TURN_ORIGIN: ProviderEventIngestor.ProviderTurnOrigin = {
+ createdBy: "agent",
+ creationSource: "provider",
+ scheduled: false,
+ subagent: true,
+};
+
const backgroundCapableTurnItemTypes: ReadonlySet<OrchestrationV2TurnItem["type"]> = new Set([
"command_execution",
"dynamic_tool",
@@ -883,6 +891,12 @@ export const layer: Layer.Layer<
return RunExecutionServiceV2.of({
startRootRun: Effect.fn("RunExecutionService.startRootRun")(function* (input) {
+ const rootTurnOrigin: ProviderEventIngestor.ProviderTurnOrigin = {
+ createdBy: input.message.createdBy,
+ creationSource: input.message.creationSource,
+ scheduled: input.message.scheduledTaskId !== undefined,
+ subagent: input.appThread.lineage.relationshipToParent === "subagent",
+ };
// Startup failure and stream shutdown can report the same attempt.
const refreshAfterTurn = yield* Effect.cached(
finalizationObserver.refreshAfterTurn(input.appThread.projectId).pipe(
@@ -1375,6 +1389,11 @@ export const layer: Layer.Layer<
modelSelection: input.modelSelection,
runtimeMode: input.runtimePolicy.runtimeMode,
interactionMode: input.runtimePolicy.interactionMode,
+ origin:
+ event.type === "provider_turn.updated" &&
+ event.providerTurn.providerThreadId !== input.providerThread.id
+ ? NATIVE_SUBAGENT_TURN_ORIGIN
+ : rootTurnOrigin,
},
providerSessionId: input.providerSessionId,
providerInstanceId: input.run.providerInstanceId,
diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
index 0391412fe5f..fbc6bceb68b 100644
--- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
@@ -1597,6 +1597,73 @@ it.effect("does not let a failing same-command caller strand a concurrent durabl
}),
);
+it.effect("reports one concurrent same-command launch as new and the rest as resumed", () =>
+ Effect.gen(function* () {
+ // Both launches read no receipt before either one claims the thread.
+ const arrived = yield* Ref.make(0);
+ const bothRead = yield* Deferred.make<void>();
+ const harness = makeHarness({
+ managedFolders: Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
+ namedProjectsRoot: "/projects",
+ isScratchProject: () => Effect.succeed(false),
+ folderForThread: () =>
+ Ref.updateAndGet(arrived, (count) => count + 1).pipe(
+ Effect.tap((count) =>
+ count === 2 ? Deferred.succeed(bothRead, undefined) : Effect.void,
+ ),
+ Effect.andThen(Deferred.await(bothRead)),
+ Effect.as(Option.none()),
+ ),
+ }),
+ });
+ yield* Effect.gen(function* () {
+ const launches = yield* ThreadLaunch.ThreadLaunchService;
+ const input = launchInput({
+ command: "command:launch:concurrent-resumed",
+ thread: "thread:launch:concurrent-resumed",
+ });
+ const results = yield* Effect.all([launches.launch(input), launches.launch(input)], {
+ concurrency: "unbounded",
+ });
+ assert.deepEqual(results.map((result) => result.resumed).sort(), [false, true]);
+ }).pipe(Effect.provide(harness.layer));
+ }),
+);
+
+it.effect(
+ "does not report a retry as resumed when the earlier attempt only claimed the thread",
+ () =>
+ Effect.gen(function* () {
+ const harness = makeHarness();
+ yield* Effect.gen(function* () {
+ const launches = yield* ThreadLaunch.ThreadLaunchService;
+ const threads = yield* ThreadManagement.ThreadManagementService;
+ const input = launchInput({
+ command: "command:launch:claimed-only",
+ thread: "thread:launch:claimed-only",
+ message: "Counted once",
+ });
+ yield* threads.dispatch({
+ type: "thread.create",
+ commandId: input.commandId,
+ threadId: input.threadId,
+ projectId: input.projectId,
+ title: input.title,
+ modelSelection: input.modelSelection,
+ runtimeMode: input.runtimeMode,
+ interactionMode: input.interactionMode,
+ branch: null,
+ worktreePath: null,
+ createdBy: input.createdBy,
+ creationSource: input.creationSource,
+ });
+ const retried = yield* launches.launch(input);
+ assert.isFalse(retried.resumed);
+ assert.isTrue((yield* launches.launch(input)).resumed);
+ }).pipe(Effect.provide(harness.layer));
+ }),
+);
+
it.effect("schedules an accepted preparing message exactly once across concurrent retries", () =>
Effect.gen(function* () {
const setupEntered = yield* Deferred.make<void>();
diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts
index f1c3d432a10..5f4f2f72b6d 100644
--- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts
+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts
@@ -114,6 +114,7 @@ export interface ThreadLaunchPreparationInput {
export interface ThreadLaunchResult {
readonly threadId: ThreadId;
readonly projection: OrchestrationV2ThreadProjection;
+ /** The launch's last write (the initial message, else the thread claim) was accepted before this call. */
readonly resumed: boolean;
}
@@ -974,6 +975,8 @@ const make = Effect.gen(function* () {
creationSource: input.creationSource,
})
.pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)));
+ // A concurrent retry can read no receipt and still replay the dispatch.
+ messageWasAlreadyAccepted ||= dispatched.replayed === true;
const runCreated = dispatched.storedEvents.find(
(stored) => stored.event.type === "run.created",
);
@@ -1034,7 +1037,12 @@ const make = Effect.gen(function* () {
return {
threadId,
projection,
- resumed: Option.isSome(launchReceipt) || messageWasAlreadyAccepted,
+ // An attempt that failed after claiming the thread recorded nothing, so
+ // only a repeat of the final write counts as resumed.
+ resumed:
+ input.initialMessage === undefined
+ ? Option.isSome(launchReceipt) || claimed.replayed === true
+ : messageWasAlreadyAccepted,
};
});
},
diff --git a/apps/server/src/telemetry/FeatureUsage.test.ts b/apps/server/src/telemetry/FeatureUsage.test.ts
index e19e6a1c896..784eb670a20 100644
--- a/apps/server/src/telemetry/FeatureUsage.test.ts
+++ b/apps/server/src/telemetry/FeatureUsage.test.ts
@@ -1,29 +1,68 @@
-import { ORCHESTRATION_V2_WS_METHODS, ThreadId, WS_METHODS } from "@t3tools/contracts";
+import {
+ ORCHESTRATION_V2_WS_METHODS,
+ OrchestrationV2Command,
+ WS_METHODS,
+} from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
+import * as Schema from "effect/Schema";
-import { featureUsage } from "./FeatureUsage.ts";
+import { commandFeatureUsage, featureUsage } from "./FeatureUsage.ts";
-const dispatch = ORCHESTRATION_V2_WS_METHODS.dispatchCommand;
-const threadId = ThreadId.make("thread-private");
+const command = Schema.decodeUnknownSync(OrchestrationV2Command);
+const ids = { commandId: "command-private", threadId: "thread-private" };
it("ignores messages, housekeeping commands, and untracked RPCs", () => {
- expect(featureUsage(dispatch, { type: "message.dispatch", text: "secret prompt" })).toBe(
- undefined,
- );
- expect(featureUsage(dispatch, { type: "thread.visit", threadId })).toBe(undefined);
+ expect(
+ commandFeatureUsage(
+ command({
+ ...ids,
+ type: "message.dispatch",
+ messageId: "message-private",
+ text: "secret prompt",
+ attachments: [],
+ createdBy: "user",
+ creationSource: "web",
+ dispatchMode: { type: "start_immediately" },
+ }),
+ ),
+ ).toBe(undefined);
+ expect(
+ commandFeatureUsage(
+ command({ ...ids, type: "thread.visit", visitedAt: "2026-10-24T00:00:00.000Z" }),
+ ),
+ ).toBe(undefined);
expect(featureUsage(WS_METHODS.terminalWrite, { data: "rm -rf" })).toBe(undefined);
});
-it("reads RPC variants from enums, never from paths or text", () => {
- expect(
- featureUsage(WS_METHODS.shellOpenInEditor, { cwd: "/Users/someone/secret", editor: "cursor" }),
- ).toEqual({ feature: "editor.open", variant: "cursor" });
+it("leaves thread launches to client.thread.started", () => {
expect(
featureUsage(ORCHESTRATION_V2_WS_METHODS.launchThread, {
title: "Private title",
workspaceStrategy: { type: "worktree", baseRef: "main", branch: "secret-branch" },
}),
- ).toEqual({ feature: "thread.launch", variant: "worktree" });
+ ).toBe(undefined);
+});
+
+it("tells watching a pull request apart from unwatching it", () => {
+ const watch = (watching: boolean) =>
+ commandFeatureUsage(
+ command({
+ ...ids,
+ type: "thread.pull-request.watch",
+ host: "github.com",
+ repository: "owner/private",
+ number: 7,
+ watching,
+ }),
+ );
+ expect(watch(true)).toEqual({ feature: "thread.pull_request.watch", variant: "on" });
+ expect(watch(false)).toEqual({ feature: "thread.pull_request.watch", variant: "off" });
+});
+
+it("reads RPC variants from enums, never from paths or text", () => {
+ expect(
+ featureUsage(WS_METHODS.shellOpenInEditor, { cwd: "/Users/someone/secret", editor: "cursor" }),
+ ).toEqual({ feature: "editor.open", variant: "cursor" });
expect(featureUsage(WS_METHODS.terminalOpen, { cwd: "/Users/someone/secret" })).toEqual({
feature: "terminal.open",
});
diff --git a/apps/server/src/telemetry/FeatureUsage.ts b/apps/server/src/telemetry/FeatureUsage.ts
index c5f4903c35a..9c238c5f769 100644
--- a/apps/server/src/telemetry/FeatureUsage.ts
+++ b/apps/server/src/telemetry/FeatureUsage.ts
@@ -1,8 +1,4 @@
-import {
- ORCHESTRATION_V2_WS_METHODS,
- type OrchestrationV2Command,
- WS_METHODS,
-} from "@t3tools/contracts";
+import { type OrchestrationV2Command, WS_METHODS } from "@t3tools/contracts";
export interface FeatureUsage {
readonly feature: string;
@@ -21,11 +17,14 @@ const use = (feature: string, variant?: string): FeatureUsage =>
* User commands sent through `orchestration.dispatchCommand` that represent a
* feature choice. Housekeeping commands (visits, reorders, acknowledgements)
* and `message.dispatch`, which `client.turn.requested` already counts, are
- * left out.
+ * left out. The dispatch handler records these, not the RPC middleware, so a
+ * retried command id that changed nothing is not counted again.
*/
-const COMMAND_FEATURES: Partial<
- Record<OrchestrationV2Command["type"], (command: Payload) => FeatureUsage>
-> = {
+const COMMAND_FEATURES: {
+ readonly [Type in OrchestrationV2Command["type"]]?: (
+ command: Extract<OrchestrationV2Command, { readonly type: Type }>,
+ ) => FeatureUsage;
+} = {
"checkpoint.rollback": (command) => ({
feature: "checkpoint.rollback",
variant: command.restoreFiles === false ? "conversation_only" : "with_files",
@@ -38,11 +37,11 @@ const COMMAND_FEATURES: Partial<
"thread.pin": () => ({ feature: "thread.pin" }),
"thread.settle": () => ({ feature: "thread.settle" }),
"thread.pull-request.link": () => ({ feature: "thread.pull_request.link" }),
- "thread.pull-request.watch": () => ({ feature: "thread.pull_request.watch" }),
- "thread.runtime-mode.set": (command) =>
- use("thread.runtime_mode.set", literal(command, "runtimeMode")),
+ "thread.pull-request.watch": (command) =>
+ use("thread.pull_request.watch", command.watching ? "on" : "off"),
+ "thread.runtime-mode.set": (command) => use("thread.runtime_mode.set", command.runtimeMode),
"thread.interaction-mode.set": (command) =>
- use("thread.interaction_mode.set", literal(command, "interactionMode")),
+ use("thread.interaction_mode.set", command.interactionMode),
"run.interrupt": () => ({ feature: "run.interrupt" }),
"queued-message.promote-to-steer": () => ({ feature: "queue.steer" }),
"queued-run.edit": () => ({ feature: "queue.edit" }),
@@ -51,17 +50,9 @@ const COMMAND_FEATURES: Partial<
/**
* RPCs that represent a user starting a feature. Variants come only from
* closed enums in the contracts, so no path, id, or free text can reach analytics.
+ * Thread launches are left out because `client.thread.started` counts them.
*/
const METHOD_FEATURES: Readonly<Record<string, (payload: Payload) => FeatureUsage>> = {
- [ORCHESTRATION_V2_WS_METHODS.launchThread]: (payload) => {
- const strategy = payload.workspaceStrategy;
- return use(
- "thread.launch",
- typeof strategy === "object" && strategy !== null
- ? literal(strategy as Payload, "type")
- : undefined,
- );
- },
[WS_METHODS.terminalOpen]: () => ({ feature: "terminal.open" }),
[WS_METHODS.previewOpen]: () => ({ feature: "preview.open" }),
[WS_METHODS.deviceOpen]: () => ({ feature: "device.open" }),
@@ -81,13 +72,17 @@ const METHOD_FEATURES: Readonly<Record<string, (payload: Payload) => FeatureUsag
[WS_METHODS.serverUpsertKeybinding]: () => ({ feature: "keybinding.customize" }),
};
+/** The feature a dispatched command uses, or undefined when it is not a tracked feature. */
+export function commandFeatureUsage(command: OrchestrationV2Command): FeatureUsage | undefined {
+ // TypeScript cannot pair a union's tag with its own entry, so widen once here.
+ const mapping = COMMAND_FEATURES[command.type] as
+ | ((command: OrchestrationV2Command) => FeatureUsage)
+ | undefined;
+ return mapping?.(command);
+}
+
/** The feature a WebSocket request uses, or undefined when it is not a tracked feature. */
export function featureUsage(method: string, payload: unknown): FeatureUsage | undefined {
if (typeof payload !== "object" || payload === null) return undefined;
- const input = payload as Payload;
- if (method === ORCHESTRATION_V2_WS_METHODS.dispatchCommand) {
- const type = literal(input, "type") as OrchestrationV2Command["type"] | undefined;
- return type === undefined ? undefined : COMMAND_FEATURES[type]?.(input);
- }
- return METHOD_FEATURES[method]?.(input);
+ return METHOD_FEATURES[method]?.(payload as Payload);
}
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index b8113e7ca40..f9f289ea30a 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -229,7 +229,7 @@ import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts
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 { commandFeatureUsage, 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";
@@ -1247,12 +1247,18 @@ export const layerWsRpc = (
const analytics = yield* AnalyticsService.AnalyticsService;
const originProps = clientAnalyticsProps;
const recordClientCommandAnalytics = (command: OrchestrationV2Command) => {
- switch (command.type) {
- case "message.dispatch":
- return analytics.record("client.turn.requested", originProps).pipe(Effect.ignore);
- default:
- return Effect.void;
+ if (command.type === "message.dispatch") {
+ return analytics.record("client.turn.requested", originProps).pipe(Effect.ignore);
}
+ const usage = commandFeatureUsage(command);
+ return usage === undefined
+ ? Effect.void
+ : analytics
+ .record("feature.used", {
+ ...usage,
+ ...(originProps.surface === undefined ? {} : { surface: originProps.surface }),
+ })
+ .pipe(Effect.ignore);
};
const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;
const commandOutputHub = yield* CommandOutputHub.CommandOutputHub;
@@ -1889,7 +1895,9 @@ export const layerWsRpc = (
).pipe(Effect.provide(intakeContext)),
)
.pipe(
- Effect.tap(() => recordClientCommandAnalytics(command)),
+ Effect.tap((result) =>
+ result.replayed ? Effect.void : recordClientCommandAnalytics(command),
+ ),
Effect.map((result) => ({ sequence: result.sequence })),
Effect.mapError((cause) => {
const detail = userFacingDispatchErrorMessage(cause);
@@ -2028,17 +2036,23 @@ export const layerWsRpc = (
}).pipe(Effect.provide(intakeContext)),
)
.pipe(
- Effect.tap(() =>
- analytics
- .record("client.thread.started", originProps)
- .pipe(
- Effect.andThen(
- input.initialMessage === undefined
- ? Effect.void
- : analytics.record("client.turn.requested", originProps),
- ),
- Effect.ignore,
- ),
+ // A resumed launch is a retry of one already counted.
+ Effect.tap((result) =>
+ result.resumed
+ ? Effect.void
+ : analytics
+ .record("client.thread.started", {
+ ...originProps,
+ workspaceStrategy: input.workspaceStrategy.type,
+ })
+ .pipe(
+ Effect.andThen(
+ input.initialMessage === undefined
+ ? Effect.void
+ : analytics.record("client.turn.requested", originProps),
+ ),
+ Effect.ignore,
+ ),
),
Effect.map((result) => ({
...result,
@@ -3233,7 +3247,6 @@ export const layer = Layer.unwrap(
const clientOrigin = readClientConnectionOrigin(request);
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;
diff --git a/docs/internals/product-analytics.md b/docs/internals/product-analytics.md
index 023fe085a43..990e82ff405 100644
--- a/docs/internals/product-analytics.md
+++ b/docs/internals/product-analytics.md
@@ -47,13 +47,17 @@ runs; use `surface` for the connected client.
## Interpreting events
-Use `client.turn.requested` for active-use reports. `client.connected` counts
-reconnects, so network behavior can inflate it. One identity can appear in several
-client groups during a period; adding those groups double-counts users.
-
-Provider send and completion counts need not match. Providers can emit synthetic
-turns without a send request. Collection is best effort, with no scan or backfill
-of provider history.
+Use `client.turn.requested` for active-use reports. There is no connection event,
+because T3 Connect sessions expire hourly and each reconnect would count again.
+A command whose id was already accepted is a retry, so it records nothing again.
+One identity can appear in several client groups during a period; adding those
+groups double-counts users.
+
+Provider send and completion counts need not match. Most completions start
+without a person: provider continuations, agent sends, and delegated subagents.
+`provider.turn.completed` carries the starting message's `createdBy` and
+`creationSource`, plus `scheduled` and `subagent`; filter on them to count user
+turns. Collection is best effort, with no scan or backfill of provider history.
Token totals cover the main agent. Child agents and model rerouting prevent a turn
from representing one provider/model combination's full cost. For provider
@@ -66,8 +70,9 @@ Unknown counts stay absent. Partial usage contains valid observed counts but
cannot establish a whole-turn total. Keep these distinctions when changing token
normalization or building reports.
-`feature.used` counts WebSocket requests that start a feature, observed in the
-RPC authorization middleware after the request succeeds.
+`feature.used` counts WebSocket requests that start a feature. RPCs are observed in
+the RPC authorization middleware after the request succeeds; dispatched commands
+are recorded by the dispatch handler, which can tell a retry apart.
[Feature mapping](../../apps/server/src/telemetry/FeatureUsage.ts) allowlists
the methods and commands, and takes variants only from closed contract enums,
so paths, ids, and text never reach analytics.
@@ -80,7 +85,9 @@ Pi, and ACP agents list models from user configuration, such as local Ollama
tags, so their models stay out. Handoff settings come from closed enums and
booleans in tool arguments; prompts, titles, and ids are never read. Thread ids
are used only to look up the threads on each side and never leave the server,
-which is also why tool events carry no per-thread sequence.
+which is also why tool events carry no per-thread sequence. A handoff to several
+threads, such as `create_threads`, records one `mcp.tool.invoked` per target, each
+repeating the call's outcome and duration, so event counts are not call counts.
## Delivery
@@ -98,3 +105,7 @@ Keep analytics payloads to product metadata and normalized measurements. Do not
send prompts, authentication material, raw provider payloads, user-assigned device
names, or conversation identifiers. Client metadata is best effort; invalid values
must not reject a connection. PostHog person profiles remain disabled.
+
+Dev-runner servers and the CI archive smoke test turn telemetry off, which also
+stops relay tracing, because each would count as a new install. Set
+`T3CODE_TELEMETRY_ENABLED=true` to test analytics or relay tracing from a dev server.
diff --git a/scripts/dev-runner.test.ts b/scripts/dev-runner.test.ts
index 95b43ddd735..a46a008973d 100644
--- a/scripts/dev-runner.test.ts
+++ b/scripts/dev-runner.test.ts
@@ -90,6 +90,31 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
}),
);
+ it.effect("turns product analytics off unless the developer opts in", () =>
+ Effect.gen(function* () {
+ const input = {
+ mode: "dev",
+ serverOffset: 0,
+ webOffset: 0,
+ t3Home: undefined,
+ browser: undefined,
+ autoBootstrapProjectFromCwd: undefined,
+ logWebSocketEvents: undefined,
+ host: undefined,
+ port: undefined,
+ devUrl: undefined,
+ } as const;
+ const byDefault = yield* createDevRunnerEnv({ ...input, baseEnv: {} });
+ const optedIn = yield* createDevRunnerEnv({
+ ...input,
+ baseEnv: { T3CODE_TELEMETRY_ENABLED: "true" },
+ });
+
+ assert.equal(byDefault.T3CODE_TELEMETRY_ENABLED, "false");
+ assert.equal(optedIn.T3CODE_TELEMETRY_ENABLED, "true");
+ }),
+ );
+
it.effect("strips inherited service-launcher context", () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
diff --git a/scripts/dev-runner.ts b/scripts/dev-runner.ts
index ff09a66e9da..e655e34e26a 100644
--- a/scripts/dev-runner.ts
+++ b/scripts/dev-runner.ts
@@ -344,6 +344,10 @@ export const createDevRunnerEnv = Effect.fn("dev-runner.createDevRunnerEnv")(fun
delete output.T3_SERVICE_LAUNCHER_CONTEXT;
delete output.T3_BOOT_SERVICE_UNIT;
+ // Each worktree has its own state, so a dev server would count as a new
+ // install of the developer's real accounts. Set it explicitly to opt in.
+ output.T3CODE_TELEMETRY_ENABLED = baseEnv.T3CODE_TELEMETRY_ENABLED ?? "false";
+
if (!isDesktopMode) {
output.T3CODE_PORT = String(serverPort);
// HOST is Vite's own bind address, and the desktop branch below is the
diff --git a/scripts/smoke-cli-archive.ts b/scripts/smoke-cli-archive.ts
index 7c994153469..de5a6bec4ae 100644
--- a/scripts/smoke-cli-archive.ts
+++ b/scripts/smoke-cli-archive.ts
@@ -134,6 +134,9 @@ const smokeCliArchive = Effect.fn("smokeCliArchive")(function* (input: {
TMPDIR: scratch,
TEMP: scratch,
T3CODE_HOME: home,
+ // The archive has a release channel built in, so its events would
+ // look like a real new install.
+ T3CODE_TELEMETRY_ENABLED: "false",
},
extendEnv: false,
},