TypeScript
feat(server): count how guest sharing gets used (#24996)
Theo Browne3e9d97ae1f7c
diff --git a/apps/server/src/guest/GuestShareService.test.ts b/apps/server/src/guest/GuestShareService.test.tsindex 97cbae14e9e..adf083a79aa 100644--- a/apps/server/src/guest/GuestShareService.test.ts+++ b/apps/server/src/guest/GuestShareService.test.ts@@ -13,6 +13,7 @@ import {ThreadId,TurnItemId,} from "@t3tools/contracts";+import * as Context from "effect/Context";import * as DateTime from "effect/DateTime";import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";import * as Effect from "effect/Effect";@@ -47,6 +48,7 @@ import * as ResourceCleanupService from "../orchestration-v2/ResourceCleanupServimport * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";import * as ProviderRegistry from "../provider/ProviderRegistry.ts";import * as ServerSettings from "../serverSettings.ts";+import * as AnalyticsService from "../telemetry/AnalyticsService.ts";import * as GuestShareService from "./GuestShareService.ts";const instanceId = ProviderInstanceId.make("codex");@@ -104,6 +106,26 @@ const layerCleanup = Layer.effect(};}),).pipe(Layer.provide(layerConfig), Layer.provide(NodeServices.layer));+class RecordedAnalytics extends Context.Service<+ RecordedAnalytics,+ Ref.Ref<ReadonlyArray<Readonly<Record<string, unknown>>>>+>()("t3/guest/GuestShareService.test/RecordedAnalytics") {}+const layerAnalytics = Layer.effectContext(+ Effect.gen(function* () {+ const recorded = yield* Ref.make<ReadonlyArray<Readonly<Record<string, unknown>>>>([]);+ return Context.make(RecordedAnalytics, recorded).pipe(+ Context.add(+ AnalyticsService.AnalyticsService,+ AnalyticsService.AnalyticsService.of({+ record: (event, properties) =>+ Ref.update(recorded, (events) => [...events, { event, ...properties }]),+ flush: Effect.void,+ recordOwners: () => Effect.void,+ }),+ ),+ );+ }),+);const layerTest = GuestShareService.layer.pipe(Layer.provideMerge(CommandOutputHub.layer.pipe(@@ -113,6 +135,7 @@ const layerTest = GuestShareService.layer.pipe(Layer.provide(layerProviders),Layer.provideMerge(ServerSettings.layerTest({ guestSharingEnabled: true })),Layer.provide(layerConnect),+ Layer.provideMerge(layerAnalytics),Layer.provide(ServerSecretStore.layer),Layer.provideMerge(layerConfig),Layer.provideMerge(NodeServices.layer),@@ -172,6 +195,18 @@ it.effect("spends an invite once and ends the guest stream when the owner stops}).pipe(Effect.provide(layerTest)),);+it.effect("counts a guest joining and sending, without their name or text", () =>+ Effect.gen(function* () {+ const { guestShares, credential } = yield* shareThread;+ const { token: session, shareId } = yield* guestShares.redeem({ credential, name: "Sam" });+ yield* guestShares.submit(session, { shareId, text: "Hello" }, []);+ assert.deepEqual(yield* Ref.get(yield* RecordedAnalytics), [+ { event: "feature.used", feature: "guest_share.join" },+ { event: "feature.used", feature: "guest_message.submit", variant: "text_only" },+ ]);+ }).pipe(Effect.provide(layerTest)),+);+it.effect("streams the owner's thread events after the share and a snapshot", () =>Effect.gen(function* () {const { orchestrator, guestShares, credential } = yield* shareThread;diff --git a/apps/server/src/guest/GuestShareService.ts b/apps/server/src/guest/GuestShareService.tsindex 99d1ff3b56b..1f65217e452 100644--- a/apps/server/src/guest/GuestShareService.ts+++ b/apps/server/src/guest/GuestShareService.ts@@ -58,6 +58,7 @@ import {} from "../orchestration-v2/WireProjection.ts";import * as ProviderRegistry from "../provider/ProviderRegistry.ts";import * as ServerSettings from "../serverSettings.ts";+import * as AnalyticsService from "../telemetry/AnalyticsService.ts";import { guestShareView, guestThreadModel } from "./guestView.ts";import {classifyGuestUploads,@@ -215,6 +216,7 @@ const make = Effect.gen(function* () {const fileSystem = yield* FileSystem.FileSystem;const crypto = yield* Crypto.Crypto;const secretStore = yield* ServerSecretStore.ServerSecretStore;+ const analytics = yield* AnalyticsService.AnalyticsService;const signingKey = yield* Effect.cached(secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(Effect.orDie),);@@ -357,6 +359,8 @@ const make = Effect.gen(function* () {shareId: share.id,guestName: request.name,});+ // Guests have no client connection, so their events carry no surface.+ yield* analytics.record("feature.used", { feature: "guest_share.join" });const token = yield* signSession({ kind: "session", threadId: thread.id, shareId: share.id });return { token, shareId: share.id };});@@ -447,6 +451,10 @@ const make = Effect.gen(function* () {text: request.text,...(attachments.length === 0 ? {} : { attachments }),}).pipe(Effect.onError(() => removeStored(attachments)));+ yield* analytics.record("feature.used", {+ feature: "guest_message.submit",+ variant: attachments.length === 0 ? "text_only" : "with_files",+ });});/** Completes once the session no longer opens its share, so open reads end with it. */diff --git a/apps/server/src/telemetry/FeatureUsage.test.ts b/apps/server/src/telemetry/FeatureUsage.test.tsindex 784eb670a20..9eac0b7ab7b 100644--- a/apps/server/src/telemetry/FeatureUsage.test.ts+++ b/apps/server/src/telemetry/FeatureUsage.test.ts@@ -67,3 +67,33 @@ it("reads RPC variants from enums, never from paths or text", () => {feature: "terminal.open",});});++it("counts the owner's guest share actions, and only guest message sends", () => {+ const send = (guestMessageId?: string) =>+ commandFeatureUsage(+ command({+ ...ids,+ type: "message.dispatch",+ messageId: "message-private",+ text: "secret prompt",+ attachments: [],+ createdBy: "user",+ creationSource: "web",+ dispatchMode: { type: "start_immediately" },+ ...(guestMessageId === undefined ? {} : { guestMessageId }),+ }),+ );+ expect(send("guest-message-private")).toEqual({ feature: "guest_message.send" });+ expect(send()).toBe(undefined);+ expect(+ commandFeatureUsage(+ command({ ...ids, type: "thread.guest-message.dismiss", guestMessageId: "guest-private" }),+ ),+ ).toEqual({ feature: "guest_message.dismiss" });+ expect(commandFeatureUsage(command({ ...ids, type: "thread.guest-share.close" }))).toEqual({+ feature: "guest_share.close",+ });+ expect(featureUsage(WS_METHODS.guestShareCreate, { threadId: "thread-private" })).toEqual({+ feature: "guest_share.create",+ });+});diff --git a/apps/server/src/telemetry/FeatureUsage.ts b/apps/server/src/telemetry/FeatureUsage.tsindex d8bcfc2e52d..30d32d67d40 100644--- a/apps/server/src/telemetry/FeatureUsage.ts+++ b/apps/server/src/telemetry/FeatureUsage.ts@@ -14,14 +14,16 @@ const use = (feature: string, variant?: string): FeatureUsage =>variant === undefined ? { feature } : { feature, variant };/**- * Exclude housekeeping and `message.dispatch`, which `client.turn.requested` already counts.- * Record at command dispatch so retries that commit no change do not count twice.+ * Exclude housekeeping. `client.turn.requested` counts every `message.dispatch`; only sending a+ * guest's message is also a feature. Record at command dispatch so retries do not count twice.*/const COMMAND_FEATURES: {readonly [Type in OrchestrationV2Command["type"]]?: (command: Extract<OrchestrationV2Command, { readonly type: Type }>,- ) => FeatureUsage;+ ) => FeatureUsage | undefined;} = {+ "message.dispatch": (command) =>+ command.guestMessageId === undefined ? undefined : { feature: "guest_message.send" },"checkpoint.rollback": (command) => ({feature: "checkpoint.rollback",variant: command.restoreFiles === false ? "conversation_only" : "with_files",@@ -42,6 +44,8 @@ const COMMAND_FEATURES: {"run.interrupt": () => ({ feature: "run.interrupt" }),"queued-message.promote-to-steer": () => ({ feature: "queue.steer" }),"queued-run.edit": () => ({ feature: "queue.edit" }),+ "thread.guest-share.close": () => ({ feature: "guest_share.close" }),+ "thread.guest-message.dismiss": () => ({ feature: "guest_message.dismiss" }),};/**@@ -67,13 +71,14 @@ const METHOD_FEATURES: Readonly<Record<string, (payload: Payload) => FeatureUsag[WS_METHODS.projectCloneStart]: () => ({ feature: "project.clone" }),[WS_METHODS.sourceControlPublishRepository]: () => ({ feature: "repository.publish" }),[WS_METHODS.serverUpsertKeybinding]: () => ({ feature: "keybinding.customize" }),+ [WS_METHODS.guestShareCreate]: () => ({ feature: "guest_share.create" }),};/** 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)+ | ((command: OrchestrationV2Command) => FeatureUsage | undefined)| undefined;return mapping?.(command);}diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex e5ef646a615..032b3aeccad 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -1262,18 +1262,21 @@ export const layerWsRpc = (const analytics = yield* AnalyticsService.AnalyticsService;const originProps = clientAnalyticsProps;const recordClientCommandAnalytics = (command: OrchestrationV2Command) => {- 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);+ return Effect.all(+ [+ command.type === "message.dispatch"+ ? analytics.record("client.turn.requested", originProps)+ : Effect.void,+ usage === undefined+ ? Effect.void+ : analytics.record("feature.used", {+ ...usage,+ ...(originProps.surface === undefined ? {} : { surface: originProps.surface }),+ }),+ ],+ { discard: true },+ ).pipe(Effect.ignore);};const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;const commandOutputHub = yield* CommandOutputHub.CommandOutputHub;diff --git a/docs/internals/product-analytics.md b/docs/internals/product-analytics.mdindex 990e82ff405..3369d5832c4 100644--- a/docs/internals/product-analytics.md+++ b/docs/internals/product-analytics.md@@ -75,7 +75,9 @@ the RPC authorization middleware after the request succeeds; dispatched commandsare recorded by the dispatch handler, which can tell a retry apart.[Feature mapping](../../apps/server/src/telemetry/FeatureUsage.ts) allowliststhe methods and commands, and takes variants only from closed contract enums,-so paths, ids, and text never reach analytics.+so paths, ids, and text never reach analytics. Guests of a shared thread have no+WebSocket connection, so the guest share service records their joins and messages+itself, with no `surface`.Agent tool events report driver kinds, never instance ids: users nameinstances, so an instance id can identify an account or employer.