Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Measure aggregate product health and explicit work with privacy controls (#1323)

Deed18d3f744368
diff --git a/backend/src/analytics/productHealth.test.ts b/backend/src/analytics/productHealth.test.ts
new file mode 100644
index 000000000..91077cf28
--- /dev/null
+++ b/backend/src/analytics/productHealth.test.ts
@@ -0,0 +1,38 @@
+import { readFileSync } from 'node:fs'
+import { expect, it } from 'vitest'
+import { cleanUsageContext, HEALTH_MEASURES, HEALTH_FLOWS } from '../types/productHealthContract.js'
+import { dailyProductHealth, healthBreakdowns } from './productHealth.js'
+
+const context = { surface: 'desktop', release: '1.2.73', platform: 'macos', channel: 'production' } as const
+it('keeps the CLI contract identical and every Desktop enum in the server vocabulary', () => {
+ expect(readFileSync('../cli/src/lib/productHealthContract.ts', 'utf8')).toBe(readFileSync('src/types/productHealthContract.ts', 'utf8'))
+ const dart = readFileSync('../desktop/lib/measurement/product_health_contract.dart', 'utf8')
+ for (const metric of HEALTH_MEASURES) expect(dart).toContain(`'${metric}'`)
+ const flows = readFileSync('../desktop/lib/measurement/product_measurement.dart', 'utf8')
+ for (const flow of HEALTH_FLOWS) expect(flows).toContain(`'${flow}'`)
+})
+it('creates two independent margins with no joint dimensions or arbitrary labels', () => {
+ expect(healthBreakdowns(context, 'turns_started')).toEqual(['breakdown:release:desktop:1.2.73:turns_started', 'breakdown:platform:desktop:macos:turns_started'])
+ expect(healthBreakdowns({ ...context, channel: 'development' }, 'turns_started')).toEqual([])
+ expect(healthBreakdowns(context, 'PRIVATE')).toEqual([])
+ expect(cleanUsageContext({ ...context, release: 'PRIVATE/custom-build', private: 'PRIVATE' })).toEqual({ ...context, release: 'unknown' })
+ expect(cleanUsageContext({ ...context, platform: 'PRIVATE' })).toBeUndefined()
+})
+it('suppresses sparse labels, distinguishes missing from zero, and matures first-work cohorts', () => {
+ const row = (day: string, metric: string, value: number) => ({ dayUtc: new Date(day), metric, value })
+ const data = dailyProductHealth([
+ row('2026-10-01', 'health_cli_first_interactive_work', 10),
+ row('2026-10-01', 'health_cli_first_work_d1_return', 4),
+ row('2026-10-02', 'health_cli_collector_days', 30),
+ row('2026-10-01', 'breakdown:release:desktop:1.2.73:health_desktop_collector_days', 19),
+ row('2026-10-01', 'breakdown:platform:desktop:macos:health_desktop_collector_days', 20),
+ row('2026-10-01', 'breakdown:release:desktop:PRIVATE:turns_started', 500),
+ row('2026-10-01', 'create_requests', 4), row('2026-10-01', 'create_ok', 2),
+ ], new Date('2026-10-04'))
+ expect(data.breakdowns).toHaveLength(1); expect(JSON.stringify(data)).not.toContain('1.2.73')
+ expect(JSON.stringify(data)).not.toContain('PRIVATE')
+ expect(data.daily[0].firstWorkRetention[0]).toMatchObject({ denominator: 10, returned: 4, percent: 40, mature: true })
+ expect(data.daily[0].firstWorkRetention[1].percent).toBeNull()
+ expect(data.daily[0].requestReconciliation[0]).toMatchObject({ starts: 4, outcomes: 2, difference: 2 })
+ expect(data.daily[1].firstWorkRetention[0].denominator).toBeNull()
+})
diff --git a/backend/src/analytics/productHealth.ts b/backend/src/analytics/productHealth.ts
new file mode 100644
index 000000000..45341aeb6
--- /dev/null
+++ b/backend/src/analytics/productHealth.ts
@@ -0,0 +1,81 @@
+import { PRODUCT_USAGE_METRICS, PRODUCT_USAGE_SETUP_METRICS, PRODUCT_USAGE_ACTIONS } from '../types/productUsage.js'
+import { cleanUsageContext, type ProductUsageContext } from '../types/productHealthContract.js'
+
+const allowed = new Set<string>(PRODUCT_USAGE_METRICS)
+// Two marginal tables in the existing expiring total store. No release/platform cross-product,
+// account joins, per-report rows, or arbitrary attributes survive ingestion.
+export function healthBreakdowns(context: ProductUsageContext | undefined, metric: string): string[] {
+ const c = cleanUsageContext(context)
+ if (!c || c.channel !== 'production' || !allowed.has(metric)) return []
+ // Backdated returns describe an earlier cohort; the current reporting release did not enroll it.
+ if (/^(d\d+_returning_|first_launch_(work|response)_24h_|health_cli_(first_work_d\d+_return|week_worked_))/.test(metric)) return []
+ return [`breakdown:release:${c.surface}:${c.release}:${metric}`, `breakdown:platform:${c.surface}:${c.platform}:${metric}`]
+}
+
+type Row = { dayUtc: Date; metric: string; value: number }
+export function dailyProductHealth(rows: Row[], now: Date) {
+ const today = now.toISOString().slice(0, 10)
+ const readable = new Set<string>([...PRODUCT_USAGE_METRICS, ...PRODUCT_USAGE_SETUP_METRICS])
+ const days = new Map<string, Record<string, number>>()
+ const groups = new Map<string, { day: string; dimension: string; surface: string; bucket: string; counters: Record<string, number> }>()
+ for (const row of rows) {
+ if (!Number.isSafeInteger(row.value) || row.value < 0) continue
+ const day = row.dayUtc.toISOString().slice(0, 10)
+ if (readable.has(row.metric)) {
+ const c = days.get(day) ?? {}; c[row.metric] = (c[row.metric] ?? 0) + row.value; days.set(day, c)
+ } else {
+ const m = /^breakdown:(release|platform):(cli|desktop):([^:]+):(.+)$/.exec(row.metric)
+ if (!m || !allowed.has(m[4])) continue
+ const context = cleanUsageContext({ surface: m[2], release: m[1] === 'release' ? m[3] : 'unknown',
+ platform: m[1] === 'platform' ? m[3] : 'other', channel: 'production' })
+ if (!context || (m[1] === 'release' && context.release !== m[3])) continue
+ const key = `${day}:${m[1]}:${m[2]}:${m[3]}`
+ const g = groups.get(key) ?? { day, dimension: m[1], surface: m[2], bucket: m[3], counters: {} }
+ g.counters[m[4]] = (g.counters[m[4]] ?? 0) + row.value; groups.set(key, g)
+ }
+ }
+ const daily = [...days].sort(([a], [b]) => a.localeCompare(b)).map(([day, c]) => ({
+ day, complete: day < today,
+ coverage: { cli: c.health_cli_collector_days ?? null, desktopSessions: c.health_desktop_collector_days ?? null },
+ requestReconciliation: PRODUCT_USAGE_ACTIONS.map(action => {
+ const starts = c[`${action}_requests`] ?? null
+ const outcomes = ['ok', 'failed', 'pending', 'unknown'].reduce((sum, outcome) => sum + (c[`${action}_${outcome}`] ?? 0), 0)
+ return { action, starts, outcomes: starts === null ? null : outcomes,
+ difference: starts === null ? null : starts - outcomes,
+ interpretation: 'Start and result reports can arrive separately or cross a choice/day boundary. A difference is incomplete observation, not a failed action.' }
+ }),
+ signals: Object.fromEntries(Object.entries(c).filter(([k]) => k.startsWith('health_') || k.startsWith('request_'))),
+ activation: ['setup_desktop', 'health_desktop'].map(prefix => ({
+ population: prefix === 'setup_desktop' ? 'Voluntary signed-out setup episodes' : 'Consented signed-in app sessions',
+ milestones: Object.fromEntries(['setup_seen', 'sign_in_seen', 'workspace_ready', 'first_work', 'first_response'].map(step => [step, c[`${prefix}_funnel_${step}`] ?? null])),
+ waitBuckets: Object.fromEntries(['first_work', 'first_response'].flatMap(step => ['under_1m', '1m_to_5m', 'over_5m'].map(bucket => [`${step}_${bucket}`, c[`${prefix}_${step}_${bucket}`] ?? null]))),
+ definition: 'Locally deduplicated episodes, not a joined per-person funnel. Stages can cross UTC days; no daily conversion ratio is inferred.',
+ })),
+ firstWorkRetention: [1, 7, 28].map(lag => {
+ const mature = Date.parse(day) + (lag + 1) * 86400000 <= Date.parse(today)
+ const denominator = c.health_cli_first_interactive_work ?? null
+ const followUp = days.get(new Date(Date.parse(day) + lag * 86400000).toISOString().slice(0, 10))
+ const observable = !!followUp?.health_cli_collector_days
+ const returned = mature && observable && denominator ? c[`health_cli_first_work_d${lag}_return`] ?? 0 : null
+ return { lag, mature, followUpObserved: observable, denominator, returned,
+ percent: returned !== null && denominator && returned <= denominator ? Math.round(1000 * returned / denominator) / 10 : null }
+ }),
+ }))
+ const breakdowns = [...groups.values()].flatMap(group => {
+ const coverage = group.counters[`health_${group.surface}_collector_days`] ?? 0
+ // Suppress the label as well as values. Session/installation observations are not distinct people;
+ // this threshold limits sparse disclosure but is deliberately not described as k-anonymity.
+ if (coverage < 20) return []
+ return [{ ...group, coverage, partial: group.day === today }]
+ })
+ return { daily, breakdowns, sparseBreakdownsSuppressed: groups.size - breakdowns.length,
+ definitions: {
+ attribution: 'Release and platform are separate aggregate margins. Development-context reports are excluded. Old clients have unknown context; version comparison alone cannot establish causality.',
+ sources: 'app/tool describe the request transport; automatic identifies fixed polling operations. Only explicitly marked composer submissions establish interactive work. Raw terminal work remains unclassified.',
+ retention: 'Return after first measured interactive work on this installation, not signup retention; resets and missing reports affect coverage.',
+ stability: 'Unclean prior runs can be force quits or power loss, not proven crashes. Resource buckets cover the measured process only. Main-frame load is not a judgment of rendered content.',
+ timing: 'App start is process launch to first consented observation of a connected workspace; sign-in and preference delay are included. One in 60 rendered frames is sampled; idle freezes and exits before reporting can be missed.',
+ habit: 'Weekly work-day bins describe completed UTC weeks from installations that report again; non-returners may be missing. First-work returns are specific to explicitly marked composer work, not all human activity.',
+ privacy: 'Fixed aggregate totals; no identity or content joins. Sparse margins require 20 collector observations, which are not 20 distinct people. No guarantee of anonymity is inferred from that threshold.',
+ } }
+}
diff --git a/backend/src/lib/productUsage.test.ts b/backend/src/lib/productUsage.test.ts
index 85305946f..3c16def8b 100644
--- a/backend/src/lib/productUsage.test.ts
+++ b/backend/src/lib/productUsage.test.ts
@@ -19,6 +19,20 @@ vi.mock('../config/env.js', () => ({ env: { PRODUCT_USAGE_SUBJECT_KEY: 'k'.repea
import { activitySubject, deleteActivity, deleteLegacyProductUsage, ensureProductUsageExpiry, markActivity, resetActivityMarksForTests, ingestProductUsage, ingestSetupUsage, productUsageChoice, recordRelayUsage, setProductUsageChoice } from './productUsage.js'
import type { ProductUsageReport } from '../types/productUsage.js'
+it('commits release and platform margins under the same unlinked receipt and discards development reports', async () => {
+ const context = { surface: 'desktop', release: '1.2.73', platform: 'macos', channel: 'production' } as const
+ expect(await ingestProductUsage('PRIVATE_ACCOUNT', { ...report, context }, now)).toEqual({ accepted: true })
+ expect(db.$transaction).toHaveBeenCalledOnce()
+ expect(db.productUsageTotal.upsert).toHaveBeenCalledTimes(6)
+ const stored = JSON.stringify([db.productUsageReceipt.create.mock.calls, db.productUsageTotal.upsert.mock.calls])
+ expect(stored).not.toContain('PRIVATE_ACCOUNT')
+ expect(stored).not.toContain('1.2.73:macos')
+ expect(stored).toContain('breakdown:release:desktop:1.2.73:turns_started')
+ db.$transaction.mockClear()
+ expect(await ingestProductUsage('PRIVATE_ACCOUNT', { ...report, context: { ...context, channel: 'development' } }, now)).toMatchObject({ accepted: true, reason: 'DEVELOPMENT' })
+ expect(db.$transaction).not.toHaveBeenCalled()
+})
+
const report: ProductUsageReport = { schemaVersion: 1, revision: 0, id: 'cf1c5a03-388c-4265-b5fb-a4c3d47e407f', day: '2026-10-13', counters: { turns_started: 4, turns_ended: 3 } }
const now = new Date('2026-10-13T12:00:00Z')
beforeEach(() => {
@@ -165,11 +179,16 @@ it('setup ingestion never reads an account and expires after yesterday', async (
expect(await ingestSetupUsage({ ...setup, day: '2026-10-12' }, now)).toMatchObject({ accepted: true })
})
-it('keeps the native app collectors and anonymous transport identical', () => {
- for (const file of ['product_measurement.dart', 'setup_transport.dart', 'setup_usage_choice.dart']) {
+it('keeps anonymous transport and consent unchanged across native apps while Desktop health evolves independently', () => {
+ for (const file of ['setup_transport.dart', 'setup_usage_choice.dart']) {
expect(readFileSync(new URL(`../../../desktop/lib/measurement/${file}`, import.meta.url), 'utf8'))
.toBe(readFileSync(new URL(`../../../mobile/lib/measurement/${file}`, import.meta.url), 'utf8'))
}
+ const mobile = readFileSync(new URL('../../../mobile/lib/measurement/product_measurement.dart', import.meta.url), 'utf8')
+ const desktop = readFileSync(new URL('../../../desktop/lib/measurement/product_measurement.dart', import.meta.url), 'utf8')
+ const mobileFlows = [...mobile.split('enum ProductOutcome')[0].matchAll(/\w+\('([a-z_]+)'\)/g)].map(m => m[1])
+ for (const flow of mobileFlows) expect(desktop).toContain(`'${flow}'`)
+ expect(mobile).not.toContain('product_health_contract.dart')
})
describe('activity marks', () => {
diff --git a/backend/src/lib/productUsage.ts b/backend/src/lib/productUsage.ts
index c457421bb..0ce220636 100644
--- a/backend/src/lib/productUsage.ts
+++ b/backend/src/lib/productUsage.ts
@@ -1,3 +1,5 @@
+import { healthBreakdowns } from '../analytics/productHealth.js'
+import type { ProductUsageContext } from '../types/productHealthContract.js'
import { createHmac } from 'node:crypto'
import type { Prisma } from '@prisma/client'
import { env } from '../config/env.js'
@@ -36,7 +38,7 @@ function validDay(day: string, now: Date): boolean {
/** Identity is used for permission only. Neither it nor the report body reaches analytics storage. */
export async function ingestProductUsage(userId: string, report: ProductUsageReport, now = new Date()) {
if (!validDay(report.day, now)) return { accepted: false, reason: 'EXPIRED' }
- return ingestCounters(report, userId)
+ return ingestCounters(report, userId, now)
}
export interface SetupUsageReport { id: string; day: string; counters: Record<string, number> }
@@ -47,7 +49,8 @@ export async function ingestSetupUsage(report: SetupUsageReport, now = new Date(
return ingestCounters(report)
}
-async function ingestCounters(report: SetupUsageReport & { revision?: number }, userId?: string) {
+async function ingestCounters(report: SetupUsageReport & { revision?: number; context?: ProductUsageContext }, userId?: string, now = new Date()) {
+ if (report.context?.channel === 'development') return { accepted: true, reason: 'DEVELOPMENT' }
try {
return await prisma.$transaction(async tx => {
if (userId) {
@@ -60,10 +63,18 @@ async function ingestCounters(report: SetupUsageReport & { revision?: number },
} })
for (const [metric, value] of Object.entries(report.counters)) {
if (!value) continue
- await tx.productUsageTotal.upsert({
- where: { dayUtc_metric: { dayUtc: new Date(report.day), metric } },
- create: { dayUtc: new Date(report.day), metric, value }, update: { value: { increment: value } },
- })
+ for (const name of [metric, ...healthBreakdowns(report.context, metric)]) {
+ await tx.productUsageTotal.upsert({
+ where: { dayUtc_metric: { dayUtc: new Date(report.day), metric: name } },
+ create: { dayUtc: new Date(report.day), metric: name, value }, update: { value: { increment: value } },
+ })
+ }
+ }
+ if (report.context && report.day < now.toISOString().slice(0, 10)) {
+ const dayUtc = new Date(Math.floor(now.getTime() / DAY) * DAY)
+ const metric = `health_${report.context.surface}_report_late`
+ await tx.productUsageTotal.upsert({ where: { dayUtc_metric: { dayUtc, metric } },
+ create: { dayUtc, metric, value: 1 }, update: { value: { increment: 1 } } })
}
return { accepted: true }
})
diff --git a/backend/src/productUsageReport.ts b/backend/src/productUsageReport.ts
index 5b2a1f310..f537cf618 100644
--- a/backend/src/productUsageReport.ts
+++ b/backend/src/productUsageReport.ts
@@ -1,3 +1,4 @@
+import { dailyProductHealth } from './analytics/productHealth.js'
/** Aggregate-only daily report. Run with a read-only database identity; never prints identifiers. */
import { PrismaClient } from '@prisma/client'
import { DAILY_PRODUCT_METRICS, dailyProductUsage } from './analytics/dailyProductUsage.js'
@@ -14,6 +15,10 @@ try {
where: { dayUtc: { gte: new Date(today - 92 * 86400000), lt: new Date(today + 86400000) }, metric: { in: [...DAILY_PRODUCT_METRICS, ...PEOPLE_METRICS] } },
select: { dayUtc: true, metric: true, value: true }, orderBy: [{ dayUtc: 'asc' }, { metric: 'asc' }], take: 93 * (DAILY_PRODUCT_METRICS.length + PEOPLE_METRICS.length),
})
+ const breakdowns = await db.productUsageTotal.findMany({
+ where: { dayUtc: { gte: new Date(today - (days - 1) * 86400000), lt: new Date(today + 86400000) }, metric: { startsWith: 'breakdown:' } },
+ select: { dayUtc: true, metric: true, value: true }, orderBy: [{ dayUtc: 'desc' }, { metric: 'asc' }], take: 50000,
+ })
console.log(JSON.stringify({ generatedAt: new Date().toISOString(), timezone: 'UTC',
definitions: {
population: 'Daemon counts cover participating signed-in installations, including staff and both service environments. App flows and optional signed-out setup counts are separate populations, never unique people.',
@@ -25,6 +30,6 @@ try {
outcomes: 'Matched observed turn ends and interruptions, not task success. Missing or interrupted telemetry is not a failed task.',
relay: 'Legacy relay event totals are separate; never add them to the client counters.',
coverage: 'New local counters need updated clients. Delayed/offline reports and privacy changes can affect counts; today is incomplete.',
- }, ...dailyProductUsage(rows, days, new Date()), review: dailyProductReview(rows, new Date()), people: dailyProductPeople(rows, days, new Date()) }, null, 2))
+ }, ...dailyProductUsage(rows, days, new Date()), review: dailyProductReview(rows, new Date()), people: dailyProductPeople(rows, days, new Date()), health: { ...dailyProductHealth([...rows, ...breakdowns], new Date()), breakdownReadLimitReached: breakdowns.length === 50000 } }, null, 2))
} catch { console.error('Could not read aggregate product usage. Check the read-only connection and schema.'); process.exitCode = 1 }
finally { await db.$disconnect() }
diff --git a/backend/src/routes/productUsage.test.ts b/backend/src/routes/productUsage.test.ts
index 614a9d389..4c7cc88bf 100644
--- a/backend/src/routes/productUsage.test.ts
+++ b/backend/src/routes/productUsage.test.ts
@@ -64,12 +64,22 @@ it('the visible control changes only the authenticated account', async () => {
it('the complete vocabulary fits bounded chunks, including the longest metric keys', async () => {
for (let i = 0; i < PRODUCT_USAGE_METRICS.length; i += 64) {
- const payload = { ...good, counters: Object.fromEntries(PRODUCT_USAGE_METRICS.slice(i, i + 64).map(k => [k, PRODUCT_USAGE_MAX_COUNT])) }
+ const payload = { ...good, context: { surface: 'desktop', release: '999.999.999', platform: 'windows', channel: 'production' }, counters: Object.fromEntries(PRODUCT_USAGE_METRICS.slice(i, i + 64).map(k => [k, PRODUCT_USAGE_MAX_COUNT])) }
expect(Buffer.byteLength(JSON.stringify(payload))).toBeLessThan(8192)
expect((await submit(payload)).statusCode).toBe(200)
}
})
+it('rejects extra context, custom versions and device fingerprints without echoing them', async () => {
+ const context = { surface: 'desktop', release: '1.2.73', platform: 'macos', channel: 'production' }
+ for (const c of [{ ...context, path: 'PRIVATE_CANARY' }, { ...context, release: 'PRIVATE_CANARY' },
+ { ...context, platform: 'PRIVATE_CANARY' }, { ...context, channel: 'PRIVATE_CANARY' }]) {
+ const response = await submit({ ...good, context: c })
+ expect(response.statusCode).toBe(400); expect(response.body).not.toContain('PRIVATE_CANARY')
+ }
+ expect(methods.ingestProductUsage).not.toHaveBeenCalled()
+})
+
const setup = { schemaVersion: 1, consent: true, id: good.id, day: good.day, counters: { setup_desktop_sign_in_started: 1 } }
const sendSetup = (payload: unknown = setup, headers = {}) => app.inject({ method: 'POST', url: '/api/product-usage/setup', payload: payload as Record<string, unknown>, headers })
it('accepts only explicitly enabled setup counts without credentials or account lookup', async () => {
diff --git a/backend/src/routes/productUsage.ts b/backend/src/routes/productUsage.ts
index 3533f945a..ff08cd116 100644
--- a/backend/src/routes/productUsage.ts
+++ b/backend/src/routes/productUsage.ts
@@ -2,9 +2,18 @@ import type { FastifyInstance } from 'fastify'
import { z } from 'zod'
import { ingestProductUsage, ingestSetupUsage, productUsageChoice, setProductUsageChoice } from '../lib/productUsage.js'
import { PRODUCT_FEEDBACK, PRODUCT_USAGE_MAX_COUNT, PRODUCT_USAGE_METRICS, PRODUCT_USAGE_SETUP_METRICS } from '../types/productUsage.js'
+import { releaseBucket } from '../types/productHealthContract.js'
import { sendError, sendSuccess } from '../utils/response.js'
+const contextSchema = z.strictObject({
+ surface: z.enum(['cli', 'desktop']),
+ release: z.string().max(11).refine(v => v === 'unknown' || releaseBucket(v) === v),
+ platform: z.enum(['macos', 'linux', 'windows', 'other']),
+ channel: z.enum(['production', 'development']),
+})
+
export const productUsageReportSchema = z.strictObject({
+ context: contextSchema.optional(),
schemaVersion: z.literal(1), revision: z.number().int().nonnegative(), id: z.uuid(),
day: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
counters: z.partialRecord(z.enum(PRODUCT_USAGE_METRICS), z.number().int().min(0).max(PRODUCT_USAGE_MAX_COUNT)),
diff --git a/backend/src/types/productHealthContract.ts b/backend/src/types/productHealthContract.ts
new file mode 100644
index 000000000..d973261ed
--- /dev/null
+++ b/backend/src/types/productHealthContract.ts
@@ -0,0 +1,53 @@
+/** Fixed health vocabulary. Keep the CLI/backend copies identical. No arbitrary labels. */
+export const HEALTH_SOURCES = ['app', 'tool', 'automatic', 'unknown'] as const
+export const HEALTH_ACTIONS = ['create', 'resume', 'restart', 'model_change', 'history', 'fork', 'close', 'delete',
+ 'search', 'history_page', 'store_list', 'store_install', 'store_update', 'store_remove',
+ 'model_list', 'model_download', 'model_start', 'model_stop', 'browser_open', 'message'] as const
+export const HEALTH_RESULTS = ['started', 'ok', 'failed', 'pending', 'cancelled', 'unknown'] as const
+export const HEALTH_FAILURES = ['setup', 'auth', 'unavailable', 'invalid', 'not_found', 'conflict', 'timeout', 'other'] as const
+export const HEALTH_FLOWS = ['app_start', 'workspace_ready', 'viewer_load', 'update_apply', 'update_relaunch',
+ 'connect_user', 'connect_auto', 'resume_recovery'] as const
+export const HEALTH_MEASURES = [
+ 'collector_days', 'report_failed', 'report_rejected', 'report_expired', 'report_late', 'queue_capped', 'observation_overflow',
+ 'unclean_restart', 'framework_error', 'async_error',
+ 'rss_under_256m', 'rss_256m_to_1g', 'rss_over_1g',
+ 'cpu_under_10pct', 'cpu_10pct_to_50pct', 'cpu_over_50pct',
+ 'frame_under_16ms', 'frame_16ms_to_50ms', 'frame_50ms_to_250ms', 'frame_over_250ms',
+ 'feedback_outcome_shown', 'feedback_outcome_answered', 'feedback_outcome_dismissed',
+ 'feedback_reason_shown', 'feedback_reason_answered', 'feedback_reason_dismissed',
+ 'funnel_setup_seen', 'funnel_sign_in_seen', 'funnel_workspace_ready', 'funnel_first_work', 'funnel_first_response',
+ 'first_work_under_1m', 'first_work_1m_to_5m', 'first_work_over_5m',
+ 'first_response_under_1m', 'first_response_1m_to_5m', 'first_response_over_5m',
+ 'install_new', 'install_upgrade', 'install_unknown',
+ 'connect_error_auth', 'connect_error_unlinked', 'connect_error_offline', 'connect_error_timeout', 'connect_error_other',
+ 'interactive_turns_started', 'tool_turns_started', 'unclassified_turns_started',
+ 'interactive_work_days', 'first_interactive_work', 'first_work_d1_return', 'first_work_d7_return', 'first_work_d28_return',
+ 'week_worked_1day', 'week_worked_2to3days', 'week_worked_4to5days', 'week_worked_6to7days',
+] as const
+export const PRODUCT_HEALTH_METRICS = [
+ ...(['cli', 'desktop'] as const).flatMap(surface => HEALTH_MEASURES.map(m => `health_${surface}_${m}` as const)),
+ ...HEALTH_SOURCES.flatMap(source => HEALTH_ACTIONS.flatMap(action => [
+ ...HEALTH_RESULTS.map(result => `request_${source}_${action}_${result}` as const),
+ ...HEALTH_FAILURES.map(failure => `request_${source}_${action}_error_${failure}` as const),
+ ])),
+] as const
+export type ProductHealthMetric = typeof PRODUCT_HEALTH_METRICS[number]
+export type HealthSource = typeof HEALTH_SOURCES[number]
+export interface ProductUsageContext {
+ surface: 'cli' | 'desktop'
+ release: string
+ platform: 'macos' | 'linux' | 'windows' | 'other'
+ channel: 'production' | 'development'
+}
+/** Public numeric release only. Custom build names, hashes and suffixes cannot become labels. */
+export function releaseBucket(value: unknown): string {
+ return typeof value === 'string' && /^(0|[1-9]\d{0,2})\.(0|[1-9]\d{0,2})\.(0|[1-9]\d{0,2})$/.test(value) ? value : 'unknown'
+}
+export function cleanUsageContext(value: unknown): ProductUsageContext | undefined {
+ if (!value || typeof value !== 'object') return
+ const c = value as ProductUsageContext
+ if (!['cli', 'desktop'].includes(c.surface) || !['macos', 'linux', 'windows', 'other'].includes(c.platform)
+ || !['production', 'development'].includes(c.channel)) return
+ return { surface: c.surface, release: releaseBucket(c.release), platform: c.platform, channel: c.channel }
+}
+
diff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.ts
index 0fb3daa26..fdc70df0f 100644
--- a/backend/src/types/productUsage.ts
+++ b/backend/src/types/productUsage.ts
@@ -1,3 +1,4 @@
+import { HEALTH_FLOWS, PRODUCT_HEALTH_METRICS, type ProductUsageContext } from './productHealthContract.js'
/** Fixed vocabulary only. Keep the CLI copy identical; conformance is tested. */
export const PRODUCT_USAGE_VERSION = 1
export const PRODUCT_USAGE_DAYS = 35
@@ -14,19 +15,24 @@ export const PRODUCT_USAGE_AUTOMATIC_ACTIONS: readonly typeof PRODUCT_USAGE_ACTI
export const PRODUCT_USAGE_FEATURE_MEASURES = ['installation_days', 'first_installations', 'repeat_installation_days'] as const
export const PRODUCT_USAGE_SURFACES = ['desktop', 'phone', 'web'] as const
export const PRODUCT_USAGE_FLOWS = ['setup', 'setup_harness', 'setup_tmux', 'setup_clipboard', 'sign_in',
- 'workspace_connect', 'computer_link', 'remote_connect', 'viewer_open', 'update_check', 'update_stage'] as const
+ 'workspace_connect', 'computer_link', 'remote_connect', 'viewer_open', 'update_check', 'update_stage', ...HEALTH_FLOWS] as const
export const PRODUCT_USAGE_FLOW_MEASURES = ['started', 'ok', 'failed', 'cancelled', 'unknown',
'under_1s', '1s_to_10s', '10s_to_1m', 'over_1m'] as const
export const PRODUCT_USAGE_UI_METRICS = PRODUCT_USAGE_SURFACES.flatMap(surface =>
PRODUCT_USAGE_FLOWS.flatMap(flow => PRODUCT_USAGE_FLOW_MEASURES.map(measure => `ui_${surface}_${flow}_${measure}` as const)))
// A signed-out report is explicitly enabled on this app. It cannot carry account/work metrics.
-export const PRODUCT_USAGE_SETUP_METRICS = PRODUCT_USAGE_SURFACES.flatMap(surface =>
+export const PRODUCT_USAGE_SETUP_METRICS = [...PRODUCT_USAGE_SURFACES.flatMap(surface =>
(['setup', 'setup_harness', 'setup_tmux', 'setup_clipboard', 'sign_in'] as const).flatMap(flow =>
- PRODUCT_USAGE_FLOW_MEASURES.map(measure => `setup_${surface}_${flow}_${measure}` as const)))
+ PRODUCT_USAGE_FLOW_MEASURES.map(measure => `setup_${surface}_${flow}_${measure}` as const))),
+ ...(['funnel_setup_seen', 'funnel_sign_in_seen', 'funnel_workspace_ready', 'funnel_first_work', 'funnel_first_response',
+ 'first_work_under_1m', 'first_work_1m_to_5m', 'first_work_over_5m',
+ 'first_response_under_1m', 'first_response_1m_to_5m', 'first_response_over_5m'] as const).map(m => `setup_desktop_${m}` as const),
+] as const
export const PRODUCT_USAGE_ACTION_MEASURES = ['requests', 'ok', 'failed', 'pending', 'unknown',
'error_setup', 'error_auth', 'error_unavailable', 'error_invalid', 'error_other',
'under_1s', '1s_to_10s', '10s_to_1m', 'over_1m'] as const
export const PRODUCT_USAGE_METRICS = [
+ ...PRODUCT_HEALTH_METRICS,
'active_installation_days', 'working_installation_days', 'first_work_installations',
'repeat_work_installation_days', 'weekly_working_installations', 'weekly_returning_installations',
'monthly_working_installations', 'monthly_returning_installations', 'reactivated_after_7d_installations',
@@ -50,6 +56,7 @@ export const PRODUCT_USAGE_METRICS = [
export type ProductUsageMetric = typeof PRODUCT_USAGE_METRICS[number]
export interface ProductUsageReport {
schemaVersion: 1
+ context?: ProductUsageContext
revision: number
id: string
day: string
diff --git a/cli/e2e/productUsage.e2e.ts b/cli/e2e/productUsage.e2e.ts
index a0ade49d2..0439fb904 100644
--- a/cli/e2e/productUsage.e2e.ts
+++ b/cli/e2e/productUsage.e2e.ts
@@ -39,7 +39,7 @@ it('reports only local counters from a real turn, and the account switch stops t
const agentId = created.agent.id
const turn = async () => {
const ended = client!.next(frame => frame.type === 'turn_ended' && frame.agentId === agentId, 45000)
- client!.send('message', { agentId, content: 'PRIVATE_PROMPT_CANARY: say hello' })
+ client!.send('message', { agentId, content: 'PRIVATE_PROMPT_CANARY: say hello', usageIntent: 'interactive' })
await ended
}
await until('agent ready', async () => {
@@ -61,6 +61,9 @@ it('reports only local counters from a real turn, and the account switch stops t
expect(sum('launch_created')).toBe(1)
expect(sum('launch_failed')).toBe(1)
expect(sum('turns_with_response')).toBeGreaterThan(0)
+ expect(sum('health_cli_interactive_work_days')).toBe(1)
+ expect(sum('health_cli_first_interactive_work')).toBe(1)
+ expect(sum('request_app_message_started')).toBeGreaterThan(0)
const wire = JSON.stringify(backend.productUsage.reports)
for (const privateValue of ['PRIVATE_', creationId, machine.machineId, machine.computerId, machine.token, agentId, cwd, 'userMessage', 'payload']) expect(wire).not.toContain(privateValue)
expect((await fetch(settings, { method: 'POST', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: '{"enabled":false}' })).status).toBe(200)
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 6d3083000..6caa61b22 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -1,4 +1,4 @@
-import { productUsageLaunch, productUsageRequest } from './lib/productUsageSignals.js'
+import { productUsageIntent, productUsageLaunch, productUsageRequest } from './lib/productUsageSignals.js'
import { isLocalOnly, withoutUpdate } from './lib/cardUpdate.js'
import type { PurgeAgentService } from './lib/purgeAgentService.js'
import { MESSAGES_REQUESTS, SHARE_REQUESTS, type Asker, type LocalWindows, type WindowSurface, type BackendNotice, type GatewayEvents, type GatewayPort, type ModelsPort, type RemoteClient, type RemoteRole, type RemoteTransport } from './core/api.js'
@@ -826,7 +826,11 @@ export class BackendSocket {
}
const launchMeasured = productUsageLaunch(type, (frame.payload as { creationId?: unknown } | undefined)?.creationId,
signal => this.toGateway('usage', gateway => gateway.usageLaunch?.(signal)))
- const measured = productUsageRequest(type, (metric) => this.toGateway('usage', (gateway) => gateway.usageCounter?.(metric)))
+ const usageSource = local && connId && this.toolClients.has(connId) ? 'tool' : local || role === 'web' ? 'app' : 'unknown'
+ const measured = productUsageRequest(type, (metric) => this.toGateway('usage', (gateway) => gateway.usageCounter?.(metric)), Date.now, usageSource)
+ productUsageIntent(type, (frame.payload as { usageIntent?: unknown } | undefined)?.usageIntent,
+ (frame.payload as { agentId?: unknown } | undefined)?.agentId, usageSource,
+ signal => this.toGateway('usage', gateway => gateway.usageLaunch?.(signal)))
const reply = (t: string, rid: unknown, p: Record<string, unknown>): void => {
if (t === type) {
measured(p.error ?? (p.failure as { code?: unknown } | undefined)?.code, p.state, !!p.agent, p.ok)
diff --git a/cli/src/gateway/productHealth.spec.ts b/cli/src/gateway/productHealth.spec.ts
new file mode 100644
index 000000000..330a1932f
--- /dev/null
+++ b/cli/src/gateway/productHealth.spec.ts
@@ -0,0 +1,58 @@
+import { expect, it, vi } from 'vitest'
+import { cleanHealthState, createProductHealth } from './productHealth.js'
+
+it('counts only explicit interactive intent and never serializes its identifiers', () => {
+ let now = Date.parse('2026-10-01T12:00:00Z')
+ const add = vi.fn(), health = createProductHealth(add, () => now, cleanHealthState(null, now))
+ health.start('0.3.96')
+ health.work('PRIVATE_RAW_TERMINAL')
+ health.intent('PRIVATE_TOOL', 'tool'); health.work('PRIVATE_TOOL')
+ health.intent('PRIVATE_MIXED', 'interactive'); health.intent('PRIVATE_MIXED', 'tool'); health.work('PRIVATE_MIXED')
+ health.intent('PRIVATE_USER', 'interactive'); health.work('PRIVATE_USER')
+ health.intent('PRIVATE_USER', 'interactive'); health.work('PRIVATE_USER')
+ expect(add.mock.calls.filter(([k]) => k === 'health_cli_interactive_work_days')).toHaveLength(1)
+ expect(add).toHaveBeenCalledWith('health_cli_unclassified_turns_started', undefined)
+ expect(add).toHaveBeenCalledWith('health_cli_tool_turns_started', undefined)
+ expect(add.mock.calls.filter(([k]) => k === 'health_cli_unclassified_turns_started')).toHaveLength(2)
+ for (const lag of [1, 7, 28]) {
+ now = Date.parse('2026-10-01T12:00:00Z') + lag * 86400000
+ health.intent('PRIVATE_USER', 'interactive'); health.work('PRIVATE_USER')
+ expect(add).toHaveBeenCalledWith(`health_cli_first_work_d${lag}_return`, '2026-10-01')
+ }
+ expect(JSON.stringify([health.snapshot(), add.mock.calls])).not.toContain('PRIVATE_')
+ now += 40 * 86400000
+ health.snapshot(); health.intent('PRIVATE_USER', 'interactive'); health.work('PRIVATE_USER')
+ expect(add.mock.calls.filter(([k]) => k === 'health_cli_first_interactive_work')).toHaveLength(1)
+})
+
+it('bounds RAM, expires unobserved intent, resets on a changed choice and samples at most once a minute', () => {
+ let now = Date.parse('2026-10-01T12:00:00Z')
+ const add = vi.fn(), health = createProductHealth(add, () => now, cleanHealthState(null, now))
+ for (let i = 0; i < 1001; i++) health.intent(`intent-${i}`, 'interactive')
+ expect(add).toHaveBeenCalledWith('health_cli_observation_overflow', undefined)
+ now += 120001; health.work('intent-0')
+ expect(add).toHaveBeenCalledWith('health_cli_unclassified_turns_started', undefined)
+ health.reset(); health.intent('old', 'interactive'); health.clearObservations(); health.work('old')
+ expect(health.snapshot().hasWorked).toBe(false)
+ const sample = vi.fn(() => ({ rss: 900 * 1024 ** 2, cpuPercent: 35 }))
+ health.sample(sample); health.sample(sample)
+ expect(sample).toHaveBeenCalledOnce()
+ expect(add).toHaveBeenCalledWith('health_cli_cpu_10pct_to_50pct', undefined)
+ now += 60000; expect(() => health.sample(() => { throw Error('PRIVATE_ERROR') })).not.toThrow()
+})
+
+it('reports only completed observed weeks and a prior unclean run, without claiming a crash', () => {
+ let now = Date.parse('2026-10-05T12:00:00Z')
+ const add = vi.fn(), initial = cleanHealthState({ cleanExit: false, release: '0.3.95' }, now)
+ const health = createProductHealth(add, () => now, initial)
+ health.start('0.3.96'); health.start('0.3.96'); health.checkpoint()
+ health.intent('a', 'interactive'); health.work('a')
+ now += 86400000; health.intent('a', 'interactive'); health.work('a')
+ now += 6 * 86400000; health.checkpoint(); health.checkpoint()
+ expect(add.mock.calls.filter(([k]) => k === 'health_cli_unclean_restart')).toHaveLength(1)
+ expect(add).toHaveBeenCalledWith('health_cli_week_worked_2to3days', '2026-10-05')
+ health.stop(); expect(health.snapshot().cleanExit).toBe(true)
+ const clean = cleanHealthState({ firstWork: '2026-02-30', workDays: ['PRIVATE', '2026-02-30', '2099-01-01'], release: 'PRIVATE', extra: 'PRIVATE' }, now)
+ expect(clean.workDays).toEqual([]); expect(clean.firstWork).toBeNull()
+ expect(JSON.stringify(clean)).not.toContain('PRIVATE')
+})
diff --git a/cli/src/gateway/productHealth.ts b/cli/src/gateway/productHealth.ts
new file mode 100644
index 000000000..6b0d5be6c
--- /dev/null
+++ b/cli/src/gateway/productHealth.ts
@@ -0,0 +1,92 @@
+import type { ProductUsageMetric } from '../lib/productUsageContract.js'
+
+const DAY = 86400000
+const key = (n: number) => new Date(n).toISOString().slice(0, 10)
+const monday = (n: number) => key(n - ((new Date(n).getUTCDay() + 6) % 7) * DAY)
+export interface HealthState {
+ hasWorked: boolean
+ firstWork: string | null
+ workDays: string[]
+ week: string | null
+ cleanExit: boolean
+ release: string | null
+}
+export function cleanHealthState(raw: unknown, now: number): HealthState {
+ const s = (raw ?? {}) as Partial<HealthState>
+ const valid = (v: unknown): v is string => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(v)
+ && Number.isFinite(Date.parse(v)) && key(Date.parse(v)) === v && v <= key(now) && Date.parse(v) > now - 36 * DAY
+ return { hasWorked: s.hasWorked === true || typeof s.firstWork === 'string', firstWork: valid(s.firstWork) ? s.firstWork : null,
+ workDays: Array.isArray(s.workDays) ? [...new Set(s.workDays.filter(valid))].sort().slice(-35) : [],
+ week: valid(s.week) ? s.week : null, cleanExit: s.cleanExit !== false,
+ release: typeof s.release === 'string' && /^(\d{1,3}\.){2}\d{1,3}$/.test(s.release) ? s.release : null }
+}
+
+/** Local date flags and a bounded RAM intent map. No keystrokes, content, ids or event history on disk. */
+export function createProductHealth(add: (metric: ProductUsageMetric, day?: string) => void, now: () => number,
+ initial: HealthState) {
+ let state = initial
+ let started = false, sampledAt = 0
+ const intents = new Map<string, { at: number; origin: 'interactive' | 'tool' | 'unclassified' }>()
+ const count = (m: string, day?: string) => add(`health_cli_${m}` as ProductUsageMetric, day)
+ return {
+ snapshot: () => state = cleanHealthState(state, now()),
+ reset() { state = cleanHealthState(null, now()); intents.clear(); started = false; sampledAt = 0 },
+ clearObservations() { intents.clear() },
+ start(release?: string) {
+ if (started) return
+ started = true
+ if (!state.cleanExit) count('unclean_restart')
+ count(state.release && release && state.release !== release ? 'install_upgrade' : 'install_unknown')
+ state.cleanExit = false; state.release = release ?? null
+ },
+ stop() { state.cleanExit = true; intents.clear() },
+ intent(id: string, origin: 'interactive' | 'tool') {
+ for (const [key, intent] of intents) if (now() - intent.at > 120000) intents.delete(key)
+ if (intents.size >= 1000) { count('observation_overflow'); return }
+ const previous = intents.get(id)
+ intents.set(id, { at: now(), origin: previous && previous.origin !== origin ? 'unclassified' : origin })
+ },
+ work(id: string) {
+ const intent = intents.get(id); intents.delete(id)
+ const origin = intent && now() - intent.at <= 120000 ? intent.origin : 'unclassified'
+ count(`${origin}_turns_started`)
+ if (origin !== 'interactive') return
+ const day = key(now())
+ if (state.workDays.includes(day)) return
+ count('interactive_work_days')
+ if (!state.hasWorked) { state.hasWorked = true; state.firstWork = day; count('first_interactive_work') }
+ for (const lag of [1, 7, 28]) if (state.firstWork === key(now() - lag * DAY)) count(`first_work_d${lag}_return`, state.firstWork)
+ state.workDays = [...state.workDays, day].slice(-35)
+ },
+ checkpoint() {
+ const week = monday(now())
+ if (state.week && state.week < week) {
+ const days = state.workDays.filter(d => d >= state.week! && d < key(Date.parse(state.week!) + 7 * DAY)).length
+ if (days) count(days === 1 ? 'week_worked_1day' : days <= 3 ? 'week_worked_2to3days' : days <= 5 ? 'week_worked_4to5days' : 'week_worked_6to7days', state.week)
+ }
+ state.week = week
+ },
+ sample(sample?: () => { rss: number; cpuPercent?: number }) {
+ if (!sample || now() - sampledAt < 60000) return
+ sampledAt = now()
+ try {
+ const value = sample()
+ if (Number.isFinite(value.rss) && value.rss >= 0) count(value.rss < 256 * 1024 ** 2 ? 'rss_under_256m' : value.rss < 1024 ** 3 ? 'rss_256m_to_1g' : 'rss_over_1g')
+ if (value.cpuPercent !== undefined && Number.isFinite(value.cpuPercent) && value.cpuPercent >= 0) {
+ count(value.cpuPercent < 10 ? 'cpu_under_10pct' : value.cpuPercent < 50 ? 'cpu_10pct_to_50pct' : 'cpu_over_50pct')
+ }
+ } catch { /* Resource observation cannot affect work. */ }
+ },
+ }
+}
+
+/** Called on the gateway's existing minute tick. No process enumeration or core timer. */
+export function gatewayResourceSample() {
+ let cpu = process.cpuUsage(), stamp = performance.now()
+ return () => {
+ const next = process.cpuUsage(), at = performance.now(), elapsed = at - stamp
+ const cpuPercent = elapsed >= 1000 && elapsed <= 120000 ? (next.user + next.system - cpu.user - cpu.system) / (elapsed * 10) : undefined
+ cpu = next; stamp = at
+ return { rss: process.memoryUsage.rss(), cpuPercent }
+ }
+}
diff --git a/cli/src/gateway/productUsage.spec.ts b/cli/src/gateway/productUsage.spec.ts
index 84c2d8e90..3030084a3 100644
--- a/cli/src/gateway/productUsage.spec.ts
+++ b/cli/src/gateway/productUsage.spec.ts
@@ -26,6 +26,29 @@ const totals = () => {
return result
}
+it('keeps upgrade backlogs unattributed and fences explicit-work intent on unavailable consent', async () => {
+ await usage.stop()
+ const context = { surface: 'cli', release: '0.3.95', platform: 'macos', channel: 'production' } as const
+ usage = createProductUsage({ file, now: () => now, request, context })
+ await usage.sync()
+ usage.launch({ id: 'PRIVATE_USER_INTENT', phase: 'work_requested', origin: 'interactive' })
+ usage.observe('turn_started', 'PRIVATE_USER_INTENT', false)
+ usage.observe('turn_ended', 'PRIVATE_USER_INTENT', false)
+ await usage.stop()
+ usage = createProductUsage({ file, now: () => now, request, context: { ...context, release: '0.3.96' } })
+ await usage.sync(); await usage.sync()
+ const workReport = (sent as { counters: Record<string, number>; context: typeof context }[]).find(r => r.counters.health_cli_interactive_work_days)
+ expect(workReport?.context.release).toBe('unknown')
+ expect(totals().health_cli_first_interactive_work).toBe(1)
+ usage.launch({ id: 'PRIVATE_STALE_INTENT', phase: 'work_requested', origin: 'interactive' })
+ request.mockResolvedValueOnce({ status: 503, body: {} })
+ await usage.sync(); await usage.sync()
+ usage.observe('turn_started', 'PRIVATE_STALE_INTENT', false); await usage.sync()
+ expect(totals().health_cli_unclassified_turns_started).toBe(1)
+ expect(JSON.stringify(sent)).not.toContain('PRIVATE')
+ expect(readFileSync(file, 'utf8')).not.toContain('PRIVATE')
+})
+
it('keeps first-launch 24-hour value counts on their original cohort day across restart, without an identity', async () => {
await usage.sync()
now = Date.parse('2026-10-12T23:30:00Z')
@@ -63,6 +86,16 @@ it('collects nothing before it can check the preference, and respects off', asyn
expect(sent).toEqual([])
})
+it('discards a permanently invalid packet so later reports and loss counts can recover', async () => {
+ await usage.sync(); usage.counter('search_requests')
+ request.mockImplementationOnce(async () => ({ status: 200, body: { data: { enabled: true, revision: 0 } } }))
+ .mockImplementationOnce(async () => ({ status: 400, body: {} }))
+ await usage.sync()
+ expect(JSON.parse(readFileSync(file, 'utf8')).pending).toBeNull()
+ await usage.sync()
+ expect(totals().health_cli_report_rejected).toBe(1)
+})
+
it('reduces turns locally, excludes replay, and never persists or uploads agent identity', async () => {
await usage.sync()
usage.opened('desktop')
diff --git a/cli/src/gateway/productUsage.ts b/cli/src/gateway/productUsage.ts
index b2388c0e5..b78668afa 100644
--- a/cli/src/gateway/productUsage.ts
+++ b/cli/src/gateway/productUsage.ts
@@ -1,3 +1,5 @@
+import { cleanUsageContext, type ProductUsageContext } from '../lib/productHealthContract.js'
+import { cleanHealthState, createProductHealth, type HealthState } from './productHealth.js'
import { readFileSync, statSync } from 'node:fs'
import { mkdir, rename, writeFile } from 'node:fs/promises'
import { dirname } from 'node:path'
@@ -18,6 +20,9 @@ const key = (now: number) => new Date(now).toISOString().slice(0, 10)
const week = (now: number) => { const d = new Date(now); return key(now - ((d.getUTCDay() + 6) % 7) * DAY) }
type Counters = Partial<Record<ProductUsageMetric, number>>
interface State {
+ dayContexts: Record<string, ProductUsageContext>
+ health: HealthState
+ healthDay: string | null
revision: number
activeDay: string | null
workDay: string | null
@@ -36,12 +41,14 @@ interface State {
days: Record<string, Counters>
pending: ProductUsageReport | null
}
-const fresh = (revision: number): State => ({ revision, activeDay: null, workDay: null, workWeek: null,
+const fresh = (revision: number): State => ({ dayContexts: {}, health: cleanHealthState(null, Date.now()), healthDay: null, revision, activeDay: null, workDay: null, workWeek: null,
workMonth: null, measurementDay: null, featureDays: {}, featuresUsed: [],
workedBefore: false, respondedBefore: false, launchedBefore: false, firstLaunchAt: null,
launchWorked: false, launchResponded: false, workDays: [], days: {}, pending: null })
export interface ProductUsageDeps {
file: string
+ context?: ProductUsageContext
+ sample?: () => { rss: number; cpuPercent?: number }
request(method: string, path: string, body?: unknown): Promise<{ status: number; body: Record<string, unknown> }>
now?(): number
uuid?(): string
@@ -55,6 +62,7 @@ export interface ProductUsageDeps {
*/
export function createProductUsage(deps: ProductUsageDeps) {
const now = deps.now ?? Date.now, uuid = deps.uuid ?? randomUUID
+ const context = cleanUsageContext(deps.context)
let state = fresh(-1), enabled = false, stopped = false, active = false
let syncing: Promise<void> | null = null, persistTimer: ReturnType<typeof setTimeout> | undefined
let writing: Promise<boolean> | null = null, writeAgain = false
@@ -66,6 +74,8 @@ export function createProductUsage(deps: ProductUsageDeps) {
const saved = JSON.parse(readFileSync(deps.file, 'utf8')) as State
if (Number.isSafeInteger(saved.revision) && saved.revision >= 0) {
state = fresh(saved.revision)
+ state.health = cleanHealthState(saved.health, now())
+ state.healthDay = typeof saved.healthDay === 'string' && validDay(saved.healthDay) ? saved.healthDay : null
for (const field of ['activeDay', 'workDay', 'workWeek', 'measurementDay'] as const) {
if (typeof saved[field] === 'string' && validDay(saved[field]!)) state[field] = saved[field]
}
@@ -82,16 +92,23 @@ export function createProductUsage(deps: ProductUsageDeps) {
state.launchWorked = saved.launchWorked === true
state.launchResponded = saved.launchResponded === true
state.workDays = Array.isArray(saved.workDays) ? [...new Set(saved.workDays.filter(d => typeof d === 'string' && validDay(d)))].slice(-35) : []
- for (const [day, counters] of Object.entries(saved.days ?? {})) if (validDay(day)) state.days[day] = clean(counters)
+ for (const [day, counters] of Object.entries(saved.days ?? {})) if (validDay(day)) {
+ state.days[day] = clean(counters)
+ const c = cleanUsageContext(saved.dayContexts?.[day])
+ if (c) state.dayContexts[day] = c
+ else if (context) state.dayContexts[day] = { ...context, release: 'unknown', platform: 'other' }
+ }
const pending = saved.pending
if (pending && pending.schemaVersion === 1 && pending.revision === state.revision && validDay(pending.day)
&& typeof pending.id === 'string' && /^[a-f0-9-]{36}$/.test(pending.id)) {
- const restored = { schemaVersion: 1 as const, revision: state.revision, id: pending.id, day: pending.day, counters: clean(pending.counters) }
+ const restored = { schemaVersion: 1 as const, revision: state.revision, id: pending.id, day: pending.day, counters: clean(pending.counters), ...(cleanUsageContext(pending.context) ? { context: cleanUsageContext(pending.context) } : {}) }
if (Buffer.byteLength(JSON.stringify(restored)) <= 8192) state.pending = restored
}
}
} catch { /* Missing or unreadable telemetry must not affect a session. */ }
+ const health = createProductHealth(add, now, state.health)
+
function validDay(day: string): boolean {
const stamp = Date.parse(day + 'T00:00:00.000Z'), today = Math.floor(now() / DAY) * DAY
return /^\d{4}-\d{2}-\d{2}$/.test(day) && Number.isFinite(stamp) && key(stamp) === day
@@ -106,9 +123,11 @@ export function createProductUsage(deps: ProductUsageDeps) {
return result
}
function snapshot(): string {
+ state.health = health.snapshot()
clearTimeout(persistTimer); persistTimer = undefined
for (const field of ['activeDay', 'workDay', 'workWeek', 'measurementDay'] as const) if (state[field] && !validDay(state[field]!)) state[field] = null
for (const day of Object.keys(state.days)) if (!validDay(day)) delete state.days[day]
+ for (const day of Object.keys(state.dayContexts)) if (!state.days[day]) delete state.dayContexts[day]
for (const action of PRODUCT_USAGE_ACTIONS) if (!validDay(state.featureDays[action] ?? '')) delete state.featureDays[action]
state.workDays = state.workDays.filter(validDay)
if (state.firstLaunchAt !== null && !validDay(key(state.firstLaunchAt))) state.firstLaunchAt = null
@@ -156,6 +175,14 @@ export function createProductUsage(deps: ProductUsageDeps) {
;(state.days[state.measurementDay] ??= {}).measurement_v2_installation_days = 1
}
const counters = state.days[day] ??= {}
+ if (context) {
+ const prior = state.dayContexts[day]
+ state.dayContexts[day] = !prior ? context : { ...context,
+ release: prior.release === context.release ? context.release : 'unknown',
+ platform: prior.platform === context.platform ? context.platform : 'other',
+ channel: prior.channel === 'production' && context.channel === 'production' ? 'production' : 'development' }
+ if ((counters[metric] ?? 0) >= PRODUCT_USAGE_MAX_COUNT) counters.health_cli_queue_capped = 1
+ }
counters[metric] = Math.min(PRODUCT_USAGE_MAX_COUNT, (counters[metric] ?? 0) + 1)
dirty()
}
@@ -173,7 +200,7 @@ export function createProductUsage(deps: ProductUsageDeps) {
}
async function choice(value: ProductUsageChoice): Promise<void> {
if (state.revision !== value.revision || (!value.enabled && (enabled || state.pending || Object.keys(state.days).length))) {
- state = fresh(value.revision); running.clear(); launches.clear()
+ state = fresh(value.revision); running.clear(); launches.clear(); health.reset()
enabled = false
if (!await persist()) return
}
@@ -185,9 +212,13 @@ export function createProductUsage(deps: ProductUsageDeps) {
if (stopped) return
const body = response.body.data as ProductUsageChoice | undefined
if (response.status !== 200 || typeof body?.enabled !== 'boolean'
- || !Number.isSafeInteger(body.revision) || body.revision < 0) { enabled = false; running.clear(); launches.clear(); return }
+ || !Number.isSafeInteger(body.revision) || body.revision < 0) { enabled = false; running.clear(); launches.clear(); health.clearObservations(); return }
await choice(body)
if (!enabled) return
+ if (context) {
+ health.start(context.release); health.checkpoint(); health.sample(deps.sample)
+ if (state.healthDay !== key(now())) { state.healthDay = key(now()); add('health_cli_collector_days') }
+ }
for (const turn of running.values()) if (!turn.response && !turn.waited && now() - turn.started >= 60_000) {
turn.waited = true; add('turns_waiting_over_1m')
}
@@ -200,9 +231,10 @@ export function createProductUsage(deps: ProductUsageDeps) {
const day = Object.keys(state.days).sort().find(d => validDay(d) && Object.keys(state.days[d]).length)
if (!day) return
const counters = Object.fromEntries(Object.entries(state.days[day]).slice(0, MAX_REPORT_METRICS)) as Counters
- state.pending = { schemaVersion: 1, revision: state.revision, id: uuid(), day, counters }
+ const reportContext = state.dayContexts[day] ?? context
+ state.pending = { schemaVersion: 1, revision: state.revision, id: uuid(), day, counters, ...(reportContext ? { context: reportContext } : {}) }
for (const metric of Object.keys(counters)) delete state.days[day][metric as ProductUsageMetric]
- if (!Object.keys(state.days[day]).length) delete state.days[day]
+ if (!Object.keys(state.days[day]).length) { delete state.days[day]; delete state.dayContexts[day] }
}
// Persist the immutable receipt before sending. A crash or ambiguous response retries that id.
if (!await persist() || stopped || !enabled) return
@@ -212,9 +244,17 @@ export function createProductUsage(deps: ProductUsageDeps) {
if (stopped) return
const result = answer.body.data as { accepted?: boolean; reason?: string } | undefined
if (answer.status === 200 && result?.accepted === true) { state.pending = null; await persist() }
- else if (result?.reason === 'CHOICE_CHANGED') { enabled = false; state = fresh(-1); running.clear(); launches.clear(); await persist() }
- else if (result?.reason === 'EXPIRED') { state.pending = null; await persist() }
- } catch { enabled = false; running.clear(); launches.clear() /* No error text or request body in logs. */ }
+ else if (result?.reason === 'CHOICE_CHANGED') { enabled = false; state = fresh(-1); running.clear(); launches.clear(); health.reset(); await persist() }
+ else if (result?.reason === 'EXPIRED') { state.pending = null; add('health_cli_report_expired'); await persist() }
+ else {
+ add('health_cli_report_rejected')
+ // A permanently invalid packet must not block every future report behind it.
+ if (answer.status === 400 || answer.status === 413) { state.pending = null; await persist() }
+ }
+ } catch {
+ if (enabled) add('health_cli_report_failed')
+ enabled = false; running.clear(); launches.clear(); health.clearObservations() /* No error text or request body in logs. */
+ }
}
const sync = (): Promise<void> => syncing ??= syncOnce().finally(() => { syncing = null })
const timer = setInterval(() => { void sync() }, 60_000)
@@ -234,7 +274,12 @@ export function createProductUsage(deps: ProductUsageDeps) {
}
},
launch(signal: ProductUsageLaunchSignal): void {
- if (!enabled || stopped || !signal || typeof signal.id !== 'string' || !/^[a-zA-Z0-9_-]{16,96}$/.test(signal.id)) return
+ if (!enabled || stopped || !signal || typeof signal.id !== 'string') return
+ if (signal.phase === 'work_requested') {
+ if (!running.has(signal.id) && signal.id.length > 0 && signal.id.length <= 256 && (signal.origin === 'interactive' || signal.origin === 'tool')) health.intent(signal.id, signal.origin)
+ return
+ }
+ if (!/^[a-zA-Z0-9_-]{16,96}$/.test(signal.id)) return
if (signal.phase === 'start') {
if (launches.has(signal.id)) return
if (!state.launchedBefore) {
@@ -274,7 +319,7 @@ export function createProductUsage(deps: ProductUsageDeps) {
if (type === 'turn_started') {
if (running.has(agent)) return
if (running.size >= 1000) { add('turn_observation_overflow'); return }
- running.set(agent, { started: now(), response: false, error: false, waited: false }); markActive(); add('turns_started')
+ running.set(agent, { started: now(), response: false, error: false, waited: false }); markActive(); add('turns_started'); if (context) health.work(agent)
launchValue(false)
if (state.workDay !== key(now())) {
if (state.workDay && now() - Date.parse(state.workDay) >= 7 * DAY) add('reactivated_after_7d_installations')
@@ -328,8 +373,8 @@ export function createProductUsage(deps: ProductUsageDeps) {
}
},
stop(discard = false): Promise<boolean> {
- stopped = true; enabled = false; clearInterval(timer); running.clear(); launches.clear()
- if (discard) state = fresh(-1)
+ stopped = true; enabled = false; clearInterval(timer); running.clear(); launches.clear(); health.stop()
+ if (discard) { state = fresh(-1); health.reset() }
return persist()
},
}
diff --git a/cli/src/gateway/start.ts b/cli/src/gateway/start.ts
index d039a2e23..92d51b8e5 100644
--- a/cli/src/gateway/start.ts
+++ b/cli/src/gateway/start.ts
@@ -1,3 +1,5 @@
+import { VERSION, IS_RELEASE_BUILD } from '../version.js'
+import { gatewayResourceSample } from './productHealth.js'
/**
* The gateway, started: everything that holds this machine's keys or speaks for them, built in one place
* so that it runs the same in the core's process (`HARNESSD_SERVICES=none`, or a master that does not run
@@ -140,6 +142,8 @@ export function startGateway(host: GatewayHost): StartedGateway {
const usage = host.signedIn ? createProductUsage({
file: join(env.ADAPTER_DATA_DIR, 'product-usage', createHash('sha256').update(host.autonomousEnv + ':' + host.machineId).digest('hex') + '.json'),
request: (method, path, body) => accountHttp.backend(method, path, body, 5_000),
+ context: { surface: 'cli', release: VERSION, platform: process.platform === 'darwin' ? 'macos' : process.platform === 'linux' ? 'linux' : process.platform === 'win32' ? 'windows' : 'other', channel: host.autonomousEnv === 'prod' && IS_RELEASE_BUILD ? 'production' : 'development' },
+ sample: gatewayResourceSample(),
}) : null
if (usage) { gateway.productUsage = usage; void usage.sync() }
diff --git a/cli/src/lib/productHealthContract.ts b/cli/src/lib/productHealthContract.ts
new file mode 100644
index 000000000..d973261ed
--- /dev/null
+++ b/cli/src/lib/productHealthContract.ts
@@ -0,0 +1,53 @@
+/** Fixed health vocabulary. Keep the CLI/backend copies identical. No arbitrary labels. */
+export const HEALTH_SOURCES = ['app', 'tool', 'automatic', 'unknown'] as const
+export const HEALTH_ACTIONS = ['create', 'resume', 'restart', 'model_change', 'history', 'fork', 'close', 'delete',
+ 'search', 'history_page', 'store_list', 'store_install', 'store_update', 'store_remove',
+ 'model_list', 'model_download', 'model_start', 'model_stop', 'browser_open', 'message'] as const
+export const HEALTH_RESULTS = ['started', 'ok', 'failed', 'pending', 'cancelled', 'unknown'] as const
+export const HEALTH_FAILURES = ['setup', 'auth', 'unavailable', 'invalid', 'not_found', 'conflict', 'timeout', 'other'] as const
+export const HEALTH_FLOWS = ['app_start', 'workspace_ready', 'viewer_load', 'update_apply', 'update_relaunch',
+ 'connect_user', 'connect_auto', 'resume_recovery'] as const
+export const HEALTH_MEASURES = [
+ 'collector_days', 'report_failed', 'report_rejected', 'report_expired', 'report_late', 'queue_capped', 'observation_overflow',
+ 'unclean_restart', 'framework_error', 'async_error',
+ 'rss_under_256m', 'rss_256m_to_1g', 'rss_over_1g',
+ 'cpu_under_10pct', 'cpu_10pct_to_50pct', 'cpu_over_50pct',
+ 'frame_under_16ms', 'frame_16ms_to_50ms', 'frame_50ms_to_250ms', 'frame_over_250ms',
+ 'feedback_outcome_shown', 'feedback_outcome_answered', 'feedback_outcome_dismissed',
+ 'feedback_reason_shown', 'feedback_reason_answered', 'feedback_reason_dismissed',
+ 'funnel_setup_seen', 'funnel_sign_in_seen', 'funnel_workspace_ready', 'funnel_first_work', 'funnel_first_response',
+ 'first_work_under_1m', 'first_work_1m_to_5m', 'first_work_over_5m',
+ 'first_response_under_1m', 'first_response_1m_to_5m', 'first_response_over_5m',
+ 'install_new', 'install_upgrade', 'install_unknown',
+ 'connect_error_auth', 'connect_error_unlinked', 'connect_error_offline', 'connect_error_timeout', 'connect_error_other',
+ 'interactive_turns_started', 'tool_turns_started', 'unclassified_turns_started',
+ 'interactive_work_days', 'first_interactive_work', 'first_work_d1_return', 'first_work_d7_return', 'first_work_d28_return',
+ 'week_worked_1day', 'week_worked_2to3days', 'week_worked_4to5days', 'week_worked_6to7days',
+] as const
+export const PRODUCT_HEALTH_METRICS = [
+ ...(['cli', 'desktop'] as const).flatMap(surface => HEALTH_MEASURES.map(m => `health_${surface}_${m}` as const)),
+ ...HEALTH_SOURCES.flatMap(source => HEALTH_ACTIONS.flatMap(action => [
+ ...HEALTH_RESULTS.map(result => `request_${source}_${action}_${result}` as const),
+ ...HEALTH_FAILURES.map(failure => `request_${source}_${action}_error_${failure}` as const),
+ ])),
+] as const
+export type ProductHealthMetric = typeof PRODUCT_HEALTH_METRICS[number]
+export type HealthSource = typeof HEALTH_SOURCES[number]
+export interface ProductUsageContext {
+ surface: 'cli' | 'desktop'
+ release: string
+ platform: 'macos' | 'linux' | 'windows' | 'other'
+ channel: 'production' | 'development'
+}
+/** Public numeric release only. Custom build names, hashes and suffixes cannot become labels. */
+export function releaseBucket(value: unknown): string {
+ return typeof value === 'string' && /^(0|[1-9]\d{0,2})\.(0|[1-9]\d{0,2})\.(0|[1-9]\d{0,2})$/.test(value) ? value : 'unknown'
+}
+export function cleanUsageContext(value: unknown): ProductUsageContext | undefined {
+ if (!value || typeof value !== 'object') return
+ const c = value as ProductUsageContext
+ if (!['cli', 'desktop'].includes(c.surface) || !['macos', 'linux', 'windows', 'other'].includes(c.platform)
+ || !['production', 'development'].includes(c.channel)) return
+ return { surface: c.surface, release: releaseBucket(c.release), platform: c.platform, channel: c.channel }
+}
+
diff --git a/cli/src/lib/productUsageContract.ts b/cli/src/lib/productUsageContract.ts
index 0fb3daa26..fdc70df0f 100644
--- a/cli/src/lib/productUsageContract.ts
+++ b/cli/src/lib/productUsageContract.ts
@@ -1,3 +1,4 @@
+import { HEALTH_FLOWS, PRODUCT_HEALTH_METRICS, type ProductUsageContext } from './productHealthContract.js'
/** Fixed vocabulary only. Keep the CLI copy identical; conformance is tested. */
export const PRODUCT_USAGE_VERSION = 1
export const PRODUCT_USAGE_DAYS = 35
@@ -14,19 +15,24 @@ export const PRODUCT_USAGE_AUTOMATIC_ACTIONS: readonly typeof PRODUCT_USAGE_ACTI
export const PRODUCT_USAGE_FEATURE_MEASURES = ['installation_days', 'first_installations', 'repeat_installation_days'] as const
export const PRODUCT_USAGE_SURFACES = ['desktop', 'phone', 'web'] as const
export const PRODUCT_USAGE_FLOWS = ['setup', 'setup_harness', 'setup_tmux', 'setup_clipboard', 'sign_in',
- 'workspace_connect', 'computer_link', 'remote_connect', 'viewer_open', 'update_check', 'update_stage'] as const
+ 'workspace_connect', 'computer_link', 'remote_connect', 'viewer_open', 'update_check', 'update_stage', ...HEALTH_FLOWS] as const
export const PRODUCT_USAGE_FLOW_MEASURES = ['started', 'ok', 'failed', 'cancelled', 'unknown',
'under_1s', '1s_to_10s', '10s_to_1m', 'over_1m'] as const
export const PRODUCT_USAGE_UI_METRICS = PRODUCT_USAGE_SURFACES.flatMap(surface =>
PRODUCT_USAGE_FLOWS.flatMap(flow => PRODUCT_USAGE_FLOW_MEASURES.map(measure => `ui_${surface}_${flow}_${measure}` as const)))
// A signed-out report is explicitly enabled on this app. It cannot carry account/work metrics.
-export const PRODUCT_USAGE_SETUP_METRICS = PRODUCT_USAGE_SURFACES.flatMap(surface =>
+export const PRODUCT_USAGE_SETUP_METRICS = [...PRODUCT_USAGE_SURFACES.flatMap(surface =>
(['setup', 'setup_harness', 'setup_tmux', 'setup_clipboard', 'sign_in'] as const).flatMap(flow =>
- PRODUCT_USAGE_FLOW_MEASURES.map(measure => `setup_${surface}_${flow}_${measure}` as const)))
+ PRODUCT_USAGE_FLOW_MEASURES.map(measure => `setup_${surface}_${flow}_${measure}` as const))),
+ ...(['funnel_setup_seen', 'funnel_sign_in_seen', 'funnel_workspace_ready', 'funnel_first_work', 'funnel_first_response',
+ 'first_work_under_1m', 'first_work_1m_to_5m', 'first_work_over_5m',
+ 'first_response_under_1m', 'first_response_1m_to_5m', 'first_response_over_5m'] as const).map(m => `setup_desktop_${m}` as const),
+] as const
export const PRODUCT_USAGE_ACTION_MEASURES = ['requests', 'ok', 'failed', 'pending', 'unknown',
'error_setup', 'error_auth', 'error_unavailable', 'error_invalid', 'error_other',
'under_1s', '1s_to_10s', '10s_to_1m', 'over_1m'] as const
export const PRODUCT_USAGE_METRICS = [
+ ...PRODUCT_HEALTH_METRICS,
'active_installation_days', 'working_installation_days', 'first_work_installations',
'repeat_work_installation_days', 'weekly_working_installations', 'weekly_returning_installations',
'monthly_working_installations', 'monthly_returning_installations', 'reactivated_after_7d_installations',
@@ -50,6 +56,7 @@ export const PRODUCT_USAGE_METRICS = [
export type ProductUsageMetric = typeof PRODUCT_USAGE_METRICS[number]
export interface ProductUsageReport {
schemaVersion: 1
+ context?: ProductUsageContext
revision: number
id: string
day: string
diff --git a/cli/src/lib/productUsageSignals.spec.ts b/cli/src/lib/productUsageSignals.spec.ts
index 2f2b00e83..777b02d81 100644
--- a/cli/src/lib/productUsageSignals.spec.ts
+++ b/cli/src/lib/productUsageSignals.spec.ts
@@ -1,5 +1,27 @@
import { expect, it, vi } from 'vitest'
-import { productUsageLaunch, productUsageRequest } from './productUsageSignals.js'
+import { productUsageIntent, productUsageLaunch, productUsageRequest } from './productUsageSignals.js'
+
+it('separates automated polling, tool and app RPCs without inspecting error objects or content', () => {
+ const emit = vi.fn()
+ productUsageRequest('models_list', emit, Date.now, 'app')(undefined, undefined, false)
+ productUsageRequest('models_list', emit, Date.now, 'tool')(undefined, undefined, false)
+ productUsageRequest('agent_resume', emit, Date.now, 'tool')('AGENT_NOT_FOUND', 'failed', false)
+ productUsageRequest('agent_close', emit, Date.now, 'app')(undefined, 'cancelled', false)
+ const secret = { toString() { throw Error('PRIVATE') } }
+ expect(() => productUsageRequest('agent_restart', emit, Date.now, 'unknown')(secret, 'failed', false)).not.toThrow()
+ expect(emit.mock.calls.flat()).toEqual(expect.arrayContaining(['request_automatic_model_list_ok', 'request_tool_resume_error_not_found', 'request_app_close_cancelled', 'request_unknown_restart_error_other']))
+ expect(JSON.stringify(emit.mock.calls)).not.toContain('PRIVATE')
+ expect(emit.mock.calls.flat()).toContain('request_tool_model_list_ok')
+})
+it('requires an explicit composer marker for interactive work; raw terminal input is unclassified', () => {
+ const emit = vi.fn()
+ productUsageIntent('terminal_input', 'interactive', 'agent', 'app', emit)
+ productUsageIntent('message', undefined, 'agent', 'app', emit)
+ expect(emit).not.toHaveBeenCalled()
+ productUsageIntent('message', 'interactive', 'agent', 'app', emit)
+ expect(emit).toHaveBeenCalledWith({ id: 'agent', phase: 'work_requested', origin: 'interactive' })
+ expect(() => productUsageIntent('message', undefined, 'agent', 'tool', () => { throw Error() })).not.toThrow()
+})
it('distinguishes a pending launch from a launched harness, and counts replies once', () => {
let now = 0
diff --git a/cli/src/lib/productUsageSignals.ts b/cli/src/lib/productUsageSignals.ts
index f71b0b7ec..85be77fb4 100644
--- a/cli/src/lib/productUsageSignals.ts
+++ b/cli/src/lib/productUsageSignals.ts
@@ -1,3 +1,4 @@
+import type { HealthSource } from './productHealthContract.js'
import type { ProductUsageMetric } from './productUsageContract.js'
const actions = { agent_create: 'create', agent_resume: 'resume', agent_restart: 'restart',
@@ -26,7 +27,8 @@ function failureKind(error: unknown): Failure {
export interface ProductUsageLaunchSignal {
/** Local RAM only, discarded on stop/choice change; never part of a report or persisted queue. */
id: string
- phase: 'start' | 'pending' | 'created' | 'failed' | 'cancelled' | 'unconfirmed'
+ phase: 'start' | 'pending' | 'created' | 'failed' | 'cancelled' | 'unconfirmed' | 'work_requested'
+ origin?: 'interactive' | 'tool'
failure?: Failure
wait?: 'install' | 'model' | 'native' | 'other'
}
@@ -54,25 +56,37 @@ export function productUsageLaunch(type: string, id: unknown, emit: (signal: Pro
* A pending durable launch is an acknowledgement, never a successful launch. Status polling is
* excluded: counting each poll as a launch would turn a slow install into hundreds of attempts.
*/
-export function productUsageRequest(type: string, emit: (metric: ProductUsageMetric) => void, now = Date.now) {
- const action = Object.hasOwn(actions, type) ? actions[type as keyof typeof actions] : null
+export function productUsageRequest(type: string, emit: (metric: ProductUsageMetric) => void, now = Date.now, source?: HealthSource) {
+ const action = type === 'message' ? 'message' : Object.hasOwn(actions, type) ? actions[type as keyof typeof actions] : null
// In particular, streaming frames and polling do not allocate clocks or observers.
if (!action) return unmeasured
const started = now()
let answered = false
- const count = (measure: string) => { if (action) { try { emit(`${action}_${measure}` as ProductUsageMetric) } catch { /* Optional measurement. */ } } }
- count('requests')
+ const origin = source === 'app' && ['history', 'history_page', 'store_list', 'model_list'].includes(action) ? 'automatic' : source
+ const count = (measure: string) => { if (action && action !== 'message') { try { emit(`${action}_${measure}` as ProductUsageMetric) } catch { /* Optional measurement. */ } } }
+ const detail = (measure: string) => { if (!source) return; try { emit(`request_${origin}_${action}_${measure}` as ProductUsageMetric) } catch { /* Optional measurement. */ } }
+ count('requests'); detail('started')
return (error: unknown, state: unknown, hasAgent: boolean, ok?: unknown) => {
if (!action || answered) return
answered = true
if (error != null || state === 'failed' || ok === false) {
- count('failed')
+ count('failed'); detail('failed')
count(`error_${failureKind(error)}`)
- } else if (state === 'pending' || state === 'preparing' || state === 'starting') count('pending')
- else if (state === 'unconfirmed' || state === 'unavailable' || state === 'cancelled') count('unknown')
- else if (!['create', 'resume', 'restart', 'fork'].includes(action) || hasAgent || state === 'created') count('ok')
- else count('unknown')
+ detail(`error_${error === 'TIMEOUT' ? 'timeout' : typeof error === 'string' && ['AGENT_NOT_FOUND', 'SESSION_NOT_FOUND', 'NOT_FOUND'].includes(error) ? 'not_found' : typeof error === 'string' && ['DELETE_IN_PROGRESS', 'WORKTREE_BUSY', 'BUSY'].includes(error) ? 'conflict' : failureKind(error)}`)
+ } else if (state === 'pending' || state === 'preparing' || state === 'starting') { count('pending'); detail('pending') }
+ else if (state === 'unconfirmed' || state === 'unavailable' || state === 'cancelled') { count('unknown'); detail(state === 'cancelled' ? 'cancelled' : 'unknown') }
+ else if (!['create', 'resume', 'restart', 'fork'].includes(action) || hasAgent || state === 'created') { count('ok'); detail('ok') }
+ else { count('unknown'); detail('unknown') }
const elapsed = Math.max(0, now() - started)
count(elapsed < 1000 ? 'under_1s' : elapsed < 10_000 ? '1s_to_10s' : elapsed < 60_000 ? '10s_to_1m' : 'over_1m')
}
}
+
+/** Explicit composer intent only. Never infer a human from keystrokes, text or an open window. */
+export function productUsageIntent(type: string, intent: unknown, agent: unknown, source: HealthSource, emit: (signal: ProductUsageLaunchSignal) => void): void {
+ if (type !== 'message' || typeof agent !== 'string' || !agent || agent.length > 256) return
+ try {
+ if (source === 'app' && intent === 'interactive') emit({ id: agent, phase: 'work_requested', origin: 'interactive' })
+ else if (source === 'tool') emit({ id: agent, phase: 'work_requested', origin: 'tool' })
+ } catch { /* Optional observation cannot block a message. */ }
+}
diff --git a/cli/src/version.ts b/cli/src/version.ts
index 8d83d9300..e0fc11b12 100644
--- a/cli/src/version.ts
+++ b/cli/src/version.ts
@@ -22,3 +22,5 @@ function resolveVersion(): string {
}
export const VERSION: string = resolveVersion()
+/** Source runs and prerelease builds never contribute production health totals. */
+export const IS_RELEASE_BUILD = typeof __ADAPTER_VERSION__ !== 'undefined' && __ADAPTER_VERSION__ !== '0.0.1' && /^\d+\.\d+\.\d+$/.test(__ADAPTER_VERSION__)
diff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dart
index fb8234d2a..298071045 100644
--- a/desktop/lib/app_shell.dart
+++ b/desktop/lib/app_shell.dart
@@ -2,6 +2,9 @@ import 'core/app_version.dart';
import 'measurement/setup_usage_choice.dart';
import 'dart:async';
+
+import 'measurement/product_runtime_health.dart';
+
import 'dart:ui' show AppExitResponse;
import 'package:flutter/material.dart';
@@ -73,6 +76,7 @@ Future<void> startHarness({
/// [TerminalTransportPlugin]); the desktop passes none.
TerminalTransportPluginFactory? transportPlugins,
}) async {
+ if (!kIsWeb) ProductRuntimeHealth.launched();
// Share links and OAuth own the browser URL. Flutter's default hash routing would
// erase the share's pinned identity on the first navigation or window resize.
if (kIsWeb) setUrlStrategy(null);
@@ -236,6 +240,7 @@ class _RootShellState extends ConsumerState<RootShell>
@override
Future<AppExitResponse> didRequestAppExit() async {
final app = ref.read(appStateProvider);
+ app.productRuntimeHealth?.cleanExit();
// A sign-in still waiting on the browser or a phone ends with the app: its
// CLI would otherwise wait on, holding the lock the next sign-in needs.
if (app.canCancelLogin) app.cancelLogin();
diff --git a/desktop/lib/core/crash_log.dart b/desktop/lib/core/crash_log.dart
index 5283d1abd..9e25f4ae2 100644
--- a/desktop/lib/core/crash_log.dart
+++ b/desktop/lib/core/crash_log.dart
@@ -17,6 +17,14 @@ import 'test_run.dart';
/// Everything here is best-effort and bounded. Diagnostics must never be the
/// reason something fails.
class CrashLog {
+ /// The observer receives only the error channel, never the exception or stack.
+ static void Function(bool framework)? healthError;
+ static void _health(bool framework) {
+ try {
+ healthError?.call(framework);
+ } catch (_) {}
+ }
+
static const _maxBytes = 256 * 1024;
@visibleForTesting
@@ -79,12 +87,14 @@ class CrashLog {
static void install() {
final previousFlutterError = FlutterError.onError;
FlutterError.onError = (details) {
+ _health(true);
record(details.exception, details.stack, context: 'flutter');
previousFlutterError?.call(details);
};
final previousPlatformError = PlatformDispatcher.instance.onError;
PlatformDispatcher.instance.onError = (error, stack) {
+ _health(false);
record(error, stack, context: 'async');
return previousPlatformError?.call(error, stack) ?? false;
};
diff --git a/desktop/lib/measurement/product_connections.dart b/desktop/lib/measurement/product_connections.dart
new file mode 100644
index 000000000..f68ed1bf4
--- /dev/null
+++ b/desktop/lib/measurement/product_connections.dart
@@ -0,0 +1,100 @@
+import 'product_measurement.dart';
+
+/// Existing connection keys stay in this bounded RAM map and never reach a counter.
+class ProductConnections {
+ ProductConnections(this.measurement) {
+ measurement.addListener(_choiceChanged);
+ }
+ final ProductMeasurement measurement;
+ final _pending = <String, void Function(ProductOutcome)>{};
+ final _manual = <String, Object>{};
+ final _failures = <String, ProductHealthMeasure>{};
+ int _generation = -1;
+ void _choiceChanged() {
+ if (!measurement.sharing ||
+ _generation != measurement.observationGeneration) {
+ clear();
+ }
+ _generation = measurement.observationGeneration;
+ }
+
+ void refused(String key, ProductHealthMeasure failure) {
+ if (_pending.containsKey(key) || _manual.containsKey(key)) {
+ _failures.putIfAbsent(key, () => failure);
+ }
+ }
+
+ void Function(ProductOutcome) manual(String key) {
+ _choiceChanged();
+ if (!measurement.healthEnabled || !measurement.sharing) return (_) {};
+ if (_manual.length >= 64 && !_manual.containsKey(key)) {
+ measurement.health(ProductHealthMeasure.observationOverflow);
+ return (_) {};
+ }
+ _pending.remove(key)?.call(ProductOutcome.cancelled);
+ _failures.remove(key);
+ final ticket = Object();
+ _manual[key] = ticket;
+ final finish = measurement.begin(ProductFlow.connectUser);
+ var done = false;
+ return (outcome) {
+ if (done) return;
+ done = true;
+ if (_manual[key] == ticket) {
+ _manual.remove(key);
+ final failure = _failures.remove(key);
+ if (outcome == ProductOutcome.failed && failure != null) {
+ measurement.health(failure);
+ }
+ }
+ finish(outcome);
+ };
+ }
+
+ void status(
+ String key, {
+ required bool connecting,
+ required bool connected,
+ ProductHealthMeasure? failure,
+ }) {
+ _choiceChanged();
+ if (!measurement.healthEnabled || !measurement.sharing) {
+ clear();
+ return;
+ }
+ if (_manual.containsKey(key)) return;
+ if (connecting) {
+ if (_pending.length >= 64 && !_pending.containsKey(key)) {
+ measurement.health(ProductHealthMeasure.observationOverflow);
+ return;
+ }
+ _pending.putIfAbsent(
+ key,
+ () => measurement.begin(ProductFlow.connectAuto),
+ );
+ } else {
+ final finish = _pending.remove(key);
+ failure = _failures.remove(key) ?? failure;
+ if (finish == null) return;
+ finish(
+ connected
+ ? ProductOutcome.ok
+ : failure == null
+ ? ProductOutcome.unknown
+ : ProductOutcome.failed,
+ );
+ if (!connected && failure != null) measurement.health(failure);
+ }
+ }
+
+ void clear() {
+ _pending.clear();
+ _manual.clear();
+ _failures.clear();
+ }
+
+ void dispose() {
+ measurement.removeListener(_choiceChanged);
+ clear();
+ }
+}
diff --git a/desktop/lib/measurement/product_health_contract.dart b/desktop/lib/measurement/product_health_contract.dart
new file mode 100644
index 000000000..d24f68c9e
--- /dev/null
+++ b/desktop/lib/measurement/product_health_contract.dart
@@ -0,0 +1,86 @@
+// Fixed scalar vocabulary; mirrored by the backend contract and checked in tests.
+enum ProductHealthMeasure {
+ collectorDays('collector_days'),
+ reportFailed('report_failed'),
+ reportRejected('report_rejected'),
+ reportExpired('report_expired'),
+ reportLate('report_late'),
+ queueCapped('queue_capped'),
+ observationOverflow('observation_overflow'),
+ uncleanRestart('unclean_restart'),
+ frameworkError('framework_error'),
+ asyncError('async_error'),
+ rssUnder256m('rss_under_256m'),
+ rss256mTo1g('rss_256m_to_1g'),
+ rssOver1g('rss_over_1g'),
+ cpuUnder10pct('cpu_under_10pct'),
+ cpu10pctTo50pct('cpu_10pct_to_50pct'),
+ cpuOver50pct('cpu_over_50pct'),
+ frameUnder16ms('frame_under_16ms'),
+ frame16msTo50ms('frame_16ms_to_50ms'),
+ frame50msTo250ms('frame_50ms_to_250ms'),
+ frameOver250ms('frame_over_250ms'),
+ feedbackOutcomeShown('feedback_outcome_shown'),
+ feedbackOutcomeAnswered('feedback_outcome_answered'),
+ feedbackOutcomeDismissed('feedback_outcome_dismissed'),
+ feedbackReasonShown('feedback_reason_shown'),
+ feedbackReasonAnswered('feedback_reason_answered'),
+ feedbackReasonDismissed('feedback_reason_dismissed'),
+ funnelSetupSeen('funnel_setup_seen'),
+ funnelSignInSeen('funnel_sign_in_seen'),
+ funnelWorkspaceReady('funnel_workspace_ready'),
+ funnelFirstWork('funnel_first_work'),
+ funnelFirstResponse('funnel_first_response'),
+ firstWorkUnder1m('first_work_under_1m'),
+ firstWork1mTo5m('first_work_1m_to_5m'),
+ firstWorkOver5m('first_work_over_5m'),
+ firstResponseUnder1m('first_response_under_1m'),
+ firstResponse1mTo5m('first_response_1m_to_5m'),
+ firstResponseOver5m('first_response_over_5m'),
+ installNew('install_new'),
+ installUpgrade('install_upgrade'),
+ installUnknown('install_unknown'),
+ connectErrorAuth('connect_error_auth'),
+ connectErrorUnlinked('connect_error_unlinked'),
+ connectErrorOffline('connect_error_offline'),
+ connectErrorTimeout('connect_error_timeout'),
+ connectErrorOther('connect_error_other'),
+ interactiveTurnsStarted('interactive_turns_started'),
+ toolTurnsStarted('tool_turns_started'),
+ unclassifiedTurnsStarted('unclassified_turns_started'),
+ interactiveWorkDays('interactive_work_days'),
+ firstInteractiveWork('first_interactive_work'),
+ firstWorkD1Return('first_work_d1_return'),
+ firstWorkD7Return('first_work_d7_return'),
+ firstWorkD28Return('first_work_d28_return'),
+ weekWorked1day('week_worked_1day'),
+ weekWorked2to3days('week_worked_2to3days'),
+ weekWorked4to5days('week_worked_4to5days'),
+ weekWorked6to7days('week_worked_6to7days');
+
+ const ProductHealthMeasure(this.wire);
+ final String wire;
+}
+
+class ProductUsageContext {
+ ProductUsageContext({
+ required String release,
+ required this.platform,
+ required this.production,
+ }) : release =
+ RegExp(r'^(0|[1-9]\d{0,2})\.(0|[1-9]\d{0,2})\.(0|[1-9]\d{0,2})$')
+ .hasMatch(release)
+ ? release
+ : 'unknown';
+ final String release;
+ final String platform;
+ final bool production;
+ Map<String, dynamic> toJson() => {
+ 'surface': 'desktop',
+ 'release': release,
+ 'platform': const ['macos', 'linux', 'windows'].contains(platform)
+ ? platform
+ : 'other',
+ 'channel': production ? 'production' : 'development',
+ };
+}
diff --git a/desktop/lib/measurement/product_measurement.dart b/desktop/lib/measurement/product_measurement.dart
index 8eb19d2dc..90b243b2a 100644
--- a/desktop/lib/measurement/product_measurement.dart
+++ b/desktop/lib/measurement/product_measurement.dart
@@ -3,6 +3,9 @@ import 'dart:math';
import 'package:flutter/foundation.dart';
+import 'product_health_contract.dart';
+export 'product_health_contract.dart';
+
enum ProductFlow {
setup('setup'),
setupHarness('setup_harness'),
@@ -14,7 +17,15 @@ enum ProductFlow {
remoteConnect('remote_connect'),
viewerOpen('viewer_open'),
updateCheck('update_check'),
- updateStage('update_stage');
+ updateStage('update_stage'),
+ appStart('app_start'),
+ workspaceReady('workspace_ready'),
+ viewerLoad('viewer_load'),
+ updateApply('update_apply'),
+ updateRelaunch('update_relaunch'),
+ connectUser('connect_user'),
+ connectAuto('connect_auto'),
+ resumeRecovery('resume_recovery');
const ProductFlow(this.wire);
final String wire;
@@ -29,7 +40,8 @@ typedef ProductReportRequest = Future<Map<String, dynamic>> Function(
typedef ProductChoiceRequest = Future<Map<String, dynamic>> Function();
/// Fixed counters only: no event log, identifiers, errors, request/response objects or content.
-/// Nothing is saved. Signed-out sharing is an explicit choice for this app session; a close/crash can lose queued counts.
+/// Counters stay in RAM. The separate runtime observer saves only last-run control flags locally.
+/// Signed-out sharing is an explicit choice for this app session; a close/crash can lose queued counts.
/// Requests and retries are serialized and never awaited by a product action.
class ProductMeasurement extends ChangeNotifier {
ProductMeasurement({
@@ -38,6 +50,7 @@ class ProductMeasurement extends ChangeNotifier {
DateTime Function()? now,
String Function()? receipt,
this.automatic = true,
+ this.context,
}) : assert(const ['desktop', 'phone', 'web'].contains(surface)),
_now = now ?? DateTime.now,
_receipt = receipt ?? newProductReceipt {
@@ -45,6 +58,15 @@ class ProductMeasurement extends ChangeNotifier {
}
final String surface;
+ ProductUsageContext? context;
+ bool get healthEnabled => surface == 'desktop' && context != null;
+ String? _coverageDay;
+ final _funnelSeen = <String, Set<ProductHealthMeasure>>{};
+ final _funnelStarted = <String, DateTime>{};
+ final _expires = <Object, DateTime>{};
+ final _expire = <Object, void Function(ProductOutcome)>{};
+ int get choiceRevision => _revision;
+ int get observationGeneration => _accountEpoch;
final ProductReportRequest sendSetup;
final bool automatic;
final DateTime Function() _now;
@@ -68,6 +90,7 @@ class ProductMeasurement extends ChangeNotifier {
bool get sharing => _account != null && _enabled == true;
bool get _setupAllowed =>
surface != 'web' &&
+ (!healthEnabled || context!.production) &&
signedOutSharing &&
(_account == null || _enabled == true);
@@ -89,6 +112,12 @@ class ProductMeasurement extends ChangeNotifier {
}) {
if (_disposed || scope == _account) return;
_accountEpoch++;
+ if (_account != null) {
+ _guestEpoch++;
+ signedOutSharing = false;
+ _clear('setup');
+ _setup.clear();
+ }
_account = scope;
_enabled = null;
_revision = -1;
@@ -124,16 +153,116 @@ class ProductMeasurement extends ChangeNotifier {
void _clear(String channel) {
_days.removeWhere((key, _) => key.startsWith('$channel:'));
_pending.remove(channel);
- _active.removeWhere((_, value) => value == channel);
+ for (final ticket
+ in _active.keys.where((key) => _active[key] == channel).toList()) {
+ _active.remove(ticket);
+ _expires.remove(ticket);
+ _expire.remove(ticket);
+ }
+ _funnelSeen.remove(channel);
+ _funnelStarted.remove(channel);
+ if (channel == 'ui') _coverageDay = null;
+ }
+
+ void _coverage() {
+ if (!healthEnabled || !sharing || _disposed) return;
+ final day = _now().toUtc().toIso8601String().substring(0, 10);
+ if (_coverageDay == day) return;
+ _coverageDay = day;
+ _count('ui', day, 'health_desktop_collector_days');
+ }
+
+ /// Only fixed enum scalars enter the queue. Called after checking the account choice.
+ void health(ProductHealthMeasure measure) {
+ if (!healthEnabled || !sharing || _disposed) return;
+ _coverage();
+ _count(
+ 'ui',
+ _now().toUtc().toIso8601String().substring(0, 10),
+ 'health_desktop_${measure.wire}',
+ );
+ }
+
+ /// Observed readiness since process launch; only its coarse duration is kept.
+ void observedStartup(Duration elapsed) {
+ if (!healthEnabled || !sharing || _disposed) return;
+ _coverage();
+ final day = _now().toUtc().toIso8601String().substring(0, 10);
+ const prefix = 'ui_desktop_app_start_';
+ final ms = elapsed.inMilliseconds;
+ _count('ui', day, '${prefix}started');
+ _count('ui', day, '${prefix}ok');
+ _count(
+ 'ui',
+ day,
+ '$prefix${ms < 1000
+ ? 'under_1s'
+ : ms < 10000
+ ? '1s_to_10s'
+ : ms < 60000
+ ? '10s_to_1m'
+ : 'over_1m'}',
+ );
+ }
+
+ /// A consented app-session funnel, never a click trail or an account join.
+ /// Its clock starts at the first permitted observation, not retrospectively at install.
+ void milestone(ProductHealthMeasure measure) {
+ if (!healthEnabled || _disposed || !measure.wire.startsWith('funnel_')) {
+ return;
+ }
+ final channel = _setupAllowed
+ ? 'setup'
+ : sharing
+ ? 'ui'
+ : null;
+ if (channel == null) return;
+ final seen = _funnelSeen.putIfAbsent(channel, () => {});
+ if (!seen.add(measure)) return;
+ final now = _now().toUtc();
+ final start = _funnelStarted.putIfAbsent(channel, () => now);
+ final day = now.toIso8601String().substring(0, 10);
+ if (channel == 'ui') _coverage();
+ void count(String name) => _count(
+ channel,
+ day,
+ channel == 'setup' ? 'setup_desktop_$name' : 'health_desktop_$name',
+ );
+ count(measure.wire);
+ if (measure == ProductHealthMeasure.funnelFirstWork ||
+ measure == ProductHealthMeasure.funnelFirstResponse) {
+ final elapsed = now.difference(start).inSeconds;
+ final value = measure == ProductHealthMeasure.funnelFirstWork
+ ? 'first_work'
+ : 'first_response';
+ count(
+ '${value}_${elapsed < 60
+ ? 'under_1m'
+ : elapsed < 300
+ ? '1m_to_5m'
+ : 'over_5m'}',
+ );
+ }
}
void Function(ProductOutcome) begin(ProductFlow flow) {
+ if (flow == ProductFlow.signIn) {
+ milestone(ProductHealthMeasure.funnelSignInSeen);
+ }
+ if (flow.index >= ProductFlow.appStart.index && !healthEnabled) {
+ return (_) {};
+ }
+ _coverage();
final channel = sharing
? 'ui'
: flow.beforeSignIn && _setupAllowed
? 'setup'
: null;
- if (_disposed || channel == null || _active.length >= 64) return (_) {};
+ if (_disposed || channel == null) return (_) {};
+ if (_active.length >= 64) {
+ health(ProductHealthMeasure.observationOverflow);
+ return (_) {};
+ }
final epoch = channel == 'setup' ? _guestEpoch : _accountEpoch;
final started = _now().toUtc();
final watch = Stopwatch()..start();
@@ -143,10 +272,12 @@ class ProductMeasurement extends ChangeNotifier {
_active[ticket] = channel;
_count(channel, day, '${prefix}started');
var done = false;
- return (outcome) {
+ void finish(ProductOutcome outcome) {
if (done) return;
done = true;
if (_active.remove(ticket) == null) return;
+ _expires.remove(ticket);
+ _expire.remove(ticket);
watch.stop();
if (_disposed ||
(channel == 'setup'
@@ -167,6 +298,20 @@ class ProductMeasurement extends ChangeNotifier {
? '10s_to_1m'
: 'over_1m'}',
);
+ }
+
+ if (healthEnabled) {
+ _expires[ticket] = started.add(const Duration(minutes: 15));
+ _expire[ticket] = finish;
+ }
+ return finish;
+ }
+
+ /// A widget's delayed callback cannot count after sign-out or a choice revision.
+ VoidCallback observer(ProductHealthMeasure measure) {
+ final epoch = _accountEpoch;
+ return () {
+ if (epoch == _accountEpoch) health(measure);
};
}
@@ -179,6 +324,7 @@ class ProductMeasurement extends ChangeNotifier {
}
void _observeSetupFacts() {
+ if (_setupFacts.isNotEmpty) milestone(ProductHealthMeasure.funnelSetupSeen);
if (!_setupAllowed && !sharing) return;
for (final entry in _setupFacts.entries) {
if (!entry.key.beforeSignIn || entry.key == ProductFlow.signIn) continue;
@@ -210,6 +356,9 @@ class ProductMeasurement extends ChangeNotifier {
today.difference(DateTime.parse(key.split(':')[1])).inDays > 1,
);
final counters = _days.putIfAbsent('$channel:$day', () => {});
+ if ((counters[metric] ?? 0) >= 1000 && healthEnabled && channel == 'ui') {
+ counters['health_desktop_queue_capped'] = 1;
+ }
counters[metric] = min(1000, (counters[metric] ?? 0) + 1);
_schedule();
}
@@ -243,6 +392,11 @@ class ProductMeasurement extends ChangeNotifier {
Future<void> _flush() async {
if (_disposed) return;
_lastAttempt = _now();
+ for (final ticket in _expires.keys.toList()) {
+ if (!_now().toUtc().isBefore(_expires[ticket]!)) {
+ _expire[ticket]?.call(ProductOutcome.unknown);
+ }
+ }
final account = _account, read = _readChoice;
final choiceEpoch = _accountEpoch;
if (account != null && read != null) {
@@ -279,6 +433,7 @@ class ProductMeasurement extends ChangeNotifier {
'day': key.split(':')[1],
'counters': batch,
if (channel == 'setup') 'consent': true else 'revision': _revision,
+ if (channel == 'ui' && healthEnabled) 'context': context!.toJson(),
};
_pending[channel] = report;
}
@@ -288,6 +443,7 @@ class ProductMeasurement extends ChangeNotifier {
.inDays >
1) {
_pending.remove(channel);
+ if (channel == 'ui') health(ProductHealthMeasure.reportExpired);
continue;
}
try {
@@ -302,6 +458,14 @@ class ProductMeasurement extends ChangeNotifier {
}
if (result['accepted'] == true || result['reason'] == 'EXPIRED') {
_pending.remove(channel);
+ if (result['reason'] == 'EXPIRED' && channel == 'ui') {
+ health(ProductHealthMeasure.reportExpired);
+ }
+ }
+ if (result['accepted'] != true &&
+ result['reason'] != 'EXPIRED' &&
+ result['reason'] != 'CHOICE_CHANGED') {
+ health(ProductHealthMeasure.reportRejected);
}
if (result['reason'] == 'CHOICE_CHANGED') {
_enabled = null;
@@ -309,6 +473,7 @@ class ProductMeasurement extends ChangeNotifier {
_clear('setup');
}
} catch (_) {
+ if (channel == 'ui') health(ProductHealthMeasure.reportFailed);
/* Same receipt on the next timer. No logs, aggressive retry, or product failure. */
}
}
@@ -322,6 +487,8 @@ class ProductMeasurement extends ChangeNotifier {
_pending.clear();
_setup.clear();
_active.clear();
+ _expires.clear();
+ _expire.clear();
super.dispose();
}
}
diff --git a/desktop/lib/measurement/product_runtime_health.dart b/desktop/lib/measurement/product_runtime_health.dart
new file mode 100644
index 000000000..3ced73f40
--- /dev/null
+++ b/desktop/lib/measurement/product_runtime_health.dart
@@ -0,0 +1,274 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:cryptography/dart.dart' show DartSha256;
+import 'package:flutter/scheduler.dart';
+
+import '../core/app_version.dart';
+import '../core/harness_file_store.dart';
+import 'product_measurement.dart';
+
+/// Only the last consented run's control flags live locally. No history or content.
+/// The local scope hash fences account changes; it is never a report field.
+class ProductRuntimeHealth {
+ static final _launchClock = Stopwatch();
+ static void launched() {
+ if (!_launchClock.isRunning) _launchClock.start();
+ }
+
+ ProductRuntimeHealth(
+ this.measurement, {
+ this.readState,
+ this.writeState,
+ this.readVersion,
+ }) {
+ measurement.addListener(_choiceChanged);
+ }
+ final ProductMeasurement measurement;
+ final Future<Map<String, dynamic>> Function()? readState;
+ final Future<void> Function(Map<String, dynamic>)? writeState;
+ final Future<String> Function()? readVersion;
+ String? _scope;
+ String? _accountId;
+ int _epoch = 0, _revision = -1, _frame = 0;
+ bool _disposed = false,
+ _active = false,
+ _timingsInstalled = false,
+ _ready = false,
+ _readyCounted = false;
+ bool newInstallation = false;
+ Timer? _sample;
+ Map<String, dynamic> _state = {};
+ Map<String, dynamic>? _pending;
+ Future<void>? _saving;
+ void Function(ProductOutcome)? _workspace;
+
+ File get _file => File(
+ '${HarnessFileStore.defaultDirectoryPath()}/product-health-state.json',
+ );
+
+ void account(String? account) {
+ if (_accountId == account) return;
+ _accountId = account;
+ final scope = account == null
+ ? null
+ : const DartSha256()
+ .hashSync(utf8.encode(account))
+ .bytes
+ .map((b) => b.toRadixString(16).padLeft(2, '0'))
+ .join();
+ if (_scope == scope) return;
+ final previous = _scope;
+ _scope = scope;
+ _ready = false;
+ _stop();
+ if (previous != null) _save({});
+ _choiceChanged();
+ }
+
+ void _choiceChanged() {
+ final permitted =
+ !_disposed &&
+ _scope != null &&
+ measurement.healthEnabled &&
+ measurement.sharing;
+ if (!permitted) {
+ _stop();
+ // An explicit off is observable through the revision; never keep a previous run across it.
+ if (measurement.choiceRevision >= 0 && !measurement.sharing) _save({});
+ return;
+ }
+ if (_active && _revision == measurement.choiceRevision) return;
+ _stop();
+ _active = true;
+ _revision = measurement.choiceRevision;
+ unawaited(_start(_epoch));
+ }
+
+ Future<void> _start(int epoch) async {
+ try {
+ final previous = readState != null ? await readState!() : await _read();
+ final rawVersion = await (readVersion?.call() ?? runningAppVersion());
+ if (!_active || _disposed || epoch != _epoch) return;
+ final oldContext = measurement.context!;
+ measurement.context = ProductUsageContext(
+ release: rawVersion,
+ platform: oldContext.platform,
+ production: oldContext.production,
+ );
+ final version = measurement.context!.release;
+ final same =
+ previous['scope'] == _scope && previous['revision'] == _revision;
+ if (same && previous['pendingUpdate'] is String) {
+ measurement.begin(ProductFlow.updateRelaunch)(
+ version != 'unknown' && previous['pendingUpdate'] == version
+ ? ProductOutcome.ok
+ : ProductOutcome.unknown,
+ );
+ } else if (same && previous['clean'] == false) {
+ measurement.health(ProductHealthMeasure.uncleanRestart);
+ }
+ measurement.health(
+ newInstallation
+ ? ProductHealthMeasure.installNew
+ : same &&
+ version != 'unknown' &&
+ previous['release'] != null &&
+ previous['release'] != 'unknown' &&
+ previous['release'] != version
+ ? ProductHealthMeasure.installUpgrade
+ : ProductHealthMeasure.installUnknown,
+ );
+ _state = {
+ 'scope': _scope,
+ 'revision': _revision,
+ 'release': measurement.context!.release,
+ 'clean': false,
+ };
+ _save(_state);
+ _workspace = measurement.begin(ProductFlow.workspaceReady);
+ if (_ready) ready();
+ SchedulerBinding.instance.addTimingsCallback(_frames);
+ _timingsInstalled = true;
+ _sample = Timer.periodic(
+ const Duration(minutes: 1),
+ (_) => sampleResources(),
+ );
+ sampleResources();
+ } catch (_) {
+ // Unavailable local measurement storage does not affect startup.
+ if (epoch == _epoch) _stop();
+ }
+ }
+
+ Future<Map<String, dynamic>> _read() async {
+ try {
+ if (await _file.length() > 2048) return {};
+ final value = jsonDecode(await _file.readAsString());
+ return value is Map<String, dynamic> ? value : {};
+ } catch (_) {
+ return {};
+ }
+ }
+
+ void _save(Map<String, dynamic> value) {
+ _pending = Map.of(value);
+ _saving ??= _drain().whenComplete(() {
+ _saving = null;
+ if (_pending != null) _save(_pending!);
+ });
+ }
+
+ Future<void> _drain() async {
+ while (_pending != null) {
+ final value = _pending!;
+ _pending = null;
+ try {
+ if (writeState != null) {
+ await writeState!(value);
+ } else if (value.isEmpty) {
+ if (await _file.exists()) await _file.delete();
+ } else {
+ await _file.parent.create(recursive: true);
+ final temporary = File('${_file.path}.tmp');
+ await temporary.writeAsString(jsonEncode(value), flush: true);
+ await temporary.rename(_file.path);
+ }
+ } catch (_) {
+ /* Only one in-flight write and one latest state, never a promise queue. */
+ }
+ }
+ }
+
+ void ready() {
+ _ready = true;
+ if (!_active || _state.isEmpty || _readyCounted) return;
+ _readyCounted = true;
+ _workspace?.call(ProductOutcome.ok);
+ _workspace = null;
+ if (_launchClock.isRunning) {
+ measurement.observedStartup(_launchClock.elapsed);
+ }
+ measurement.milestone(ProductHealthMeasure.funnelWorkspaceReady);
+ }
+
+ void sampleResources() {
+ if (!_active || !measurement.sharing) return;
+ try {
+ final rss = ProcessInfo.currentRss;
+ measurement.health(
+ rss < 256 * 1024 * 1024
+ ? ProductHealthMeasure.rssUnder256m
+ : rss < 1024 * 1024 * 1024
+ ? ProductHealthMeasure.rss256mTo1g
+ : ProductHealthMeasure.rssOver1g,
+ );
+ } catch (_) {
+ /* Unsupported resource samples stay unknown. */
+ }
+ }
+
+ void _frames(List<FrameTiming> timings) {
+ if (!_active || _state.isEmpty || !measurement.sharing) return;
+ for (final frame in timings) {
+ if (_frame++ % 60 != 0) continue;
+ final ms = frame.totalSpan.inMilliseconds;
+ measurement.health(
+ ms < 16
+ ? ProductHealthMeasure.frameUnder16ms
+ : ms < 50
+ ? ProductHealthMeasure.frame16msTo50ms
+ : ms < 250
+ ? ProductHealthMeasure.frame50msTo250ms
+ : ProductHealthMeasure.frameOver250ms,
+ );
+ }
+ }
+
+ void expectUpdate(String version) {
+ if (!_active || !measurement.sharing) return;
+ _state['pendingUpdate'] = ProductUsageContext(
+ release: version,
+ platform: 'other',
+ production: true,
+ ).release;
+ _save(_state);
+ }
+
+ void cancelUpdate() {
+ if (_active && _state.isNotEmpty) {
+ _state.remove('pendingUpdate');
+ _save(_state);
+ }
+ }
+
+ void cleanExit() {
+ if (_active && _state.isNotEmpty) {
+ _state['clean'] = true;
+ _save(_state);
+ }
+ }
+
+ void _stop() {
+ _epoch++;
+ _active = false;
+ _sample?.cancel();
+ _sample = null;
+ if (_timingsInstalled) {
+ SchedulerBinding.instance.removeTimingsCallback(_frames);
+ _timingsInstalled = false;
+ }
+ _workspace = null;
+ _state = {};
+ _readyCounted = false;
+ }
+
+ void dispose() {
+ if (_disposed) return;
+ cleanExit();
+ _disposed = true;
+ _stop();
+ measurement.removeListener(_choiceChanged);
+ }
+}
diff --git a/desktop/lib/measurement/task_feedback.dart b/desktop/lib/measurement/task_feedback.dart
index 2c026bfee..51b20aa16 100644
--- a/desktop/lib/measurement/task_feedback.dart
+++ b/desktop/lib/measurement/task_feedback.dart
@@ -3,11 +3,13 @@ import 'package:flutter/material.dart';
import '../shared/widgets/app_dialog.dart';
import '../shared/widgets/product_feedback.dart';
import '../widgets/desktop_chrome.dart';
+import 'product_measurement.dart';
Future<void> showTaskFeedback(
BuildContext context, {
required Future<Map<String, dynamic>> Function() choice,
required ProductFeedbackRequest send,
+ ProductMeasurement? measurement,
}) async {
final permitted = choice();
await showAppDialog<void>(
@@ -47,10 +49,28 @@ Future<void> showTaskFeedback(
key: const ValueKey('outcome'),
send: send,
outcome: true,
+ onShown: measurement?.observer(
+ ProductHealthMeasure.feedbackOutcomeShown,
+ ),
+ onAnswered: measurement?.observer(
+ ProductHealthMeasure.feedbackOutcomeAnswered,
+ ),
+ onDismissed: measurement?.observer(
+ ProductHealthMeasure.feedbackOutcomeDismissed,
+ ),
),
ProductFeedback(
key: const ValueKey('reason'),
send: send,
+ onShown: measurement?.observer(
+ ProductHealthMeasure.feedbackReasonShown,
+ ),
+ onAnswered: measurement?.observer(
+ ProductHealthMeasure.feedbackReasonAnswered,
+ ),
+ onDismissed: measurement?.observer(
+ ProductHealthMeasure.feedbackReasonDismissed,
+ ),
),
],
),
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index ba9b05257..fe5b5291c 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -6840,7 +6840,14 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
),
'app.add_phone': () => unawaited(_addPhone()),
- 'app.product_feedback': () => unawaited(showTaskFeedback(context, choice: () => app.api.productUsageSettings(), send: app.api.productUsageFeedback)),
+ 'app.product_feedback': () => unawaited(
+ showTaskFeedback(
+ context,
+ choice: () => app.api.productUsageSettings(),
+ send: app.api.productUsageFeedback,
+ measurement: app.productMeasurement,
+ ),
+ ),
'app.store': _openStore,
'app.daemon': _openCompanions,
'app.daemon_talk': _talkToDaemon,
diff --git a/desktop/lib/settings/sections/privacy_section.dart b/desktop/lib/settings/sections/privacy_section.dart
index 56da76031..9ecdca7bf 100644
--- a/desktop/lib/settings/sections/privacy_section.dart
+++ b/desktop/lib/settings/sections/privacy_section.dart
@@ -1,10 +1,13 @@
import 'package:flutter/material.dart';
+import 'package:flutter/foundation.dart' show kIsWeb;
import '../../shared/widgets/section_scaffold.dart';
import '../../shared/widgets/setting_row.dart';
import '../../shared/widgets/product_feedback.dart';
import '../../state/app_state.dart';
import '../../measurement/setup_usage_choice.dart';
+import '../../measurement/task_feedback.dart';
+import '../../measurement/product_measurement.dart';
typedef UsagePreferenceRequest = Future<Map<String, dynamic>> Function({
bool? enabled,
@@ -36,6 +39,7 @@ class PrivacySection extends StatelessWidget {
return value;
},
feedback: notifier.api.productUsageFeedback,
+ measurement: notifier.productMeasurement,
),
),
);
@@ -47,9 +51,11 @@ class ProductUsagePreference extends StatefulWidget {
super.key,
required this.request,
this.feedback,
+ this.measurement,
});
final UsagePreferenceRequest request;
final ProductFeedbackRequest? feedback;
+ final ProductMeasurement? measurement;
@override
State<ProductUsagePreference> createState() => _ProductUsagePreferenceState();
@@ -159,6 +165,13 @@ class _ProductUsagePreferenceState extends State<ProductUsagePreference> {
'• First response waits, missing responses and error-event counts; first-launch 24-hour response counts and D1/D7/D28 working-day returns\n'
'• A fixed feedback answer only when you choose to send one\n'
'• Protocol version and the revision of your sharing preference\n\n'
+ 'Desktop and CLI also share separate release and operating-system totals; '
+ 'fixed startup, viewer-load, update-apply, reconnect and resume-to-work outcomes; '
+ 'coarse memory, CPU and frame-time buckets; and counts of errors and interrupted app runs. '
+ 'No error text, stack trace, device specification or browsing address is sent. '
+ 'Local day flags measure explicit composer work and weekly use; they are never uploaded. '
+ 'The last app run keeps only local restart/update control flags, removed when sharing is off. '
+ 'Feedback views, answers and dismissals are counted without linking them to a task.\n\n'
'Older apps contribute connection, remote-session, and turn-start totals. '
'These event counts are separate from active computer counts.\n\n'
'Sign-in checks your preference. Account, computer, and agent identifiers are not stored '
@@ -172,8 +185,29 @@ class _ProductUsagePreferenceState extends State<ProductUsagePreference> {
'A turn ending does not tell us whether your task succeeded.',
),
],
- if (_enabled == true && widget.feedback != null)
- ProductFeedback(send: widget.feedback!),
+ if (_enabled == true && widget.feedback != null) ...[
+ if (!kIsWeb) TextButton(
+ onPressed: () => showTaskFeedback(
+ context,
+ choice: widget.request,
+ send: widget.feedback!,
+ measurement: widget.measurement,
+ ),
+ child: const Text('Rate task outcome'),
+ ),
+ ProductFeedback(
+ send: widget.feedback!,
+ onShown: widget.measurement?.observer(
+ ProductHealthMeasure.feedbackReasonShown,
+ ),
+ onAnswered: widget.measurement?.observer(
+ ProductHealthMeasure.feedbackReasonAnswered,
+ ),
+ onDismissed: widget.measurement?.observer(
+ ProductHealthMeasure.feedbackReasonDismissed,
+ ),
+ ),
+ ],
],
),
);
diff --git a/desktop/lib/shared/widgets/product_feedback.dart b/desktop/lib/shared/widgets/product_feedback.dart
index 8533b69d6..01ae9dd6b 100644
--- a/desktop/lib/shared/widgets/product_feedback.dart
+++ b/desktop/lib/shared/widgets/product_feedback.dart
@@ -9,9 +9,17 @@ typedef ProductFeedbackRequest = Future<void> Function(
/// A voluntary, fixed-choice response. It carries no task, account or session context.
class ProductFeedback extends StatefulWidget {
- const ProductFeedback({super.key, required this.send, this.outcome = false});
+ const ProductFeedback({
+ super.key,
+ required this.send,
+ this.outcome = false,
+ this.onShown,
+ this.onAnswered,
+ this.onDismissed,
+ });
final ProductFeedbackRequest send;
final bool outcome;
+ final VoidCallback? onShown, onAnswered, onDismissed;
@override
State<ProductFeedback> createState() => _ProductFeedbackState();
}
@@ -33,6 +41,20 @@ class _ProductFeedbackState extends State<ProductFeedback> {
String? _answer, _status;
bool _busy = false, _sent = false;
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) widget.onShown?.call();
+ });
+ }
+
+ @override
+ void dispose() {
+ if (!_sent) widget.onDismissed?.call();
+ super.dispose();
+ }
+
static String _newReceipt() {
final random = Random.secure();
final bytes = List.generate(16, (_) => random.nextInt(256));
@@ -50,6 +72,8 @@ class _ProductFeedbackState extends State<ProductFeedback> {
});
try {
await widget.send(answer, _receipt);
+ if (!mounted) return;
+ if (!_sent) widget.onAnswered?.call();
if (mounted) {
setState(() {
_sent = true;
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index a1f6f90e8..1c2877735 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1,4 +1,7 @@
import '../measurement/product_measurement.dart';
+import '../measurement/product_runtime_health.dart';
+import '../measurement/product_connections.dart';
+import '../core/crash_log.dart';
import '../measurement/setup_transport.dart';
import 'attached_task_delivery.dart';
import 'task_route.dart';
@@ -651,6 +654,11 @@ class AppNotifier extends ChangeNotifier {
AppConfig config;
late ApiClient api;
late final ProductMeasurement productMeasurement;
+ ProductRuntimeHealth? productRuntimeHealth;
+ late final ProductConnections productConnections;
+ final _measurementResumes = <String, void Function(ProductOutcome)>{};
+ void Function(bool)? _measurementError;
+ int _measurementGeneration = -1;
final _measurementConnections = <String, void Function(ProductOutcome)>{};
/// Signs in, and says whether this computer is signed in: the harness CLI in a desktop build,
@@ -3258,9 +3266,34 @@ class AppNotifier extends ChangeNotifier {
? 'desktop'
: 'phone',
automatic: !kUnderTest,
+ context: !kIsWeb && this.viewer == null
+ ? ProductUsageContext(
+ release: 'unknown',
+ platform: Platform.isMacOS
+ ? 'macos'
+ : Platform.isWindows
+ ? 'windows'
+ : Platform.isLinux
+ ? 'linux'
+ : 'other',
+ production:
+ kReleaseMode && this.config.autonomousEnv == 'prod',
+ )
+ : null,
sendSetup: (report) =>
sendSetupMeasurement(this.config.apiBaseUrl, report),
);
+ productConnections = ProductConnections(this.productMeasurement);
+ this.productMeasurement.addListener(_measurementChoiceChanged);
+ if (!kUnderTest && this.productMeasurement.healthEnabled) {
+ productRuntimeHealth = ProductRuntimeHealth(this.productMeasurement);
+ _measurementError = (framework) => this.productMeasurement.health(
+ framework
+ ? ProductHealthMeasure.frameworkError
+ : ProductHealthMeasure.asyncError,
+ );
+ CrashLog.healthError = _measurementError;
+ }
addListener(_syncProductMeasurement);
_initDeviceLog();
// `grid.AppTheme.palette`, not the prefs store: main.dart copies the saved
@@ -3285,6 +3318,15 @@ class AppNotifier extends ChangeNotifier {
}
void _syncProductMeasurement() {
+ final context = productMeasurement.context;
+ final production = kReleaseMode && _autonomousEnv == 'prod';
+ if (context != null && context.production != production) {
+ productMeasurement.context = ProductUsageContext(
+ release: context.release,
+ platform: context.platform,
+ production: production,
+ );
+ }
final scope =
signedIn &&
!signingIn &&
@@ -3298,7 +3340,31 @@ class AppNotifier extends ChangeNotifier {
choice: () => api.productUsageSettings(),
send: api.productUsageReport,
);
- if (scope == null) _measurementConnections.clear();
+ productRuntimeHealth?.account(
+ scope == null ? null : '$_autonomousEnv:${currentUser!.id}',
+ );
+ if (scope == null) {
+ _measurementConnections.clear();
+ productConnections.clear();
+ _measurementResumes.clear();
+ } else if (machineStates.values.any(
+ (machine) => machine.connectionStatus == ConnectionStatus.connected,
+ )) {
+ productRuntimeHealth?.ready();
+ productMeasurement.milestone(ProductHealthMeasure.funnelWorkspaceReady);
+ }
+ if (status == AppStatus.unauthenticated) {
+ productMeasurement.milestone(ProductHealthMeasure.funnelSignInSeen);
+ }
+ }
+
+ void _measurementChoiceChanged() {
+ if (!productMeasurement.sharing ||
+ _measurementGeneration != productMeasurement.observationGeneration) {
+ _measurementConnections.clear();
+ _measurementResumes.clear();
+ }
+ _measurementGeneration = productMeasurement.observationGeneration;
}
// Connection keys already belong to the app. Only fixed outcomes reach measurement, never the key.
@@ -4629,6 +4695,7 @@ class AppNotifier extends ChangeNotifier {
}
if (firstHarness) {
firstArrival.begin(downloads: agentPrefetch?.started ?? false);
+ productRuntimeHealth?.newInstallation = true;
}
if (!result.isReady) {
status = AppStatus.preparingEnvironment;
@@ -6008,6 +6075,7 @@ class AppNotifier extends ChangeNotifier {
// Reassigned once the manifest has been re-read below; the failure messages
// at the end name whichever build was actually attempted.
final finish = productMeasurement.begin(ProductFlow.updateStage);
+ void Function(ProductOutcome)? finishApply;
var info = chosen;
isInstallingUpdate = true;
updateDownloadFraction = null;
@@ -6064,22 +6132,30 @@ class AppNotifier extends ChangeNotifier {
updateError = 'Could not download and verify Harness ${info.version}.';
return false;
}
- // A staged download is observable; successful relaunch is not. Never delay the update for reporting.
+ // The next consented launch can confirm the version; never wait for reporting.
finish(ProductOutcome.ok);
+ productRuntimeHealth?.expectUpdate(info.version);
+ finishApply = productMeasurement.begin(ProductFlow.updateApply);
final applied = await updater.applyStaged(staged, selfPid: pid);
+ finishApply(applied ? ProductOutcome.ok : ProductOutcome.failed);
if (!applied) {
+ productRuntimeHealth?.cancelUpdate();
updateError =
'This copy of Harness cannot install updates automatically.';
return false;
}
flushAppLog();
+ productRuntimeHealth?.cleanExit();
exit(0);
} catch (error) {
finish(ProductOutcome.failed);
+ finishApply?.call(ProductOutcome.failed);
+ productRuntimeHealth?.cancelUpdate();
updateError = 'Could not install Harness ${info.version}: $error';
return false;
} finally {
finish(ProductOutcome.unknown);
+ finishApply?.call(ProductOutcome.unknown);
isInstallingUpdate = false;
updateDownloadFraction = null;
if (!_disposed) notifyListeners();
@@ -6531,6 +6607,14 @@ class AppNotifier extends ChangeNotifier {
void _onLocalFailure(String machineId, int code, String reason) {
final machine = machineStates[machineId];
if (machine == null) return;
+ productConnections.refused(
+ machineId,
+ code == 4404
+ ? ProductHealthMeasure.connectErrorUnlinked
+ : code == 4401 || code == 4403
+ ? ProductHealthMeasure.connectErrorAuth
+ : ProductHealthMeasure.connectErrorOther,
+ );
if (code == 4403) {
if (machine.isLocalMachine) {
unawaited(_onLocalMachineMismatch(machine, reason));
@@ -6824,6 +6908,19 @@ class AppNotifier extends ChangeNotifier {
final settling =
nextStatus == ConnectionStatus.disconnected &&
_trustSettling.contains(machineId);
+ productConnections.status(
+ machineId,
+ connecting:
+ settling ||
+ nextStatus == ConnectionStatus.connecting ||
+ nextStatus == ConnectionStatus.reconnecting,
+ connected: nextStatus == ConnectionStatus.connected,
+ failure: machine.needsLink
+ ? ProductHealthMeasure.connectErrorUnlinked
+ : machine.nodeOnline == false
+ ? ProductHealthMeasure.connectErrorOffline
+ : null,
+ );
// An unlinked machine is redialled every 5 s by the link retry and refused at once each time
// (4404 NO_PEER_LINK): measured per dial, one such machine read as ~720 failed connects an hour,
// and prod's first day showed 1,197 of 1,233 remote connects "failed", nearly all under a second.
@@ -6871,11 +6968,7 @@ class AppNotifier extends ChangeNotifier {
// set by onLocalFailure, which runs before this branch for 4404 (see WsConn._onDone).
if (!machine.needsLink && !settling) {
unawaited(
- _applyNodeStatus(
- machine,
- false,
- why: 'socket ${nextStatus.name}',
- ),
+ _applyNodeStatus(machine, false, why: 'socket ${nextStatus.name}'),
);
}
}
@@ -7479,6 +7572,7 @@ class AppNotifier extends ChangeNotifier {
}) async {
final state = machineStates[machineId];
if (state == null || state.machine.isShared) return false;
+ final finishConnection = productConnections.manual(machineId);
final done = Completer<bool>();
var dialed = false;
void settle() {
@@ -7506,8 +7600,19 @@ class AppNotifier extends ChangeNotifier {
if (machineStates[machineId] case final current?)
_connectMachine(current);
settle();
- return await done.future;
+ final connected = await done.future;
+ if (!connected) {
+ productConnections.refused(
+ machineId,
+ machineStates[machineId]?.needsLink == true
+ ? ProductHealthMeasure.connectErrorUnlinked
+ : ProductHealthMeasure.connectErrorTimeout,
+ );
+ }
+ finishConnection(connected ? ProductOutcome.ok : ProductOutcome.failed);
+ return connected;
} finally {
+ finishConnection(ProductOutcome.unknown);
timer.cancel();
removeListener(settle);
}
@@ -13099,7 +13204,8 @@ class AppNotifier extends ChangeNotifier {
return refused(review['error'], review['detail']);
}
final reviewId = review['reviewId'];
- if (reviewId is! String) return 'Could not review this harness for deletion.';
+ if (reviewId is! String)
+ return 'Could not review this harness for deletion.';
final result = await _conn(machineId).request(
'agent_purge',
payload: {...target, 'mode': 'delete', 'reviewId': reviewId},
@@ -13321,6 +13427,24 @@ class AppNotifier extends ChangeNotifier {
}
attempt._awaitingConfirmation = true;
final resuming = attempt.agent?.isStopped == true;
+ final measurementKey = _turnActivityKey(machineId, agentId);
+ if (resuming &&
+ !checking &&
+ productMeasurement.healthEnabled &&
+ productMeasurement.sharing) {
+ if (_measurementResumes.length >= 64) {
+ productMeasurement.health(ProductHealthMeasure.observationOverflow);
+ _measurementResumes
+ .remove(_measurementResumes.keys.first)
+ ?.call(ProductOutcome.unknown);
+ }
+ _measurementResumes
+ .remove(measurementKey)
+ ?.call(ProductOutcome.cancelled);
+ _measurementResumes[measurementKey] = productMeasurement.begin(
+ ProductFlow.resumeRecovery,
+ );
+ }
final unknown = RestartAgentResult(
error: resuming
? 'Still waiting for the Open response. Select the harness again to check status.'
@@ -13378,6 +13502,7 @@ class AppNotifier extends ChangeNotifier {
return unknown;
}
attempt._awaitingConfirmation = false;
+ _measurementResumes.remove(measurementKey)?.call(ProductOutcome.failed);
return RestartAgentResult(
error: _restartFailure(code, result['detail'], resuming: resuming),
);
@@ -13402,6 +13527,7 @@ class AppNotifier extends ChangeNotifier {
final failure = result['failure'];
if (failure is! Map || failure['code'] is! String) return unknown;
attempt._awaitingConfirmation = false;
+ _measurementResumes.remove(measurementKey)?.call(ProductOutcome.failed);
return RestartAgentResult(
error: _restartFailure(
failure['code'] as String,
@@ -17330,6 +17456,13 @@ class AppNotifier extends ChangeNotifier {
}
}
if (type == 'agent_activity') return;
+ if (type == 'text_delta' &&
+ event['replay'] != true &&
+ machine.liveTurnAgents.contains(
+ _eventAgentId(machine, event, payload),
+ )) {
+ productMeasurement.milestone(ProductHealthMeasure.funnelFirstResponse);
+ }
if (reportedActivity == null &&
event['replay'] != true &&
const {
@@ -17872,6 +18005,10 @@ class AppNotifier extends ChangeNotifier {
if (agentId != null) {
if (type == 'turn_started' && event['replay'] != true) {
machine.liveTurnAgents.add(agentId);
+ productMeasurement.milestone(ProductHealthMeasure.funnelFirstWork);
+ _measurementResumes
+ .remove(_turnActivityKey(machineId, agentId))
+ ?.call(ProductOutcome.ok);
changed = machine.failedTurnAgents.remove(agentId);
}
if (reportedActivity == null &&
@@ -18098,6 +18235,13 @@ class AppNotifier extends ChangeNotifier {
@override
void dispose() {
+ if (identical(CrashLog.healthError, _measurementError)) {
+ CrashLog.healthError = null;
+ }
+ productRuntimeHealth?.dispose();
+ productConnections.dispose();
+ _measurementResumes.clear();
+ productMeasurement.removeListener(_measurementChoiceChanged);
productMeasurement.dispose();
_measurementConnections.clear();
if (cliLogin case final CliLogin cli) {
diff --git a/desktop/lib/terminal/terminal_session.dart b/desktop/lib/terminal/terminal_session.dart
index 494fbb500..64b5ff925 100644
--- a/desktop/lib/terminal/terminal_session.dart
+++ b/desktop/lib/terminal/terminal_session.dart
@@ -1022,6 +1022,7 @@ class TerminalSession extends ChangeNotifier {
'content': content,
'agentId': agentId,
'mode': 'auto',
+ if (!kIsWeb && client?.kind == 'desktop') 'usageIntent': 'interactive',
});
}
diff --git a/desktop/lib/widgets/web_pane_panel.dart b/desktop/lib/widgets/web_pane_panel.dart
index 033c2aacd..cca3a3a06 100644
--- a/desktop/lib/widgets/web_pane_panel.dart
+++ b/desktop/lib/widgets/web_pane_panel.dart
@@ -16,6 +16,7 @@ import '../shared/theme/app_pane_icon.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/theme/workspace_bar_style.dart';
import '../state/app_state.dart';
+import '../measurement/product_measurement.dart';
import '../state/harness_monitor_controller.dart';
import '../state/terminal_pane.dart';
import '../theme/app_theme.dart';
@@ -106,6 +107,21 @@ class _WebPanePanelState extends State<WebPanePanel> {
String? _loadedUrl;
bool _loading = false;
String? _failure;
+ void Function(ProductOutcome)? _finishLoad;
+ void _startLoad() {
+ _finishLoad?.call(ProductOutcome.cancelled);
+ _finishLoad = widget.notifier.productMeasurement.begin(
+ ProductFlow.viewerLoad,
+ );
+ }
+
+ void _remoteLoaded() {
+ if (_remote?.image != null) {
+ _finishLoad?.call(ProductOutcome.ok);
+ } else if (_remote?.error != null) {
+ _finishLoad?.call(ProductOutcome.failed);
+ }
+ }
/// The appearance last stamped on the page, so a rebuild that changed nothing runs no script.
Brightness? _stampedBrightness;
@@ -133,6 +149,10 @@ class _WebPanePanelState extends State<WebPanePanel> {
(payload) => notifier.viewerSurface(machineId, agentId, payload),
onHostAction: (action) => unawaited(_hostAction(action)),
);
+ if (!kIsWeb) {
+ _startLoad();
+ _remote!.addListener(_remoteLoaded);
+ }
pane.focusViewerInput = _focusRemote;
}
@@ -140,6 +160,7 @@ class _WebPanePanelState extends State<WebPanePanel> {
@override
void dispose() {
+ _finishLoad?.call(ProductOutcome.cancelled);
if (widget.pane.focusViewerInput == _focusRemote) {
widget.pane.focusViewerInput = null;
}
@@ -164,10 +185,12 @@ class _WebPanePanelState extends State<WebPanePanel> {
..setNavigationDelegate(
NavigationDelegate(
onPageStarted: (_) => _set(() {
+ _startLoad();
_loading = true;
_failure = null;
}),
onPageFinished: (_) {
+ _finishLoad?.call(ProductOutcome.ok);
_set(() => _loading = false);
// A fresh document has no stamp; give it the app's appearance before it is looked at.
_stampedBrightness = null;
@@ -178,6 +201,7 @@ class _WebPanePanelState extends State<WebPanePanel> {
// and images of its own, and one of those failing is its business
// to show, not ours to call a dead viewer.
if (error.isForMainFrame == false) return;
+ _finishLoad?.call(ProductOutcome.failed);
_set(() {
_loading = false;
_failure = error.description.isNotEmpty
diff --git a/desktop/test/privacy_section_test.dart b/desktop/test/privacy_section_test.dart
index 7176fbbdb..65abfd5c0 100644
--- a/desktop/test/privacy_section_test.dart
+++ b/desktop/test/privacy_section_test.dart
@@ -19,6 +19,23 @@ void main() {
await tester.pumpAndSettle();
}
+ testWidgets('offers task feedback directly from the privacy controls', (
+ tester,
+ ) async {
+ await show(
+ tester,
+ ({bool? enabled}) async => {'enabled': true, 'revision': 0},
+ );
+ await tester.tap(find.text('Rate task outcome'));
+ await tester.pumpAndSettle();
+ expect(find.text('Did you finish what you wanted?'), findsOneWidget);
+ expect(find.text('Partly completed'), findsOneWidget);
+ expect(
+ find.textContaining('without your task or its contents'),
+ findsWidgets,
+ );
+ });
+
testWidgets(
'shows the saved preference and turns sharing off for the account',
(tester) async {
@@ -41,10 +58,19 @@ void main() {
expect(find.textContaining('kept 10 days'), findsOneWidget);
// A keyed code can be recomputed from the account id (that is how opt-out deletes it): pseudonymous, not anonymous.
expect(find.textContaining('anonymous code'), findsNothing);
- expect(find.textContaining('coded ID instead of your account'), findsWidgets);
+ expect(
+ find.textContaining('coded ID instead of your account'),
+ findsWidgets,
+ );
expect(find.textContaining('sign-up day'), findsOneWidget);
- expect(find.textContaining('New reports create no per-person history'), findsNothing);
- expect(find.textContaining('are not stored with the combined totals'), findsOneWidget);
+ expect(
+ find.textContaining('New reports create no per-person history'),
+ findsNothing,
+ );
+ expect(
+ find.textContaining('are not stored with the combined totals'),
+ findsOneWidget,
+ );
expect(
find.textContaining('does not tell us whether your task succeeded'),
findsOneWidget,
diff --git a/desktop/test/product_feedback_test.dart b/desktop/test/product_feedback_test.dart
index 45df24f1a..955754276 100644
--- a/desktop/test/product_feedback_test.dart
+++ b/desktop/test/product_feedback_test.dart
@@ -3,6 +3,38 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/widgets/product_feedback.dart';
void main() {
+ testWidgets(
+ 'counts exposure, successful answer, and dismissal without task context',
+ (tester) async {
+ var shown = 0, answered = 0, dismissed = 0;
+ Future<void> show() => tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ProductFeedback(
+ send: (_, _) async {},
+ onShown: () => shown++,
+ onAnswered: () => answered++,
+ onDismissed: () => dismissed++,
+ ),
+ ),
+ ),
+ );
+ await show();
+ await tester.pump();
+ expect(shown, 1);
+ expect(answered, 0);
+ await tester.tap(find.text('Useful'));
+ await tester.pumpAndSettle();
+ expect(answered, 1);
+ await tester.pumpWidget(const SizedBox());
+ expect(dismissed, 0);
+ await show();
+ await tester.pump();
+ await tester.pumpWidget(const SizedBox());
+ expect(shown, 2);
+ expect(dismissed, 1);
+ },
+ );
testWidgets(
'voluntary feedback sends only a fixed answer and retries the same receipt',
(tester) async {
diff --git a/desktop/test/product_health_test.dart b/desktop/test/product_health_test.dart
new file mode 100644
index 000000000..5cbdf1159
--- /dev/null
+++ b/desktop/test/product_health_test.dart
@@ -0,0 +1,208 @@
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/measurement/product_measurement.dart';
+import 'package:harness/measurement/product_connections.dart';
+import 'package:harness/measurement/product_runtime_health.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late ProductMeasurement usage;
+ late List<Map<String, dynamic>> reports, setup;
+ late DateTime now;
+ late Map<String, dynamic> choice;
+ setUp(() {
+ now = DateTime.utc(2026, 10, 14, 12);
+ reports = [];
+ choice = {'enabled': true, 'revision': 0};
+ setup = [];
+ usage = ProductMeasurement(
+ surface: 'desktop',
+ automatic: false,
+ context: ProductUsageContext(
+ release: '1.2.73',
+ platform: 'macos',
+ production: true,
+ ),
+ now: () => now,
+ sendSetup: (report) async {
+ setup.add(report);
+ return {'accepted': true};
+ },
+ );
+ usage.account(
+ 'PRIVATE_ACCOUNT',
+ choice: () async => choice,
+ send: (report) async {
+ reports.add(jsonDecode(jsonEncode(report)));
+ return {'accepted': true};
+ },
+ );
+ });
+ tearDown(() => usage.dispose());
+ test('development builds do not send anonymous setup counts', () async {
+ usage.account(null);
+ usage.context = ProductUsageContext(
+ release: 'unknown',
+ platform: 'macos',
+ production: false,
+ );
+ await usage.setSignedOutSharing(true);
+ usage.begin(ProductFlow.setup)(ProductOutcome.ok);
+ usage.milestone(ProductHealthMeasure.funnelSetupSeen);
+ await usage.flush();
+ expect(setup, isEmpty);
+ });
+ Map<String, int> totals() {
+ final all = <String, int>{};
+ for (final report in [...reports, ...setup]) {
+ for (final e in (report['counters'] as Map).entries)
+ all[e.key as String] = (all[e.key] ?? 0) + (e.value as int);
+ }
+ return all;
+ }
+
+ test('connection observations restart cleanly after off/on with the same machine', () async {
+ await usage.flush();
+ final connections = ProductConnections(usage);
+ connections.status('PRIVATE_MACHINE', connecting: true, connected: false);
+ usage.savedChoice({'enabled': false, 'revision': 1});
+ choice = {'enabled': true, 'revision': 2};
+ usage.savedChoice(choice);
+ connections.status('PRIVATE_MACHINE', connecting: true, connected: false);
+ connections.status('PRIVATE_MACHINE', connecting: false, connected: true);
+ await usage.flush();
+ expect(totals()['ui_desktop_connect_auto_started'], 1);
+ expect(totals()['ui_desktop_connect_auto_ok'], 1);
+ connections.dispose();
+ });
+
+ test('consented funnel is once per local episode, with coarse waits and no identity', () async {
+ usage.milestone(ProductHealthMeasure.funnelFirstWork);
+ expect(totals(), isEmpty);
+ usage.account(null);
+ await usage.setSignedOutSharing(true);
+ usage.milestone(ProductHealthMeasure.funnelSetupSeen);
+ now = now.add(const Duration(minutes: 2));
+ usage.milestone(ProductHealthMeasure.funnelFirstWork);
+ usage.milestone(ProductHealthMeasure.funnelFirstWork);
+ now = now.add(const Duration(minutes: 4));
+ usage.milestone(ProductHealthMeasure.funnelFirstResponse);
+ await usage.flush();
+ expect(totals()['setup_desktop_funnel_first_work'], 1);
+ expect(totals()['setup_desktop_first_work_1m_to_5m'], 1);
+ expect(totals()['setup_desktop_first_response_over_5m'], 1);
+ expect(jsonEncode(setup), isNot(contains('PRIVATE')));
+ });
+
+ test('manual connect and automatic retries remain separate; missing outcomes expire as unknown', () async {
+ await usage.flush();
+ final connections = ProductConnections(usage);
+ connections.status('PRIVATE_MACHINE', connecting: true, connected: false);
+ connections.status(
+ 'PRIVATE_MACHINE',
+ connecting: false,
+ connected: false,
+ failure: ProductHealthMeasure.connectErrorUnlinked,
+ );
+ final manual = connections.manual('PRIVATE_MACHINE');
+ connections.status('PRIVATE_MACHINE', connecting: true, connected: false);
+ connections.status('PRIVATE_MACHINE', connecting: false, connected: true);
+ manual(ProductOutcome.ok);
+ manual(ProductOutcome.failed);
+ usage.begin(ProductFlow.resumeRecovery);
+ now = now.add(const Duration(minutes: 16));
+ await usage.flush();
+ await usage.flush();
+ expect(totals()['ui_desktop_connect_auto_failed'], 1);
+ expect(totals()['ui_desktop_connect_user_ok'], 1);
+ expect(totals()['ui_desktop_connect_auto_started'], 1);
+ expect(totals()['ui_desktop_resume_recovery_unknown'], 1);
+ expect(jsonEncode(reports), isNot(contains('PRIVATE')));
+ expect(reports.first['context'], usage.context!.toJson());
+ });
+
+ test('opt-out and account changes fence delayed callbacks, counters, and retries', () async {
+ await usage.flush();
+ final old = usage.begin(ProductFlow.viewerLoad);
+ final feedback = usage.observer(
+ ProductHealthMeasure.feedbackOutcomeAnswered,
+ );
+ usage.savedChoice({'enabled': false, 'revision': 1});
+ usage.savedChoice({'enabled': true, 'revision': 2});
+ old(ProductOutcome.ok);
+ feedback();
+ await usage.flush();
+ expect(totals()['ui_desktop_viewer_load_ok'], isNull);
+ expect(totals()['health_desktop_feedback_outcome_answered'], isNull);
+ usage.health(ProductHealthMeasure.frameworkError);
+ usage.account('DIFFERENT_PRIVATE_ACCOUNT');
+ await usage.flush();
+ expect(totals()['health_desktop_framework_error'], isNull);
+ });
+
+ testWidgets(
+ 'runtime stores only last-run control flags and removes them after opt-out',
+ (tester) async {
+ Map<String, dynamic> saved = {};
+ final runtime = ProductRuntimeHealth(
+ usage,
+ readState: () async => Map.of(saved),
+ writeState: (value) async {
+ saved = Map.of(value);
+ },
+ readVersion: () async => '1.2.73',
+ );
+ runtime.account('PRIVATE_ACCOUNT');
+ runtime.ready();
+ ProductRuntimeHealth.launched();
+ await usage.flush();
+ await tester.pump();
+ expect(saved.keys.toSet(), {'scope', 'revision', 'release', 'clean'});
+ expect(saved['clean'], false);
+ expect(jsonEncode(saved), isNot(contains('PRIVATE')));
+ runtime.expectUpdate('1.2.74');
+ await tester.pump();
+ expect(saved['pendingUpdate'], '1.2.74');
+ usage.savedChoice({'enabled': false, 'revision': 1});
+ await tester.pump();
+ expect(saved, isEmpty);
+ runtime.dispose();
+ await tester.pump();
+ expect(saved, isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'relaunch confirms only the expected public version and sharing revision',
+ (tester) async {
+ Map<String, dynamic> saved = {};
+ ProductRuntimeHealth create(String version) => ProductRuntimeHealth(
+ usage,
+ readState: () async => Map.of(saved),
+ writeState: (value) async {
+ saved = Map.of(value);
+ },
+ readVersion: () async => version,
+ );
+ var runtime = create('1.2.73');
+ runtime.account('PRIVATE_ACCOUNT');
+ await usage.flush();
+ await tester.pump();
+ runtime.expectUpdate('1.2.74');
+ await tester.pump();
+ runtime.dispose();
+ await tester.pump();
+ runtime = create('1.2.74');
+ runtime.account('PRIVATE_ACCOUNT');
+ await tester.pump();
+ await usage.flush();
+ await usage.flush();
+ expect(totals()['ui_desktop_update_relaunch_ok'], 1);
+ expect(totals()['health_desktop_install_upgrade'], 1);
+ expect(jsonEncode(reports), isNot(contains('scope')));
+ runtime.dispose();
+ await tester.pump();
+ },
+ );
+}
diff --git a/docs/plans/2026-10-14-product-health-measurement.md b/docs/plans/2026-10-14-product-health-measurement.md
new file mode 100644
index 000000000..8b0af7ff2
--- /dev/null
+++ b/docs/plans/2026-10-14-product-health-measurement.md
@@ -0,0 +1,44 @@
+# Aggregate product health measurement
+
+Requested 2026-10-14 08:31 UTC. Scope: Desktop, CLI/gateway, backend ingestion and the daily report.
+Web and mobile keep their existing instrumentation. This extends fleet aggregates, not the separate
+optional people-retention records on main. No new identity, content, event-history or join key is collected.
+
+## Definitions and implementation
+
+- Preserve legacy counters. Add explicit coverage markers for the new observations so missing data is
+ unknown. Separate application requests, tool requests and unknown sources; a source is not proof of human intent.
+- Measure explicit composed-message submissions separately; raw terminal input is never inspected.
+ Working days and first-work return cohorts are calculated from bounded local flags. Unclassified work stays unknown.
+- Add bounded public release versions and broad platform categories as **separate marginal totals**.
+ Never store their cross-product or attach them to people records. Development reports do not enter
+ production totals. Hide sparse breakdowns in the review; this is not a claim of mathematical anonymity.
+- Observe setup milestones only after consent, with no retrospective replay. First-use counts include
+ an unknown installation class when an upgrade cannot be distinguished from a fresh install.
+- Observe viewer main-frame load, update apply/relaunch, manual connection attempts, automatic retries,
+ recovery and fixed refusal categories. App closure, timeout and missing replies remain separate from failure.
+- Measure startup readiness, coarse UI frame stalls, process resource buckets and unexpected restarts.
+ An unclean prior run is not proof of a crash. Never send stacks, error messages, URLs or machine inventories.
+- Count feedback shown/answered/dismissed with the existing voluntary fixed answers. No task association.
+- Report upload rejection/failure/expiry, observation overflow, capped counts and unmatched starts. Synthetic
+ fixtures exercise every path, privacy off/on and account switching, and failures of the measurement service.
+
+## Validation selected before implementation
+
+1. Backend and CLI typechecks; affected measurement, protocol, boundary and report tests while developing.
+2. Automatic full backend/CLI/Desktop PR suites on a stable ready head; no second equivalent local full suite.
+3. Local CLI coverage gates if their covered files change; macOS Desktop affected tests and native callback
+ fixtures for changed platform behavior. Core grows only for existing scalar forwarding, if needed.
+4. Disposable Mongo integration: strict schemas, atomic dedupe and marginal totals, no identity fields,
+ expiry, choice fencing and old-client compatibility. No production writes or user records.
+5. Real daemon measurement isolation and the existing on/off/stalled collector benchmark, with synthetic
+ work and the pinned toolchain. New timers must remain outside core and bounded.
+6. Review final diff independently of implementation while CI runs. Record implementation, validation,
+ merge, publication and waiting separately under ignored `.harness/measurement-health/`.
+
+## Deliberate limits
+
+No exact attribution of private task success, individual churn reasons or arbitrary click trails.
+Counters describe participating clients; opt-outs and missing uploads affect coverage. Public release
+comparisons are descriptive, not causal experiments. Unexpected exits are only observable on a later
+consented launch. Synthetic benchmarks supply controlled performance evidence without collecting work.
diff --git a/docs/product-measurement.md b/docs/product-measurement.md
index 00506609f..59c4bd862 100644
--- a/docs/product-measurement.md
+++ b/docs/product-measurement.md
@@ -43,6 +43,40 @@ linked to the account so the switch works everywhere.
## Runtime and storage budget
+Desktop/CLI health adds separate marginal totals for the numeric public release and broad OS
+(`macos`, `linux`, `windows`, `other`). The two dimensions are never stored together or joined to
+the optional people records. The daily report suppresses margin labels and counts below 20
+collector observations; these are not 20 distinct people and this is not a claim of anonymity.
+Source/dev builds send a development context that ingestion drops without writing totals or receipts.
+Legacy clients without context remain separately unattributed. Mixed-release queued days use
+`unknown`; immutable in-flight receipts preserve their original context. Backdated returns are
+excluded from release/platform margins so a return's release cannot be mistaken for its cohort's.
+
+`health` in `usage:daily` reports consented setup/workspace/first-work/first-response milestones,
+coarse waits, request-source reconciliation, explicit composer-work D1/D7/D28 cohorts, weekly work-day
+bins, process health, and collector loss/rejection/late-report signals. Milestones describe local
+app episodes, can cross UTC days, and do not establish a joined signup conversion rate. First-work
+cohorts use explicit composer messages; terminal keystrokes and automatic work remain unclassified.
+Weekly bins cover completed weeks from installations that report again, so non-returners can be missing.
+
+Native Desktop observes main-frame/first-frame viewer loading, updater apply acknowledgements and
+the next observed version, explicit versus automatic connections, and resume-to-observed-work.
+The startup bucket measures launch to the first consented observation of a connected workspace,
+including preference/sign-in delay. One in 60 rendered frames supplies a coarse duration bucket;
+it cannot reliably detect an idle freeze. Error hooks pass only framework/async categories.
+Desktop RSS and gateway RSS/CPU sample once per minute; they describe those processes, not the
+whole machine or agents. Sampling adds no core timer, process enumeration, or subprocess.
+
+Desktop's only new disk state is the last consented run's version, clean-exit/update flags, choice
+revision and a local-only account-scope hash. One serialized asynchronous write plus one latest
+pending value bounds disk work. It is cleared on sign-out/off and never enters a report. An unclean
+run can mean a force quit or power loss, and only becomes observable if the app returns. Update
+flags are best effort; analytics never delays exit. Gateway work-day flags expire after 35 days;
+a local yes/no marker prevents an old installation from being counted as newly activated again.
+All new fields are allowlisted; no URLs, raw error strings, stack traces, device specifications,
+task/session IDs or content are accepted. Feedback is voluntary and shown/answered/dismissed
+counts are unlinked to the task and to the separate fixed-choice answer totals.
+
The daemon collector belongs to the gateway service, ordinarily a separate process. The core
forwards fixed counters with a 64 KiB optional-traffic backpressure limit, never waits for reporting,
and never wakes a service just to send measurement. Existing lifecycle broadcasts supply scalar