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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(usage): code delete/restart refusals, measure message outcomes
tony37282223214f
diff --git a/backend/src/routes/productUsage.test.ts b/backend/src/routes/productUsage.test.tsindex a626710db..844dd4c83 100644--- a/backend/src/routes/productUsage.test.ts+++ b/backend/src/routes/productUsage.test.ts@@ -115,13 +115,17 @@ it('takes the CLI\'s launch codes, late launch failures and first launches by enconst counters = { launch_failed_other: 2, launch_failed_code_invalid_prompt: 1, launch_failed_code_unlisted: 1,launch_late_failed: 1, launch_late_failed_code_engine_did_not_start: 1, create_error_code_none: 1,resume_error_code_session_not_found: 1, first_launch_engine_claude: 1, first_launch_claude_signed_in: 1,- first_launch_engine_other: 1, first_launch_codex_unknown: 1 }+ first_launch_engine_other: 1, first_launch_codex_unknown: 1,+ // Every delete and restart refusal by its code, the `setup` kind's own included.+ delete_error_code_delete_failed: 1, restart_error_code_spawn_failed: 1, restart_error_code_internal: 1,+ // The phone's again, apart.+ phone_delete_error_code_delete_failed: 1, phone_restart_error_code_spawn_failed: 1 }expect((await submit({ ...good, context, counters })).statusCode).toBe(200)expect(methods.ingestProductUsage).toHaveBeenCalledWith('account', expect.objectContaining({ counters }))methods.ingestProductUsage.mockClear()// A name outside the list is never stored: the report keeps its known counters without it (an unknown// name no longer refuses the whole report), and alone it is still refused.- for (const name of ['launch_failed_code_PRIVATE_CANARY', 'launch_failed_code_ENGINE_DID_NOT_START', 'restart_error_code_internal',+ for (const name of ['launch_failed_code_PRIVATE_CANARY', 'launch_failed_code_ENGINE_DID_NOT_START', 'fork_error_code_internal','first_launch_engine_cursor', 'first_launch_opencode_signed_in', 'launch_late_failed_other']) {const response = await submit({ ...good, context, counters: { launch_late_failed: 1, [name]: 1 } })expect(response.statusCode, name).toBe(200)diff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.tsindex a84601d60..d27d5ad02 100644--- a/backend/src/types/productUsage.ts+++ b/backend/src/types/productUsage.ts@@ -50,6 +50,14 @@ export const PRODUCT_USAGE_ONBOARDING_MARKS = ['ui_phone_sign_in_retried', 'ui_pexport const PRODUCT_USAGE_ONBOARDING_METRICS = [...PRODUCT_USAGE_ONBOARDING_MARKS,...PRODUCT_USAGE_LONG_FLOWS.flatMap(flow => PRODUCT_USAGE_LONG_MEASURES.map(measure => `ui_phone_${flow}_${measure}` as const)),] as const+/** Why a phone launch's computers had not answered yet (mobile/lib/measurement/launch_measurement.dart,+ * `LaunchWait`), each at most once per launch beside its `app_start`: the account's list had no computer,+ * could not be read, or said every one was offline; a computer wanted this phone's password; a dial to a+ * computer said to be online failed; or a minute passed on screen with none answering. On 2026-10-19 21 of+ * 44 launches ended in no outcome at all, which said none of this. */+export const PRODUCT_USAGE_PHONE_LAUNCH_MARKS = ['ui_phone_app_start_no_computer', 'ui_phone_app_start_list_failed',+ 'ui_phone_app_start_offline', 'ui_phone_app_start_locked', 'ui_phone_app_start_connect_failed',+ 'ui_phone_app_start_waited_1m'] as const/** The phone's two side pages, counted each time one opens and by how: a sideways swipe on the* terminal (Find from the left, Computers from the right), or a button (Computers' row in Settings,* its link on a long wait at home). Find's key and screen-reader actions are not counted. Which page@@ -99,7 +107,10 @@ export const PRODUCT_USAGE_SETUP_METRICS = [...PRODUCT_USAGE_SURFACES.flatMap(su* invalid), by its code: the daemon's own fixed error names, lower-cased. On 2026-10-16 production counted* 23 of 25 launch failures, 22 create refusals and 9 resume refusals as `other`, with nothing to say* which. `unlisted` is a code not named here, `none` a refusal that named no code; each family adds up to- * its `_other` total, and the late failures to `launch_late_failed`. Codes only, never a message. */+ * its `_other` total, and the late failures to `launch_late_failed`. A delete or restart refusal is counted+ * by its code whatever its kind, so those two families add up to `delete_failed` and `restart_failed`: on+ * 2026-10-19 the phone's 3 delete refusals were `other` and its 2 restart refusals `setup`, a kind of nine+ * codes (listed below). Codes only, never a message. */export const LAUNCH_ERROR_CODES = [// What a new harness asked for, refused before anything starts (core/agents/launches.ts, lib/engineLaunch.ts).'invalid_codex_home', 'invalid_prompt', 'prompt_too_long', 'prompt_unsupported', 'invalid_agent', 'invalid_session',@@ -127,12 +138,18 @@ export const LAUNCH_ERROR_CODES = ['guest_not_allowed', 'guest_unsupported', 'guest_harness', 'guest_unavailable', 'guest_helper_required','guest_engine_unsupported', 'guest_relay_failed', 'guest_folder_unavailable', 'guest_invalid', 'guest_helper_missing','guest_helper_not_authorized', 'guest_helper_failed',+ // The `setup` kind's own codes, named for a delete or restart refusal (cli/src/lib/productUsageSignals.ts).+ 'tmux_unavailable', 'tmux_too_old_for_dsh', 'tmux_too_old_for_grid', 'engine_unavailable', 'native_launch_held',+ 'dsh_materialize_failed', 'spawn_failed', 'registration_failed', 'grid_config_failed','unlisted', 'none',] as constexport type LaunchErrorCode = typeof LAUNCH_ERROR_CODES[number]-/** The families counted by code: a launch's failure, its start failing after it was created, and the create- * and resume requests' refusals. */-export const LAUNCH_ERROR_FAMILIES = ['launch_failed_code', 'launch_late_failed_code', 'create_error_code', 'resume_error_code'] as const+/** The families counted by code: a launch's failure, its start failing after it was created, the create+ * and resume requests' `other` refusals, and every delete and restart refusal — from any client, and again,+ * apart, those the phone asked for (`phone_`), which a daemon's report otherwise carries mixed with the+ * Desktop's, the TUI's and tools'. */+export const LAUNCH_ERROR_FAMILIES = ['launch_failed_code', 'launch_late_failed_code', 'create_error_code', 'resume_error_code',+ 'delete_error_code', 'restart_error_code', 'phone_delete_error_code', 'phone_restart_error_code'] as const/** The engine an installation's first launch asked for; any other engine is `other`. */export const PRODUCT_USAGE_LAUNCH_ENGINES = ['opencode', 'claude', 'codex', 'other'] as constexport type ProductUsageLaunchEngine = typeof PRODUCT_USAGE_LAUNCH_ENGINES[number]@@ -173,6 +190,7 @@ export const PRODUCT_USAGE_METRICS = [.map(measure => `${action}_user_${measure}` as const)),...PRODUCT_USAGE_UI_METRICS,...PRODUCT_USAGE_ONBOARDING_METRICS,+ ...PRODUCT_USAGE_PHONE_LAUNCH_MARKS,...PRODUCT_USAGE_PHONE_SCREEN_METRICS,...PRODUCT_USAGE_ADD_PHONE_METRICS,'ui_phone_first_open',diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 451a87b3d..4cd91a154 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -3844,6 +3844,32 @@ describe('request sources', () => {expect(phone).not.toContain('request_app_search_started')expect(await startedFor({})).toContain('request_app_search_started')})++ it('counts what became of a phone\'s message, which nothing answers, under the phone', async () => {+ const socket = relaySocket('token')+ socket.connect()+ const ws = wsMock.instances.at(-1)!+ ws.open()+ const counted: string[] = []+ vi.spyOn(gatewayOf(socket), 'usageCounter').mockImplementation((metric) => { counted.push(metric) })+ const message = { type: 'message', payload: { agentId: 'a1', content: 'PRIVATE_TEXT', usageSurface: 'phone' } }+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue(message)+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')+ const handed: Array<[Record<string, unknown>, ((outcome: 'started' | 'held') => void) | undefined]> = []+ socket.messageProvider = (payload, receipt) => { handed.push([payload, receipt]) }+ for (const n of [1, 2]) {+ ws.message({ t: 'down', connId: 'conn-1', frame: { type: 'message', payload: { __e2e: { v: 1, k: 's', n, ct: 'ciphertext' } } } })+ }+ await vi.waitFor(() => expect(handed).toHaveLength(2))+ expect(counted).toEqual(['request_phone_message_started', 'request_phone_message_started'])+ handed[0]![1]!('started')+ handed[1]![1]!('held')+ expect(counted.slice(2)).toEqual(['request_phone_message_ok', 'request_phone_message_failed', 'request_phone_message_error_conflict'])+ expect(JSON.stringify(counted)).not.toContain('PRIVATE')+ await socket.stop()+ vi.restoreAllMocks()+ })})describe('machines_changed relay', () => {@@ -4173,9 +4199,10 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()bindMessageRequest(socket, onMessage)socket.registerLocalClient('local:app', { sendFrame: () => true, sendBinary: () => true })await dispatch({ type: 'message', payload: { content: 'hi', agentId: 'a1' } }, 'local:app', 'local')- expect(onMessage).toHaveBeenCalledWith('a1', 'hi')+ // With what became of it, for its measurement.+ expect(onMessage).toHaveBeenCalledWith('a1', 'hi', undefined, expect.any(Function))await dispatch({ type: 'message', payload: { content: 'task in A', agentId: 'a1', tabId: 'swarm-a' } }, 'local:app', 'local')- expect(onMessage).toHaveBeenLastCalledWith('a1', 'task in A')+ expect(onMessage).toHaveBeenLastCalledWith('a1', 'task in A', undefined, expect.any(Function))})})diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 8f0494b44..4ef61245a 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -1,4 +1,5 @@-import { productObservation, productUsageIntent, productUsageLaunch, productUsageRequest, productUsageSource } from './lib/productUsageSignals.js'+import { messageReceipt, productObservation, productUsageIntent, productUsageLaunch, productUsageRequest, productUsageSource } from './lib/productUsageSignals.js'+import type { MessageReceipt } from './lib/sessionInput.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, type TabFrame } from './core/api.js'@@ -240,8 +241,9 @@ export class BackendSocket {/** Called when the web/device sends chat input to an agent terminal. */onMessage: ((sessionId: string, content: string, deliveryId?: string) => void) | null = null/** Takes a `message` frame: text a person typed for an agent, into its pane (cli.ts binds core/input.ts).- * Agent Messages and the orchestrator deliver through `onMessage` above. */- messageProvider: ((payload: Record<string, unknown>) => void) | null = null+ * Agent Messages and the orchestrator deliver through `onMessage` above. [receipt]: what became of it, for+ * its request's measurement (lib/productUsageSignals.ts `messageReceipt`). */+ messageProvider: ((payload: Record<string, unknown>, receipt?: MessageReceipt) => void) | null = null/** Answers `agent_update` through its last argument, before the windows hear of the change: a rename, a* model and effort, or an app opening the agent (cli.ts binds core/agents/update.ts). */agentUpdateProvider: ((payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null@@ -1220,7 +1222,7 @@ export class BackendSocket {// Text typed for an agent, into its pane (core/input.ts, bound by cli.ts).case 'message':- if (this.messageProvider) this.messageProvider(payload)+ if (this.messageProvider) this.messageProvider(payload, messageReceipt(measured))else console.warn('[backend] message handler is not wired; terminal input was not dispatched')returndiff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.tsindex 84f751495..f1ad25ca1 100644--- a/cli/src/core/input.spec.ts+++ b/cli/src/core/input.spec.ts@@ -481,6 +481,25 @@ describe('message', () => {message({ content: 'nobody to type into' })expect(submit.mock.calls).toEqual([['a1', 'hi'], ['s1', 'hi'], ['a1', 'in a tab']])})++ it('hands what became of it to its measurement: a dropped frame is invalid, a kept one carries the receipt down', () => {+ const submit = vi.fn(), receipt = vi.fn()+ const message = createMessageRequest(submit)+ message({ content: '', agentId: 'a1' }, receipt)+ message({ content: 'nobody to type into' }, receipt)+ expect(receipt.mock.calls).toEqual([['invalid'], ['invalid']])+ message({ content: 'hi', agentId: 'a1' }, receipt)+ message({ content: 'scoped', agentId: 'a1', inputContext: 'conversation-input-context' }, receipt)+ expect(submit.mock.calls).toEqual([['a1', 'hi', undefined, receipt], ['a1', 'scoped', 'conversation-input-context', receipt]])+ expect(receipt).toHaveBeenCalledTimes(2)++ const inputs = createInput(deps().deps)+ const into = vi.spyOn(inputs.input, 'submit').mockImplementation(() => {})+ vi.spyOn(console, 'log').mockImplementation(() => {})+ inputs.messageRequest({ content: 'hello', agentId: 's1' }, receipt)+ inputs.messageRequest({ content: 'hello', agentId: 's1', inputContext: 'conversation-input-context' }, receipt)+ expect(into.mock.calls).toEqual([['a1', 'hello', undefined, undefined, receipt], ['a1', 'hello', undefined, 'conversation-input-context', receipt]])+ })})describe('every route a message takes to a pane', () => {diff --git a/cli/src/core/input.ts b/cli/src/core/input.tsindex 35030ac0c..26f958a73 100644--- a/cli/src/core/input.ts+++ b/cli/src/core/input.ts@@ -17,7 +17,7 @@ import { adaptSlashCommand } from '../lib/goalCommand.js'import { sid } from '../lib/log.js'import type { LiveEvent } from '../engines/kit/events.js'import type { RegisteredSession } from '../lib/registry.js'-import { SessionInputController, type SessionInputDelivery, type SessionInputDeps } from '../lib/sessionInput.js'+import { SessionInputController, type MessageReceipt, type SessionInputDelivery, type SessionInputDeps } from '../lib/sessionInput.js'import { passingHold } from '../lib/messageHolds.js'import type { ScreenReader } from '../lib/screenReader.js'import type { SubmissionReader } from '../lib/submissionReader.js'@@ -215,7 +215,7 @@ export function createInput(deps: InputDeps) {releaseInput()}}- const submitAgent = (id: string, content: string, deliveryId?: string, inputContext?: string): void => {+ const submitAgent = (id: string, content: string, deliveryId?: string, inputContext?: string, receipt?: MessageReceipt): void => {const record = resolve(id)const sessionId = record?.sessionId ?? idconst engine = record?.engine ?? 'claude'@@ -229,10 +229,11 @@ export function createInput(deps: InputDeps) {}console.log(`[msg] ${sid(sessionId)} recv · engine=${engine} · bytes=${Buffer.byteLength(adapted, 'utf8')}`)const target = record?.agentId ?? sessionId- if (inputContext) input.submit(target, adapted, deliveryId, inputContext)+ if (receipt) input.submit(target, adapted, deliveryId, inputContext, receipt)+ else if (inputContext) input.submit(target, adapted, deliveryId, inputContext)else input.submit(target, adapted, deliveryId)}- const messageRequest = createMessageRequest((id, content, context) => submitAgent(id, content, undefined, context), deps.typed)+ const messageRequest = createMessageRequest((id, content, context, receipt) => submitAgent(id, content, undefined, context, receipt), deps.typed)return { input, deviceInput, acquireTerminalControl, submitAgent, messageRequest }}@@ -243,18 +244,20 @@ export function createInput(deps: InputDeps) {** Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md).*/-export function createMessageRequest(submit: (id: string, content: string, inputContext?: string) => void, typed?: (id: string) => void) {- return (payload: Record<string, unknown>): void => {+export function createMessageRequest(submit: (id: string, content: string, inputContext?: string, receipt?: MessageReceipt) => void, typed?: (id: string) => void) {+ // [receipt]: what became of it, for the request's measurement (lib/sessionInput.ts `MessageReceipt`).+ return (payload: Record<string, unknown>, receipt?: MessageReceipt): void => {const content = payload.content as string | undefinedconst target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)- if (!content || !target) return+ if (!content || !target) { receipt?.('invalid'); return }// A `message` frame is a person's: the windows' and the phone's composer. Agents and experiments deliver theirs// under a delivery id (`turns.deliver`), which never comes this way.typed?.(target)// From the relay this is only reached sealed: text typed into an agent is never taken from the relay// in the clear.const context = inputContextIn(payload.inputContext)- if (context) submit(target, content, context)+ if (receipt) submit(target, content, context ?? undefined, receipt)+ else if (context) submit(target, content, context)else submit(target, content)}}diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 0e893d082..29c1e6dbd 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -2695,10 +2695,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (!sent) { submitAgent(id, content, deliveryId); return }if (deliveryId) void sent.then((result) => deliveries.settled({ deliveryId, sessionId: id, state: result.ok ? 'delivered' : 'rejected', ...(result.ok ? {} : { reason: result.error }) }))}- backend.messageProvider = (payload) => {+ backend.messageProvider = (payload, receipt) => {const agentId = typeof payload.agentId === 'string' ? payload.agentId : typeof payload.sessionId === 'string' ? payload.sessionId : ''if (cloud.owns(agentId)) { void cloud.deliver(agentId, typeof payload.content === 'string' ? payload.content : ''); return }- inputs.messageRequest(payload)+ inputs.messageRequest(payload, receipt)}backend.onCancelOrchestratorMessage = id => input.cancelDelivery(id)deliveries.ready() // The input is wired: what was delivered meanwhile (Agent Messages' queue resuming) is written now.diff --git a/cli/src/lib/productUsageContract.ts b/cli/src/lib/productUsageContract.tsindex a84601d60..d27d5ad02 100644--- a/cli/src/lib/productUsageContract.ts+++ b/cli/src/lib/productUsageContract.ts@@ -50,6 +50,14 @@ export const PRODUCT_USAGE_ONBOARDING_MARKS = ['ui_phone_sign_in_retried', 'ui_pexport const PRODUCT_USAGE_ONBOARDING_METRICS = [...PRODUCT_USAGE_ONBOARDING_MARKS,...PRODUCT_USAGE_LONG_FLOWS.flatMap(flow => PRODUCT_USAGE_LONG_MEASURES.map(measure => `ui_phone_${flow}_${measure}` as const)),] as const+/** Why a phone launch's computers had not answered yet (mobile/lib/measurement/launch_measurement.dart,+ * `LaunchWait`), each at most once per launch beside its `app_start`: the account's list had no computer,+ * could not be read, or said every one was offline; a computer wanted this phone's password; a dial to a+ * computer said to be online failed; or a minute passed on screen with none answering. On 2026-10-19 21 of+ * 44 launches ended in no outcome at all, which said none of this. */+export const PRODUCT_USAGE_PHONE_LAUNCH_MARKS = ['ui_phone_app_start_no_computer', 'ui_phone_app_start_list_failed',+ 'ui_phone_app_start_offline', 'ui_phone_app_start_locked', 'ui_phone_app_start_connect_failed',+ 'ui_phone_app_start_waited_1m'] as const/** The phone's two side pages, counted each time one opens and by how: a sideways swipe on the* terminal (Find from the left, Computers from the right), or a button (Computers' row in Settings,* its link on a long wait at home). Find's key and screen-reader actions are not counted. Which page@@ -99,7 +107,10 @@ export const PRODUCT_USAGE_SETUP_METRICS = [...PRODUCT_USAGE_SURFACES.flatMap(su* invalid), by its code: the daemon's own fixed error names, lower-cased. On 2026-10-16 production counted* 23 of 25 launch failures, 22 create refusals and 9 resume refusals as `other`, with nothing to say* which. `unlisted` is a code not named here, `none` a refusal that named no code; each family adds up to- * its `_other` total, and the late failures to `launch_late_failed`. Codes only, never a message. */+ * its `_other` total, and the late failures to `launch_late_failed`. A delete or restart refusal is counted+ * by its code whatever its kind, so those two families add up to `delete_failed` and `restart_failed`: on+ * 2026-10-19 the phone's 3 delete refusals were `other` and its 2 restart refusals `setup`, a kind of nine+ * codes (listed below). Codes only, never a message. */export const LAUNCH_ERROR_CODES = [// What a new harness asked for, refused before anything starts (core/agents/launches.ts, lib/engineLaunch.ts).'invalid_codex_home', 'invalid_prompt', 'prompt_too_long', 'prompt_unsupported', 'invalid_agent', 'invalid_session',@@ -127,12 +138,18 @@ export const LAUNCH_ERROR_CODES = ['guest_not_allowed', 'guest_unsupported', 'guest_harness', 'guest_unavailable', 'guest_helper_required','guest_engine_unsupported', 'guest_relay_failed', 'guest_folder_unavailable', 'guest_invalid', 'guest_helper_missing','guest_helper_not_authorized', 'guest_helper_failed',+ // The `setup` kind's own codes, named for a delete or restart refusal (cli/src/lib/productUsageSignals.ts).+ 'tmux_unavailable', 'tmux_too_old_for_dsh', 'tmux_too_old_for_grid', 'engine_unavailable', 'native_launch_held',+ 'dsh_materialize_failed', 'spawn_failed', 'registration_failed', 'grid_config_failed','unlisted', 'none',] as constexport type LaunchErrorCode = typeof LAUNCH_ERROR_CODES[number]-/** The families counted by code: a launch's failure, its start failing after it was created, and the create- * and resume requests' refusals. */-export const LAUNCH_ERROR_FAMILIES = ['launch_failed_code', 'launch_late_failed_code', 'create_error_code', 'resume_error_code'] as const+/** The families counted by code: a launch's failure, its start failing after it was created, the create+ * and resume requests' `other` refusals, and every delete and restart refusal — from any client, and again,+ * apart, those the phone asked for (`phone_`), which a daemon's report otherwise carries mixed with the+ * Desktop's, the TUI's and tools'. */+export const LAUNCH_ERROR_FAMILIES = ['launch_failed_code', 'launch_late_failed_code', 'create_error_code', 'resume_error_code',+ 'delete_error_code', 'restart_error_code', 'phone_delete_error_code', 'phone_restart_error_code'] as const/** The engine an installation's first launch asked for; any other engine is `other`. */export const PRODUCT_USAGE_LAUNCH_ENGINES = ['opencode', 'claude', 'codex', 'other'] as constexport type ProductUsageLaunchEngine = typeof PRODUCT_USAGE_LAUNCH_ENGINES[number]@@ -173,6 +190,7 @@ export const PRODUCT_USAGE_METRICS = [.map(measure => `${action}_user_${measure}` as const)),...PRODUCT_USAGE_UI_METRICS,...PRODUCT_USAGE_ONBOARDING_METRICS,+ ...PRODUCT_USAGE_PHONE_LAUNCH_MARKS,...PRODUCT_USAGE_PHONE_SCREEN_METRICS,...PRODUCT_USAGE_ADD_PHONE_METRICS,'ui_phone_first_open',diff --git a/cli/src/lib/productUsageSignals.spec.ts b/cli/src/lib/productUsageSignals.spec.tsindex b7f202e0a..a7a32e16f 100644--- a/cli/src/lib/productUsageSignals.spec.ts+++ b/cli/src/lib/productUsageSignals.spec.ts@@ -2,7 +2,8 @@ import { readdirSync, readFileSync } from 'node:fs'import { join } from 'node:path'import { fileURLToPath } from 'node:url'import { expect, it, vi } from 'vitest'-import { failureKind, launchErrorCode, productObservation, productUsageIntent, productUsageLaunch, productUsageRequest, productUsageSource } from './productUsageSignals.js'+import { failureKind, launchErrorCode, messageReceipt, productObservation, productUsageIntent, productUsageLaunch, productUsageRequest, productUsageSource } from './productUsageSignals.js'+import type { MessageOutcome } from './sessionInput.js'import { LAUNCH_ERROR_CODES, PRODUCT_USAGE_FLOWS, PRODUCT_USAGE_METRICS, PRODUCT_USAGE_SETUP_METRICS } from './productUsageContract.js'import { HEALTH_MEASURES } from './productHealthContract.js'@@ -110,14 +111,85 @@ it('counts the code of an `other` create or resume refusal beside its kind, so eproductUsageRequest('agent_resume', emit, () => 0, 'app')('SESSION_NOT_FOUND', 'failed', false)productUsageRequest('agent_resume', emit, () => 0, 'app')(undefined, undefined, false, false)// Other actions keep their kinds only.- productUsageRequest('agent_restart', emit, () => 0, 'app')('RESTART_FAILED', 'failed', false)+ productUsageRequest('agent_fork', emit, () => 0, 'app')('PRIVATE_FORK_ERROR', 'failed', false)const names: string[] = emit.mock.calls.flat()const family = (prefix: string) => names.filter(name => name.startsWith(prefix)).sort()expect(family('create_error_code_')).toEqual(['create_error_code_none', 'create_error_code_prompt_too_long', 'create_error_code_unlisted'])expect(names.filter(name => name === 'create_error_other')).toHaveLength(3)expect(family('resume_error_code_')).toEqual(['resume_error_code_none', 'resume_error_code_session_not_found'])expect(names.filter(name => name === 'resume_error_other')).toHaveLength(2)- expect(names.some(name => name.startsWith('restart_error_code_'))).toBe(false)+ expect(names.some(name => name.startsWith('fork_error_code_'))).toBe(false)+ for (const name of names) expect(PRODUCT_USAGE_METRICS).toContain(name)+ expect(JSON.stringify(names)).not.toContain('PRIVATE_')+})++it('measures a person\'s message by what became of it, under its source, once', () => {+ const said = (outcome: MessageOutcome, source: 'phone' | 'app' = 'phone') => {+ const emit = vi.fn()+ const receipt = messageReceipt(productUsageRequest('message', emit, () => 0, source))+ receipt(outcome)+ receipt('started')+ return emit.mock.calls.flat().filter(name => name !== `request_${source}_message_started`)+ }+ expect(said('started')).toEqual(['request_phone_message_ok'])+ expect(said('taken', 'app')).toEqual(['request_app_message_ok'])+ expect(said('agent_gone')).toEqual(['request_phone_message_failed', 'request_phone_message_error_not_found'])+ expect(said('runtime_gone')).toEqual(['request_phone_message_failed', 'request_phone_message_error_unavailable'])+ for (const busy of ['held', 'withheld', 'queue_full'] as const) {+ expect(said(busy)).toEqual(['request_phone_message_failed', 'request_phone_message_error_conflict'])+ }+ for (const late of ['not_submitted', 'queue_expired'] as const) {+ expect(said(late)).toEqual(['request_phone_message_failed', 'request_phone_message_error_timeout'])+ }+ expect(said('invalid')).toEqual(['request_phone_message_failed', 'request_phone_message_error_invalid'])+ expect(said('paste_failed')).toEqual(['request_phone_message_failed', 'request_phone_message_error_other'])+ for (const unsure of ['ambiguous', 'prompt_mismatch', 'turn_ended'] as const) {+ expect(said(unsure)).toEqual(['request_phone_message_unknown'])+ }+ expect(said('cancelled')).toEqual(['request_phone_message_cancelled'])+ // The message's own name is never a product counter, nor its time: as before, only its request's.+ const every = (['started', 'agent_gone', 'cancelled', 'ambiguous'] as const).flatMap(outcome => said(outcome))+ for (const name of every) {+ expect(name).toMatch(/^request_phone_message_/)+ expect(PRODUCT_USAGE_METRICS).toContain(name)+ }+})++it('counts every delete or restart refusal by its code, whatever its kind, so each family adds up to `_failed`', () => {+ const emit = vi.fn()+ productUsageRequest('agent_delete', emit, () => 0, 'phone')('DELETE_FAILED', undefined, false)+ productUsageRequest('agent_delete', emit, () => 0, 'phone')('PRIVATE_ERROR_WITH_PATH', 'failed', false)+ productUsageRequest('agent_delete', emit, () => 0, 'phone')({ message: 'PRIVATE_OBJECT' }, undefined, false)+ productUsageRequest('agent_delete', emit, () => 0, 'phone')('DELETE_IN_PROGRESS', undefined, false)+ productUsageRequest('agent_restart', emit, () => 0, 'phone')('SPAWN_FAILED', undefined, false)+ productUsageRequest('agent_restart', emit, () => 0, 'phone')('TMUX_UNAVAILABLE', 'failed', false)+ productUsageRequest('agent_restart', emit, () => 0, 'phone')('RESTART_FAILED', 'failed', false)+ // Another client's: in the totals, never in the phone's own families.+ productUsageRequest('agent_delete', emit, () => 0, 'app')('DELETE_FAILED', undefined, false)+ productUsageRequest('agent_restart', emit, () => 0, 'tool')('SPAWN_FAILED', undefined, false)+ // Answered without a refusal: no code.+ productUsageRequest('agent_delete', emit, () => 0, 'phone')(undefined, undefined, false)+ productUsageRequest('agent_restart', emit, () => 0, 'phone')(undefined, 'created', true)+ const names: string[] = emit.mock.calls.flat()+ const family = (prefix: string) => names.filter(name => name.startsWith(prefix)).sort()+ expect(family('delete_error_code_')).toEqual(['delete_error_code_delete_failed', 'delete_error_code_delete_failed',+ 'delete_error_code_delete_in_progress', 'delete_error_code_none', 'delete_error_code_unlisted'])+ expect(names.filter(name => name === 'delete_failed')).toHaveLength(5)+ expect(family('restart_error_code_')).toEqual(['restart_error_code_restart_failed', 'restart_error_code_spawn_failed',+ 'restart_error_code_spawn_failed', 'restart_error_code_tmux_unavailable'])+ expect(names.filter(name => name === 'restart_failed')).toHaveLength(4)+ // The phone's own: its four delete and three restart refusals, nobody else's.+ expect(family('phone_delete_error_code_')).toEqual(['phone_delete_error_code_delete_failed',+ 'phone_delete_error_code_delete_in_progress', 'phone_delete_error_code_none', 'phone_delete_error_code_unlisted'])+ expect(family('phone_restart_error_code_')).toEqual(['phone_restart_error_code_restart_failed',+ 'phone_restart_error_code_spawn_failed', 'phone_restart_error_code_tmux_unavailable'])+ expect(names.filter(name => name === 'restart_error_setup')).toHaveLength(3)+ // The phone's own split is kept beside them.+ expect(names.filter(name => name === 'request_phone_delete_error_other')).toHaveLength(3)+ expect(names).toContain('request_phone_delete_error_conflict')+ expect(names.filter(name => name === 'request_phone_restart_error_setup')).toHaveLength(2)+ expect(names).toContain('delete_ok')+ expect(names).toContain('restart_ok')for (const name of names) expect(PRODUCT_USAGE_METRICS).toContain(name)expect(JSON.stringify(names)).not.toContain('PRIVATE_')})diff --git a/cli/src/lib/productUsageSignals.ts b/cli/src/lib/productUsageSignals.tsindex c34d59494..aed6d11c3 100644--- a/cli/src/lib/productUsageSignals.ts+++ b/cli/src/lib/productUsageSignals.ts@@ -1,4 +1,5 @@-import { HEALTH_MEASURES, type HealthSource, type ResumeReason } from './productHealthContract.js'+import { HEALTH_FAILURES, HEALTH_MEASURES, type HealthSource, type ResumeReason } from './productHealthContract.js'+import type { MessageOutcome, MessageReceipt } from './sessionInput.js'import { LAUNCH_ERROR_CODES, PRODUCT_USAGE_FLOWS, PRODUCT_USAGE_LAUNCH_ENGINES, PRODUCT_USAGE_USER_OPENED_ACTIONS,type LaunchErrorCode, type ProductUsageLaunchEngine, type ProductUsageMetric } from './productUsageContract.js'@@ -135,7 +136,8 @@ export function productUsageRequest(type: string, emit: (metric: ProductUsageMetconst detail = (measure: string) => { if (!source) return; try { emit(`request_${origin}_${action}_${measure}` as ProductUsageMetric) } catch { /* Optional measurement. */ } }count('requests'); detail('started')if (userAction && (PRODUCT_USAGE_USER_OPENED_ACTIONS as readonly string[]).includes(action)) count('user_requests')- return (error: unknown, state: unknown, hasAgent: boolean, ok?: unknown) => {+ // [failure]: the kind of a refusal its caller already knows (a message's, [messageReceipt]), not read off a code.+ return (error: unknown, state: unknown, hasAgent: boolean, ok?: unknown, failure?: typeof HEALTH_FAILURES[number]) => {if (!action || answered) returnanswered = trueif (action === 'resume' && (error != null || ok === false || ['failed', 'cancelled', 'unconfirmed', 'unavailable'].some(value => state === value))) {@@ -153,7 +155,16 @@ export function productUsageRequest(type: string, emit: (metric: ProductUsageMet// Which code an `other` refusal of a create or a resume had: 22 creates and 9 resumes were `other` on// 2026-10-16 (production counters), with nothing to say why. A fixed name from the list, or unlisted.if (kind === 'other' && (action === 'create' || action === 'resume')) count(`error_code_${launchErrorCode(error)}`)- 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)}`)+ // A delete's or a restart's, whatever its kind: the phone's 3 delete refusals were `other` and its 2 restart+ // refusals `setup` on 2026-10-19, a kind of nine codes, with nothing to say which.+ if (action === 'delete' || action === 'restart') {+ count(`error_code_${launchErrorCode(error)}`)+ // The phone's again, apart: the family above mixes every client of this daemon.+ if (origin === 'phone') {+ try { emit(`phone_${action}_error_code_${launchErrorCode(error)}` as ProductUsageMetric) } catch { /* Optional measurement. */ }+ }+ }+ detail(`error_${failure ? failure : 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') }@@ -163,6 +174,27 @@ export function productUsageRequest(type: string, emit: (metric: ProductUsageMet}}+/** Each refusal of a person's message by the kind the person was told (lib/sessionInput.ts `MessageOutcome`). */+const messageFailures = {+ agent_gone: 'not_found', runtime_gone: 'unavailable', held: 'conflict', withheld: 'conflict', queue_full: 'conflict',+ not_submitted: 'timeout', queue_expired: 'timeout', invalid: 'invalid', paste_failed: 'other',+} as const satisfies Partial<Record<MessageOutcome, typeof HEALTH_FAILURES[number]>>++/**+ * A person's message measured by what became of it: until 2026-10-20 a `message` request had its `started` and+ * nothing more, as nothing answers it (2026-10-19: 14 from the phone). `ok` once its engine took it, `failed` by+ * the kind of what the person was told, `unknown` typed and never confirmed, `cancelled` stopped by the person.+ * The request's own counters only (`request_<source>_message_<result>`): no text, agent or reason leaves here.+ */+export function messageReceipt(measured: ReturnType<typeof productUsageRequest>): MessageReceipt {+ return (outcome) => {+ if (outcome === 'started' || outcome === 'taken') measured(undefined, undefined, false)+ else if (outcome === 'cancelled') measured(undefined, 'cancelled', false)+ else if (outcome === 'ambiguous' || outcome === 'prompt_mismatch' || outcome === 'turn_ended') measured(undefined, 'unconfirmed', false)+ else measured(undefined, 'failed', false, undefined, messageFailures[outcome])+ }+}+/** 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) returndiff --git a/cli/src/lib/sessionInput.spec.ts b/cli/src/lib/sessionInput.spec.tsindex e9fff26ac..3e5d32e2d 100644--- a/cli/src/lib/sessionInput.spec.ts+++ b/cli/src/lib/sessionInput.spec.ts@@ -1293,3 +1293,157 @@ describe('optional lamp delivery preserves legacy behavior', () => {controller.forget('s1')})})++describe('what became of a person\'s message, for its measurement', () => {+ afterEach(() => vi.useRealTimers())++ function setup(overrides: Partial<ConstructorParameters<typeof SessionInputController>[0]> = {}) {+ const onError = vi.fn(), onSubmitted = vi.fn()+ const inject = vi.fn<(...args: unknown[]) => Promise<boolean | TerminalActionResult>>(async () => true)+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session('claude'), validateRuntime: async () => true, inject, sendKey: async () => true,+ capture: async () => claudeBox(''), onError, onSubmitted, ...overrides })+ const said: string[] = []+ const receipt = (outcome: string) => { said.push(outcome) }+ return { controller, inject, onError, onSubmitted, said, receipt }+ }++ it('started once its turn begins, and said once', async () => {+ const { controller, onSubmitted, said, receipt } = setup()+ controller.submit('s1', 'hello', undefined, undefined, receipt)+ await vi.waitFor(() => expect(onSubmitted).toHaveBeenCalled())+ expect(said).toEqual([])+ controller.onTurnStarted('s1', 'hello')+ controller.onTurnEnded('s1')+ controller.onTurnStarted('s1', 'hello')+ expect(said).toEqual(['started'])+ controller.forget('s1')+ })++ it('a turn that is not the one typed leaves it unknown', async () => {+ const { controller, onSubmitted, said, receipt } = setup({ getSession: () => session('commandcode') })+ controller.submit('s1', 'hello', undefined, undefined, receipt)+ await vi.waitFor(() => expect(onSubmitted).toHaveBeenCalled())+ controller.onTurnStarted('s1', 'something else')+ expect(said).toEqual(['prompt_mismatch'])+ controller.forget('s1')+ })++ it('typed while a turn runs, it is taken when that turn ends; one typed after it settles the first', async () => {+ const { controller, onSubmitted, said, receipt } = setup()+ const later: string[] = []+ controller.setTurnOpen('s1', true)+ controller.submit('s1', 'first', undefined, undefined, receipt)+ await vi.waitFor(() => expect(onSubmitted).toHaveBeenCalledTimes(1))+ controller.submit('s1', 'second', undefined, undefined, (outcome) => { later.push(outcome) })+ await vi.waitFor(() => expect(onSubmitted).toHaveBeenCalledTimes(2))+ expect(said).toEqual(['taken'])+ controller.onTurnEnded('s1')+ expect(later).toEqual(['taken'])+ controller.forget('s1')+ })++ it('taken once it left the composer, without a turn seen yet', async () => {+ vi.useFakeTimers()+ const { controller, onError, said, receipt } = setup()+ controller.submit('s1', 'hello', undefined, undefined, receipt)+ await vi.advanceTimersByTimeAsync(120_000)+ expect(onError).not.toHaveBeenCalled()+ expect(said).toEqual(['taken'])+ controller.forget('s1')+ })++ it.each([+ ['not_submitted', { capture: async (): Promise<string> => claudeBox('hello') }],+ ['ambiguous', { capture: async (): Promise<string> => 'Sign in required' }],+ ] as const)('%s when the person is told so after the paste', async (outcome, overrides) => {+ vi.useFakeTimers()+ const { controller, onError, said, receipt } = setup(overrides)+ controller.submit('s1', 'hello', undefined, undefined, receipt)+ await vi.advanceTimersByTimeAsync(120_000)+ expect(onError).toHaveBeenCalledTimes(1)+ expect(said).toEqual([outcome])+ controller.forget('s1')+ })++ it.each([+ ['runtime_gone', { validateRuntime: async (): Promise<boolean> => false }],+ ['held', { inject: async (): Promise<TerminalActionResult> => ({ state: 'failed', dispatch: 'not_started', reason: 'permission_open' }) }],+ ['withheld', { inject: async (): Promise<TerminalActionResult> => ({ state: 'unknown', dispatch: 'possibly_executed', reason: 'enter_withheld:permission_open' }) }],+ ['paste_failed', { inject: async (): Promise<boolean> => false }],+ ] as const)('%s, refused at the paste', async (outcome, overrides) => {+ const { controller, onError, said, receipt } = setup(overrides)+ controller.submit('s1', 'hello', undefined, undefined, receipt)+ await vi.waitFor(() => expect(onError).toHaveBeenCalledTimes(1))+ expect(said).toEqual([outcome])+ controller.forget('s1')+ })++ it('agent_gone for a harness not there, at once or when its turn in the queue comes', () => {+ let there = true+ const { controller, said, receipt, inject } = setup({ getSession: () => there ? session('commandcode') : undefined })+ controller.setTurnOpen('s1', true)+ controller.submit('s1', 'queued', undefined, undefined, receipt)+ expect(said).toEqual([])+ there = false+ controller.onTurnEnded('s1')+ expect(said).toEqual(['agent_gone'])+ const now: string[] = []+ controller.submit('s1', 'to nobody', undefined, undefined, (o) => { now.push(o) })+ expect(now).toEqual(['agent_gone'])+ expect(inject).not.toHaveBeenCalled()+ controller.forget('s1')+ })++ it('queue_full past the queue\'s 8, queue_expired after its 5 minutes, agent_gone for one left when it goes', async () => {+ vi.useFakeTimers()+ const { controller, inject } = setup({ getSession: () => session('commandcode') })+ controller.setTurnOpen('s1', true)+ const outcomes: string[][] = Array.from({ length: 9 }, () => [])+ for (let i = 0; i < 9; i++) controller.submit('s1', `m${i}`, undefined, undefined, (o) => { outcomes[i]!.push(o) })+ expect(outcomes[8]).toEqual(['queue_full'])+ expect(outcomes.slice(0, 8).flat()).toEqual([])+ await vi.advanceTimersByTimeAsync(5 * 60_000 + 1)+ const fresh: string[] = []+ controller.submit('s1', 'fresh', undefined, undefined, (o) => { fresh.push(o) })+ expect(outcomes.slice(0, 8)).toEqual(Array.from({ length: 8 }, () => ['queue_expired']))+ expect(fresh).toEqual([])+ controller.forget('s1')+ expect(fresh).toEqual(['agent_gone'])+ expect(inject).not.toHaveBeenCalled()+ })++ it('cancelled by the person, and ambiguous for a harness gone while it waited', async () => {+ const { controller, onSubmitted, said, receipt } = setup()+ controller.submit('s1', 'one', undefined, undefined, receipt)+ await vi.waitFor(() => expect(onSubmitted).toHaveBeenCalledTimes(1))+ expect(await controller.cancelConfirmed('s1')).toBe(true)+ expect(said).toEqual(['cancelled'])++ const later: string[] = []+ controller.submit('s1', 'two', undefined, undefined, (o) => { later.push(o) })+ await vi.waitFor(() => expect(onSubmitted).toHaveBeenCalledTimes(2))+ controller.forget('s1')+ expect(later).toEqual(['ambiguous'])+ })++ it('a write that throws is unknown, and fails as before', async () => {+ const { controller, said, receipt } = setup({ inject: async () => { throw new Error('PRIVATE') } })+ controller.submit('s1', 'hello', undefined, undefined, receipt)+ await vi.waitFor(() => expect(said).toEqual(['ambiguous']))+ controller.forget('s1')+ })++ it('a receipt that throws changes nothing about the message', async () => {+ const { controller, onSubmitted, onError, inject } = setup()+ const receipt = vi.fn(() => { throw new Error('measurement broke') })+ controller.submit('s1', 'hello', undefined, undefined, receipt)+ await vi.waitFor(() => expect(onSubmitted).toHaveBeenCalled())+ controller.onTurnStarted('s1', 'hello')+ controller.onTurnEnded('s1')+ expect(receipt).toHaveBeenCalledTimes(1)+ expect(inject).toHaveBeenCalledTimes(1)+ expect(onError).not.toHaveBeenCalled()+ controller.forget('s1')+ })+})diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.tsindex 9c1d81d7b..842f14986 100644--- a/cli/src/lib/sessionInput.ts+++ b/cli/src/lib/sessionInput.ts@@ -71,9 +71,34 @@ export interface SessionInputDelivery {reason?: string}+/**+ * What became of a person's message, one without a delivery id (the windows' and the phone's composers), said+ * once and for measurement only: the request's measurement had its start and nothing more (2026-10-19: 14 phone+ * messages, no outcome). `started`, its turn began; `taken`, the engine took it without a turn being seen yet (it+ * left the composer, or a running turn it follows ended). The person was told why for each of the next nine+ * (`agent_gone`, `runtime_gone`, `held`, `withheld`, `paste_failed`, `not_submitted`, `queue_full`,+ * `queue_expired`, `invalid`, nothing sent for most); `ambiguous`, `prompt_mismatch` and `turn_ended` were typed+ * and never confirmed either way; `cancelled`, the person stopped it.+ */+export type MessageOutcome = 'started' | 'taken' | 'agent_gone' | 'runtime_gone' | 'held' | 'withheld' | 'paste_failed'+ | 'not_submitted' | 'queue_full' | 'queue_expired' | 'invalid' | 'ambiguous' | 'prompt_mismatch' | 'turn_ended' | 'cancelled'+export type MessageReceipt = (outcome: MessageOutcome) => void++/** [receipt] said at most once, and never into the input path: a receipt that throws is measurement lost. */+function sayOnce(receipt?: MessageReceipt): MessageReceipt | undefined {+ if (!receipt) return undefined+ let said = false+ return (outcome) => {+ if (said) return+ said = true+ try { receipt(outcome) } catch { /* Optional measurement. */ }+ }+}+interface QueuedInput {deliveryId?: stringinputContext?: string+ receipt?: MessageReceiptcontent: stringbytes: numberexpiresAt: number@@ -91,6 +116,8 @@ interface InputState {turnOpen: booleanawaitingFingerprint: string | nullawaitingContent: string | null+ /** The receipt of the person's message typed last, until it is settled ([settle]). */+ awaitingReceipt?: MessageReceiptcontrolLocked: booleansettling: booleanqueue: QueuedInput[]@@ -240,6 +267,13 @@ export class SessionInputController {this.delivery(sessionId, id, outcome, reason)}+ /** The awaited person's message is settled as [outcome]: wherever its wait for a turn ends. */+ private settle(state: InputState, outcome: MessageOutcome): void {+ const receipt = state.awaitingReceipt+ state.awaitingReceipt = undefined+ receipt?.(outcome)+ }+/** Revoke queued work only; a paste already in progress cannot be recalled. */cancelDelivery(deliveryId: string): boolean {for (const [sessionId, state] of this.states) {@@ -258,9 +292,12 @@ export class SessionInputController {return false}- submit(sessionId: string, content: string, deliveryId?: string, inputContext?: string): void {+ /** [receipt]: what became of a person's message (one with no [deliveryId]), for its measurement. */+ submit(sessionId: string, content: string, deliveryId?: string, inputContext?: string, receipt?: MessageReceipt): void {+ const said = sayOnce(receipt)const session = this.controlSession(sessionId)if (!session) {+ said?.('agent_gone')this.delivery(sessionId, deliveryId, 'rejected', 'agent_gone')if (!deliveryId?.startsWith('team:')) this.deps.onError(sessionId, 'This harness is no longer available.')return@@ -271,7 +308,7 @@ export class SessionInputController {|| (deliveryId && (state.deliveryId || state.dispatching || state.turnOpen || state.awaitingFingerprint || state.settling))|| (!this.typesWhileBusy(session.engine) && (state.turnOpen || state.awaitingFingerprint || state.settling))) {console.log(`[inject] ${sid(sessionId)} queued · engine=${session.engine} · depth=${state.queue.length + 1}`)- this.enqueue(sessionId, state, content, deliveryId, inputContext)+ this.enqueue(sessionId, state, content, deliveryId, inputContext, said)return}this.delivery(sessionId, deliveryId, 'queued')@@ -283,7 +320,7 @@ export class SessionInputController {// agent as it is by then, which a restart in between may have changed.// With nothing in flight the write starts at once, so a cancel or a control request that follows// the submit sees it, as before.- const write = (): Promise<void> => this.inject(sessionId, this.controlSession(sessionId) ?? session, content, deliveryId, inputContext)+ const write = (): Promise<void> => this.inject(sessionId, this.controlSession(sessionId) ?? session, content, deliveryId, inputContext, said)const running = state.writes ? state.writes.then(write, write) : write()const settled: Promise<void> = running.catch(() => {}).then(() => { if (state.writes === settled) state.writes = undefined })state.writes = settled@@ -358,10 +395,12 @@ export class SessionInputController {if (state.awaitingFingerprint) {const warn = () => console.warn(`[inject] ${sessionId.slice(0, 8)} observed a different terminal prompt while awaiting submit`)const expected = state.awaitingFingerprint+ const receipt = state.awaitingReceipt+ state.awaitingReceipt = undefinedif (expected !== observedFingerprint) {- if (engineReads) void this.echoes(session, userMessage, expected).then(matched => { if (!matched) warn() })- else warn()- }+ if (engineReads) void this.echoes(session, userMessage, expected).then(matched => { if (!matched) warn(); receipt?.(matched ? 'started' : 'prompt_mismatch') })+ else { warn(); receipt?.('prompt_mismatch') }+ } else receipt?.('started')state.awaitingFingerprint = nullstate.awaitingContent = nullstate.retries = 0@@ -404,6 +443,8 @@ export class SessionInputController {onTurnEnded(sessionId: string): void {const state = this.state(sessionId)if (!state.dispatching) this.finishDelivery(sessionId, state, 'unknown', 'turn_ended_without_start')+ // Typed while a turn ran, the engine holds it as that turn's follow-up; otherwise no turn was seen for it.+ this.settle(state, state.turnOpen ? 'taken' : 'turn_ended')state.turnOpen = falsestate.awaitingFingerprint = nullstate.awaitingContent = null@@ -436,6 +477,7 @@ export class SessionInputController {await this.deps.sendKey(session.agentId, 'C-c')const state = this.state(sessionId)this.finishDelivery(sessionId, state, 'unknown', 'cancelled_after_paste')+ this.settle(state, 'cancelled')state.turnOpen = falsestate.awaitingFingerprint = nullstate.awaitingContent = null@@ -452,6 +494,7 @@ export class SessionInputController {const result = await this.deps.sendKey(session.agentId, 'C-c')const state = this.state(sessionId)this.finishDelivery(sessionId, state, 'unknown', 'cancelled_after_paste')+ this.settle(state, 'cancelled')state.turnOpen = falsestate.awaitingFingerprint = nullstate.awaitingContent = null@@ -468,17 +511,22 @@ export class SessionInputController {if (state?.settleTimer) clearTimeout(state.settleTimer)if (state) {this.finishDelivery(sessionId, state, state.writing || state.awaitingFingerprint || state.deliveryFingerprint ? 'unknown' : 'rejected', 'agent_gone')- for (const item of state.queue) this.delivery(sessionId, item.deliveryId, 'rejected', 'agent_gone')+ this.settle(state, 'ambiguous')+ for (const item of state.queue) {+ this.delivery(sessionId, item.deliveryId, 'rejected', 'agent_gone')+ item.receipt?.('agent_gone')+ }state.cancelled = true}this.states.delete(sessionId)}/** Preserve the established injection path for every caller that opts out of receipts. */- private async injectLegacy(sessionId: string, session: RegisteredSession, content: string, inputContext?: string): Promise<void> {+ private async injectLegacy(sessionId: string, session: RegisteredSession, content: string, inputContext?: string, receipt?: MessageReceipt): Promise<void> {const state = this.state(sessionId)if (!(await this.deps.validateRuntime(session))) {console.warn(`[inject] ${sid(sessionId)} abort · engine=${session.engine} · process not running`)+ receipt?.('runtime_gone')this.deps.onError(sessionId, 'This agent process is no longer running.')return}@@ -508,6 +556,7 @@ export class SessionInputController {if (withheld) {// Typed, its Enter not pressed: never pressed later either, which would send it into whatever is open.console.warn(`[inject] ${sid(sessionId)} typed, not sent · engine=${session.engine} · ${withheld} opened before Enter`)+ receipt?.('withheld')this.deps.onError(sessionId, messageWithheldText(session.engine, withheld))return}@@ -515,14 +564,19 @@ export class SessionInputController {const held = heldBack(delivery)if (held) {console.warn(`[inject] ${sid(sessionId)} not typed · engine=${session.engine} · ${held}`)+ receipt?.('held')this.deps.onError(sessionId, messageHoldText(session.engine, held))return}console.warn(`[inject] ${sid(sessionId)} paste failed · engine=${session.engine} · target=${session.agentId}`)+ receipt?.('paste_failed')this.deps.onError(sessionId, 'The message could not be delivered to the agent.')return}console.log(`[inject] ${sid(sessionId)} paste ok · engine=${session.engine} · target=${session.agentId} · len=${content.length}`)+ // The one typed before it, never refused, was taken as the message before this one.+ this.settle(state, 'taken')+ state.awaitingReceipt = receiptstate.awaitingFingerprint = fingerprint(content)state.awaitingContent = contentstate.retries = 0@@ -536,13 +590,18 @@ export class SessionInputController {return inputContext ? this.deps.inject(id, content, inputContext) : this.deps.inject(id, content)}- private async inject(sessionId: string, session: RegisteredSession, content: string, deliveryId?: string, inputContext?: string): Promise<void> {+ private async inject(sessionId: string, session: RegisteredSession, content: string, deliveryId?: string, inputContext?: string, receipt?: MessageReceipt): Promise<void> {const state = this.state(sessionId)if (!deliveryId) {// A local submission keeps its original scheduling. Overlap removes our ability// to attribute a later terminal turn to the lamp; it must not block local input.this.finishDelivery(sessionId, state, 'unknown', 'prompt_mismatch')- return this.injectLegacy(sessionId, session, content, inputContext)+ if (!receipt) return this.injectLegacy(sessionId, session, content, inputContext)+ // A write that threw may have typed something: unknown, and thrown on as before.+ return this.injectLegacy(sessionId, session, content, inputContext, receipt).catch((error: unknown) => {+ receipt('ambiguous')+ throw error+ })}state.deliveryId = deliveryIdstate.deliveryFingerprint = undefined@@ -705,6 +764,7 @@ export class SessionInputController {console.warn(`[inject] ${sid(sessionId)} not accepted · engine=cursor · composer clear of draft`)state.awaitingFingerprint = nullstate.awaitingContent = null+ this.settle(state, 'not_submitted')this.finishDelivery(sessionId, state, 'unknown', 'not_submitted')this.deps.onError(sessionId, 'The agent did not accept the message. Please try again.')return@@ -739,6 +799,7 @@ export class SessionInputController {state.awaitingContent = nullstate.observes = 0state.ambiguousDispatch = false+ this.settle(state, 'taken')return}if (capture) {@@ -771,6 +832,7 @@ export class SessionInputController {state.awaitingFingerprint = nullstate.awaitingContent = nullstate.ambiguousDispatch = false+ this.settle(state, 'not_submitted')this.finishDelivery(sessionId, state, 'unknown', 'not_submitted')this.deps.onError(sessionId, 'The agent did not accept the message. Please try again.')return@@ -779,6 +841,7 @@ export class SessionInputController {const valid = await this.deps.validateRuntime(session)if (!valid) {this.finishDelivery(sessionId, state, 'unknown', 'runtime_gone_post_paste')+ this.settle(state, 'runtime_gone')state.awaitingFingerprint = nullstate.awaitingContent = nullstate.ambiguousDispatch = false@@ -827,6 +890,7 @@ export class SessionInputController {state.awaitingFingerprint = nullstate.awaitingContent = nullstate.observes = 0+ this.settle(state, 'taken')}/**@@ -851,11 +915,13 @@ export class SessionInputController {state.awaitingContent = nullstate.observes = 0state.ambiguousDispatch = false+ this.settle(state, 'taken')return true}private failAmbiguousSubmission(sessionId: string, state: InputState): void {this.finishDelivery(sessionId, state, 'unknown', 'dispatch_ambiguous')+ this.settle(state, 'ambiguous')state.awaitingFingerprint = nullstate.awaitingContent = nullstate.ambiguousDispatch = false@@ -871,28 +937,34 @@ export class SessionInputController {const session = this.controlSession(sessionId)if (!session) {this.delivery(sessionId, next.deliveryId, 'rejected', 'agent_gone')+ next.receipt?.('agent_gone')if (!next.deliveryId?.startsWith('team:')) this.deps.onError(sessionId, 'This harness is no longer available.')return}- void this.inject(sessionId, session, next.content, next.deliveryId, next.inputContext)+ void this.inject(sessionId, session, next.content, next.deliveryId, next.inputContext, next.receipt)}- private enqueue(sessionId: string, state: InputState, content: string, deliveryId?: string, inputContext?: string): void {+ private enqueue(sessionId: string, state: InputState, content: string, deliveryId?: string, inputContext?: string, receipt?: MessageReceipt): void {const bytes = Buffer.byteLength(content, 'utf8')const queuedBytes = state.queue.reduce((sum, item) => sum + item.bytes, 0)if (state.queue.length >= MAX_QUEUE_ITEMS || queuedBytes + bytes > MAX_QUEUE_BYTES) {this.delivery(sessionId, deliveryId, 'rejected', 'queue_full')+ receipt?.('queue_full')if (!deliveryId?.startsWith('team:')) this.deps.onError(sessionId, 'This agent already has too many queued messages. Try again after the current operation finishes.')return}- state.queue.push({ content, bytes, expiresAt: Date.now() + ITEM_TTL_MS, deliveryId, inputContext })+ state.queue.push({ content, bytes, expiresAt: Date.now() + ITEM_TTL_MS, deliveryId, inputContext, ...(receipt ? { receipt } : {}) })this.delivery(sessionId, deliveryId, 'queued')}private dropExpired(sessionId: string, state: InputState): void {const now = Date.now()const expiredLocalInput = state.queue.some(item => item.expiresAt <= now && !item.deliveryId?.startsWith('team:'))- for (const item of state.queue) if (item.expiresAt <= now) this.delivery(sessionId, item.deliveryId, 'rejected', 'queue_expired')+ for (const item of state.queue) {+ if (item.expiresAt > now) continue+ this.delivery(sessionId, item.deliveryId, 'rejected', 'queue_expired')+ item.receipt?.('queue_expired')+ }state.queue = state.queue.filter((item) => item.expiresAt > now)if (expiredLocalInput) this.deps.onError(sessionId, 'A queued message expired before the agent became available.')}diff --git a/docs/product-measurement.md b/docs/product-measurement.mdindex 5596823aa..d64a71a6d 100644--- a/docs/product-measurement.md+++ b/docs/product-measurement.md@@ -10,7 +10,7 @@ automatically proven improvement. Changes still need review, tests and a deliber| --- | --- | --- || Does first measured use lead to work? | First-launch installation cohorts; work and first text response within 24 hours; the first launch's engine (`first_launch_engine_opencode`, `_claude`, `_codex`, `_other`) and, for Claude Code and Codex, whether that engine had a credential here (`first_launch_<engine>_signed_in`, `_signed_out`, `_unknown`) | Same participating installation, not signup conversion, same-task success or unique people. Existing users enter when updated; mature only after the full follow-up day ends. The credential is one presence check per installation, in the gateway (`cli/src/lib/engineAccount.ts`: a file stat'ed or parsed for a token, a Keychain item looked up without its secret); it reads the gateway's own environment and starts no login shell, so a key only a shell profile exports reads as signed out on a daemon launchd or systemd started. `unknown` is a Codex that keeps its tokens in the OS keyring, or a check that failed. An answer lost to a stop or a choice change leaves the engine count without one. || Where does a launch stall or fail? | Pending install/model/native waits; observed launch created/failed/cancelled/unconfirmed; fixed failure categories and duration buckets; an `other` failure's code (`launch_failed_code_<code>`); a created launch whose engine then did not start (`launch_late_failed`, by code in `launch_late_failed_code_<code>`) | Polls are not attempts. Missing outcomes, daemon restarts and the 15-minute observation bound reduce coverage. Inspect unknowns alongside failures. Codes are the daemon's own fixed names, lower-cased (`LAUNCH_ERROR_CODES`); `unlisted` is a code not in the list and `none` a failure that named none, so the codes add up to `launch_failed_other`. A late failure (the new-pane watcher's ENGINE_DID_NOT_START, ENGINE_NOT_INSTALLED or START_TIMEOUT, set after the reply said created) is one of the `launch_created`, never a `launch_failed`; the gateway reads it from the agent's own announcement for 15 minutes after the launch was created, and earlier CLI releases counted these only as created (compare releases separately). |-| Which actions break? | Create, resume, restart, model-change, history, fork, close, delete, search, history paging, Store list/install/update/remove, model list/download/start/stop and browser-open requests, fixed outcomes/errors and latency buckets; the code of an `other` create or resume refusal (`create_error_code_<code>`, `resume_error_code_<code>`) | Request acceptance is not task success. Pending/unknown requests are separate from completed replies. Requests are also counted by source: `app`, `tool`, `automatic` (fixed polls, whichever app makes them), `unknown` and `phone` — the phone marks the requests the daemon measures (`usageSurface: 'phone'`, inside the E2EE payload); older phones still count as `app`. Each code family adds up to its `create_error_other` or `resume_error_other`. |+| Which actions break? | Create, resume, restart, model-change, history, fork, close, delete, search, history paging, Store list/install/update/remove, model list/download/start/stop and browser-open requests, fixed outcomes/errors and latency buckets; the code of an `other` create or resume refusal (`create_error_code_<code>`, `resume_error_code_<code>`), and of every delete or restart refusal (`delete_error_code_<code>`, `restart_error_code_<code>`; the phone's again apart, `phone_delete_error_code_<code>`, `phone_restart_error_code_<code>`) | Request acceptance is not task success. Pending/unknown requests are separate from completed replies. A person's message (`request_<source>_message_*`), which nothing answers, is `ok` once its engine took it (its turn began, or it left the composer), `failed` by what the person was told (`not_found`, `unavailable`, `conflict` for a pane busy with a dialog or a full queue, `timeout`, `invalid`, `other`), `unknown` when typed and never confirmed, `cancelled` when stopped; from the CLI release that carries it (an older one counts only `started`), and not yet for cloud agents. Requests are also counted by source: `app`, `tool`, `automatic` (fixed polls, whichever app makes them), `unknown` and `phone` — the phone marks the requests the daemon measures (`usageSurface: 'phone'`, inside the E2EE payload); older phones still count as `app`. Each code family adds up to its `create_error_other` or `resume_error_other`; the delete and restart families add up to `delete_failed` and `restart_failed`, whatever the kind (the phone's 2026-10-19 refusals were `other` and `setup`). || Does work get a response promptly? | First text response buckets; over-one-minute waits; error events; matched ends without text; interruptions | Includes automation. Tool-only turns, interruptions and missing lifecycle events can explain missing text. No message is inspected. || Do installations return to work? | D1/D7/D28 working-day cohorts, consecutive complete-week and calendar-month returns, return after a seven-day gap | Any working day can be a cohort; not new-signup retention. Local date flags produce unlinked totals. Opt-outs, reinstallations, resets and missing uploads affect results. || Was the task useful? | Optional Completed / Partly completed / Not completed plus five fixed reason choices from clients that offer feedback; current Desktop Settings no longer exposes feedback controls | Voluntary and self-selected; not representative success or satisfaction. There is no free-text input. |@@ -20,7 +20,7 @@ automatically proven improvement. Changes still need review, tests and a deliber| Which features get tried and used again? | First measured installations and daily first/repeat feature reach | Locally deduplicated installation-days, not unique accounts. Reads the apps make on their own (history, history paging, Store list, model list; `PRODUCT_USAGE_AUTOMATIC_ACTIONS`) count reliability only. The Store and model lists get reach only from the request an app marks `userAction` when a person opens them (`<action>_user_*`, `PRODUCT_USAGE_USER_OPENED_ACTIONS`); history has none. || Where do app flows break? | Setup, Harness/tmux/clipboard steps, sign-in, workspace/remote connections, computer linking, viewer-pane opening and manual update checking/staging; a setup step whose tool was missing at a check (`setup_desktop_setup_<step>_missing`); the agents a new computer downloads beside setup (`setup_desktop_agent_download_<opencode\|codex\|claude>_started`, `_ok`, `_failed`, with under 1 min, 1–5 min and over 5 min) | Fixed started/ok/failed/cancelled/unknown counts and coarse duration buckets. Opening a viewer pane is not rendering its content; staging an update is not a successful relaunch. A setup step stays open from the first check until its tool is in place, so a tool that was missing and then installed is one ok step and one `_missing` mark; only a setup that ends failed fails its step. Earlier Desktop releases counted every check that found a tool missing as a failed step (on 2026-10-16 the Harness step read 72 failed of 221 while 0 setups failed): compare releases separately. `_missing` is any tool a check found absent or out of date (a Harness CLI older than this Desktop needs, on a computer already in use, counts too), not only new computers. A step left waiting (the review, a Linux Terminal handoff, manual mode, someone who walks away) now ends `unknown` at the 15-minute observation bound instead of `failed`, so expect `setup_*_unknown` to rise, mostly on Linux. `_missing` and the download counts are anonymous setup counts only. A download whose prerequisite (curl, Harness's Node) never arrived counts as started and failed; `ok` means the agent's program is in place, judged per engine. || Where does the phone's onboarding stall? | After sign-in: waiting for the first computer, opening its session, the first message, the notification prompt. A sign-in that went through, by button, counted again under the account's sharing. Waits past a minute split into 1–5 min, 5–15 min, 15 min–1 h and over 1 h for the computer and the first message. Once per step per sign-in: `resumed` (reopened in a run that did not sign in), "Not you? Sign out", the address sent from the share sheet, a joining computer that wants its password or is offline, `joined_after_leaving` (the computer turned up after the app left the wait), `new_account` (a sign-in that created the account). Once per install: `first_open` (signed out `setup_phone_first_open`, signed in `ui_phone_first_open`) | Stage totals per day, not a linked funnel. A wait's `ok` is a computer that turned up while its screen was open: add `joined_after_leaving` for the computers that came while the app was away (16–19 October 2026: 5 `ok` in 49 fresh waits, while 91% of the phone's people had a computer on the same account). `new_account` is an account minutes old at sign-in, its first Harness sign-in anywhere. `first_open` is set once per install by a local flag that is never sent: the step between a store's download and a sign-in. Subtract `resumed` from starts for fresh starts; an unmatched start is a closed app or a step still waiting. A resumed step's duration starts at the reopening. Signed-in sign-in counts are successes only; failures and cancels before an account remain the signed-out counts', but a success is marked `retried` (a failed or cancelled try came first in that app run) or `switched` (another button was tried first). Phone reports carry release and iOS/Android, so every phone count also splits by those two margins (above 20 collector days); debug builds are not kept. A chosen sign-out sends what is queued first (up to 2 s), so "Not you? Sign out" reaches the totals. |-| How fast does the phone get back to work? | A launch that came back signed in, to its first computer answering (`app_start`); a dial the person asked for ("Try again", `connect_user`) apart from the app's own (`connect_auto`), beside the unchanged `remote_connect`; a stopped harness resumed from the phone, to its first live turn (`resume_recovery`) | A launch that signs in is the onboarding's and is not counted; one that leaves the screen before a computer answers is `unknown`, one whose computers never answer stays started. An asked-for dial fails at 12 s, as Desktop Connect does. A phone dial is `failed` only when the phone knows why (locked or offline), `unknown` otherwise; the reasons (`connect_error_*`) are Desktop health counters. |+| How fast does the phone get back to work? | A launch that came back signed in, to its first computer answering (`app_start`); a dial the person asked for ("Try again", `connect_user`) apart from the app's own (`connect_auto`), beside the unchanged `remote_connect`; a stopped harness resumed from the phone, to its first live turn (`resume_recovery`) | A launch that signs in is the onboarding's and is not counted; one that leaves the screen before a computer answers is `unknown`, one whose computers never answer stays started. What a launch waited on is counted beside it, once each, until a computer answers or the app leaves the screen (`ui_phone_app_start_<why>`): `no_computer` and `list_failed` (the account's list had none, or could not be read), `offline` (it said every computer was offline), `locked` (a computer wanted the phone's password), `connect_failed` (a dial to a computer said to be online failed) and `waited_1m` (a minute on screen); a launch can name several. An asked-for dial fails at 12 s, as Desktop Connect does. A phone dial is `failed` only when the phone knows why (locked or offline), `unknown` otherwise; the reasons (`connect_error_*`) are Desktop health counters. || Are the phone's side pages used? | Find and Computers opens, by a sideways swipe on the terminal or by a button (Computers' row in Settings, its link on a long wait at home) | Which page and which way, nothing more. Find's key and screen-reader actions are not counted; a swipe that lets Find go back opened nothing. || Does Desktop's Add Phone card get used, and where else is Add Phone opened? | The card's flow (`ui_desktop_phone_offer_*`): started once it is on screen, `ok` by its Add Phone, `cancelled` by its ×, `unknown` when it went another way (Add Phone opened from elsewhere, a sign-out); every Add Phone opening by its way in (`ui_desktop_add_phone_<offer\|titlebar\|menu\|account\|machines\|command>`) | The card is offered once per computer, so its starts are computers, not people, and it has no 15-minute bound: started minus outcomes is an app closed with the card still up. An opening is the dialog shown, not a phone paired. `menu` includes a key bound to Harness ▸ Add Phone… on macOS; `command` is `> add phone` or a key bound to it elsewhere. The browser counts none. Vocabulary 3: counted from the start, but sent only once the local CLI has answered that it forwards them, so a Desktop on an older CLI sends none. || Is measurement losing coverage? | Updated collector installation-days, pruned queues, full observation maps, unmatched app starts | Loss signals warrant caution. No signal does not prove complete collection. |