From 01989691c9b3660b1a0b26e0062dc72919bd0c55 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:00:43 -0500 Subject: [PATCH] fix(telemetry): tighten analytics privacy and add v0.11 feature events --- .../src/app/DesktopCrashReport.test.ts | 12 +- apps/desktop/src/app/DesktopCrashReport.ts | 28 ++- .../src/assistants/AssistantMcpServer.ts | 27 ++- apps/server/src/assistants/AssistantsLive.ts | 22 ++- apps/server/src/device/DeviceService.ts | 124 +++++++----- apps/server/src/mcp/McpDeviceServer.ts | 21 +- apps/server/src/mcp/McpRoomServer.ts | 3 + apps/server/src/mcp/roomToolHandlers.ts | 38 +++- apps/server/src/moves/ThreadMoves.ts | 26 +++ apps/server/src/observability/StallMonitor.ts | 19 ++ .../Layers/ContinueAtResetSweeper.ts | 13 ++ .../orchestration/Layers/GoalWaitReactor.ts | 15 +- .../Layers/ProjectionSnapshotQuery.test.ts | 3 + .../Layers/ProjectionSnapshotQuery.ts | 30 ++- .../Layers/ProviderCommandReactor.ts | 18 +- .../Services/ProjectionSnapshotQuery.ts | 3 + .../src/outsideAgents/McpConnectServer.ts | 27 +-- .../provider/Layers/ProviderService.test.ts | 169 ++++++++++++++++ .../src/provider/Layers/ProviderService.ts | 140 ++++++++++---- .../src/provider/providerMaintenanceRunner.ts | 51 ++++- .../server/src/secrets/AgentSecretRequests.ts | 8 + .../server/src/secrets/SecretScrubber.test.ts | 40 +++- apps/server/src/secrets/SecretScrubber.ts | 46 ++++- apps/server/src/secrets/secretScrubberCore.ts | 7 +- apps/server/src/server.ts | 5 +- apps/server/src/serverRuntimeStartup.test.ts | 85 ++++++++ apps/server/src/serverRuntimeStartup.ts | 72 ++++++- apps/server/src/serverSettings.ts | 3 +- .../src/telemetry/AnalyticsProperties.test.ts | 90 +++++++++ .../src/telemetry/AnalyticsProperties.ts | 58 +++++- .../server/src/telemetry/DailyCounter.test.ts | 116 +++++++++++ apps/server/src/telemetry/DailyCounter.ts | 91 +++++++++ .../telemetry/Layers/AnalyticsService.test.ts | 182 ++++++++++++++++++ .../src/telemetry/Layers/AnalyticsService.ts | 182 +++++++++++++++--- .../telemetry/Services/AnalyticsService.ts | 11 ++ docs/telemetry.md | 95 ++++++--- packages/contracts/src/provider.ts | 6 + 37 files changed, 1690 insertions(+), 196 deletions(-) create mode 100644 apps/server/src/telemetry/DailyCounter.test.ts create mode 100644 apps/server/src/telemetry/DailyCounter.ts diff --git a/apps/desktop/src/app/DesktopCrashReport.test.ts b/apps/desktop/src/app/DesktopCrashReport.test.ts index cc8ef7fb8..003d42cb1 100644 --- a/apps/desktop/src/app/DesktopCrashReport.test.ts +++ b/apps/desktop/src/app/DesktopCrashReport.test.ts @@ -125,13 +125,21 @@ describe("resolveTelemetryConsent", () => { ); }); - it("keeps the default when settings are unreadable", () => { - assert.isTrue( + it("fails closed when an existing settings file is malformed or unreadable", () => { + assert.isFalse( resolveTelemetryConsent({ envOverride: undefined, throwawayRun: false, rawSettingsJson: "not json", }), ); + assert.isFalse( + resolveTelemetryConsent({ + envOverride: undefined, + throwawayRun: false, + rawSettingsJson: undefined, + settingsReadFailed: true, + }), + ); }); }); diff --git a/apps/desktop/src/app/DesktopCrashReport.ts b/apps/desktop/src/app/DesktopCrashReport.ts index 3abd247c5..6403a5caf 100644 --- a/apps/desktop/src/app/DesktopCrashReport.ts +++ b/apps/desktop/src/app/DesktopCrashReport.ts @@ -106,23 +106,25 @@ const decodeServerSettingsJson = Schema.decodeUnknownOption(ServerSettingsJson); * Mirrors the server's telemetry consent: `THREADLINES_TELEMETRY_ENABLED` * wins when set, a throwaway run (CI, or a data folder in the temp folder) * sends nothing, otherwise `usageAnalyticsEnabled` from settings.json decoded - * with the same lenient JSONC parser the server uses, defaulting to enabled - * when the file is absent or undecodable. + * with the same lenient JSONC parser the server uses. A missing file uses the + * default; an unreadable or malformed existing file fails closed. */ export function resolveTelemetryConsent(input: { readonly envOverride: string | undefined; readonly throwawayRun: boolean; readonly rawSettingsJson: string | undefined; + readonly settingsReadFailed?: boolean; }): boolean { const override = parseTelemetryEnabledOverride(input.envOverride); if (override !== undefined) return override; if (input.throwawayRun) return false; + if (input.settingsReadFailed === true) return false; if (input.rawSettingsJson === undefined) { return DEFAULT_SERVER_SETTINGS.usageAnalyticsEnabled; } return Option.match(decodeServerSettingsJson(input.rawSettingsJson), { - onNone: () => DEFAULT_SERVER_SETTINGS.usageAnalyticsEnabled, + onNone: () => false, onSome: (settings) => settings.usageAnalyticsEnabled, }); } @@ -164,9 +166,22 @@ const makeDesktopCrashReport = Effect.gen(function* () { const posthogHost = process.env.THREADLINES_POSTHOG_HOST?.trim() || bundledPosthogHost; if (!posthogKey) return; - const rawSettingsJson = yield* fileSystem + const settingsRead = yield* fileSystem .readFileString(environment.serverSettingsPath) - .pipe(Effect.map(Option.some), Effect.orElseSucceed(Option.none)); + .pipe(Effect.result); + let rawSettingsJson: string | undefined; + let settingsReadFailed = false; + if (settingsRead._tag === "Success") { + rawSettingsJson = settingsRead.success; + } else { + const error = settingsRead.failure; + const isMissing = + typeof error === "object" && + error !== null && + "reason" in error && + (error as { readonly reason?: { readonly _tag?: string } }).reason?._tag === "NotFound"; + settingsReadFailed = !isMissing; + } const realPathOrSelf = (path: string) => fileSystem.realPath(path).pipe(Effect.orElseSucceed(() => path)); const tempDir = NodeOS.tmpdir(); @@ -177,7 +192,8 @@ const makeDesktopCrashReport = Effect.gen(function* () { tempDirs: [tempDir, yield* realPathOrSelf(tempDir)], ciEnv: process.env.CI, }), - rawSettingsJson: Option.getOrUndefined(rawSettingsJson), + rawSettingsJson, + settingsReadFailed, }); if (!consented) return; diff --git a/apps/server/src/assistants/AssistantMcpServer.ts b/apps/server/src/assistants/AssistantMcpServer.ts index ee8970e2c..8e3e42120 100644 --- a/apps/server/src/assistants/AssistantMcpServer.ts +++ b/apps/server/src/assistants/AssistantMcpServer.ts @@ -43,6 +43,7 @@ import { ThreadWaitTool, } from "../outsideAgents/connectTools.ts"; import { OutsideAgentConnections } from "../outsideAgents/OutsideAgentConnections.ts"; +import { makeDailyAnalyticsCounter } from "../telemetry/DailyCounter.ts"; import { AssistantAlerts } from "./AssistantAlerts.ts"; import { type AssistantMcpTool, makeAssistantMcp, mapStrings } from "./AssistantMcp.ts"; import { makeAssistantMcpEvents } from "./assistantMcpEvents.ts"; @@ -172,13 +173,37 @@ export const AssistantMcpServerLive = Layer.effectDiscard( }, }, ]; + const toolCallCounter = yield* makeDailyAnalyticsCounter<{ + readonly tool: string; + readonly outcome: string; + readonly door: "assistant"; + }>({ + event: "outside_agent.tool_calls", + keyOf: ({ tool, outcome }) => `${tool}\u0000${outcome}`, + }); + const countedTools: ReadonlyArray = tools.map((entry) => ({ + ...entry, + run: (caller, parameters) => + Effect.tap(entry.run(caller, parameters), (result) => + Effect.sync(() => { + const outcome = + typeof result === "object" && + result !== null && + "outcome" in result && + typeof (result as { readonly outcome?: unknown }).outcome === "string" + ? (result as { readonly outcome: string }).outcome + : "ok"; + toolCallCounter.increment({ tool: entry.tool.name, outcome, door: "assistant" }); + }), + ), + })); const handler = makeAssistantMcp({ authenticate: assistants.authenticate, listed: (caller) => connections .grant(caller.connectionId) .pipe(Effect.map((grant) => listedToolsFor(grant?.access ?? null))), - tools, + tools: countedTools, events: makeAssistantMcpEvents({ alerts, grantOf: connections.grant, diff --git a/apps/server/src/assistants/AssistantsLive.ts b/apps/server/src/assistants/AssistantsLive.ts index e1e3aadb3..457ba2d2a 100644 --- a/apps/server/src/assistants/AssistantsLive.ts +++ b/apps/server/src/assistants/AssistantsLive.ts @@ -76,6 +76,7 @@ import { SERVER_SIGNING_SECRET_NAME, } from "../auth/Layers/SessionCredentialService.ts"; import { ServerSecretStore } from "../auth/Services/ServerSecretStore.ts"; +import { AnalyticsService } from "../telemetry/Services/AnalyticsService.ts"; import { makeKeyedLock } from "../links/keyedLock.ts"; import { assistantOfRow, @@ -213,6 +214,7 @@ const frameBytes = (frame: unknown) => Buffer.byteLength(JSON.stringify(frame), export const makeAssistants = Effect.gen(function* () { const relay = yield* AssistantRelay; const repository = yield* OutsideAgentConnectionRepository; + const analytics = yield* Effect.serviceOption(AnalyticsService); const reviewComputer = yield* Config.Boolean(ASSISTANT_REVIEW_COMPUTER_ENV).pipe( Config.withDefault(false), Effect.orElseSucceed(() => false), @@ -778,11 +780,12 @@ export const makeAssistants = Effect.gen(function* () { identity: identityOf(entry.signIn), clientName: entry.name, }; + const assistant = assistantOfRow(shown); return { connectionId, name: connectionNameOf(shown), givenName: connectionNameOf(shown) === entry.name ? null : entry.name, - assistant: assistantOfRow(shown), + assistant, kind: "assistant", signIn: "oauth", identity: shown.identity, @@ -884,8 +887,16 @@ export const makeAssistants = Effect.gen(function* () { ); yield* notify; yield* recountConnections; + const connection = connectionOfRow(row); + if (Option.isSome(analytics)) { + yield* analytics.value.record("assistant.connected", { + assistant: connection.assistant ?? "other", + signIn: "key", + access: row.access, + }); + } return { - connection: connectionOfRow(row), + connection, key: formatAssistantCredential({ kind: "key", route, secret }), address: door.address, }; @@ -989,6 +1000,13 @@ export const makeAssistants = Effect.gen(function* () { yield* notify; // The one it replaced is revoked at the relay. yield* connectionsChanged; + if (Option.isSome(analytics)) { + yield* analytics.value.record("assistant.connected", { + assistant: assistantOfRow(row) ?? "other", + signIn: "oauth", + access: row.access, + }); + } return tokensFor(row, issued.route, 0, now); }); diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.ts index ddb7202ac..938f0cf53 100644 --- a/apps/server/src/device/DeviceService.ts +++ b/apps/server/src/device/DeviceService.ts @@ -33,6 +33,7 @@ import { type DeviceSummary, type ThreadId, } from "@threadlines/contracts"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -51,6 +52,7 @@ import * as SynchronizedRef from "effect/SynchronizedRef"; import { writeFileStringAtomically } from "../atomicWrite.ts"; import { ServerConfig } from "../config.ts"; import { ServerSettingsService } from "../serverSettings.ts"; +import { AnalyticsService } from "../telemetry/Services/AnalyticsService.ts"; import { agentDeviceLauncherKey, bindAgentDeviceLauncher, @@ -169,6 +171,7 @@ export const make = Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const scope = yield* Scope.Scope; + const analytics = yield* Effect.serviceOption(AnalyticsService); const stateDir = config.stateDir; const claimsPath = path.join(deviceStateDir(path, stateDir), "claims.json"); const services = (effect: Effect.Effect) => @@ -454,55 +457,82 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`, const open: DeviceServiceShape["open"] = (input, openedBy = "user") => Effect.gen(function* () { - const releasesAtStart = releaseCounts.get(input.threadId) ?? 0; - yield* ensurePlatform(input.platform); - const ready = yield* readiness; - let state = yield* refresh(ready); - let device = findDevice(state, input.deviceId); - if (!device) return yield* new DeviceNotFoundError({ deviceId: input.deviceId }); - if (device.platform === "android" && !device.physical) yield* requireAndroidVideo(ready); - let bootedNow = false; - if (!device.booted && input.boot !== false) { - const booting = { ...device, threadId: input.threadId }; - yield* publish((current) => ({ - ...current, - bootingDevices: [ - ...current.bootingDevices.filter((entry) => entry.id !== booting.id), - booting, - ], - })); - const bootedId = yield* ready.devices.boot(device).pipe( - Effect.ensuring( - publish((current) => ({ - ...current, - bootingDevices: current.bootingDevices.filter((entry) => entry.id !== booting.id), - })), - ), - ); - bootedNow = true; - state = yield* refresh(ready); - // Retained entries predate the boot, so only a complete listing confirms the booted device. - device = state.incompletePlatforms.includes(device.platform) - ? undefined - : (findDevice(state, bootedId) ?? findDevice(state, device.id)); + const startedNanos = yield* Clock.monotonicTimeNanos; + const elapsedMs = Clock.monotonicTimeNanos.pipe( + Effect.map((now) => Math.max(0, Math.round(Number(now - startedNanos) / 1_000_000))), + ); + const recordAnalytics = (event: string, properties: Readonly>) => + Option.isSome(analytics) ? analytics.value.record(event, properties) : Effect.void; + + return yield* Effect.gen(function* () { + const releasesAtStart = releaseCounts.get(input.threadId) ?? 0; + yield* ensurePlatform(input.platform); + const ready = yield* readiness; + let state = yield* refresh(ready); + let device = findDevice(state, input.deviceId); if (!device) return yield* new DeviceNotFoundError({ deviceId: input.deviceId }); - } else if (device.booted) { - yield* ready.devices.attach(device); - } - const opened = device; - const earlier = (yield* currentState).sessions.find( - (session) => session.deviceId === opened.id && session.bootedByThreadlines, + if (device.platform === "android" && !device.physical) yield* requireAndroidVideo(ready); + let bootedNow = false; + if (!device.booted && input.boot !== false) { + const booting = { ...device, threadId: input.threadId }; + yield* publish((current) => ({ + ...current, + bootingDevices: [ + ...current.bootingDevices.filter((entry) => entry.id !== booting.id), + booting, + ], + })); + const bootedId = yield* ready.devices.boot(device).pipe( + Effect.ensuring( + publish((current) => ({ + ...current, + bootingDevices: current.bootingDevices.filter((entry) => entry.id !== booting.id), + })), + ), + ); + bootedNow = true; + state = yield* refresh(ready); + // Retained entries predate the boot, so only a complete listing confirms the booted device. + device = state.incompletePlatforms.includes(device.platform) + ? undefined + : (findDevice(state, bootedId) ?? findDevice(state, device.id)); + if (!device) return yield* new DeviceNotFoundError({ deviceId: input.deviceId }); + } else if (device.booted) { + yield* ready.devices.attach(device); + } + const opened = device; + const earlier = (yield* currentState).sessions.find( + (session) => session.deviceId === opened.id && session.bootedByThreadlines, + ); + const session: DeviceSession = { + threadId: input.threadId, + deviceId: opened.id, + platform: opened.platform, + openedAt: DateTime.formatIso(yield* DateTime.now), + bootedByThreadlines: bootedNow || earlier !== undefined, + openedBy, + }; + yield* recordSession(session, releasesAtStart); + yield* recordAnalytics("device.session.opened", { + devicePlatform: opened.platform, + openedBy, + bootedNow, + physical: opened.physical, + durationMs: yield* elapsedMs, + }); + return session; + }).pipe( + Effect.tapError((error) => + Effect.flatMap(elapsedMs, (durationMs) => + recordAnalytics("device.session.open_failed", { + devicePlatform: input.platform, + openedBy, + errorKind: error._tag, + durationMs, + }), + ), + ), ); - const session: DeviceSession = { - threadId: input.threadId, - deviceId: opened.id, - platform: opened.platform, - openedAt: DateTime.formatIso(yield* DateTime.now), - bootedByThreadlines: bootedNow || earlier !== undefined, - openedBy, - }; - yield* recordSession(session, releasesAtStart); - return session; }).pipe(Effect.withSpan("DeviceService.open")); /** Removes launchers whose session is gone. Under the launcher lock, so binding never races it. */ diff --git a/apps/server/src/mcp/McpDeviceServer.ts b/apps/server/src/mcp/McpDeviceServer.ts index fe9a1805a..9548c6f07 100644 --- a/apps/server/src/mcp/McpDeviceServer.ts +++ b/apps/server/src/mcp/McpDeviceServer.ts @@ -22,6 +22,7 @@ import { McpProtocol, McpSchema, McpServer, Tool } from "effect/ai"; import { HttpRouter, HttpServerRequest, type HttpServerResponse } from "effect/http"; import { DeviceService } from "../device/DeviceService.ts"; +import { makeDailyAnalyticsCounter } from "../telemetry/DailyCounter.ts"; import { deviceClose, deviceList, deviceOpen, deviceScreenshot } from "./deviceToolHandlers.ts"; import { makeOutsideToolLimits } from "./outsideToolLimit.ts"; import { @@ -209,6 +210,14 @@ const registerDeviceTools = Effect.fn("McpDeviceServer.registerDeviceTools")(fun ), }; + const toolCallCounter = yield* makeDailyAnalyticsCounter<{ + readonly tool: string; + readonly outcome: "ok" | "error"; + }>({ + event: "device.tool_calls", + keyOf: ({ tool, outcome }) => `${tool}\u0000${outcome}`, + }); + for (const tool of DEVICE_TOOLS) { const handle = handlers[tool.name]!; yield* server.addTool({ @@ -216,7 +225,17 @@ const registerDeviceTools = Effect.fn("McpDeviceServer.registerDeviceTools")(fun annotations: tool.annotations, handle: (payload) => Effect.withFiber((fiber) => - handle(callerOf(fiber), payload).pipe(Effect.provideService(DeviceService, devices)), + handle(callerOf(fiber), payload).pipe( + Effect.provideService(DeviceService, devices), + Effect.tap((result) => + Effect.sync(() => { + toolCallCounter.increment({ + tool: tool.name, + outcome: result.isError === true ? "error" : "ok", + }); + }), + ), + ), ), }); } diff --git a/apps/server/src/mcp/McpRoomServer.ts b/apps/server/src/mcp/McpRoomServer.ts index 40fe33f73..c89ab1c2c 100644 --- a/apps/server/src/mcp/McpRoomServer.ts +++ b/apps/server/src/mcp/McpRoomServer.ts @@ -65,6 +65,7 @@ import { type McpInvocationScope, mcpSessionRegistry } from "./McpSessionRegistr import { limitReaches, makeOutsideToolLimits, outsideLimitDetail } from "./outsideToolLimit.ts"; import { makeRoomRequestRegistry } from "./roomRequests.ts"; import { makeRoomToolHandlers } from "./roomToolHandlers.ts"; +import { AnalyticsService } from "../telemetry/Services/AnalyticsService.ts"; import { McpRoomInvocation, RoomToolkit } from "./roomTools.ts"; import { makeGuideToolHandler } from "./guideToolHandlers.ts"; import { GuideToolkit } from "./guideTools.ts"; @@ -245,6 +246,7 @@ const RoomToolHandlersLive = RoomEndpointToolkit.toLayer( return model?.shortName ?? model?.name ?? selection.model; }), ); + const analytics = yield* Effect.serviceOption(AnalyticsService); const handlers = makeRoomToolHandlers({ engine, readThread, @@ -278,6 +280,7 @@ const RoomToolHandlersLive = RoomEndpointToolkit.toLayer( ), git, requests, + ...(Option.isSome(analytics) ? { recordAnalytics: analytics.value.record } : {}), }); // Scheduled tasks, when this server has them (docs/design/fleet.md, Part 6). const scheduledTasks = yield* Effect.serviceOption(ScheduledTasks); diff --git a/apps/server/src/mcp/roomToolHandlers.ts b/apps/server/src/mcp/roomToolHandlers.ts index 9d0ec6c31..efef6a2e1 100644 --- a/apps/server/src/mcp/roomToolHandlers.ts +++ b/apps/server/src/mcp/roomToolHandlers.ts @@ -174,6 +174,10 @@ export interface RoomToolDeps { readonly invitesMode: Effect.Effect; readonly git: Pick; readonly requests: RoomRequestRegistry; + readonly recordAnalytics?: ( + event: string, + properties?: Readonly>, + ) => Effect.Effect; } interface Room { @@ -675,13 +679,23 @@ export function makeRoomToolHandlers(deps: RoomToolDeps) { readonly abandoned: Effect.Effect; /** A review asked of several agents: its batch, and the basis captured once for all. */ readonly batch?: { readonly batchId: RoomAgentBatchId; readonly reviewInput: RoomReviewInput }; + readonly onSubmitSettled?: (submitted: boolean) => Effect.Effect; }) => Effect.scoped( Effect.gen(function* () { const { scope, kind, arrival } = input; + let submitSettled = false; + const settleSubmit = (didSubmit: boolean) => + Effect.suspend(() => { + if (submitSettled) return Effect.void; + submitSettled = true; + return input.onSubmitSettled?.(didSubmit) ?? Effect.void; + }); + yield* Effect.addFinalizer(() => settleSubmit(false)); const base = { agent: agentLabel(arrival.target) }; const refusal = precheck(scope, kind, arrival, input.batch?.batchId); if (refusal !== null) { + yield* settleSubmit(false); return { ...base, outcome: refusal.outcome, @@ -689,6 +703,7 @@ export function makeRoomToolHandlers(deps: RoomToolDeps) { } satisfies RoomAnswerResult; } if (!(yield* canAnswerOnTheSide(arrival.target))) { + yield* settleSubmit(false); return { ...base, outcome: "refused", @@ -788,7 +803,7 @@ export function makeRoomToolHandlers(deps: RoomToolDeps) { Effect.tap((rejection) => Effect.sync(() => { submitted = rejection === undefined; - }), + }).pipe(Effect.andThen(settleSubmit(rejection === undefined))), ), Effect.uninterruptible, ); @@ -799,8 +814,12 @@ export function makeRoomToolHandlers(deps: RoomToolDeps) { const sent = yield* Effect.raceFirst(send, callEnds); if (typeof sent === "object") { + yield* settleSubmit(false); return sent; } + if (sent !== "sent") { + yield* settleSubmit(false); + } const what = kind === "review" ? "review" : "answer"; let ending: "timeout" | "abandoned"; if (sent === "sent") { @@ -1009,6 +1028,22 @@ export function makeRoomToolHandlers(deps: RoomToolDeps) { batchId: RoomAgentBatchId.make(randomUUID()), reviewInput: captured.success, }; + const recordAnalytics = deps.recordAnalytics; + let remainingSubmissions = arrivals.length; + let startedReviewers = 0; + const onSubmitSettled = + arrivals.length >= 2 && recordAnalytics !== undefined + ? (didSubmit: boolean) => + Effect.suspend(() => { + if (didSubmit) startedReviewers += 1; + remainingSubmissions -= 1; + return remainingSubmissions === 0 && startedReviewers >= 2 + ? recordAnalytics("room.council_review.started", { + reviewerCount: startedReviewers, + }) + : Effect.void; + }) + : undefined; const reviews = yield* Effect.forEach( arrivals, (arrival) => @@ -1020,6 +1055,7 @@ export function makeRoomToolHandlers(deps: RoomToolDeps) { basis: input.basis, abandoned, batch, + ...(onSubmitSettled !== undefined ? { onSubmitSettled } : {}), }), { concurrency: "unbounded" }, ); diff --git a/apps/server/src/moves/ThreadMoves.ts b/apps/server/src/moves/ThreadMoves.ts index 34e407358..b757b93fb 100644 --- a/apps/server/src/moves/ThreadMoves.ts +++ b/apps/server/src/moves/ThreadMoves.ts @@ -64,6 +64,7 @@ import * as Stream from "effect/Stream"; import { ServerConfig } from "../config.ts"; import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts"; +import { AnalyticsService } from "../telemetry/Services/AnalyticsService.ts"; import { ComputerLinkClient, type PeerClient } from "../links/ComputerLinkClient.ts"; import { ComputerLinkRepository, isUsableLink } from "../links/ComputerLinkRepository.ts"; import { generalChatThreadScratchCwd } from "../orchestration/generalChats.ts"; @@ -729,6 +730,7 @@ const make = Effect.gen(function* () { const environment = yield* ServerEnvironment; const providers = yield* ProviderService; const actionGate = yield* ThreadActionGate; + const analytics = yield* Effect.serviceOption(AnalyticsService); const descriptor = yield* environment.getDescriptor; const moveDir = (transferId: string) => NodePath.join(config.stateDir, "moves", transferId); @@ -1366,6 +1368,10 @@ const make = Effect.gen(function* () { : "final" }`, ); + const beforeMove = + step.kind !== "progress" && Option.isSome(analytics) + ? yield* currentMove(threadId, transferId).pipe(Effect.orElseSucceed(() => null)) + : null; const dispatched = engine.dispatch( step.kind === "progress" ? { @@ -1412,6 +1418,26 @@ const make = Effect.gen(function* () { () => new ThreadMoveFailure({ reason: "The move's outcome couldn't be recorded." }), ), ); + if (step.kind !== "progress" && beforeMove !== null && Option.isSome(analytics)) { + const startedMs = beforeMove ? Date.parse(beforeMove.startedAt) : Number.NaN; + const finishedMs = Date.parse(createdAt); + const durationMs = + Number.isFinite(startedMs) && Number.isFinite(finishedMs) + ? Math.max(0, finishedMs - startedMs) + : undefined; + yield* analytics.value.record("thread.move.finished", { + outcome: step.kind === "complete" ? "completed" : "aborted", + ...(step.kind === "abort" + ? { abortCode: step.code } + : { keptParent: step.keptParent, adoptedCount: step.adopted.length }), + isRoom: (beforeMove?.roomAgents?.length ?? 0) > 0, + isFamily: beforeMove?.family !== undefined, + isBatch: beforeMove?.batchId !== undefined, + queued: beforeMove?.queuedRequestId !== undefined, + interruptedWork: beforeMove?.interrupted !== undefined, + ...(durationMs !== undefined ? { durationMs } : {}), + }); + } }); /** diff --git a/apps/server/src/observability/StallMonitor.ts b/apps/server/src/observability/StallMonitor.ts index 8dd349160..05c6f28a7 100644 --- a/apps/server/src/observability/StallMonitor.ts +++ b/apps/server/src/observability/StallMonitor.ts @@ -57,6 +57,11 @@ import * as Schedule from "effect/Schedule"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; +import { + type AnalyticsStallDurationBucket, + stallDurationBucket, +} from "../telemetry/AnalyticsProperties.ts"; +import { makeDailyAnalyticsCounter } from "../telemetry/DailyCounter.ts"; import { readDatabaseCallMs } from "./databaseCallTime.ts"; /** How often the clocks are read. */ @@ -284,6 +289,15 @@ export class StallMonitor extends Context.Service({ + event: "server.stall", + keyOf: ({ cause, durationBucket, heldByDatabase }) => + `${cause}\u0000${durationBucket}\u0000${heldByDatabase}`, + }); const runId = randomUUID().slice(0, 8); let sequence = 0; const latest = yield* SubscriptionRef.make>(Option.none()); @@ -313,6 +327,11 @@ const make = Effect.gen(function* () { // and what clients are told never wait on it. const record = (stall: RecordedStall) => Effect.gen(function* () { + stallCounter.increment({ + cause: stall.cause, + durationBucket: stallDurationBucket(stall.durationMs), + heldByDatabase: stall.databaseMs !== undefined, + }); if (stall.cause === "overloaded" || stall.cause === "unknown") { yield* Effect.forkIn( Effect.flatMap(readTopProcesses, (top) => logStall(stall, top)), diff --git a/apps/server/src/orchestration/Layers/ContinueAtResetSweeper.ts b/apps/server/src/orchestration/Layers/ContinueAtResetSweeper.ts index 4a983dc53..b83283620 100644 --- a/apps/server/src/orchestration/Layers/ContinueAtResetSweeper.ts +++ b/apps/server/src/orchestration/Layers/ContinueAtResetSweeper.ts @@ -11,6 +11,7 @@ import * as Clock from "effect/Clock"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Schedule from "effect/Schedule"; import * as Semaphore from "effect/Semaphore"; @@ -21,6 +22,7 @@ import { import { SystemWake } from "../../power/Services/SystemWake.ts"; import { freshOrCurrentSnapshot } from "../../provider/freshProviderSnapshot.ts"; import { ProviderRegistry } from "../../provider/Services/ProviderRegistry.ts"; +import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts"; import { ContinueAtResetSweeper, type ContinueAtResetSweeperShape, @@ -64,6 +66,7 @@ const makeContinueAtResetSweeper = (options?: ContinueAtResetSweeperLiveOptions) const providerRegistry = yield* ProviderRegistry; const orchestrationEngine = yield* OrchestrationEngineService; const systemWake = yield* SystemWake; + const analytics = yield* Effect.serviceOption(AnalyticsService); // The interval and `sweepNow` must not both continue one thread. const sweepSemaphore = yield* Semaphore.make(1); /** @@ -215,6 +218,11 @@ const makeContinueAtResetSweeper = (options?: ContinueAtResetSweeperLiveOptions) yield* Effect.logInfo("thread.continue-at-reset.continued-early", { threadId: entry.threadId, }); + if (Option.isSome(analytics)) { + yield* analytics.value.record("provider.turn.usage_limit_continued", { + early: true, + }); + } return true; }).pipe( Effect.catchCause((cause) => @@ -281,6 +289,11 @@ const makeContinueAtResetSweeper = (options?: ContinueAtResetSweeperLiveOptions) createdAt, }); yield* Effect.logInfo("thread.continue-at-reset.continued", { threadId: entry.threadId }); + if (Option.isSome(analytics)) { + yield* analytics.value.record("provider.turn.usage_limit_continued", { + early: false, + }); + } return true; }).pipe( Effect.catchCause((cause) => diff --git a/apps/server/src/orchestration/Layers/GoalWaitReactor.ts b/apps/server/src/orchestration/Layers/GoalWaitReactor.ts index bb03a8d6b..55bb0ab21 100644 --- a/apps/server/src/orchestration/Layers/GoalWaitReactor.ts +++ b/apps/server/src/orchestration/Layers/GoalWaitReactor.ts @@ -18,6 +18,7 @@ import * as Stream from "effect/Stream"; import { ProviderService } from "../../provider/Services/ProviderService.ts"; import { ScheduledTasks } from "../../scheduled/ScheduledTasks.ts"; +import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts"; import { GoalWaitReactor, type GoalWaitReactorShape } from "../Services/GoalWaitReactor.ts"; import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; @@ -75,6 +76,7 @@ export const make = Effect.gen(function* () { const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; const providerService = yield* ProviderService; const scheduledTasks = yield* Effect.serviceOption(ScheduledTasks); + const analytics = yield* Effect.serviceOption(AnalyticsService); const scheduleWaiting = Option.isSome(scheduledTasks) ? scheduledTasks.value.waitingThreadIds @@ -122,7 +124,7 @@ export const make = Effect.gen(function* () { // Forgetting a mark sends the provider nothing; a pause or resume needs // a provider that has one. if (step === null || (step.send !== null && !(yield* canPauseGoal(thread)))) return; - yield* orchestrationEngine + const dispatched = yield* orchestrationEngine .dispatch({ type: "thread.goal.wait.sync", commandId: CommandId.make(`goal-wait-sync:${threadId}:${randomUUID()}`), @@ -133,11 +135,18 @@ export const make = Effect.gen(function* () { createdAt: yield* nowIso, }) .pipe( - Effect.asVoid, + Effect.as(true), Effect.catchCause((cause) => - Effect.logWarning("goal wait sync failed", { threadId, cause: Cause.pretty(cause) }), + Effect.logWarning("goal wait sync failed", { threadId, cause: Cause.pretty(cause) }).pipe( + Effect.as(false), + ), ), ); + if (dispatched && step.send !== null && Option.isSome(analytics)) { + yield* analytics.value.record("provider.goal.wait_sync", { + action: step.send, + }); + } }); // A thread already queued is looked at once, read as it stands then; the diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts index 359f1a4c2..0908c7d78 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts @@ -997,6 +997,9 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { assert.deepEqual(counts, { projectCount: 2, threadCount: 3, + leadChatCount: 0, + projectsWithBriefCount: 0, + projectNoteCount: 0, }); const project = yield* snapshotQuery.getActiveProjectByWorkspaceRoot("/tmp/workspace"); diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 9020410c7..e97f0187b 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -433,6 +433,9 @@ const ProjectionStateDbRowSchema = ProjectionState; const ProjectionCountsRowSchema = Schema.Struct({ projectCount: Schema.Number, threadCount: Schema.Number, + leadChatCount: Schema.Number, + projectsWithBriefCount: Schema.Number, + projectNoteCount: Schema.Number, }); const WorkspaceRootLookupInput = Schema.Struct({ workspaceRoot: Schema.String, @@ -1867,7 +1870,29 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { sql` SELECT (SELECT COUNT(*) FROM projection_projects) AS "projectCount", - (SELECT COUNT(*) FROM projection_threads) AS "threadCount" + (SELECT COUNT(*) FROM projection_threads) AS "threadCount", + ( + SELECT COUNT(*) + FROM projection_projects p + INNER JOIN projection_threads lead + ON lead.thread_id = p.lead_thread_id + AND lead.project_id = p.project_id + AND lead.archived_at IS NULL + AND lead.deleted_at IS NULL + WHERE p.deleted_at IS NULL + ) AS "leadChatCount", + ( + SELECT COUNT(*) + FROM project_briefs b + INNER JOIN projection_projects p ON p.project_id = b.project_id + WHERE p.deleted_at IS NULL AND TRIM(b.text) != '' + ) AS "projectsWithBriefCount", + ( + SELECT COUNT(*) + FROM project_notes n + INNER JOIN projection_projects p ON p.project_id = n.project_id + WHERE p.deleted_at IS NULL + ) AS "projectNoteCount" `, }); @@ -3597,6 +3622,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { Effect.map((row): ProjectionSnapshotCounts => ({ projectCount: row.projectCount, threadCount: row.threadCount, + leadChatCount: row.leadChatCount, + projectsWithBriefCount: row.projectsWithBriefCount, + projectNoteCount: row.projectNoteCount, })), ); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 4ae3b1b16..f4f6a0d92 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -116,6 +116,7 @@ import { makeSessionLaunchGenerations, withoutLaunchMark } from "../sessionLaunc import { buildIndependentReviewPrompt } from "../roomReviewPrompt.ts"; import { messageSentFromNote, previousMessageSentFrom } from "../messageSentFrom.ts"; import { turnMessageOrigin } from "../turnOrigin.ts"; +import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts"; import { agentMessageFrame, buildRoomCatchUp } from "../roomCatchUp.ts"; import { isContinueTrigger, latestTurnStartFor } from "../continueTurns.ts"; @@ -625,6 +626,7 @@ const make = Effect.gen(function* () { const vcsStatusBroadcaster = yield* VcsStatusBroadcaster; const textGeneration = yield* TextGeneration; const serverSettingsService = yield* ServerSettingsService; + const analytics = yield* Effect.serviceOption(AnalyticsService); // Absent on a CLI-only server, which has no agents to bring in. const providerRegistry = yield* Effect.serviceOption(ProviderRegistry); const fileSystem = yield* FileSystem.FileSystem; @@ -3806,6 +3808,7 @@ const make = Effect.gen(function* () { ...turnRequest, requestedAt, origin, + lane: "main", // Its sender reads the reply here: Codex suggests their next message. ...(origin === "person" ? { suggestNextMessage: true } : {}), ...(resend !== undefined ? { resend } : {}), @@ -6783,6 +6786,7 @@ const make = Effect.gen(function* () { ...(deviceNote !== undefined ? { deviceNote } : {}), modelSelection, interactionMode: "default", + lane: isReview ? "side_review" : "side", origin: turnMessageOrigin({ message: question, askedByAgent: sideTurn.askedBy !== undefined, @@ -6906,7 +6910,13 @@ const make = Effect.gen(function* () { const processSideTurnSettled = Effect.fn("processSideTurnSettled")(function* ( event: Extract, ) { - const { threadId, sideTurnId, participantId } = event.payload; + const { threadId, sideTurnId, participantId, outcome, error } = event.payload; + if (Option.isSome(analytics)) { + yield* analytics.value.record("room.side_turn.settled", { + outcome, + timedOut: error === "it ran for 30 minutes and was stopped.", + }); + } yield* stopSideRuntime(threadId, { sideTurnId, participantId }).pipe(Effect.forkScoped); // Only the agent the message waits for: another agent's answer ending // releases nothing. @@ -7461,6 +7471,12 @@ const make = Effect.gen(function* () { Effect.map((settings) => settings.continueAfterRestart), Effect.orElseSucceed(() => false), ); + if (Option.isSome(analytics)) { + yield* analytics.value.record("provider.turn.restart_recovery", { + count: cut.length, + continueAfterRestart: settingOn, + }); + } for (const { threadId, turnId, participantId, waitingOnUser } of cut) { const createdAt = yield* nowIso; yield* orchestrationEngine diff --git a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts index 15983074b..15820896a 100644 --- a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts @@ -38,6 +38,9 @@ import type { ProjectionRepositoryError } from "../../persistence/Errors.ts"; export interface ProjectionSnapshotCounts { readonly projectCount: number; readonly threadCount: number; + readonly leadChatCount?: number; + readonly projectsWithBriefCount?: number; + readonly projectNoteCount?: number; } export interface ProjectionSnapshotSequence { diff --git a/apps/server/src/outsideAgents/McpConnectServer.ts b/apps/server/src/outsideAgents/McpConnectServer.ts index 7477ecd19..06e283e73 100644 --- a/apps/server/src/outsideAgents/McpConnectServer.ts +++ b/apps/server/src/outsideAgents/McpConnectServer.ts @@ -17,10 +17,8 @@ * `tools/list` shows what the connection's live grant allows, read again at * every listing; every handler checks the grant again anyway. */ -import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import type * as Types from "effect/Types"; import { McpProtocol, McpServer } from "effect/ai"; import { HttpRouter, HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http"; @@ -30,7 +28,7 @@ import { normalizeMcpHttpResponse, readBearerToken, } from "../mcp/McpHttpServer.ts"; -import { AnalyticsService } from "../telemetry/Services/AnalyticsService.ts"; +import { makeDailyAnalyticsCounter } from "../telemetry/DailyCounter.ts"; import { makeConnectToolDeps } from "./connectToolDeps.ts"; import { makeConnectToolHandlers } from "./connectToolHandlers.ts"; import { ConnectToolkit, listedToolsFor, McpConnectInvocation } from "./connectTools.ts"; @@ -109,28 +107,21 @@ const AuthenticationLive = HttpRouter.middleware<{ * per tool and outcome. Never a thread's content or an agent's name. */ const makeToolCallCounts = Effect.gen(function* () { - const analytics = yield* Effect.serviceOption(AnalyticsService); - const counts = new Map(); - const report = Effect.suspend(() => { - const entries = [...counts.values()]; - counts.clear(); - return Option.isNone(analytics) - ? Effect.void - : Effect.forEach(entries, (entry) => analytics.value.record(TOOL_CALLS_EVENT, entry), { - discard: true, - }); + const counter = yield* makeDailyAnalyticsCounter<{ + readonly tool: string; + readonly outcome: string; + readonly door: "local"; + }>({ + event: TOOL_CALLS_EVENT, + keyOf: ({ tool, outcome }) => `${tool}\u0000${outcome}`, }); - yield* report.pipe(Effect.delay(Duration.days(1)), Effect.forever, Effect.forkScoped); - yield* Effect.addFinalizer(() => report); return ( tool: string, call: Effect.Effect, ) => Effect.tap(call, (result) => Effect.sync(() => { - const key = `${tool}\u0000${result.outcome}`; - const entry = counts.get(key) ?? { tool, outcome: result.outcome, count: 0 }; - counts.set(key, { ...entry, count: entry.count + 1 }); + counter.increment({ tool, outcome: result.outcome, door: "local" }); }), ); }); diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index 2547dc10a..dc307fff1 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -912,6 +912,175 @@ it.effect("ProviderServiceLive reports a failure under the category the agent na }).pipe(Effect.provide(NodeServices.layer)), ); +it.effect( + "ProviderServiceLive keeps custom instance ids out of fork telemetry, tags community agents, and counts active sessions on shutdown", + () => + Effect.gen(function* () { + const claude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); + const communityDriver = ProviderDriverKind.make("acpRegistry"); + const community = makeFakeCodexAdapter(communityDriver); + const workClaudeId = ProviderInstanceId.make("claudeAgent_acme_work"); + const communityInstanceId = ProviderInstanceId.make("acp_pi-acp"); + + const recorded: Array<{ + readonly event: string; + readonly properties: Readonly> | undefined; + }> = []; + + const adaptersByInstance = new Map< + ProviderInstanceId, + { + readonly adapter: ProviderAdapterShape; + readonly communityAgentId?: string; + } + >([ + [workClaudeId, { adapter: claude.adapter }], + [communityInstanceId, { adapter: community.adapter, communityAgentId: "pi-acp" }], + ]); + + const registry: ProviderAdapterRegistryShape = { + getByInstance: (instanceId) => { + const entry = adaptersByInstance.get(instanceId); + return entry + ? Effect.succeed(entry.adapter) + : Effect.fail( + new ProviderUnsupportedError({ provider: ProviderDriverKind.make(instanceId) }), + ); + }, + getInstanceInfo: (instanceId) => { + const entry = adaptersByInstance.get(instanceId); + if (!entry) { + return Effect.fail( + new ProviderUnsupportedError({ provider: ProviderDriverKind.make(instanceId) }), + ); + } + return Effect.succeed({ + instanceId, + driverKind: entry.adapter.provider, + displayName: undefined, + enabled: true, + continuationIdentity: { + driverKind: entry.adapter.provider, + continuationKey: `${entry.adapter.provider}:instance:${instanceId}`, + }, + ...(entry.communityAgentId !== undefined + ? { communityAgentId: entry.communityAgentId } + : {}), + }); + }, + listInstances: () => Effect.succeed(Array.from(adaptersByInstance.keys())), + listProviders: () => Effect.succeed([CLAUDE_AGENT_DRIVER, communityDriver]), + streamChanges: Stream.empty, + subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => + PubSub.subscribe(pubsub), + ), + }; + + const directoryLayer = ProviderSessionDirectoryLive.pipe( + Layer.provide( + ProviderSessionRuntimeRepositoryLive.pipe(Layer.provide(SqlitePersistenceMemory)), + ), + ); + const providerLayer = makeProviderServiceWithScrubber().pipe( + Layer.provide(ThreadSessionAdmissionPermissive), + Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)), + Layer.provide(directoryLayer), + Layer.provide(defaultServerSettingsLayer), + Layer.provide( + Layer.succeed(AnalyticsService, { + record: (event, properties) => Effect.sync(() => recorded.push({ event, properties })), + flush: Effect.void, + }), + ), + Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), + ); + + yield* Effect.gen(function* () { + const provider = yield* ProviderService; + // 1. Fork from a custom-labeled Claude account onto a community agent. + const forkedThreadId = asThreadId("thread-fork-privacy"); + yield* provider.startSession(forkedThreadId, { + provider: communityDriver, + providerInstanceId: communityInstanceId, + threadId: forkedThreadId, + modelSelection: createModelSelection(communityInstanceId, "gemini-4-argon"), + runtimeMode: "full-access", + }); + yield* provider.sendTurn({ + threadId: forkedThreadId, + input: "continue here", + modelSelection: createModelSelection(communityInstanceId, "gemini-4-argon"), + telemetryContext: { + kind: "thread_fork", + sourceModelSelection: createModelSelection(workClaudeId, "claude-sonnet-4-6"), + seedMode: "context-seed", + includedMessageCount: 2, + includedToolSummaryCount: 1, + includedAttachmentCount: 0, + omittedAttachmentCount: 0, + }, + }); + + // 2. Stop the session (keeps persisted binding), then force a failed-resume recovery. + yield* provider.stopSession({ threadId: forkedThreadId }); + const startCommunity = community.startSession.getMockImplementation()!; + community.startSession.mockImplementationOnce((input) => + startCommunity(input).pipe(Effect.map((session) => ({ ...session, resumeFailed: true }))), + ); + yield* provider.sendTurn({ + threadId: forkedThreadId, + input: "after restart", + modelSelection: createModelSelection(communityInstanceId, "gemini-4-argon"), + }); + + // 3. A second thread is started and stopped so 2 bindings exist but only 1 session is active + // when ProviderService's scope finalizer runs stopAll. + const stoppedThreadId = asThreadId("thread-already-stopped"); + yield* provider.startSession(stoppedThreadId, { + provider: CLAUDE_AGENT_DRIVER, + providerInstanceId: workClaudeId, + threadId: stoppedThreadId, + runtimeMode: "full-access", + }); + yield* provider.stopSession({ threadId: stoppedThreadId }); + }).pipe(Effect.provide(providerLayer)); + + const fork = recorded.find((entry) => entry.event === "thread.fork.created")?.properties; + assert.include(fork, { + sourceProvider: "claudeAgent", + targetProvider: "acpRegistry", + targetCommunityAgentId: "pi-acp", + providerChanged: true, + sourceModel: "claude-sonnet-4-6", + targetModel: "gemini-4-argon", + }); + assert.notInclude(JSON.stringify(fork), "acme"); + assert.notInclude(JSON.stringify(fork), "acp_pi-acp"); + + const stoppedCommunity = recorded.find( + (entry) => + entry.event === "provider.session.stopped" && + entry.properties?.provider === "acpRegistry", + )?.properties; + assert.include(stoppedCommunity, { provider: "acpRegistry", communityAgentId: "pi-acp" }); + + const recovered = recorded.find( + (entry) => entry.event === "provider.session.recovered", + )?.properties; + assert.include(recovered, { + provider: "acpRegistry", + communityAgentId: "pi-acp", + strategy: "resume-thread", + resumeFailed: true, + }); + + const stoppedAll = recorded.find( + (entry) => entry.event === "provider.sessions.stopped_all", + )?.properties; + assert.deepStrictEqual(stoppedAll, { sessionCount: 1 }); + }).pipe(Effect.provide(NodeServices.layer)), +); + it.effect("ProviderServiceLive keeps a turn the provider took when a write after it fails", () => Effect.gen(function* () { const codex = makeFakeCodexAdapter(); diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index 0c8abebd0..426135b7d 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -865,9 +865,13 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( input.binding.threadId, ); yield* analytics.record("provider.session.recovered", { - provider: existing.provider, + ...analyticsAgentProperties({ + provider: existing.provider, + communityAgentId: yield* communityAgentIdOf(bindingInstanceId), + }), strategy: "adopt-existing", hasResumeCursor: existing.resumeCursor !== undefined, + resumeFailed: false, }); return { adapter, session: existing, historyOwed: false } as const; } @@ -929,9 +933,13 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( historyOwed ? { historyOwed: true } : undefined, ); yield* analytics.record("provider.session.recovered", { - provider: resumed.provider, + ...analyticsAgentProperties({ + provider: resumed.provider, + communityAgentId: yield* communityAgentIdOf(bindingInstanceId), + }), strategy: "resume-thread", hasResumeCursor: resumed.resumeCursor !== undefined, + resumeFailed: historyOwed, startMs, }); return { adapter, session: resumed, historyOwed } as const; @@ -1016,9 +1024,17 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( yield* adapter.stopSession(input.threadId).pipe( Effect.tap(() => - analytics.record("provider.session.stopped", { - provider: adapter.provider, - }), + communityAgentIdOf(instanceId).pipe( + Effect.flatMap((communityAgentId) => + analytics.record( + "provider.session.stopped", + analyticsAgentProperties({ + provider: adapter.provider, + communityAgentId, + }), + ), + ), + ), ), Effect.catchCause((cause) => Effect.logWarning("provider.session.stop-stale-failed", { @@ -1428,13 +1444,16 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( ) => Effect.gen(function* () { const nowMs = yield* Clock.currentTimeMillis; - const provider = yield* registry.getInstanceInfo(entry.instanceId as ProviderInstanceId).pipe( - Effect.map((info) => info.driverKind), - Effect.orElseSucceed(() => "unknown"), + const agent = yield* registry.getInstanceInfo(entry.instanceId as ProviderInstanceId).pipe( + Effect.map((info) => ({ + provider: info.driverKind, + communityAgentId: info.communityAgentId, + })), + Effect.orElseSucceed(() => ({ provider: "unknown", communityAgentId: undefined })), ); yield* Effect.logInfo("provider service stopped an unused early session", { reason }); yield* analytics.record("provider.session.early_unused", { - provider, + ...analyticsAgentProperties(agent), reason, ageMs: Math.max(0, nowMs - entry.startedAtMs), }); @@ -1768,20 +1787,33 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( }); if (input.telemetryContext?.kind === "thread_fork") { const sourceModelSelection = input.telemetryContext.sourceModelSelection; - // Model names are read by agent kind (Pi's own list applies to every Pi instance). - const sourceDriver = sourceModelSelection - ? yield* registry.getByInstance(sourceModelSelection.instanceId).pipe( - Effect.map((adapter) => adapter.provider), + // Model names and fork telemetry use the driver kind (and public + // community agent id), never a user-defined instance id slug. + const sourceInfo = sourceModelSelection + ? yield* registry.getInstanceInfo(sourceModelSelection.instanceId).pipe( + Effect.map((info) => ({ + provider: info.driverKind, + communityAgentId: info.communityAgentId, + })), Effect.orElseSucceed(() => undefined), ) : undefined; + const sourceDriver = sourceInfo?.provider; yield* analytics.record("thread.fork.created", { - sourceProvider: sourceModelSelection?.instanceId ?? "unknown", - targetProvider: input.modelSelection?.instanceId ?? routed.instanceId, + ...analyticsAgentProperties({ + provider: sourceDriver ?? "unknown", + communityAgentId: sourceInfo?.communityAgentId, + prefix: "source", + }), + ...analyticsAgentProperties({ + provider: routed.adapter.provider, + communityAgentId, + prefix: "target", + }), providerChanged: sourceModelSelection !== undefined && - input.modelSelection !== undefined && - sourceModelSelection.instanceId !== input.modelSelection.instanceId, + sourceModelSelection.instanceId !== + (input.modelSelection?.instanceId ?? routed.instanceId), modelChanged: sourceModelSelection !== undefined && input.modelSelection !== undefined && @@ -1814,6 +1846,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( attachmentCount: input.attachments.length, hasInput: typeof input.input === "string" && input.input.trim().length > 0, ...(input.origin !== undefined ? { origin: input.origin } : {}), + ...(input.lane !== undefined ? { lane: input.lane } : {}), }); }).pipe( Effect.catchCause((cause) => @@ -2009,7 +2042,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( }, }); yield* analytics.record("provider.review.started", { - provider: routed.adapter.provider, + ...analyticsAgentProperties({ + provider: routed.adapter.provider, + communityAgentId: yield* communityAgentIdOf(routed.instanceId), + }), targetType: input.target.type, delivery: input.delivery, }); @@ -2432,9 +2468,13 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( }), ), ); - yield* analytics.record("provider.context.compact_requested", { - provider: routed.adapter.provider, - }); + yield* analytics.record( + "provider.context.compact_requested", + analyticsAgentProperties({ + provider: routed.adapter.provider, + communityAgentId: yield* communityAgentIdOf(routed.instanceId), + }), + ); }).pipe( withMetrics({ counter: providerTurnsTotal, @@ -2505,7 +2545,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( }, ); yield* analytics.record("provider.goal.set", { - provider: routed.adapter.provider, + ...analyticsAgentProperties({ + provider: routed.adapter.provider, + communityAgentId: yield* communityAgentIdOf(routed.instanceId), + }), status: goal.status, }); return goal; @@ -2556,9 +2599,13 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( payload: {}, }, ); - yield* analytics.record("provider.goal.cleared", { - provider: routed.adapter.provider, - }); + yield* analytics.record( + "provider.goal.cleared", + analyticsAgentProperties({ + provider: routed.adapter.provider, + communityAgentId: yield* communityAgentIdOf(routed.instanceId), + }), + ); }, ); @@ -2626,9 +2673,13 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( status: "paused", origin: "automatic", }); - yield* analytics.record("provider.goal.paused_for_stop", { - provider: routed.adapter.provider, - }); + yield* analytics.record( + "provider.goal.paused_for_stop", + analyticsAgentProperties({ + provider: routed.adapter.provider, + communityAgentId: yield* communityAgentIdOf(routed.instanceId), + }), + ); return pausedGoal; }); @@ -2659,7 +2710,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( secretScrubber.restoreAnswer(routed.threadId, input.requestId, input.decision), ); yield* analytics.record("provider.request.responded", { - provider: routed.adapter.provider, + ...analyticsAgentProperties({ + provider: routed.adapter.provider, + communityAgentId: yield* communityAgentIdOf(routed.instanceId), + }), decision: input.decision, }); }).pipe( @@ -2794,9 +2848,13 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( }, }); } - yield* analytics.record("provider.session.stopped", { - provider: routed.adapter.provider, - }); + yield* analytics.record( + "provider.session.stopped", + analyticsAgentProperties({ + provider: routed.adapter.provider, + communityAgentId: yield* communityAgentIdOf(routed.instanceId), + }), + ); }).pipe( withMetrics({ counter: providerSessionsTotal, @@ -2939,7 +2997,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( yield* upsertSessionBinding(rolledBackSession, routed.threadId); } yield* analytics.record("provider.conversation.rolled_back", { - provider: routed.adapter.provider, + ...analyticsAgentProperties({ + provider: routed.adapter.provider, + communityAgentId: yield* communityAgentIdOf(routed.instanceId), + }), turns: input.numTurns, }); return { @@ -3058,7 +3119,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( } const forgotten = yield* forgetConversation(threadId); yield* analytics.record("provider.conversation.rolled_back", { - provider: adapter.provider, + ...analyticsAgentProperties({ + provider: adapter.provider, + communityAgentId: yield* communityAgentIdOf(binding.providerInstanceId), + }), turns: numTurns, }); return forgotten; @@ -3301,7 +3365,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( } yield* directory.deleteBinding(input.threadId); yield* analytics.record("provider.thread.deleted", { - provider: routed.adapter.provider, + ...analyticsAgentProperties({ + provider: routed.adapter.provider, + communityAgentId: yield* communityAgentIdOf(routed.instanceId), + }), nativeDelete: routed.adapter.deleteThread !== undefined, }); }).pipe( @@ -3468,7 +3535,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( ); const runStopAll = Effect.fn("runStopAll")(function* () { - const threadIds = yield* directory.listThreadIds(); const currentAdapters = yield* getAdapterEntries; const activeSessions = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) => adapter.listSessions().pipe( @@ -3510,7 +3576,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( }), ).pipe(Effect.asVoid); yield* analytics.record("provider.sessions.stopped_all", { - sessionCount: threadIds.length, + sessionCount: activeSessions.length, }); yield* analytics.flush; }); diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts index d962bc58e..a57ad6536 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.ts @@ -1,4 +1,5 @@ import { + ACP_REGISTRY_DRIVER_KIND, defaultInstanceIdForDriver, ProviderDriverKind, ServerProviderUpdateError, @@ -27,7 +28,10 @@ import * as Schema from "effect/Schema"; import { HttpClient } from "effect/http"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { ProviderInstanceRegistry } from "./Services/ProviderInstanceRegistry.ts"; import { ProviderRegistry } from "./Services/ProviderRegistry.ts"; +import { analyticsAgentProperties } from "../telemetry/AnalyticsProperties.ts"; +import { AnalyticsService } from "../telemetry/Services/AnalyticsService.ts"; import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenanceCommandCoordinator.ts"; import { enrichProviderSnapshotWithVersionAdvisory } from "./providerMaintenance.ts"; import type { @@ -572,6 +576,8 @@ function logUnsuccessfulMaintenance(input: { export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { const scope = yield* Effect.scope; const providerRegistry = yield* ProviderRegistry; + const instanceRegistry = yield* Effect.serviceOption(ProviderInstanceRegistry); + const analytics = yield* Effect.serviceOption(AnalyticsService); const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const httpClient = yield* HttpClient.HttpClient; const runMaintenanceCommand = ( @@ -768,6 +774,26 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { reason: copy.unsupported, }); } + // Derive telemetry identity from the live registry instance so a caller-supplied + // `target.provider` slug or unverified local community id can never reach PostHog. + const resolvedInstance = (yield* providerRegistry.getProviders).find( + (candidate) => candidate.instanceId === instanceId, + ); + const liveInstances = Option.isSome(instanceRegistry) + ? yield* instanceRegistry.value.listInstances + : []; + const verifiedCommunityAgentId = liveInstances.find( + (candidate) => candidate.instanceId === instanceId, + )?.communityAgentId; + const telemetryProvider = resolvedInstance + ? resolvedInstance.driver + : provider === ACP_REGISTRY_DRIVER_KIND || Object.hasOwn(PROVIDER_DISPLAY_NAMES, provider) + ? provider + : "unknown"; + const telemetryAgentProps = analyticsAgentProperties({ + provider: telemetryProvider, + communityAgentId: verifiedCommunityAgentId, + }); const setUpdateState = (state: ServerProviderUpdateState | null) => providerRegistry.setProviderMaintenanceActionState({ @@ -786,14 +812,31 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { const runProviderUpdate = Effect.fn("ProviderMaintenanceRunner.runProviderUpdate")( function* () { - const finish = (state: ServerProviderUpdateState) => - (state.status === "succeeded" - ? Effect.void - : logUnsuccessfulMaintenance({ provider, instanceId, action, state }) + const finish = (state: ServerProviderUpdateState) => { + const startedMs = state.startedAt ? Date.parse(state.startedAt) : Number.NaN; + const finishedMs = state.finishedAt ? Date.parse(state.finishedAt) : Number.NaN; + const durationMs = + Number.isFinite(startedMs) && Number.isFinite(finishedMs) + ? Math.max(0, finishedMs - startedMs) + : undefined; + const recordOutcome = Option.isSome(analytics) + ? analytics.value.record("provider.runtime.maintained", { + ...telemetryAgentProps, + action, + status: state.status, + ...(durationMs !== undefined ? { durationMs } : {}), + }) + : Effect.void; + return ( + state.status === "succeeded" + ? Effect.void + : logUnsuccessfulMaintenance({ provider, instanceId, action, state }) ).pipe( + Effect.andThen(recordOutcome), Effect.andThen(setUpdateState(state)), Effect.map((providers) => ({ providers })), ); + }; const startedAtRef = yield* Ref.make(null); const runCommandAndVerify = Effect.fn("ProviderMaintenanceRunner.runCommandAndVerify")( diff --git a/apps/server/src/secrets/AgentSecretRequests.ts b/apps/server/src/secrets/AgentSecretRequests.ts index 0a51b66da..2d8752484 100644 --- a/apps/server/src/secrets/AgentSecretRequests.ts +++ b/apps/server/src/secrets/AgentSecretRequests.ts @@ -55,6 +55,7 @@ import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSna import type { ProjectionRepositoryError } from "../persistence/Errors.ts"; import { ProcessRunner } from "../processRunner.ts"; import { SecretScrubber } from "./SecretScrubber.ts"; +import { AnalyticsService } from "../telemetry/Services/AnalyticsService.ts"; import { type SecretDestinations, makeSecretDestinations } from "./secretDestinations.ts"; export interface AgentSecretRequestsShape { @@ -161,6 +162,7 @@ export const make = ( ) => Effect.gen(function* () { const engine = yield* OrchestrationEngineService; + const analytics = yield* Effect.serviceOption(AnalyticsService); const lock = yield* Semaphore.make(1); const scope = yield* Effect.scope; const recovered = yield* Deferred.make(); @@ -218,6 +220,12 @@ export const make = ( : {}), createdAt: yield* nowIso, }); + if (Option.isSome(analytics)) { + yield* analytics.value.record("secret_request.settled", { + outcome: fields.ending, + destinationKind: request.use.kind, + }); + } return true; }).pipe( Effect.catch((error) => diff --git a/apps/server/src/secrets/SecretScrubber.test.ts b/apps/server/src/secrets/SecretScrubber.test.ts index c40a20d6a..279dffe50 100644 --- a/apps/server/src/secrets/SecretScrubber.test.ts +++ b/apps/server/src/secrets/SecretScrubber.test.ts @@ -11,7 +11,7 @@ import { import * as Effect from "effect/Effect"; import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test"; -import { readBackSecret } from "./SecretScrubber.ts"; +import { makeSecretScrubber, readBackSecret, type SecretScrubSurface } from "./SecretScrubber.ts"; import { threadKeyOf } from "./secretDestinations.ts"; const THREAD = ThreadId.make("thread-1"); @@ -60,4 +60,42 @@ describe("reading saved keys back at startup", () => { expect(await read(request({ ...env, status: "declined" }))).toBeUndefined(); expect(await read(request({ ...env, name: "MISSING_KEY" }))).toBeUndefined(); }); + + it("counts cross-chunk streaming interceptions via holdPiece", () => { + const counts: Array<{ surface: SecretScrubSurface; count: number }> = []; + const scrubber = makeSecretScrubber({ + onScrub: (surface, count) => counts.push({ surface, count }), + }); + scrubber.watch("STRIPE_SECRET_KEY", "sk_test_51HvQq2abc"); + + const first = scrubber.holdPiece(undefined, "pay sk_te"); + const second = scrubber.holdPiece(first.state, "st_51HvQq2abc done"); + + expect(second.names).toEqual(["STRIPE_SECRET_KEY"]); + expect(counts).toEqual([{ surface: "runtime", count: 1 }]); + }); + + it("does not count partial-tail trimming as a runtime secret match", () => { + const counts: Array<{ surface: SecretScrubSurface; count: number }> = []; + const scrubber = makeSecretScrubber({ + onScrub: (surface, count) => counts.push({ surface, count }), + }); + scrubber.watch("STRIPE_SECRET_KEY", "sk_test_51HvQq2abc"); + + const events = scrubber.scrubRuntimeEvent({ + type: "item.updated", + eventId: "event-1" as never, + provider: "codex" as never, + threadId: THREAD, + createdAt: "2026-11-19T10:00:00.000Z" as never, + payload: { + itemType: "assistant_message", + status: "inProgress", + detail: "prefix sk_test_", + }, + } as never); + + expect(events).toHaveLength(1); + expect(counts).toEqual([]); + }); }); diff --git a/apps/server/src/secrets/SecretScrubber.ts b/apps/server/src/secrets/SecretScrubber.ts index 774f9c577..6b6d67b3c 100644 --- a/apps/server/src/secrets/SecretScrubber.ts +++ b/apps/server/src/secrets/SecretScrubber.ts @@ -25,6 +25,7 @@ import * as Schedule from "effect/Schedule"; import { ServerConfig } from "../config.ts"; import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; +import { makeDailyAnalyticsCounter } from "../telemetry/DailyCounter.ts"; import { threadKeyOf } from "./secretDestinations.ts"; import { type HeldText, @@ -87,21 +88,41 @@ export class SecretScrubber extends Context.Service void; +}): SecretScrubberShape { const core = makeSecretScrubberCore(); const notices = makeNoticeMemory(); - const runtime = makeRuntimeEventScrubber(core, notices); + const onScrub = options?.onScrub; + const runtime = makeRuntimeEventScrubber(core, notices, { + ...(onScrub !== undefined ? { onMatched: (count) => onScrub("runtime", count) } : {}), + }); return { watch: core.watch, gone: core.gone, - scrubText: (text, options) => core.scrubText(text, options), - scrubDeep: (value: A) => core.scrubDeep(value, new Set()) as A, + scrubText: (text, scrubOptions) => { + const result = core.scrubText(text, scrubOptions); + if (result.names.length > 0) onScrub?.("text", result.names.length); + return result; + }, + scrubDeep: (value: A) => { + const names = new Set(); + const result = core.scrubDeep(value, names) as A; + if (names.size > 0) onScrub?.("deep", names.size); + return result; + }, contains: core.contains, longestFormBytes: () => core.longestFormBytes, scrubRuntimeEvent: runtime.scrubRuntimeEvent, restoreAnswer: runtime.restoreAnswer, - holdPiece: core.holdPiece, + holdPiece: (state, piece) => { + const result = core.holdPiece(state, piece); + if (result.names.length > 0) onScrub?.("runtime", result.names.length); + return result; + }, afterRelease: core.afterRelease, noticeLine: core.noticeLine, takeNotices: (threadId, turnId, names) => notices.take(threadId, turnId, names), @@ -148,7 +169,20 @@ export const readBackSecret = ( }); /** The registry, empty until `loadSavedKeys` and Save fill it. One for the server. */ -export const layer = Layer.sync(SecretScrubber, makeSecretScrubber); +export const layer = Layer.effect( + SecretScrubber, + Effect.gen(function* () { + const scrubCounter = yield* makeDailyAnalyticsCounter<{ + readonly surface: SecretScrubSurface; + }>({ + event: "secret.scrubbed", + keyOf: ({ surface }) => surface, + }); + return makeSecretScrubber({ + onScrub: (surface, count) => scrubCounter.increment({ surface }, count), + }); + }), +); /** * Fills the registry at startup from every live thread's saved keys; the diff --git a/apps/server/src/secrets/secretScrubberCore.ts b/apps/server/src/secrets/secretScrubberCore.ts index 5c9020b82..c95df24a9 100644 --- a/apps/server/src/secrets/secretScrubberCore.ts +++ b/apps/server/src/secrets/secretScrubberCore.ts @@ -475,7 +475,11 @@ const isStreamPiece = ( * them there. A question or approval remembers what it was shown with, for * the answer. */ -export function makeRuntimeEventScrubber(core: SecretScrubberCore, notices: NoticeMemory) { +export function makeRuntimeEventScrubber( + core: SecretScrubberCore, + notices: NoticeMemory, + options?: { readonly onMatched?: (count: number) => void }, +) { /** Per session and request: each string a question or approval was shown with, and its original. */ const originals = new Map>(); const requestKey = (session: string, requestId: string) => `${session}\u0000${requestId}`; @@ -596,6 +600,7 @@ export function makeRuntimeEventScrubber(core: SecretScrubberCore, notices: Noti } const names = new Set(); const scrubbed = isStreamPiece(event) ? scrubPiece(event, names) : scrubWhole(event, names); + if (names.size > 0) options?.onMatched?.(names.size); forget(event); const after = noticesFor(event, names); return after.length === 0 ? [scrubbed] : [scrubbed, ...after]; diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 257f26382..e3f715a5e 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -586,7 +586,7 @@ const RelayLayerLive = RelayHostLive.pipe( const AssistantsLayerLive = AssistantsLive.pipe( Layer.provide(AssistantRelayLive), Layer.provide(RelayLayerLive), - Layer.provide(OutsideAgentConnectionRepositoryLive), + Layer.provideMerge(OutsideAgentConnectionRepositoryLive), Layer.provide(ServerSecretStoreLive), ); @@ -747,7 +747,8 @@ const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe( // Misc. Layer.provideMerge(ProcessDiagnosticsLayerLive), Layer.provideMerge(TraceDiagnostics.layer), - Layer.provideMerge(AnalyticsServiceLayerLive), + // Same ServerSettingsLive instance as RuntimeCoreDependenciesLive: Effect memoizes it. + Layer.provideMerge(AnalyticsServiceLayerLive.pipe(Layer.provide(ServerSettingsLive))), Layer.provideMerge(ExternalLauncher.layer), Layer.provideMerge(ServerLifecycleEventsLive), Layer.provide(NetService.layer), diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index 7ff8dea25..6290b5770 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -21,12 +21,14 @@ import { type OrchestrationEngineShape, } from "./orchestration/Services/OrchestrationEngine.ts"; import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts"; +import { ServerSettingsService } from "./serverSettings.ts"; import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts"; import { ThemeLibrary } from "./themes/ThemeLibrary.ts"; import { getAutoBootstrapDefaultModelSelection, launchStartupHeartbeat, makeCommandGate, + recordStartupHeartbeat, resolveAutoBootstrapWelcomeTargets, resolveWelcomeBase, ServerRuntimeStartupError, @@ -133,6 +135,89 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa ), ); +it.effect("recordStartupHeartbeat includes feature adoption counts and flags", () => + Effect.gen(function* () { + const recorded: Array<{ + readonly event: string; + readonly properties: Readonly> | undefined; + }> = []; + + yield* recordStartupHeartbeat.pipe( + Effect.provideService(ProjectionSnapshotQuery, { + getProjectCatalog: () => Effect.die("unused"), + getCommandReadModel: () => Effect.die("unused"), + getSnapshot: () => Effect.die("unused"), + listRunningWorkflowRuns: () => Effect.succeed([]), + listArchivedThreadsLiveState: () => Effect.succeed([]), + getShellSnapshot: () => Effect.die("unused"), + getArchivedShellSnapshot: () => Effect.die("unused"), + getSnapshotSequence: () => Effect.die("unused"), + getCounts: () => + Effect.succeed({ + projectCount: 4, + threadCount: 12, + leadChatCount: 2, + projectsWithBriefCount: 3, + projectNoteCount: 9, + }), + getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), + isProjectPhoneAlertsMuted: () => Effect.succeed(false), + getProjectShellById: () => Effect.succeed(Option.none()), + getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), + getThreadCheckpointContext: () => Effect.succeed(Option.none()), + getFullThreadDiffContext: () => Effect.succeed(Option.none()), + listThreadDiffStatBaselines: () => Effect.succeed([]), + listThreadTurnOverlapsSince: () => Effect.succeed([]), + listThreadIdsWithOpenAgentRequests: () => Effect.succeed([]), + listClaimedSettingsChanges: () => Effect.succeed([]), + listSecretRequests: () => Effect.succeed([]), + listThreadShells: () => Effect.succeed([]), + getThreadShellById: () => Effect.succeed(Option.none()), + getTurnActivities: () => Effect.succeed([]), + getThreadMessage: () => Effect.succeed(Option.none()), + hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadDetailById: () => Effect.succeed(Option.none()), + }), + Effect.provideService(AnalyticsService, { + record: (event, properties) => Effect.sync(() => recorded.push({ event, properties })), + flush: Effect.void, + }), + Effect.provide( + Layer.mergeAll( + ServerSettingsService.layerTest({ + enableDevices: true, + agentDeviceAccess: true, + continueAfterRestart: false, + providerInstances: { + [ProviderInstanceId.make("codex")]: { driver: "codex" as never }, + [ProviderInstanceId.make("claudeAgent_work")]: { driver: "claudeAgent" as never }, + [ProviderInstanceId.make("acp_pi-acp")]: { driver: "acpRegistry" as never }, + }, + }), + Layer.mock(ThemeLibrary)({ snapshot: Effect.succeed({ entries: [] }) }), + ), + ), + ); + + assert.equal(recorded.length, 1); + assert.deepStrictEqual(recorded[0], { + event: "server.boot.heartbeat", + properties: { + threadCount: 12, + projectCount: 4, + leadChatCount: 2, + projectsWithBriefCount: 3, + projectNoteCount: 9, + savedThemeCount: 0, + extraAccountCount: 1, + devicesEnabled: true, + agentDeviceAccess: true, + continueAfterRestart: false, + }, + }); + }), +); + it.effect("resolveWelcomeBase derives cwd and project name from server config", () => Effect.gen(function* () { const welcome = yield* resolveWelcomeBase.pipe( diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 374450c86..609c1df48 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -1,4 +1,5 @@ import { + ACP_REGISTRY_DRIVER_KIND, CommandId, DEFAULT_MODEL, DEFAULT_PROVIDER_INTERACTION_MODE, @@ -27,12 +28,18 @@ import { Keybindings } from "./keybindings.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; import { ensureGeneralChatsProject } from "./orchestration/generalChats.ts"; import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts"; -import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts"; +import { + ProjectionSnapshotQuery, + type ProjectionSnapshotCounts, +} from "./orchestration/Services/ProjectionSnapshotQuery.ts"; import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor.ts"; import { ComputerLinkReactors } from "./links/ComputerLinkReactors.ts"; +import { ComputerLinkRepository, isUsableLink } from "./links/ComputerLinkRepository.ts"; import { AssistantAlerts } from "./assistants/AssistantAlerts.ts"; import { AssistantEvents } from "./assistants/AssistantEvents.ts"; +import { OutsideAgentConnectionRepository } from "./outsideAgents/OutsideAgentConnectionRepository.ts"; import { PushAlerts } from "./pushAlerts/PushAlerts.ts"; +import { ScheduledTaskRepository } from "./scheduled/ScheduledTaskRepository.ts"; import { ScheduledTasks } from "./scheduled/ScheduledTasks.ts"; import { ProjectNotesUndo } from "./projectContext/ProjectNotesUndo.ts"; import { ThreadAutoArchiveSweeper } from "./orchestration/Services/ThreadAutoArchiveSweeper.ts"; @@ -144,13 +151,17 @@ export const recordStartupHeartbeat = Effect.gen(function* () { const analytics = yield* AnalyticsService; const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; const themeLibrary = yield* ThemeLibrary; + const serverSettings = yield* Effect.serviceOption(ServerSettingsService); + const computerLinks = yield* Effect.serviceOption(ComputerLinkRepository); + const scheduledTaskRepo = yield* Effect.serviceOption(ScheduledTaskRepository); + const outsideAgentRepo = yield* Effect.serviceOption(OutsideAgentConnectionRepository); - const { threadCount, projectCount } = yield* projectionSnapshotQuery.getCounts().pipe( + const counts = yield* projectionSnapshotQuery.getCounts().pipe( Effect.catch((cause) => Effect.logWarning("failed to gather startup projection counts for telemetry", { cause, }).pipe( - Effect.as({ + Effect.as({ threadCount: 0, projectCount: 0, }), @@ -168,10 +179,61 @@ export const recordStartupHeartbeat = Effect.gen(function* () { ), ); + const settingsSummary = Option.isSome(serverSettings) + ? yield* serverSettings.value.readStored.pipe( + Effect.map((settings) => { + const extraAccountCount = Object.entries(settings.providerInstances ?? {}).filter( + ([instanceId, instance]) => + instance.driver !== ACP_REGISTRY_DRIVER_KIND && instanceId !== instance.driver, + ).length; + return { + extraAccountCount, + devicesEnabled: settings.enableDevices, + agentDeviceAccess: settings.agentDeviceAccess, + continueAfterRestart: settings.continueAfterRestart, + }; + }), + Effect.catch(() => Effect.succeed(undefined)), + ) + : undefined; + + const linkedComputerCount = Option.isSome(computerLinks) + ? yield* computerLinks.value.list.pipe( + Effect.map((rows) => rows.filter(isUsableLink).length), + Effect.catch(() => Effect.succeed(undefined)), + ) + : undefined; + + const scheduledTaskCount = Option.isSome(scheduledTaskRepo) + ? yield* scheduledTaskRepo.value.listTasks.pipe( + Effect.map((rows) => rows.filter((row) => row.status === "active").length), + Effect.catch(() => Effect.succeed(undefined)), + ) + : undefined; + + const connectionCounts = Option.isSome(outsideAgentRepo) + ? yield* outsideAgentRepo.value.listLive.pipe( + Effect.map((rows) => ({ + assistantCount: rows.filter((row) => row.kind === "assistant").length, + outsideAgentCount: rows.filter((row) => row.kind === "local").length, + })), + Effect.catch(() => Effect.succeed(undefined)), + ) + : undefined; + yield* analytics.record("server.boot.heartbeat", { - threadCount, - projectCount, + threadCount: counts.threadCount, + projectCount: counts.projectCount, + ...(counts.leadChatCount !== undefined ? { leadChatCount: counts.leadChatCount } : {}), + ...(counts.projectsWithBriefCount !== undefined + ? { projectsWithBriefCount: counts.projectsWithBriefCount } + : {}), + ...(counts.projectNoteCount !== undefined ? { projectNoteCount: counts.projectNoteCount } : {}), savedThemeCount, + ...(settingsSummary ?? {}), + ...(linkedComputerCount !== undefined ? { linkedComputerCount } : {}), + ...(scheduledTaskCount !== undefined ? { scheduledTaskCount } : {}), + ...(connectionCounts ?? {}), }); }); diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index f461caa31..efc77dd95 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -665,7 +665,8 @@ const makeServerSettings = Effect.gen(function* () { path: settingsPath, issues: Cause.pretty(decoded.cause), }); - return DEFAULT_SERVER_SETTINGS; + // Fail closed on analytics consent when an existing settings file cannot be parsed. + return { ...DEFAULT_SERVER_SETTINGS, usageAnalyticsEnabled: false }; } // Every read, so a token in the file (an older version's, or a hand edit) // never reaches a provider, a client or a write. diff --git a/apps/server/src/telemetry/AnalyticsProperties.test.ts b/apps/server/src/telemetry/AnalyticsProperties.test.ts index 2bc18a29f..4b8ff659f 100644 --- a/apps/server/src/telemetry/AnalyticsProperties.test.ts +++ b/apps/server/src/telemetry/AnalyticsProperties.test.ts @@ -15,6 +15,8 @@ import { normalizeAnalyticsModel, providerChecksSettled, providerReadinessProperties, + stallDurationBucket, + themeAnalyticsProperties, } from "./AnalyticsProperties.ts"; const providerSnapshot = ( @@ -60,6 +62,39 @@ describe("AnalyticsProperties", () => { "gpt-4o-2024-08-06", ); assert.strictEqual(normalizeAnalyticsModel("grok-4.7-build-fast").model, "grok-4.7-build-fast"); + assert.strictEqual(normalizeAnalyticsModel("grok-code-fast-1").model, "grok-code-fast-1"); + assert.strictEqual( + normalizeAnalyticsModel("gemini-2.0-flash-001").model, + "gemini-2.0-flash-001", + ); + assert.deepStrictEqual(normalizeAnalyticsModel("gemini-4-argon"), { + model: "gemini-4-argon", + modelKind: "known", + modelFamily: "gemini", + }); + assert.strictEqual(normalizeAnalyticsModel("gemini-4-argon-high").model, "gemini-4-argon-high"); + assert.strictEqual(normalizeAnalyticsModel("gemini-4-carbon").model, "gemini-4-carbon"); + assert.strictEqual(normalizeAnalyticsModel("gemini-4-neon").model, "gemini-4-neon"); + assert.strictEqual( + normalizeAnalyticsModel("gemini-4-hydrogen-sonar").model, + "gemini-4-hydrogen-sonar", + ); + assert.deepStrictEqual(normalizeAnalyticsModel("muse-spark-1.3"), { + model: "muse-spark-1.3", + modelKind: "known", + modelFamily: "muse", + }); + assert.deepStrictEqual(normalizeAnalyticsModel("claude-mythos-5-1"), { + model: "claude-mythos-5-1", + modelKind: "known", + modelFamily: "claude", + }); + assert.deepStrictEqual(normalizeAnalyticsModel("o3"), { + model: "o3", + modelKind: "known", + modelFamily: "gpt", + }); + assert.strictEqual(normalizeAnalyticsModel("openai/o4-mini").model, "o4-mini"); }); it("redacts custom and provider-prefixed model strings", () => { @@ -85,6 +120,14 @@ describe("AnalyticsProperties", () => { "gpt-4o-acme-payroll", "gpt-5x-sol", "google/gemini-2.5-acme-payroll", + "gemini-4-acme", + "muse-acme-payroll", + "muse-4242-1717", + "gpt-5-4242-1717", + "grok-4-12-34-56-78", + "claude-sonnet-4-20999999", + "claude-mythos-5-acme", + "o3-acme", "openai/gpt-5.4-123456789012", // Whatever made a long name private may be past the cut. `gpt-5-${"a".repeat(96)}:acme`, @@ -162,6 +205,14 @@ describe("AnalyticsProperties", () => { analyticsAgentProperties({ provider: "acpRegistry", communityAgentId: "/Users/someone" }), { provider: "acpRegistry" }, ); + assert.deepStrictEqual( + analyticsAgentProperties({ + provider: "acpRegistry", + communityAgentId: "pi-acp", + prefix: "source", + }), + { sourceProvider: "acpRegistry", sourceCommunityAgentId: "pi-acp" }, + ); }); it("emits prefixed model properties", () => { @@ -411,4 +462,43 @@ describe("AnalyticsProperties", () => { "resume", ); }); + + it("distinguishes VS Code / Open VSX themes and buckets stall durations", () => { + const baseColors = { + background: "#111111", + foreground: "#eeeeee", + mutedForeground: "#999999", + accent: "#3366ff", + accentForeground: "#ffffff", + }; + assert.deepStrictEqual( + themeAnalyticsProperties({ + format: "threadlines-theme@1", + name: "Dracula", + base: "dark", + colors: baseColors, + createdBy: { + kind: "imported", + vscode: { extension: "dracula-theme.theme-dracula", theme: "Dracula" }, + }, + }), + { origin: "vscode", base: "dark", art: "none", customFonts: false }, + ); + assert.deepStrictEqual( + themeAnalyticsProperties({ + format: "threadlines-theme@1", + name: "Local", + base: "light", + colors: baseColors, + createdBy: { kind: "imported" }, + }), + { origin: "imported", base: "light", art: "none", customFonts: false }, + ); + + assert.strictEqual(stallDurationBucket(2_000), "2-5s"); + assert.strictEqual(stallDurationBucket(4_999), "2-5s"); + assert.strictEqual(stallDurationBucket(5_000), "5-15s"); + assert.strictEqual(stallDurationBucket(14_999), "5-15s"); + assert.strictEqual(stallDurationBucket(15_000), "15s+"); + }); }); diff --git a/apps/server/src/telemetry/AnalyticsProperties.ts b/apps/server/src/telemetry/AnalyticsProperties.ts index 1584f2153..14863be4c 100644 --- a/apps/server/src/telemetry/AnalyticsProperties.ts +++ b/apps/server/src/telemetry/AnalyticsProperties.ts @@ -94,11 +94,14 @@ const KNOWN_SAFE_MODELS = new Set([ const SAFE_PUBLIC_MODEL_PATTERNS = [ // `gpt-4o` and its kin end their version in an "o"; no other letter. - /^gpt-\d+o?(?:[.-][a-z0-9]+)*(?:-codex(?:-[a-z0-9]+)?)?$/, - /^claude-(?:fable|haiku|opus|sonnet)-\d+(?:-\d+)*(?:-\d{8})?$/, - /^gemini-\d+(?:\.\d+)?(?:-[a-z0-9]+)*$/, - /^composer-\d+(?:\.\d+)?$/, - /^grok-\d+(?:\.\d+)?(?:-[a-z]+)*$/, + /^gpt-\d{1,2}o?(?:\.\d{1,2})?(?:-(?:mini|nano|pro|turbo|preview|latest|chat|codex|spark|astra|sol|luna|terra|max|high|low|medium|fast))+(?:-20[2-3]\d-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))?$/, + /^gpt-\d{1,2}o?(?:\.\d{1,2})?(?:-20[2-3]\d-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))?$/, + /^o\d{1,2}(?:-(?:mini|pro|preview|high|low|medium))?(?:-20[2-3]\d-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))?$/, + /^claude-(?:fable|mythos|haiku|opus|sonnet)-\d{1,2}(?:-\d{1,2})?(?:-20[2-3]\d(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01]))?$/, + /^gemini-\d{1,2}(?:\.\d{1,2})?-(?:pro|flash|ultra|lite|argon|carbon|hydrogen|neon|sonar|exp|preview)(?:-(?:pro|flash|lite|sonar|exp|preview|latest|thinking|customtools|high|low|medium|minimal))*(?:-(?:0\d{2}|(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])))?$/, + /^muse-(?:spark|wonder|ember|glimmer)(?:-\d{1,2}(?:\.\d{1,2})?|-\d{1,3}b)?(?:-(?:open|contributor))?$/, + /^composer-\d{1,2}(?:\.\d{1,2})?$/, + /^grok-(?:code|\d{1,2}(?:\.\d{1,2})?)(?:-(?:fast|mini|pro|build|beta|latest|reasoning|code))*(?:-\d{1,2})?$/, /^(?:auto|default)$/, ]; @@ -136,41 +139,57 @@ const PUBLIC_MODEL_PROVIDER_PREFIXES: ReadonlySet = new Set([ * in KNOWN_SAFE_MODELS need no check. */ const PUBLIC_MODEL_WORDS: ReadonlySet = new Set([ + "argon", "astra", "beta", // Grok Build's own models: `grok-4.7-build-fast`. "build", + "carbon", "chat", "claude", "code", "codex", "composer", + "contributor", "customtools", + "ember", "exp", "fable", "fast", "flash", "gemini", + "glimmer", "gpt", "grok", "haiku", + "high", + "hydrogen", "latest", "lite", + "low", "luna", "max", + "medium", "mini", + "minimal", + "muse", + "mythos", "nano", + "neon", + "open", "opus", "preview", "pro", "reasoning", "sol", + "sonar", "sonnet", "spark", "terra", "thinking", "turbo", "ultra", + "wonder", ]); function normalizeModelString(model: string | null | undefined): string | undefined { @@ -219,7 +238,12 @@ function publicModelName(model: string): string | undefined { return KNOWN_SAFE_MODELS.has(name) || name .split(/[-.]/) - .every((word) => /^(?:\d{1,4}[a-z]?|20\d{6})$/.test(word) || PUBLIC_MODEL_WORDS.has(word)) + .every( + (word) => + /^(?:o\d{1,2}|\d{1,2}[a-z]?|0\d{2}|\d{1,3}b|20[2-3]\d|20[2-3]\d(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01]))$/.test( + word, + ) || PUBLIC_MODEL_WORDS.has(word), + ) ? name : undefined; } @@ -295,10 +319,14 @@ const isAcpRegistryAgentId = Schema.is(AcpRegistryAgentId); export function analyticsAgentProperties(input: { readonly provider: string; readonly communityAgentId?: string | undefined; + readonly prefix?: string | undefined; }): Record { + const keyPrefix = input.prefix ?? ""; + const providerKey = keyPrefix ? `${keyPrefix}Provider` : "provider"; + const communityKey = keyPrefix ? `${keyPrefix}CommunityAgentId` : "communityAgentId"; return input.communityAgentId !== undefined && isAcpRegistryAgentId(input.communityAgentId) - ? { provider: input.provider, communityAgentId: input.communityAgentId } - : { provider: input.provider }; + ? { [providerKey]: input.provider, [communityKey]: input.communityAgentId } + : { [providerKey]: input.provider }; } /** @@ -649,10 +677,22 @@ export function providerReadinessProperties( * colors, art or fonts. */ export function themeAnalyticsProperties(manifest: ThemeManifest) { + const origin = + manifest.createdBy?.vscode !== undefined || manifest.credits?.vscode !== undefined + ? "vscode" + : (manifest.createdBy?.kind ?? "unknown"); return { - origin: manifest.createdBy?.kind ?? "unknown", + origin, base: manifest.base, art: manifest.backdrop?.mode ?? "none", customFonts: manifest.fonts?.ui !== undefined || manifest.fonts?.mono !== undefined, }; } + +export type AnalyticsStallDurationBucket = "2-5s" | "5-15s" | "15s+"; + +export function stallDurationBucket(durationMs: number): AnalyticsStallDurationBucket { + if (durationMs >= 15_000) return "15s+"; + if (durationMs >= 5_000) return "5-15s"; + return "2-5s"; +} diff --git a/apps/server/src/telemetry/DailyCounter.test.ts b/apps/server/src/telemetry/DailyCounter.test.ts new file mode 100644 index 000000000..86be0402a --- /dev/null +++ b/apps/server/src/telemetry/DailyCounter.test.ts @@ -0,0 +1,116 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as TestClock from "effect/testing/TestClock"; + +import { makeDailyAnalyticsCounter } from "./DailyCounter.ts"; +import { AnalyticsService } from "./Services/AnalyticsService.ts"; + +describe("DailyCounter", () => { + it.effect("aggregates increments by key and flushes on schedule and scope close", () => + Effect.gen(function* () { + const recorded: Array<{ + readonly event: string; + readonly properties: Readonly> | undefined; + }> = []; + + yield* Effect.scoped( + Effect.gen(function* () { + const counter = yield* makeDailyAnalyticsCounter<{ + readonly tool: string; + readonly outcome: string; + }>({ + event: "test.counter", + keyOf: ({ tool, outcome }) => `${tool}\u0000${outcome}`, + interval: Duration.hours(1), + }); + + counter.increment({ tool: "open", outcome: "ok" }); + counter.increment({ tool: "open", outcome: "ok" }); + counter.increment({ tool: "open", outcome: "error" }); + + yield* TestClock.adjust(Duration.hours(1)); + assert.deepStrictEqual(recorded, [ + { event: "test.counter", properties: { tool: "open", outcome: "ok", count: 2 } }, + { event: "test.counter", properties: { tool: "open", outcome: "error", count: 1 } }, + ]); + + // New increments flush on scope close (server shutdown). + counter.increment({ tool: "close", outcome: "ok" }, 3); + }), + ).pipe( + Effect.provideService(AnalyticsService, { + record: (event, properties) => Effect.sync(() => recorded.push({ event, properties })), + flush: Effect.void, + consent: { + isEnabledSync: () => true, + onDisabled: () => () => {}, + }, + }), + ); + + assert.deepStrictEqual(recorded.at(-1), { + event: "test.counter", + properties: { tool: "close", outcome: "ok", count: 3 }, + }); + }), + ); + + it.effect("ignores opted-out increments and clears pending counts on opt-out", () => + Effect.gen(function* () { + const recorded: Array<{ + readonly event: string; + readonly properties: Readonly> | undefined; + }> = []; + let enabled = false; + const listeners = new Set<() => void>(); + const setEnabled = (next: boolean) => { + const prev = enabled; + enabled = next; + if (prev && !next) { + for (const listener of listeners) listener(); + } + }; + + yield* Effect.scoped( + Effect.gen(function* () { + const counter = yield* makeDailyAnalyticsCounter<{ readonly tool: string }>({ + event: "test.consent", + keyOf: ({ tool }) => tool, + interval: Duration.hours(1), + }); + + // Opted out: ignored, never carried forward if enabled later. + counter.increment({ tool: "opted_out" }, 5); + + setEnabled(true); + counter.increment({ tool: "before_opt_out" }, 2); + // Toggling off drops pending counts immediately. + setEnabled(false); + + setEnabled(true); + counter.increment({ tool: "after_opt_in" }, 1); + yield* counter.flush; + }), + ).pipe( + Effect.provideService(AnalyticsService, { + record: (event, properties) => Effect.sync(() => recorded.push({ event, properties })), + flush: Effect.void, + consent: { + isEnabledSync: () => enabled, + onDisabled: (listener) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + }, + }), + ); + + assert.deepStrictEqual(recorded, [ + { event: "test.consent", properties: { tool: "after_opt_in", count: 1 } }, + ]); + }), + ); +}); diff --git a/apps/server/src/telemetry/DailyCounter.ts b/apps/server/src/telemetry/DailyCounter.ts new file mode 100644 index 000000000..32d16220e --- /dev/null +++ b/apps/server/src/telemetry/DailyCounter.ts @@ -0,0 +1,91 @@ +/** + * DailyCounter - aggregates frequent telemetry events in memory and emits one + * PostHog event per dimension tuple once a day (and when the server stops). + * + * Keeps event volume bounded on hot paths such as MCP tool calls, secret + * redactions, and server stall samples. + * + * @module DailyCounter + */ +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import type * as Scope from "effect/Scope"; + +import { AnalyticsService } from "./Services/AnalyticsService.ts"; + +export type AnalyticsCounterDimensions = Readonly>; + +export interface DailyAnalyticsCounter { + readonly increment: (dimensions: T, by?: number) => void; + readonly flush: Effect.Effect; +} + +export const makeDailyAnalyticsCounter = (options: { + readonly event: string; + readonly keyOf: (dimensions: T) => string; + readonly interval?: Duration.Input; +}): Effect.Effect, never, Scope.Scope> => + Effect.gen(function* () { + const analytics = yield* Effect.serviceOption(AnalyticsService); + const counts = new Map(); + let clearGeneration = 0; + + const isAllowed = () => { + if (Option.isNone(analytics)) return false; + const consent = analytics.value.consent; + return consent === undefined ? false : consent.isEnabledSync(); + }; + + const unsubscribe = + Option.isSome(analytics) && analytics.value.consent !== undefined + ? analytics.value.consent.onDisabled(() => { + clearGeneration += 1; + counts.clear(); + }) + : undefined; + + const flush = Effect.suspend(() => { + if (!isAllowed()) { + counts.clear(); + return Effect.void; + } + if (counts.size === 0) return Effect.void; + const generation = clearGeneration; + const entries = [...counts.values()]; + counts.clear(); + return Option.isNone(analytics) + ? Effect.void + : Effect.forEach( + entries, + ({ dimensions, count }) => + Effect.suspend(() => + !isAllowed() || clearGeneration !== generation + ? Effect.void + : analytics.value.record(options.event, { ...dimensions, count }), + ), + { discard: true }, + ); + }); + + const interval = options.interval ?? Duration.days(1); + yield* flush.pipe(Effect.delay(interval), Effect.forever, Effect.forkScoped); + if (unsubscribe !== undefined) { + yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); + } + yield* Effect.addFinalizer(() => flush); + + return { + increment: (dimensions, by = 1) => { + if (by <= 0 || !isAllowed()) return; + const key = options.keyOf(dimensions); + const existing = counts.get(key); + if (existing) { + existing.count += by; + } else { + counts.set(key, { dimensions, count: by }); + } + }, + flush, + } satisfies DailyAnalyticsCounter; + }); diff --git a/apps/server/src/telemetry/Layers/AnalyticsService.test.ts b/apps/server/src/telemetry/Layers/AnalyticsService.test.ts index 1688620e6..e6ab64940 100644 --- a/apps/server/src/telemetry/Layers/AnalyticsService.test.ts +++ b/apps/server/src/telemetry/Layers/AnalyticsService.test.ts @@ -10,6 +10,7 @@ import * as HttpServerRequest from "effect/http/HttpServerRequest"; import * as HttpServerResponse from "effect/http/HttpServerResponse"; import { ServerConfig } from "../../config.ts"; +import { ServerSettingsLive, ServerSettingsService } from "../../serverSettings.ts"; import { getTelemetryIdentifier } from "../Identify.ts"; import { AnalyticsService } from "../Services/AnalyticsService.ts"; import { AnalyticsServiceLayerLive, makeAnalyticsServiceLayer } from "./AnalyticsService.ts"; @@ -305,4 +306,185 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => { assert.equal(batchRequests[0]?.body.batch[0]?.event, "test.flush.settings_enabled"); }), ); + + it.effect("reads usageAnalyticsEnabled from ServerSettingsService when provided", () => + Effect.gen(function* () { + const capturedRequests: Array = []; + const serverConfigLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "threadlines-telemetry-settings-service-", + }); + + const settingsLayer = ServerSettingsService.layerTest({ usageAnalyticsEnabled: false }); + const telemetryLayer = notTheTempDir.pipe( + Layer.provideMerge(settingsLayer), + Layer.provideMerge(serverConfigLayer), + ); + const configLayer = ConfigProvider.layer( + ConfigProvider.fromUnknown({ + THREADLINES_POSTHOG_KEY: "phc_test_key", + THREADLINES_POSTHOG_HOST: ".", + THREADLINES_TELEMETRY_FLUSH_BATCH_SIZE: 1, + }), + ); + const batchServerLayer = makeBatchServerLayer(capturedRequests); + const runtimeLayer = telemetryLayer.pipe( + Layer.provide(configLayer), + Layer.provideMerge(NodeHttpServer.layerTest), + ); + + yield* Effect.gen(function* () { + yield* Layer.launch(batchServerLayer).pipe(Effect.forkScoped); + const analytics = yield* AnalyticsService; + + yield* analytics.record("test.flush.service_disabled", { index: 0 }); + yield* analytics.flush; + }).pipe(Effect.provide(runtimeLayer)); + + assert.equal(capturedRequests.length, 0); + }), + ); + + it.effect("fails closed when settings.json is unreadable or corrupt", () => + Effect.gen(function* () { + const capturedRequests: Array = []; + const serverConfigLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "threadlines-telemetry-corrupt-settings-", + }); + + const telemetryLayer = notTheTempDir.pipe(Layer.provideMerge(serverConfigLayer)); + const configLayer = ConfigProvider.layer( + ConfigProvider.fromUnknown({ + THREADLINES_POSTHOG_KEY: "phc_test_key", + THREADLINES_POSTHOG_HOST: ".", + THREADLINES_TELEMETRY_FLUSH_BATCH_SIZE: 1, + }), + ); + const batchServerLayer = makeBatchServerLayer(capturedRequests); + const runtimeLayer = telemetryLayer.pipe( + Layer.provide(configLayer), + Layer.provideMerge(NodeHttpServer.layerTest), + ); + + yield* Effect.gen(function* () { + yield* Layer.launch(batchServerLayer).pipe(Effect.forkScoped); + const fileSystem = yield* FileSystem.FileSystem; + const serverConfig = yield* ServerConfig; + yield* fileSystem.writeFileString(serverConfig.settingsPath, "{ invalid json"); + const analytics = yield* AnalyticsService; + + yield* analytics.record("test.flush.corrupt_settings", { index: 0 }); + yield* analytics.flush; + }).pipe(Effect.provide(runtimeLayer)); + + assert.equal(capturedRequests.length, 0); + }), + ); + + it.effect("fails closed when settings.json is malformed behind live ServerSettingsLive", () => + Effect.gen(function* () { + const capturedRequests: Array = []; + const serverConfigLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "threadlines-telemetry-corrupt-live-settings-", + }); + const configLayer = ConfigProvider.layer( + ConfigProvider.fromUnknown({ + THREADLINES_POSTHOG_KEY: "phc_test_key", + THREADLINES_POSTHOG_HOST: ".", + THREADLINES_TELEMETRY_FLUSH_BATCH_SIZE: 1, + }), + ); + const batchServerLayer = makeBatchServerLayer(capturedRequests); + + yield* Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const serverConfig = yield* ServerConfig; + yield* fileSystem.writeFileString(serverConfig.settingsPath, "{ invalid json"); + + const sharedServerConfig = Layer.succeed(ServerConfig, serverConfig); + const runtimeLayer = notTheTempDir.pipe( + Layer.provide(ServerSettingsLive), + Layer.provideMerge(sharedServerConfig), + Layer.provide(configLayer), + Layer.provideMerge(NodeHttpServer.layerTest), + ); + + yield* Effect.gen(function* () { + yield* Layer.launch(batchServerLayer).pipe(Effect.forkScoped); + const analytics = yield* AnalyticsService; + + yield* analytics.record("test.flush.corrupt_live_settings", { index: 0 }); + yield* analytics.flush; + }).pipe(Effect.provide(runtimeLayer)); + }).pipe(Effect.provide(serverConfigLayer)); + + assert.equal(capturedRequests.length, 0); + }), + ); + + it.effect("caps re-queued events at maxBufferedEvents when a flush fails", () => + Effect.gen(function* () { + let failRequests = true; + const capturedRequests: Array = []; + const flakyServerLayer = HttpServer.serve( + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + if (request.method !== "POST") { + return HttpServerResponse.empty({ status: 404 }); + } + if (failRequests) { + return HttpServerResponse.empty({ status: 503 }); + } + const payload = yield* request.json.pipe( + Effect.map((body) => body as RecordedBatchRequest["body"]), + Effect.catch(() => Effect.succeed(null)), + ); + capturedRequests.push({ path: request.url, body: payload }); + return HttpServerResponse.jsonUnsafe({}); + }), + ); + + const serverConfigLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "threadlines-telemetry-backoff-", + }); + const telemetryLayer = AnalyticsServiceLayerLive.pipe(Layer.provideMerge(serverConfigLayer)); + const configLayer = ConfigProvider.layer( + ConfigProvider.fromUnknown({ + THREADLINES_TELEMETRY_ENABLED: true, + THREADLINES_POSTHOG_KEY: "phc_test_key", + THREADLINES_POSTHOG_HOST: ".", + THREADLINES_TELEMETRY_FLUSH_BATCH_SIZE: 2, + THREADLINES_TELEMETRY_MAX_BUFFERED_EVENTS: 3, + }), + ); + const runtimeLayer = telemetryLayer.pipe( + Layer.provide(configLayer), + Layer.provideMerge(NodeHttpServer.layerTest), + ); + + yield* Effect.gen(function* () { + yield* Layer.launch(flakyServerLayer).pipe(Effect.forkScoped); + const analytics = yield* AnalyticsService; + + for (let index = 0; index < 3; index += 1) { + yield* analytics.record("test.flush.retry", { index }); + } + // Fails and re-queues events 0..1 ahead of event 2 (still capped at 3). + yield* analytics.flush; + // Recording 2 more while still offline drops the oldest (0, 1), keeping 2, 3, 4. + yield* analytics.record("test.flush.retry", { index: 3 }); + yield* analytics.record("test.flush.retry", { index: 4 }); + + failRequests = false; + yield* analytics.flush; + }).pipe(Effect.provide(runtimeLayer)); + + const deliveredIndexes = capturedRequests.flatMap((request) => + (request.body?.batch ?? []) + .filter((event) => event.event === "test.flush.retry") + .map((event) => event.properties?.index) + .filter((index): index is number => typeof index === "number"), + ); + assert.deepEqual(deliveredIndexes, [2, 3, 4]); + }), + ); }); diff --git a/apps/server/src/telemetry/Layers/AnalyticsService.ts b/apps/server/src/telemetry/Layers/AnalyticsService.ts index 05dfca230..05a69d815 100644 --- a/apps/server/src/telemetry/Layers/AnalyticsService.ts +++ b/apps/server/src/telemetry/Layers/AnalyticsService.ts @@ -17,12 +17,14 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; import { DEFAULT_SERVER_SETTINGS, ServerSettings } from "@threadlines/contracts"; import { fromLenientJson } from "@threadlines/shared/schemaJson"; import { isThrowawayTelemetryRun } from "@threadlines/shared/telemetryConsent"; import { ServerConfig } from "../../config.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; import { AnalyticsService, type AnalyticsServiceShape } from "../Services/AnalyticsService.ts"; import { getTelemetryIdentifier } from "../Identify.ts"; @@ -72,13 +74,30 @@ const TelemetryEnvConfig = Config.all({ ), }); -const makeAnalyticsService = Effect.fnUntraced(function* (tempDir: string) { +const DEFAULT_FLUSH_INTERVAL_MS = 15_000; +const DEFAULT_MAX_FLUSH_BACKOFF_MS = 300_000; + +export interface AnalyticsServiceLayerOptions { + readonly tempDir: string; + readonly flushIntervalMs?: number; + readonly maxFlushBackoffMs?: number; +} + +const makeAnalyticsService = Effect.fnUntraced(function* (options: AnalyticsServiceLayerOptions) { + const { tempDir } = options; + const flushIntervalMs = Math.max(1, options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS); + const maxFlushBackoffMs = Math.max( + flushIntervalMs, + options.maxFlushBackoffMs ?? DEFAULT_MAX_FLUSH_BACKOFF_MS, + ); const telemetryConfig = yield* TelemetryEnvConfig; const httpClient = yield* HttpClient.HttpClient; const serverConfig = yield* ServerConfig; const fileSystem = yield* FileSystem.FileSystem; + const serverSettings = yield* Effect.serviceOption(ServerSettingsService); const identifierRef = yield* Ref.make(undefined); const bufferRef = yield* Ref.make>([]); + const consecutiveFailuresRef = yield* Ref.make(0); const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client"; const telemetryIdentifier = getTelemetryIdentifier.pipe( Effect.provideService(ServerConfig, serverConfig), @@ -105,6 +124,48 @@ const makeAnalyticsService = Effect.fnUntraced(function* (tempDir: string) { return identifier; }); + const hasPosthogKey = telemetryConfig.posthogKey.trim().length > 0; + let enabledCache = false; + let clearGeneration = 0; + const disabledListeners = new Set<() => void>(); + + const applyEnabled = (next: boolean) => + Effect.suspend(() => { + const effective = hasPosthogKey && next; + const wasEnabled = enabledCache; + enabledCache = effective; + if (!effective) { + clearGeneration += 1; + } + if (wasEnabled && !effective) { + for (const listener of disabledListeners) { + listener(); + } + } + return effective ? Effect.void : Ref.set(bufferRef, []); + }); + + const readSettingsFileConsent = Effect.gen(function* () { + const fileResult = yield* fileSystem + .readFileString(serverConfig.settingsPath) + .pipe(Effect.result); + if (fileResult._tag === "Failure") { + // Missing settings file means a fresh install using the default preference; any other read error fails closed. + const error = fileResult.failure; + const isMissing = + typeof error === "object" && + error !== null && + "reason" in error && + (error as { readonly reason?: { readonly _tag?: string } }).reason?._tag === "NotFound"; + return isMissing ? null : false; + } + const decodedSettings = decodeServerSettingsJson(fileResult.success); + return Option.match(decodedSettings, { + onNone: () => false, + onSome: (settings) => settings.usageAnalyticsEnabled, + }); + }).pipe(Effect.catch(() => Effect.succeed(false))); + const isTelemetryEnabled = Effect.gen(function* () { if (Option.isSome(telemetryConfig.enabledOverride)) { return telemetryConfig.enabledOverride.value; @@ -112,21 +173,45 @@ const makeAnalyticsService = Effect.fnUntraced(function* (tempDir: string) { if (throwawayRun) { return false; } + if (Option.isSome(serverSettings)) { + return yield* serverSettings.value.readStored.pipe( + Effect.map((settings) => settings.usageAnalyticsEnabled), + // Fail closed when stored settings cannot be read so an unreadable file never opts a user in. + Effect.catch(() => Effect.succeed(false)), + ); + } - const rawSettings = yield* fileSystem - .readFileString(serverConfig.settingsPath) - .pipe(Effect.catch(() => Effect.succeed(""))); - const decodedSettings = decodeServerSettingsJson(rawSettings); - return Option.match(decodedSettings, { - onNone: () => DEFAULT_SERVER_SETTINGS.usageAnalyticsEnabled, - onSome: (settings) => settings.usageAnalyticsEnabled, - }); + const fromDisk = yield* readSettingsFileConsent; + return fromDisk === null ? DEFAULT_SERVER_SETTINGS.usageAnalyticsEnabled : fromDisk; }).pipe( Effect.catch((cause) => Effect.logDebug("Failed to resolve telemetry settings", { cause }).pipe(Effect.as(false)), ), + Effect.tap((enabled) => applyEnabled(enabled)), ); + // Seed live consent state before returning so synchronous counters reflect current preference. + yield* isTelemetryEnabled; + if ( + hasPosthogKey && + Option.isSome(serverSettings) && + Option.isNone(telemetryConfig.enabledOverride) && + !throwawayRun + ) { + yield* serverSettings.value.subscribeChanges.pipe( + Effect.flatMap((changes) => + Stream.runForEach(changes, (settings) => applyEnabled(settings.usageAnalyticsEnabled)), + ), + Effect.catch(() => Effect.void), + Effect.forkScoped, + ); + } + + const clampBufferedEvents = (events: ReadonlyArray) => + events.length > telemetryConfig.maxBufferedEvents + ? events.slice(events.length - telemetryConfig.maxBufferedEvents) + : events; + const enqueueBufferedEvent = (event: string, properties?: Readonly>) => Effect.flatMap(DateTime.now, (now) => Ref.modify(bufferRef, (current) => { @@ -139,10 +224,7 @@ const makeAnalyticsService = Effect.fnUntraced(function* (tempDir: string) { } satisfies BufferedAnalyticsEvent, ]; - const next = - appended.length > telemetryConfig.maxBufferedEvents - ? appended.slice(appended.length - telemetryConfig.maxBufferedEvents) - : appended; + const next = clampBufferedEvents(appended); return [ { @@ -161,6 +243,19 @@ const makeAnalyticsService = Effect.fnUntraced(function* (tempDir: string) { if (!posthogKey) return; const enabled = yield* isTelemetryEnabled; if (!enabled) return; + // Double-check settings.json on disk once per outgoing HTTP batch so an external + // opt-out or corrupt file is still honored even if the settings file watcher died. + if ( + Option.isSome(serverSettings) && + Option.isNone(telemetryConfig.enabledOverride) && + !throwawayRun + ) { + const diskConsent = yield* readSettingsFileConsent; + if (diskConsent === false) { + yield* applyEnabled(false); + return; + } + } const identifier = yield* getIdentifier; if (!identifier) return; @@ -201,25 +296,44 @@ const makeAnalyticsService = Effect.fnUntraced(function* (tempDir: string) { }); if (batch.length === 0) { + yield* Ref.set(consecutiveFailuresRef, 0); return; } + const generation = clearGeneration; yield* sendBatch(batch).pipe( Effect.catch((error) => - Ref.update(bufferRef, (current) => [...batch, ...current]).pipe( - Effect.flatMap(() => Effect.fail(error)), - ), + (enabledCache && clearGeneration === generation + ? Ref.update(bufferRef, (current) => clampBufferedEvents([...batch, ...current])) + : Effect.void + ).pipe(Effect.flatMap(() => Effect.fail(error))), ), ); + yield* Ref.set(consecutiveFailuresRef, 0); } - }).pipe(Effect.catch((cause) => Effect.logError("Failed to flush telemetry", { cause }))); + }).pipe( + Effect.catch((cause) => + Ref.updateAndGet(consecutiveFailuresRef, (failures) => failures + 1).pipe( + Effect.flatMap((failures) => + failures === 1 + ? Effect.logWarning("Failed to flush telemetry; retrying with backoff", { cause }) + : Effect.logDebug("Failed to flush telemetry", { + cause, + consecutiveFailures: failures, + }), + ), + ), + ), + ); const record: AnalyticsServiceShape["record"] = Effect.fn("record")( function* (event, properties) { + if (!telemetryConfig.posthogKey.trim()) return; const enabled = yield* isTelemetryEnabled; if (!enabled) return; + const generation = clearGeneration; const identifier = yield* getIdentifier; - if (!identifier) return; + if (!identifier || !enabledCache || clearGeneration !== generation) return; const enqueueResult = yield* enqueueBufferedEvent(event, properties); if (enqueueResult.dropped) { @@ -231,15 +345,37 @@ const makeAnalyticsService = Effect.fnUntraced(function* (tempDir: string) { }, ); - yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), { - disableYield: true, - }).pipe(Effect.forkScoped); + const nextFlushDelayMs = Ref.get(consecutiveFailuresRef).pipe( + Effect.map((failures) => + Math.min(maxFlushBackoffMs, flushIntervalMs * 2 ** Math.min(failures, 10)), + ), + ); + + yield* Effect.forever( + nextFlushDelayMs.pipe( + Effect.flatMap((delayMs) => Effect.sleep(delayMs)), + Effect.tap(() => isTelemetryEnabled), + Effect.flatMap(() => flush), + ), + { + disableYield: true, + }, + ).pipe(Effect.forkScoped); yield* Effect.addFinalizer(() => flush); return { record, flush, + consent: { + isEnabledSync: () => enabledCache, + onDisabled: (listener) => { + disabledListeners.add(listener); + return () => { + disabledListeners.delete(listener); + }; + }, + }, } satisfies AnalyticsServiceShape; }); @@ -248,7 +384,7 @@ const makeAnalyticsService = Effect.fnUntraced(function* (tempDir: string) { * throwaway run (see `isThrowawayTelemetryRun`). Tests pass their own so * their scratch data folders can still exercise the settings opt-out. */ -export const makeAnalyticsServiceLayer = (options: { readonly tempDir: string }) => - Layer.effect(AnalyticsService, makeAnalyticsService(options.tempDir)); +export const makeAnalyticsServiceLayer = (options: AnalyticsServiceLayerOptions) => + Layer.effect(AnalyticsService, makeAnalyticsService(options)); export const AnalyticsServiceLayerLive = makeAnalyticsServiceLayer({ tempDir: OS.tmpdir() }); diff --git a/apps/server/src/telemetry/Services/AnalyticsService.ts b/apps/server/src/telemetry/Services/AnalyticsService.ts index 371fc892b..74765b124 100644 --- a/apps/server/src/telemetry/Services/AnalyticsService.ts +++ b/apps/server/src/telemetry/Services/AnalyticsService.ts @@ -10,6 +10,11 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Context from "effect/Context"; +export interface AnalyticsConsentState { + readonly isEnabledSync: () => boolean; + readonly onDisabled: (listener: () => void) => () => void; +} + export interface AnalyticsServiceShape { /** * Capture an event immediately; returns typed failure when capture fails. @@ -23,6 +28,12 @@ export interface AnalyticsServiceShape { * Flush queued telemetry. */ readonly flush: Effect.Effect; + + /** + * Live consent state so synchronous aggregators (such as DailyCounter) do not + * accumulate activity during opted-out periods and drop pending counts on opt-out. + */ + readonly consent?: AnalyticsConsentState; } export class AnalyticsService extends Context.Service()( diff --git a/docs/telemetry.md b/docs/telemetry.md index 717483cfe..fb432065c 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -13,7 +13,10 @@ Threadlines sends product and reliability events such as: - app/server startup heartbeat; - in the desktop app, how long its background service took to answer after the app started it, in milliseconds, how many tries that took, and whether - it was slow enough to show the "still starting" notice; + it was slow enough to show the "still starting" notice; and if the + background service fails to start, the failure kind, attempts, exit code, + reason, and the last 2,000 characters of startup output (with your home + folder path and common credential shapes scrubbed out first); - whether each coding agent (Codex, Claude, and the other supported agents) is turned on, installed, and signed in (yes, no, or unknown), and whether its startup check timed out. Community agents are answered together, as whether @@ -21,13 +24,47 @@ Threadlines sends product and reliability events such as: finish and again when an answer changes; - when a community agent (one from the open ACP registry) is installed or removed, with its public registry id and version; +- when an agent runtime is installed, updated, or repaired from Settings, with + the resolved agent kind (and public registry id for community agents), + action, outcome status, and duration in milliseconds (never command output); - when an agent outside Threadlines (one you approve under Settings, - Connections, Agents) connects: which kind it is (`claude-code`, `codex`, - `gemini-cli`, `cursor`, `threadlines-command` or `other`, never the name it - gave) and whether it may only see threads or also start them; + Connections, Agents) or an always-on assistant connects (or an assistant key + is created): which known kind it is (`claude-code`, `codex`, `gemini-cli`, + `cursor`, `threadlines-command`, `grok-bot`, `chatgpt`, `claude`, `muse`, or + `other`, never the name it gave), how it signed in, and whether it may only + see threads or also start them; - provider session start, stop, and recovery, with how long the agent took to - start in milliseconds; -- turn sent, steered, interrupted, and compact-requested events; + start in milliseconds and whether resuming the prior conversation failed and + had to fall back to history re-seeding; +- turn sent (including whether it ran in the main lane, as a room side answer, + or as an independent room review), steered, interrupted, native code review + started, and compact-requested events; +- room side-answer settlements (outcome and whether they hit the 30-minute + limit) and multi-agent council review starts (number of reviewers); +- automatic recovery and wait events: how many interrupted turns were picked up + after a restart (and whether restart continuation is on), when a paused + usage-limit turn continues automatically (and whether it reset early), and + when a thread goal pauses or resumes for a wait; +- thread goal events when a goal is set (with its status), cleared, or paused + on stop, never the goal's text; +- thread moves between linked computers when a move finishes or aborts: + outcome, abort code if aborted, whether it was a room, family, batch, or + queued move, whether live work was interrupted, whether a parent link or + child threads were kept/adopted, and duration in milliseconds (never computer + names, thread titles, or paths); +- device simulator sessions when opened or when opening fails: platform (`ios` + or `android`), whether a person or agent opened it, whether Threadlines + booted it, whether it is a physical device, error kind on failure, and + duration in milliseconds; plus once a day, how many agent device tool calls + succeeded or failed, by tool; +- secret requests when settled (outcome and destination kind, never key names, + paths, or values); plus once a day, how many watched-key redactions the + secret scrubber performed in agent output (counted per distinct watched key + per scrubbed event or text), by surface (never which key); +- once a day, how many server freezes (2 seconds or longer) occurred, by cause + (`busy`, `overloaded`, or `unknown`), duration bucket (`2-5s`, `5-15s`, or + `15s+`), and whether database calls held the loop (never running program + names or paths); - who a sent message came from, as one of a few kinds: a person using Threadlines, another agent in the same room, another thread's agent, an agent outside Threadlines, a scheduled or event task, or Threadlines on its @@ -56,9 +93,9 @@ Threadlines sends product and reliability events such as: you name yourself in Pi is not on it. Any other model name is reported only as `custom`; - for a community agent added from the ACP registry, its public registry id - (such as `pi-acp`) on session start, message, first-output, interrupt, - model reroute, and failure events, so reports can tell community agents - apart; + (such as `pi-acp`) on provider session, turn, fork, rollback, request, + model reroute, deletion, and failure events, so reports can tell community + agents apart; - provider session start kind, such as fresh starts, resumes, same-provider restarts, and provider switches; - model reroute events with sanitized from/to model values and a categorized reason; @@ -66,21 +103,21 @@ Threadlines sends product and reliability events such as: reasons, such as a usage limit, a full context window or a refused request. The category comes from the agent's own error code when it gives one, and otherwise from the error's wording. Only the category is sent; -- explicit thread fork events with sanitized source/target model values and - context counts; +- explicit thread fork events with source/target agent kinds (never custom + account names), sanitized source/target model values, and context counts; - provider approval/request responses; -- once a day, how many calls agents running outside Threadlines (connected - under Settings → Connections → Agents) made to each of their tools, by the - tool and how it answered (started, busy, refused and so on). Never the - agent's name, a project or a thread's content; +- once a day, how many calls agents running outside Threadlines (local or + always-on assistants over the relay) made to each of their tools, by the + tool, door (`local` or `assistant`), and how it answered (started, busy, + refused and so on). Never the agent's name, a project or a thread's content; - thread rollback and delete events; - themes: when an agent shows one in a chat (and whether it's a new version of one it showed before); when one is kept in this computer's theme library, and whether the same theme was already kept there (a Duplicate) or this was a new version updating a copy kept before; and when one is deleted from it. Each says where the theme came from (made by an - agent, imported from a file, a copy of a starter, made by hand, or unknown - for a theme file that doesn't say), whether + agent, brought in from VS Code / Open VSX, imported from a file, a copy of a + starter, made by hand, or unknown for a theme file that doesn't say), whether it's light or dark, the kind of live art it has (grid, pixels or canvas) or none, and whether it sets its own fonts. Never a theme's name, prompt, colors, art, fonts or the thread it came from. A theme another computer @@ -91,23 +128,33 @@ Threadlines sends product and reliability events such as: theme details as above plus its license and whether the prompt went with it, and when someone takes a share back (nothing about the theme). Never the theme's name, credit, GitHub account or pull request; -- basic counts such as project count, thread count, how many themes are kept - in the theme library, attachment count, and active session count. +- basic counts and feature flags on startup such as project count, thread + count, lead chat count, projects with a brief, project notes, extra accounts, + linked computers, enabled scheduled/event tasks, connected outside agents and + assistants, how many themes are kept in the theme library, and whether + devices and restart continuation are enabled. Each event includes basic environment properties such as operating system, CPU -architecture, Threadlines version, and whether the runtime is the desktop app or -CLI/web server. +architecture, Threadlines version, whether the runtime is the desktop app or +CLI/web server, and the WSL distribution name (`WSL_DISTRO_NAME`) when running +under WSL. ## What We Do Not Collect Threadlines does not send: - prompts or agent responses; -- code, diffs, file contents, file paths, or repository names; +- code, diffs, file contents, repository names, or project file paths (the + desktop startup failure report above scrubs your home folder path, though + system or non-home paths printed during a fatal server crash may still + appear); - terminal input or terminal output; - raw custom/private model names; -- raw provider error messages or stack traces; -- provider API keys, auth tokens, secrets, or environment variable values; +- raw provider error messages or stack traces (except the scrubbed startup + failure report above when the desktop app's background service cannot boot); +- provider API keys, auth tokens, secrets, or arbitrary environment variable + values (the desktop startup failure report scrubs common credential shapes, + and `WSL_DISTRO_NAME` is sent when running under WSL); - Codex, Claude, GitHub, or other third-party account identifiers, including the account name or email shown next to a signed-in agent. diff --git a/packages/contracts/src/provider.ts b/packages/contracts/src/provider.ts index 81c821c4f..312dd3dc0 100644 --- a/packages/contracts/src/provider.ts +++ b/packages/contracts/src/provider.ts @@ -289,6 +289,10 @@ export const ProviderTurnOrigin = Schema.Literals([ ]); export type ProviderTurnOrigin = typeof ProviderTurnOrigin.Type; +/** Which room lane ran a turn, for usage analytics only. */ +export const ProviderTurnLane = Schema.Literals(["main", "side", "side_review"]); +export type ProviderTurnLane = typeof ProviderTurnLane.Type; + /** * How long the steps before the agent gets a message took, for usage analytics * only. `queueMs`: waiting behind the thread's earlier work. `prepareMs`: getting @@ -330,6 +334,8 @@ export const ProviderSendTurnInput = Schema.Struct({ requestedAt: Schema.optional(IsoDateTime), /** See ProviderTurnOrigin. */ origin: Schema.optional(ProviderTurnOrigin), + /** See ProviderTurnLane. */ + lane: Schema.optional(ProviderTurnLane), /** * A person sent this from the app and reads the reply: a driver that makes * its own suggestion of their next message (Codex) does so after this turn.