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.

Fix Desktop measurement forwarding and classify report delivery failures (#1330)

Deecf7a6b4b9ae5
diff --git a/backend/src/routes/productUsage.test.ts b/backend/src/routes/productUsage.test.ts
index 4c7cc88bf..d11cbff02 100644
--- a/backend/src/routes/productUsage.test.ts
+++ b/backend/src/routes/productUsage.test.ts
@@ -1,4 +1,5 @@
import Fastify, { type FastifyRequest } from 'fastify'
+import { readFileSync } from 'node:fs'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
const methods = vi.hoisted(() => ({ ingestProductUsage: vi.fn(), ingestSetupUsage: vi.fn(), productUsageChoice: vi.fn(), setProductUsageChoice: vi.fn() }))
vi.mock('../lib/productUsage.js', () => methods)
@@ -39,6 +40,21 @@ it('does not reflect a database error or report contents', async () => {
expect(response.statusCode).toBe(503)
expect(response.body).not.toContain('PRIVATE_CANARY')
})
+it.each([['P2034', 'USAGE_WRITE_CONFLICT'], ['P2002', 'USAGE_WRITE_CONFLICT'],
+ ['P2028', 'USAGE_TRANSACTION_FAILED'], ['PRIVATE_CANARY', 'USAGE_UNAVAILABLE']])(
+ 'returns only the fixed delivery category for storage error %s', async (code, expected) => {
+ methods.ingestProductUsage.mockRejectedValue(Object.assign(new Error('PRIVATE_CANARY'), { code, meta: 'PRIVATE_CANARY' }))
+ const response = await submit(good)
+ expect(response.statusCode).toBe(503)
+ expect(response.json().error.code).toBe(expected)
+ expect(response.body).not.toContain('PRIVATE_CANARY')
+ },
+)
+it('accepts the same native Desktop report exercised through the real daemon proxy', async () => {
+ const report = JSON.parse(readFileSync(new URL('../../../tests/fixtures/desktop-product-usage-report.json', import.meta.url), 'utf8'))
+ expect((await submit(report)).statusCode).toBe(200)
+ expect(methods.ingestProductUsage).toHaveBeenCalledExactlyOnceWith('account', report)
+})
it('also sanitizes malformed JSON and oversized bodies before schema validation', async () => {
for (const payload of ['{"prompt":"PRIVATE_CANARY', JSON.stringify({ prompt: 'PRIVATE_CANARY'.repeat(1000) })]) {
const response = await app.inject({ method: 'POST', url: '/api/product-usage/report', headers: {
diff --git a/backend/src/routes/productUsage.ts b/backend/src/routes/productUsage.ts
index ff08cd116..f996b8f56 100644
--- a/backend/src/routes/productUsage.ts
+++ b/backend/src/routes/productUsage.ts
@@ -76,6 +76,12 @@ export async function productUsageRoutes(app: FastifyInstance): Promise<void> {
// Never reflect rejected fields, values or raw validation errors into logs or responses.
if (!parsed.success) return sendError(reply, 'Invalid usage report', 'INVALID_USAGE_REPORT', 400)
try { return sendSuccess(reply, await ingestProductUsage(req.user.sub, parsed.data)) }
- catch { return sendError(reply, 'Usage report unavailable', 'USAGE_UNAVAILABLE', 503) }
+ catch (error) {
+ // A fixed category can diagnose delivery without exposing database errors or report contents.
+ const storageCode = (error as { code?: unknown } | null)?.code
+ const code = storageCode === 'P2034' || storageCode === 'P2002' ? 'USAGE_WRITE_CONFLICT'
+ : storageCode === 'P2028' ? 'USAGE_TRANSACTION_FAILED' : 'USAGE_UNAVAILABLE'
+ return sendError(reply, 'Usage report unavailable', code, 503)
+ }
})
}
diff --git a/backend/src/types/productHealthContract.ts b/backend/src/types/productHealthContract.ts
index d973261ed..6317d2431 100644
--- a/backend/src/types/productHealthContract.ts
+++ b/backend/src/types/productHealthContract.ts
@@ -24,7 +24,12 @@ export const HEALTH_MEASURES = [
'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
+// Delivery attempts, including retries; separate from the cross-surface app measures.
+export const CLI_REPORT_FAILURES = ['invalid', 'too_large', 'auth', 'rate_limited', 'timeout', 'unreachable',
+ 'write_conflict', 'transaction', 'server', 'other'] as const
+export type CliReportFailure = typeof CLI_REPORT_FAILURES[number]
export const PRODUCT_HEALTH_METRICS = [
+ ...CLI_REPORT_FAILURES.map(reason => `health_cli_report_failure_${reason}` as const),
...(['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),
diff --git a/cli/e2e/productUsage.e2e.ts b/cli/e2e/productUsage.e2e.ts
index 0439fb904..7ca9bbb22 100644
--- a/cli/e2e/productUsage.e2e.ts
+++ b/cli/e2e/productUsage.e2e.ts
@@ -1,4 +1,4 @@
-import { mkdirSync, writeFileSync } from 'node:fs'
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, expect, it, onTestFailed } from 'vitest'
import { LocalClient } from './harness/client.js'
@@ -47,7 +47,8 @@ it('reports only local counters from a real turn, and the account switch stops t
return rows.agents.some((a: Record<string, unknown>) => a.id === agentId && a.sessionId) || null
}, 45000)
await client.request('session_search', { query: 'PRIVATE_SEARCH_CANARY' })
- const appReport = { schemaVersion: 1, revision: 0, id: '27b07da5-033b-412e-b91f-7316b254f991', day: new Date().toISOString().slice(0, 10), counters: { ui_desktop_computer_link_failed: 1 } }
+ // The same Desktop-format fixture must pass both the local proxy and the backend route tests.
+ const appReport = { ...JSON.parse(readFileSync(new URL('../../tests/fixtures/desktop-product-usage-report.json', import.meta.url), 'utf8')), day: new Date().toISOString().slice(0, 10) }
const forwarded = await fetch(`http://127.0.0.1:${d.port}/api/product-usage/report`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: JSON.stringify(appReport) })
expect(forwarded.status).toBe(200)
expect(backend.productUsage.reports).toContainEqual(appReport)
diff --git a/cli/src/gateway/productUsage.spec.ts b/cli/src/gateway/productUsage.spec.ts
index 0dbe5c288..bf8b4ae8e 100644
--- a/cli/src/gateway/productUsage.spec.ts
+++ b/cli/src/gateway/productUsage.spec.ts
@@ -94,6 +94,26 @@ it('discards a permanently invalid packet so later reports and loss counts can r
expect(JSON.parse(readFileSync(file, 'utf8')).pending).toBeNull()
await usage.sync()
expect(totals().health_cli_report_rejected).toBe(1)
+ expect(totals().health_cli_report_failure_invalid).toBe(1)
+})
+
+it.each([
+ [503, 'USAGE_WRITE_CONFLICT', 'write_conflict'], [503, 'USAGE_TRANSACTION_FAILED', 'transaction'],
+ [504, 'BACKEND_TIMEOUT', 'timeout'], [502, 'BACKEND_UNREACHABLE', 'unreachable'],
+ [429, 'PRIVATE_CANARY', 'rate_limited'], [502, 'AUTH_UNAVAILABLE', 'auth'],
+])('retains an immutable report on %i and queues only its fixed %s category', async (status, code, category) => {
+ await usage.sync(); usage.counter('search_requests')
+ request.mockResolvedValueOnce({ status: 200, body: { data: { enabled: true, revision: 0 } } })
+ .mockResolvedValueOnce({ status: status as number, body: { error: { code, message: 'PRIVATE_CANARY' } } })
+ await usage.sync()
+ const pending = JSON.parse(readFileSync(file, 'utf8')).pending
+ expect(pending.counters.search_requests).toBe(1)
+ await usage.sync(); await usage.sync()
+ expect(sent[0]).toEqual(pending)
+ expect(totals()[`health_cli_report_failure_${category}`]).toBe(1)
+ expect(totals().health_cli_report_rejected).toBe(1)
+ expect(JSON.stringify(sent)).not.toContain('PRIVATE_CANARY')
+ expect(readFileSync(file, 'utf8')).not.toContain('PRIVATE_CANARY')
})
it('reduces turns locally, excludes replay, and never persists or uploads agent identity', async () => {
diff --git a/cli/src/gateway/productUsage.ts b/cli/src/gateway/productUsage.ts
index 2ae0df635..afe354e99 100644
--- a/cli/src/gateway/productUsage.ts
+++ b/cli/src/gateway/productUsage.ts
@@ -1,5 +1,6 @@
import { cleanUsageContext, type ProductUsageContext } from '../lib/productHealthContract.js'
import { cleanHealthState, createProductHealth, type HealthState } from './productHealth.js'
+import { reportFailure } from './reportFailure.js'
import { readFileSync, statSync } from 'node:fs'
import { mkdir, rename, writeFile } from 'node:fs/promises'
import { dirname } from 'node:path'
@@ -254,6 +255,7 @@ export function createProductUsage(deps: ProductUsageDeps) {
else if (result?.reason === 'EXPIRED') { state.pending = null; add('health_cli_report_expired'); await persist() }
else {
add('health_cli_report_rejected')
+ add(`health_cli_report_failure_${reportFailure(answer)}`)
// A permanently invalid packet must not block every future report behind it.
if (answer.status === 400 || answer.status === 413) { state.pending = null; await persist() }
}
diff --git a/cli/src/gateway/reportFailure.spec.ts b/cli/src/gateway/reportFailure.spec.ts
new file mode 100644
index 000000000..951840099
--- /dev/null
+++ b/cli/src/gateway/reportFailure.spec.ts
@@ -0,0 +1,23 @@
+import { expect, it } from 'vitest'
+import { CLI_REPORT_FAILURES } from '../lib/productHealthContract.js'
+import { reportFailure } from './reportFailure.js'
+
+it.each([
+ [400, 'INVALID_USAGE_REPORT', 'invalid'], [413, 'USAGE_UNAVAILABLE', 'too_large'],
+ [401, 'UNAUTHORIZED', 'auth'], [403, 'PRIVATE_CANARY', 'auth'], [502, 'AUTH_UNAVAILABLE', 'auth'],
+ [409, 'ACCOUNT_CHANGED', 'auth'], [429, 'PRIVATE_CANARY', 'rate_limited'],
+ [504, 'BACKEND_TIMEOUT', 'timeout'], [502, 'BACKEND_UNREACHABLE', 'unreachable'],
+ [503, 'USAGE_WRITE_CONFLICT', 'write_conflict'], [503, 'USAGE_TRANSACTION_FAILED', 'transaction'],
+ [503, 'USAGE_UNAVAILABLE', 'server'], [504, 'PRIVATE_CANARY', 'server'],
+ [200, 'PRIVATE_CANARY', 'other'], [409, 'PRIVATE_CANARY', 'other'], [404, 'PRIVATE_CANARY', 'other'],
+])('reduces status %i and known code %s to %s', (status, code, expected) => {
+ const result = reportFailure({ status: status as number, body: { error: { code, message: 'PRIVATE_CANARY', stack: 'PRIVATE_CANARY' } } })
+ expect(result).toBe(expected)
+ expect(CLI_REPORT_FAILURES).toContain(result)
+})
+
+it('tolerates missing or malformed error bodies without exporting them', () => {
+ for (const body of [{}, { error: null }, { error: 'PRIVATE_CANARY' }, { error: ['PRIVATE_CANARY'] }]) {
+ expect(reportFailure({ status: 502, body })).toBe('server')
+ }
+})
diff --git a/cli/src/gateway/reportFailure.ts b/cli/src/gateway/reportFailure.ts
new file mode 100644
index 000000000..298a57e53
--- /dev/null
+++ b/cli/src/gateway/reportFailure.ts
@@ -0,0 +1,16 @@
+import type { CliReportFailure } from '../lib/productHealthContract.js'
+
+/** Fixed delivery categories only: neither error messages nor unknown codes become telemetry. */
+export function reportFailure(answer: { status: number; body: Record<string, unknown> }): CliReportFailure {
+ const code = (answer.body?.error as { code?: unknown } | null)?.code
+ if (answer.status === 504 && code === 'BACKEND_TIMEOUT') return 'timeout'
+ if (answer.status === 502 && code === 'BACKEND_UNREACHABLE') return 'unreachable'
+ if (answer.status === 401 || answer.status === 403 || code === 'AUTH_UNAVAILABLE' || code === 'ACCOUNT_CHANGED') return 'auth'
+ if (answer.status === 400) return 'invalid'
+ if (answer.status === 413) return 'too_large'
+ if (answer.status === 429) return 'rate_limited'
+ if (answer.status === 503 && code === 'USAGE_WRITE_CONFLICT') return 'write_conflict'
+ if (answer.status === 503 && code === 'USAGE_TRANSACTION_FAILED') return 'transaction'
+ if (answer.status >= 500 && answer.status < 600) return 'server'
+ return 'other'
+}
diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.ts
index 5e9066ac5..63215aeac 100644
--- a/cli/src/hookServer.spec.ts
+++ b/cli/src/hookServer.spec.ts
@@ -1,6 +1,6 @@
import { request, type Server } from 'node:http'
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest'
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { startHookServer, type HookServerHandlers, chooseHookAgent, hookFiredAt, knownTranscriptFor } from './hookServer.js'
@@ -380,6 +380,23 @@ describe('account Experimental settings proxy', () => {
expect(failed.status).toBe(502)
expect(await failed.text()).not.toContain('PRIVATE_CANARY')
})
+ it('forwards the current Desktop health report intact while rejecting private context', async () => {
+ const body = JSON.parse(readFileSync(new URL('../../tests/fixtures/desktop-product-usage-report.json', import.meta.url), 'utf8'))
+ const send = vi.fn(async () => ({ status: 200, body: { success: true, data: { accepted: true } } }))
+ const { base } = await start({ onProductUsageReport: send })
+ const headers = { 'content-type': 'application/json', 'x-adapter-local': '1' }
+ const post = (value: unknown, h = headers) => fetch(`${base}/api/product-usage/report`, { method: 'POST', headers: h, body: JSON.stringify(value) })
+ expect((await post(body, { ...headers, origin: 'https://untrusted.example' } as typeof headers)).status).toBe(403)
+ for (const bad of [{ ...body, context: { ...body.context, path: 'PRIVATE_CANARY' } },
+ { ...body, context: { ...body.context, release: 'PRIVATE_CANARY' } },
+ { ...body, counters: { health_cli_report_failure_auth: 1 } }]) {
+ const refused = await post(bad)
+ expect(refused.status).toBe(400); expect(await refused.text()).not.toContain('PRIVATE_CANARY')
+ }
+ expect(send).not.toHaveBeenCalled()
+ expect((await post(body)).status).toBe(200)
+ expect(send).toHaveBeenCalledExactlyOnceWith(body)
+ })
it('serves the Privacy switch and rejects cross-origin, extra-field and malformed writes', async () => {
const write = vi.fn(async () => ({ status: 200, body: { success: true, data: { enabled: false, revision: 1 } } }))
const { base } = await start({ onProductUsageRead: async () => ({ status: 200, body: { success: true, data: { enabled: true, revision: 0 } } }), onProductUsageWrite: write })
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index 8f2879bc6..af6176e33 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -1,4 +1,5 @@
-import { PRODUCT_FEEDBACK, PRODUCT_USAGE_UI_METRICS } from './lib/productUsageContract.js'
+import { PRODUCT_FEEDBACK } from './lib/productUsageContract.js'
+import { isAppProductUsageReport } from './lib/appProductUsageReport.js'
/**
* Tiny localhost HTTP server for the Claude Code hook callbacks. `hook/notify.mjs` POSTs here on
* SessionStart/SessionEnd (127.0.0.1:<PORT>). This replaces the old Fastify routes — the browser
@@ -1037,18 +1038,11 @@ export function startHookServer(
const raw = await readBody(req, 8192)
body = JSON.parse(raw)
} catch { json(400, { error: 'BAD_REQUEST' }); return }
- const report = body as { schemaVersion?: unknown; revision?: unknown; id?: unknown; day?: unknown; counters?: unknown } | null
- if (!report || typeof report !== 'object' || Object.keys(report).length !== 5 || report.schemaVersion !== 1
- || typeof report.revision !== 'number' || !Number.isSafeInteger(report.revision) || report.revision < 0
- || typeof report.id !== 'string' || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(report.id)
- || typeof report.day !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(report.day)
- || !report.counters || typeof report.counters !== 'object' || Array.isArray(report.counters)
- || Object.entries(report.counters).some(([key, value]) => !PRODUCT_USAGE_UI_METRICS.includes(key as never)
- || !Number.isSafeInteger(value) || value < 1 || value > 1000)) {
+ if (!isAppProductUsageReport(body)) {
json(400, { error: 'BAD_REQUEST' }); return
}
try {
- const result = await handlers.onProductUsageReport(report)
+ const result = await handlers.onProductUsageReport(body)
json(result.status, result.body)
} catch { json(502, { success: false, error: { code: 'USAGE_UNAVAILABLE', message: 'Product usage unavailable' } }) }
return
diff --git a/cli/src/lib/appProductUsageReport.spec.ts b/cli/src/lib/appProductUsageReport.spec.ts
new file mode 100644
index 000000000..893154a22
--- /dev/null
+++ b/cli/src/lib/appProductUsageReport.spec.ts
@@ -0,0 +1,54 @@
+import { readFileSync } from 'node:fs'
+import { expect, it } from 'vitest'
+import { isAppProductUsageReport } from './appProductUsageReport.js'
+import { HEALTH_MEASURES } from './productHealthContract.js'
+import { PRODUCT_USAGE_UI_METRICS } from './productUsageContract.js'
+
+const native = JSON.parse(readFileSync(new URL('../../../tests/fixtures/desktop-product-usage-report.json', import.meta.url), 'utf8'))
+const { context: _context, ...legacy } = native
+const old = { ...legacy, counters: { ui_desktop_sign_in_ok: 1 } }
+
+it('admits the current native report and every fixed Desktop health measure', () => {
+ expect(isAppProductUsageReport(native)).toBe(true)
+ const dart = readFileSync(new URL('../../../desktop/lib/measurement/product_health_contract.dart', import.meta.url), 'utf8')
+ const wires = [...dart.split('class ProductUsageContext')[0].matchAll(/\('([^']+)'\)/g)].map(match => match[1])
+ expect(wires).toEqual([...HEALTH_MEASURES])
+ for (const wire of wires) expect(isAppProductUsageReport({ ...native, counters: { [`health_desktop_${wire}`]: 1000 } })).toBe(true)
+ for (const platform of ['macos', 'windows', 'linux', 'other']) for (const channel of ['production', 'development']) {
+ expect(isAppProductUsageReport({ ...native, context: { ...native.context, platform, channel, release: 'unknown' } })).toBe(true)
+ }
+})
+
+it('keeps all legacy app UI counters compatible, in bounded batches', () => {
+ for (let i = 0; i < PRODUCT_USAGE_UI_METRICS.length; i += 32) {
+ const counters = Object.fromEntries(PRODUCT_USAGE_UI_METRICS.slice(i, i + 32).map(key => [key, 1000]))
+ expect(isAppProductUsageReport({ ...old, counters })).toBe(true)
+ }
+ expect(isAppProductUsageReport({ ...native, counters: old.counters })).toBe(true)
+ expect(isAppProductUsageReport({ ...old, counters: {} })).toBe(true)
+})
+
+it('refuses arbitrary context, non-Desktop attribution, daemon counts and malformed values', () => {
+ const counters = (key: string, count: unknown = 1) => ({ ...native, counters: { [key]: count } })
+ const context = (change: object) => ({ ...native, context: { ...native.context, ...change } })
+ const invalid = [null, [], {}, { ...native, prompt: 'PRIVATE_CANARY' }, { ...native, revision: -1 },
+ { ...native, revision: Number.MAX_SAFE_INTEGER + 1 }, { ...native, schemaVersion: 2 },
+ { ...native, id: 'PRIVATE_CANARY' }, { ...native, day: 'PRIVATE_CANARY' },
+ { ...native, context: null }, { ...native, context: [] }, { ...native, context: {} },
+ context({ userId: 'PRIVATE_CANARY' }), context({ release: '1.2.75-PRIVATE_CANARY' }), context({ release: '1000.1.1' }),
+ context({ release: '01.2.75' }), context({ surface: 'cli' }), context({ platform: 'PRIVATE_CANARY' }),
+ context({ channel: 'PRIVATE_CANARY' }), context({ release: undefined }),
+ counters('turns_started'), counters('request_app_create_started'), counters('health_cli_collector_days'),
+ counters('setup_desktop_sign_in_ok'), counters('ui_phone_sign_in_ok'), counters('ui_web_sign_in_ok'),
+ counters('PRIVATE_CANARY'), counters('health_desktop_collector_days', 'PRIVATE_CANARY'),
+ ...[0, -1, 1001, 1.5, NaN, Infinity].map(value => counters('health_desktop_collector_days', value)),
+ { ...old, counters: { health_desktop_collector_days: 1 } },
+ { ...native, counters: [] }, { ...native, counters: null },
+ { ...old, counters: Object.fromEntries(PRODUCT_USAGE_UI_METRICS.slice(0, 33).map(key => [key, 1])) },
+ ]
+ for (const value of invalid) expect(isAppProductUsageReport(value), JSON.stringify(value)).toBe(false)
+ for (const key of ['id', 'revision', 'schemaVersion', 'day', 'counters']) {
+ const missing = { ...native }; delete missing[key]
+ expect(isAppProductUsageReport(missing)).toBe(false)
+ }
+})
diff --git a/cli/src/lib/appProductUsageReport.ts b/cli/src/lib/appProductUsageReport.ts
new file mode 100644
index 000000000..753e21286
--- /dev/null
+++ b/cli/src/lib/appProductUsageReport.ts
@@ -0,0 +1,35 @@
+import { cleanUsageContext, HEALTH_MEASURES } from './productHealthContract.js'
+import { PRODUCT_USAGE_UI_METRICS, type ProductUsageReport } from './productUsageContract.js'
+
+const uiMetrics = new Set<string>(PRODUCT_USAGE_UI_METRICS)
+const desktopMetrics = new Set<string>([
+ ...PRODUCT_USAGE_UI_METRICS.filter(metric => metric.startsWith('ui_desktop_')),
+ ...HEALTH_MEASURES.map(measure => `health_desktop_${measure}`),
+])
+const fields = new Set(['schemaVersion', 'revision', 'id', 'day', 'counters', 'context'])
+const contextFields = new Set(['surface', 'release', 'platform', 'channel'])
+const object = (value: unknown): value is Record<string, unknown> =>
+ value !== null && typeof value === 'object' && !Array.isArray(value)
+
+/** The local proxy must admit the native Desktop format as well as older UI-only reports.
+ * Keep this narrower than the backend contract: an app cannot submit daemon counters or labels.
+ * The caller also bounds the complete JSON body to 8 KiB before parsing it.
+ */
+export function isAppProductUsageReport(value: unknown): value is ProductUsageReport {
+ if (!object(value) || Object.keys(value).some(key => !fields.has(key)) || value.schemaVersion !== 1
+ || typeof value.revision !== 'number' || !Number.isSafeInteger(value.revision) || value.revision < 0
+ || typeof value.id !== 'string' || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value.id)
+ || typeof value.day !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value.day)
+ || !object(value.counters) || Object.keys(value.counters).length > 32) return false
+ let allowed = uiMetrics
+ if ('context' in value) {
+ const context = value.context
+ if (!object(context) || Object.keys(context).length !== 4
+ || Object.keys(context).some(key => !contextFields.has(key)) || context.surface !== 'desktop') return false
+ const clean = cleanUsageContext(context)
+ if (!clean || clean.release !== context.release) return false
+ allowed = desktopMetrics
+ }
+ return Object.entries(value.counters).every(([key, count]) => allowed.has(key)
+ && typeof count === 'number' && Number.isSafeInteger(count) && count >= 1 && count <= 1000)
+}
diff --git a/cli/src/lib/productHealthContract.ts b/cli/src/lib/productHealthContract.ts
index d973261ed..6317d2431 100644
--- a/cli/src/lib/productHealthContract.ts
+++ b/cli/src/lib/productHealthContract.ts
@@ -24,7 +24,12 @@ export const HEALTH_MEASURES = [
'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
+// Delivery attempts, including retries; separate from the cross-surface app measures.
+export const CLI_REPORT_FAILURES = ['invalid', 'too_large', 'auth', 'rate_limited', 'timeout', 'unreachable',
+ 'write_conflict', 'transaction', 'server', 'other'] as const
+export type CliReportFailure = typeof CLI_REPORT_FAILURES[number]
export const PRODUCT_HEALTH_METRICS = [
+ ...CLI_REPORT_FAILURES.map(reason => `health_cli_report_failure_${reason}` as const),
...(['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),
diff --git a/docs/product-measurement.md b/docs/product-measurement.md
index 456f5f4eb..7f4733a02 100644
--- a/docs/product-measurement.md
+++ b/docs/product-measurement.md
@@ -90,6 +90,15 @@ and stay below 8 KiB. One sync runs at a time, with five-second network deadline
report interval. Unknown or failed preference checks stop collection. Slow or failed reporting can
lose counts and cannot become a product dependency. A failed disk write also disables collection.
+`health_cli_report_rejected` counts unsuccessful delivery attempts, including retries; it is not
+a count of lost reports. New `health_cli_report_failure_*` counters split those attempts into fixed
+invalid, too-large, authentication, rate-limit, timeout, unreachable, write-conflict, transaction,
+server and other categories. A transaction failure does not by itself prove a timeout. No raw error
+message, database detail, URL or unknown error code is collected. These diagnostics share the same
+privacy choice and bounded queue, so a delivery outage can delay its own diagnostic counters.
+The local app proxy accepts only bounded UI counts, or Desktop health/UI counts with the exact
+public release, OS and channel context. It does not accept daemon counters or arbitrary context.
+
Desktop and phone collectors keep only fixed counters in RAM, at most 64 in-flight observations,
with at most 32 counters per report, one pending report per channel and one flush at a time.
Callbacks from product actions never await measurement I/O. Reports retry no faster than once per
diff --git a/tests/fixtures/desktop-product-usage-report.json b/tests/fixtures/desktop-product-usage-report.json
new file mode 100644
index 000000000..81e51df32
--- /dev/null
+++ b/tests/fixtures/desktop-product-usage-report.json
@@ -0,0 +1,22 @@
+{
+ "schemaVersion": 1,
+ "revision": 0,
+ "id": "27b07da5-033b-412e-b91f-7316b254f991",
+ "day": "2026-10-14",
+ "context": {
+ "surface": "desktop",
+ "release": "1.2.75",
+ "platform": "macos",
+ "channel": "production"
+ },
+ "counters": {
+ "ui_desktop_computer_link_failed": 1,
+ "ui_desktop_app_start_under_1s": 1,
+ "health_desktop_collector_days": 1,
+ "health_desktop_funnel_workspace_ready": 1,
+ "health_desktop_first_response_under_1m": 1,
+ "health_desktop_frame_under_16ms": 1000,
+ "health_desktop_feedback_outcome_shown": 1,
+ "health_desktop_report_failed": 1
+ }
+}