The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
fix(tracking): derive Studio events and recover configuration failures
罗高f71dda66be11
diff --git a/server.ts b/server.tsindex b0606c82..fa31c71f 100644--- a/server.ts+++ b/server.ts@@ -26,9 +26,8 @@ import { phase1McpCapabilities } from './shared/phase1-tools.ts';import { recoverProjectTransactions } from './phase1-versions.ts';import { verifyExport } from './scripts/verify-export.ts';import { createAppTracking, closeTracking, saveTrackingPreference, trackingPreference, trackingLocked, type OmTracking } from './shared/tracking.ts';-import { browserEvents } from './tracking/events.ts';+import { studioEvents } from './tracking/events.ts';import { validPending } from './tracking/core.ts';-import { omEvents } from './tracking/events.ts';const sharedStore = new WorkspaceStore();export type Service = { studio?: Studio; runtimeRoot?: string; ffmpeg?: boolean; switching?: boolean; studioPort?: number; browser?: WorkspaceBrowser; editorToken?: string; ensureStudio?: (projectId?: string) => Promise<Studio>; launchStudio?: (directory: string, port: number) => Promise<Studio>; phase1?: Phase1Service; phase1Mutation?: Promise<void>; tracking?: OmTracking };@@ -267,8 +266,7 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =if (!context.tracking?.enabled()) return json(res, 200, { accepted: 0, enabled: false });const data = await input(req, 64 * 1024);if (!data || Object.keys(data).length !== 1 || !Array.isArray(data.events) || data.events.length > 16- || !data.events.every((event: unknown) => validPending(omEvents, event) && event.entrypoint === 'studio'- && (browserEvents as readonly string[]).includes(event.event))) return json(res, 400, { error: 'INVALID_TRACKING_BATCH' });+ || !data.events.every((event: unknown) => validPending(studioEvents, event) && event.entrypoint === 'studio')) return json(res, 400, { error: 'INVALID_TRACKING_BATCH' });const statuses = data.events.map((event: unknown) => context.tracking!.ingest(event));return json(res, statuses.includes('full') ? 429 : 200, { accepted: statuses.filter((status: string) => status === 'queued').length });}diff --git a/studio/src/motion/tracking.test.ts b/studio/src/motion/tracking.test.tsindex b5d0dbd7..ad819b20 100644--- a/studio/src/motion/tracking.test.ts+++ b/studio/src/motion/tracking.test.ts@@ -1,7 +1,12 @@// @vitest-environment happy-dom-import { afterEach, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';-afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); vi.resetModules(); });+const click = { page_name: 'home', area: 'workspace', element: 'new_creation' } as const;+beforeEach(() => { vi.useFakeTimers(); });+afterEach(() => {+ vi.clearAllTimers(); vi.useRealTimers(); Reflect.deleteProperty(navigator, 'doNotTrack');+ vi.unstubAllGlobals(); vi.restoreAllMocks(); vi.resetModules();+});it('keeps the project token out of browser packets and sends only explicitly invoked events', async () => {const requests: Array<{ url: string; body?: string }> = [];@@ -13,7 +18,8 @@ it('keeps the project token out of browser packets and sends only explicitly invawait tracking.initializeTracking();expect(requests).toHaveLength(1);document.body.click(); await tracking.flushMotionTracking(); expect(requests).toHaveLength(1);- await tracking.trackMotion('ui_click', { page_name: 'home', area: 'workspace', element: 'new_creation' });+ expect(await tracking.trackMotion('ui_click', click)).toBe('queued');+ expect(tracking.getMotionTrackingStatus()).toEqual({ configuration: 'ready', enabled: true, pending: 1, retryAfterMs: 0 });await tracking.flushMotionTracking();expect(requests).toHaveLength(2);const payload = JSON.parse(requests[1].body!);@@ -30,7 +36,7 @@ it('honors both local disablement and browser Do Not Track', async () => {const tracking = await import('./tracking');await tracking.trackMotion('ui_click', { page_name: 'home', area: 'workspace', element: 'new_creation' });await tracking.flushMotionTracking();- expect(fetcher).toHaveBeenCalledTimes(1);+ expect(fetcher).toHaveBeenCalledTimes(dnt === '1' ? 0 : 1);}Reflect.deleteProperty(navigator, 'doNotTrack');});@@ -43,3 +49,92 @@ it('does not let a stale configuration response undo a user opt-out', async () =await tracking.trackMotion('ui_click', { page_name: 'home', area: 'workspace', element: 'new_creation' });await tracking.flushMotionTracking(); expect(fetcher).toHaveBeenCalledTimes(1);});++it('shares initialization and recovers the original calls after a transient configuration failure', async () => {+ const fetcher = vi.fn().mockRejectedValueOnce(new Error('PRIVATE_FAILURE'))+ .mockImplementation(async () => Response.json({ enabled: true }));+ vi.stubGlobal('fetch', fetcher);+ const tracking = await import('./tracking');+ const first = tracking.trackMotion('ui_click', click), second = tracking.trackMotion('ui_click', click);+ await vi.advanceTimersByTimeAsync(999);+ expect(fetcher).toHaveBeenCalledTimes(1);+ expect(tracking.getMotionTrackingStatus()).toMatchObject({ configuration: 'loading', enabled: false, pending: 0 });+ await vi.advanceTimersByTimeAsync(1);+ expect(await Promise.all([first, second])).toEqual(['queued', 'queued']);+ expect(fetcher).toHaveBeenCalledTimes(2);+ expect(await tracking.flushMotionTracking()).toBe('accepted');+ expect(JSON.parse(fetcher.mock.calls[2][1].body).events).toHaveLength(2);+});++it.each(['network', 'http', 'json', 'shape'])('bounds %s configuration failures and retries on a later call after cooldown', async failure => {+ let failed = true;+ const fetcher = vi.fn(async () => {+ if (!failed) return Response.json({ enabled: true });+ if (failure === 'network') throw new Error('PRIVATE_URL_AND_SECRET');+ if (failure === 'http') return new Response('', { status: 503 });+ if (failure === 'json') return new Response('not json');+ return Response.json({ enabled: 'true' });+ });+ vi.stubGlobal('fetch', fetcher);+ const tracking = await import('./tracking'), pending = tracking.trackMotion('ui_click', click);+ await vi.advanceTimersByTimeAsync(3000);+ expect(await pending).toBe('config_unavailable');+ expect(fetcher).toHaveBeenCalledTimes(3);+ expect(tracking.getMotionTrackingStatus()).toEqual({ configuration: 'unavailable', enabled: false, pending: 0, retryAfterMs: 30_000 });+ expect(await tracking.flushMotionTracking()).toBe('disabled');+ expect(await tracking.trackMotion('ui_click', click)).toBe('config_unavailable');+ await vi.advanceTimersByTimeAsync(29_999);+ expect(await tracking.trackMotion('ui_click', click)).toBe('config_unavailable');+ expect(fetcher).toHaveBeenCalledTimes(3);+ await vi.advanceTimersByTimeAsync(1); failed = false;+ expect(await tracking.trackMotion('ui_click', click)).toBe('queued');+ expect(fetcher).toHaveBeenCalledTimes(4);+ expect(await tracking.flushMotionTracking()).toBe('accepted');+});++it('treats a policy disablement as final and stops retries when the user opts out', async () => {+ const fetcher = vi.fn().mockRejectedValue(new Error('offline')); vi.stubGlobal('fetch', fetcher);+ const tracking = await import('./tracking'), pending = tracking.trackMotion('ui_click', click);+ await vi.advanceTimersByTimeAsync(500);+ tracking.setMotionTrackingEnabled(false);+ expect(await pending).toBe('disabled');+ await vi.advanceTimersByTimeAsync(60_000);+ expect(await tracking.trackMotion('ui_click', click)).toBe('disabled');+ expect(fetcher).toHaveBeenCalledTimes(1);+ expect(tracking.getMotionTrackingStatus()).toEqual({ configuration: 'disabled', enabled: false, pending: 0, retryAfterMs: 0 });+});++it('does not retry a server opt-out and allows a confirmed preference change to re-enable', async () => {+ const fetcher = vi.fn(async () => Response.json({ enabled: false })); vi.stubGlobal('fetch', fetcher);+ const tracking = await import('./tracking');+ expect(await tracking.trackMotion('ui_click', click)).toBe('disabled');+ await vi.advanceTimersByTimeAsync(60_000);+ expect(await tracking.trackMotion('ui_click', click)).toBe('disabled');+ expect(fetcher).toHaveBeenCalledTimes(1);+ tracking.setMotionTrackingEnabled(true);+ expect(await tracking.trackMotion('ui_click', click)).toBe('queued');+ await tracking.flushMotionTracking();+ expect(await tracking.trackMotion('ui_click', click)).toBe('disabled');+});++it('exposes safe queue and delivery statuses while rejecting private or non-Studio payloads', async () => {+ let failing = true;+ const fetcher = vi.fn(async (_url, init?: RequestInit) => init?.method === 'POST' && failing+ ? new Response('', { status: 503 }) : Response.json({ enabled: true }));+ vi.stubGlobal('fetch', fetcher);+ const tracking = await import('./tracking');+ expect(await tracking.trackMotion('ui_click', { ...click, prompt: 'PRIVATE_CONTENT' } as any)).toBe('invalid');+ expect(await tracking.trackMotion('mcp_tool_started' as any, {+ tool_name: 'motion_get_project', call_id: crypto.randomUUID(), accepted: true,+ } as any)).toBe('invalid');+ for (let i = 0; i < 64; i++) expect(await tracking.trackMotion('ui_click', click)).toBe('queued');+ expect(await tracking.trackMotion('ui_click', click)).toBe('full');+ expect(await tracking.flushMotionTracking()).toBe('retry');+ failing = false;+ expect(await tracking.flushMotionTracking()).toBe('accepted');+ expect(JSON.parse(fetcher.mock.calls[1][1]!.body as string)).toEqual(JSON.parse(fetcher.mock.calls[2][1]!.body as string));+ expect(JSON.stringify(tracking.getMotionTrackingStatus())).not.toMatch(/PRIVATE|prompt|properties/);+ tracking.setMotionTrackingEnabled(false);+ expect(await tracking.flushMotionTracking()).toBe('disabled');+ expect(tracking.getMotionTrackingStatus().pending).toBe(0);+});diff --git a/studio/src/motion/tracking.ts b/studio/src/motion/tracking.tsindex 4b88f70b..43a34435 100644--- a/studio/src/motion/tracking.ts+++ b/studio/src/motion/tracking.ts@@ -1,24 +1,63 @@import { createBrowserTracking } from '../../../tracking/browser.ts';-import { omEvents } from '../../../tracking/events.ts';+import { studioEvents } from '../../../tracking/events.ts';+import type { StudioEvent } from '../../../tracking/events.ts';import type { EventFields } from '../../../tracking/core.ts';-const tracking = createBrowserTracking({ registry: omEvents, endpoint: '/motion-api/tracking', enabled: false });+const tracking = createBrowserTracking({ registry: studioEvents, endpoint: '/motion-api/tracking', enabled: false,+ isEnabled: () => navigator.doNotTrack !== '1' });let initialization: Promise<void> | undefined;-let preference: boolean | undefined;+let configuration: 'uninitialized' | 'loading' | 'ready' | 'disabled' | 'unavailable' = 'uninitialized';+let controller: AbortController | undefined;+let retryAt = 0;++function retryDelay(ms: number, signal: AbortSignal) {+ return new Promise<void>(resolve => {+ const finish = () => { clearTimeout(timer); signal.removeEventListener('abort', finish); resolve(); };+ const timer = setTimeout(finish, ms);+ signal.addEventListener('abort', finish, { once: true });+ if (signal.aborted) finish();+ });+}export function initializeTracking() {- initialization ??= fetch('/motion-api/tracking', { signal: AbortSignal.timeout(1000) }).then(async response => {- if (!response.ok) return;- const config = await response.json();- tracking.setEnabled((preference ?? config.enabled === true) && navigator.doNotTrack !== '1');- }).catch(() => {});+ if (configuration === 'disabled' || configuration === 'ready' || navigator.doNotTrack === '1') return Promise.resolve();+ if (initialization) return initialization;+ if (Date.now() < retryAt) return Promise.resolve();+ const request = new AbortController(); controller = request; configuration = 'loading';+ initialization = (async () => {+ for (let attempt = 0; attempt < 3 && !request.signal.aborted; attempt++) {+ try {+ const response = await fetch('/motion-api/tracking', {+ redirect: 'error', signal: AbortSignal.any([request.signal, AbortSignal.timeout(1000)]),+ });+ if (!response.ok) throw new Error('CONFIG_UNAVAILABLE');+ const config: unknown = await response.json();+ if (!config || typeof config !== 'object' || !('enabled' in config) || typeof config.enabled !== 'boolean') throw new Error('INVALID_CONFIG');+ if (request.signal.aborted) return;+ tracking.setEnabled(config.enabled);+ configuration = config.enabled ? 'ready' : 'disabled'; retryAt = 0;+ return;+ } catch {+ if (request.signal.aborted) return;+ if (attempt < 2) await retryDelay(1000 * 2 ** attempt, request.signal);+ }+ }+ if (!request.signal.aborted) { configuration = 'unavailable'; retryAt = Date.now() + 30_000; }+ })().finally(() => { initialization = undefined; if (controller === request) controller = undefined; });return initialization;}-export async function trackMotion<E extends keyof typeof omEvents>(event: E, properties: EventFields<typeof omEvents[E]>) {+export async function trackMotion<E extends StudioEvent>(event: E, properties: EventFields<typeof studioEvents[E]>) {await initializeTracking();- tracking.track(event, properties);+ if (configuration === 'unavailable' && navigator.doNotTrack !== '1') return 'config_unavailable' as const;+ return tracking.track(event, properties);+}+export function getMotionTrackingStatus() {+ return { configuration, enabled: tracking.enabled(), pending: tracking.pending(), retryAfterMs: Math.max(0, retryAt - Date.now()) };}export function flushMotionTracking() { return tracking.flush(); }-export function setMotionTrackingEnabled(enabled: boolean) { preference = enabled; tracking.setEnabled(enabled && navigator.doNotTrack !== '1'); }+export function setMotionTrackingEnabled(enabled: boolean) {+ controller?.abort(); retryAt = 0;+ tracking.setEnabled(enabled); configuration = enabled ? 'ready' : 'disabled';+}window.addEventListener('pagehide', () => { void tracking.flush(); });document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') void tracking.flush(); });diff --git a/tests/tracking-types.ts b/tests/tracking-types.tsnew file mode 100644index 00000000..8a1a3e8e--- /dev/null+++ b/tests/tracking-types.ts@@ -0,0 +1,13 @@+import { trackMotion } from '../studio/src/motion/tracking.ts';++// Compile-only calls: this function must never execute or emit events.+function studioContract() {+ void trackMotion('ui_click', { page_name: 'home', area: 'workspace', element: 'new_creation' });+ // @ts-expect-error Node-only events are not part of the Studio API.+ void trackMotion('mcp_tool_started', { tool_name: 'motion_get_project', call_id: '', accepted: true });+ // @ts-expect-error Required semantic fields remain required.+ void trackMotion('ui_click', { page_name: 'home' });+ // @ts-expect-error Enums remain closed.+ void trackMotion('ui_click', { page_name: 'private', area: 'workspace', element: 'new_creation' });+}+void studioContract;diff --git a/tests/tracking.test.ts b/tests/tracking.test.tsindex 41c5b04d..06f6d273 100644--- a/tests/tracking.test.ts+++ b/tests/tracking.test.ts@@ -2,6 +2,7 @@ import test from 'node:test';import assert from 'node:assert/strict';import { readFile, readdir, writeFile } from 'node:fs/promises';import path from 'node:path';+import { execFileSync } from 'node:child_process';import { createTracker, deviceContext } from '../tracking/core.ts';import { createPosthogSender, loadIdentity } from '../tracking/node.ts';import { omEvents } from '../tracking/events.ts';@@ -22,6 +23,13 @@ function packet(): PendingEvent {const core = (send: Parameters<typeof createTracker>[0]['send'], maxQueue = 64) =>createTracker({ registry: omEvents, entrypoint: 'mcp', enabled: true, flushIntervalMs: 0, maxQueue, send });+test('Studio event types reject Node-only events and invalid semantic fields', () => {+ execFileSync(process.execPath, [path.join(pluginRoot, 'node_modules/typescript/bin/tsc'),+ '--noEmit', '--strict', '--allowImportingTsExtensions', '--module', 'ESNext', '--moduleResolution', 'Bundler',+ '--target', 'ES2022', '--lib', 'ES2023,DOM', '--skipLibCheck', path.join(pluginRoot, 'tests/tracking-types.ts')],+ { cwd: pluginRoot, stdio: 'pipe' });+});+test('bounded queue rejects private properties, preserves UUID/time on retries and serializes flushes', async () => {const batches: PendingEvent[][] = []; let attempts = 0;const tracker = core(async events => { batches.push(structuredClone([...events])); return ++attempts === 1 ? 'retry' : 'accepted'; }, 2);@@ -104,6 +112,8 @@ test('browser ingress rejects forged identity, worker events and oversized batch{ events: [{ ...packet(), properties: { ...packet().properties, distinct_id: 'forged' } }] },{ events: [{ ...packet(), utm_source: 'forged' }] },{ events: [{ ...packet(), entrypoint: 'worker' }] },+ { events: [{ ...packet(), event: 'mcp_tool_started', properties: { tool_name: 'motion_get_project', call_id: crypto.randomUUID(), accepted: true } }] },+ { events: [{ ...packet(), event: 'export_result', properties: { job_id: crypto.randomUUID(), job_state: 'completed', duration_ms: 100, technical_check: 'passed' } }] },{ events: Array.from({ length: 17 }, packet) },{ events: [packet()], token: 'forged' },]) assert.equal((await send(data)).status, 400);diff --git a/tracking/INTEGRATION.md b/tracking/INTEGRATION.mdindex 175b0d44..0dc74742 100644--- a/tracking/INTEGRATION.md+++ b/tracking/INTEGRATION.md@@ -27,7 +27,8 @@ Add tracking for this OpenMotion behavior:Inspect the existing event registry, all callers and the actual completion path.Reuse an existing event if its meaning matches. Otherwise add its closed property-schema in tracking/events.ts; for Studio also update browserEvents there.+schema and producers in tracking/events.ts. Studio types and server admission are+derived from producers; do not maintain a separate browser event list.Use the existing trackMotion wrapper or injected OmTracking instance. Keep oneowner for each business result; do not duplicate MCP wrapper events.Do not add an SDK, direct browser-to-PostHog calls, a new identity or a capture key.@@ -56,7 +57,7 @@ the agent can determine file paths and existing helpers from code.| Committed phase-one business result | `phase1.ts` and `trackPhase1Result` in `shared/tracking.ts` | Use the shared domain completion. Replayed operations skip new domain completions. A successful call need not have made a useful edit. || Render/export terminal state | `renderNext` in `server.ts` | Emit from the worker's observed terminal state. A queued job is not a completed video. || Studio interaction or readiness | Components under `studio/src/motion/`, using `tracking.ts` there | Track an intentional handler or a guarded readiness/completion callback. Avoid unguarded render/effect reporting. |-| Browser admission | `browserEvents` in `tracking/events.ts`; ingress in `server.ts` | A Studio event needs both a schema and browser admission. Preserve rejection of identity, source, worker and credential overrides. |+| Browser admission | `producers` in `tracking/events.ts`; derived `studioEvents`; ingress in `server.ts` | Declare `producers: ['studio']` on the event. The wrapper's types and server validator use the derived registry. Preserve server-side rejection of identity, source, worker and credential overrides. |`ui_click` already describes a fixed page/area/element tuple. Reuse it for matchingintent and extend only its necessary enum values. Use a result event for persisted@@ -75,6 +76,7 @@ Add the entry inside `omEvents` in `tracking/events.ts`:```tsstudio_save_result: {+ producers: ['studio'],fields: {outcome: ['success', 'failure'],changed_file_count: 'integer',@@ -84,9 +86,13 @@ studio_save_result: {},```-Append `'studio_save_result'` to `browserEvents` in the same file. Keep the registry's-`as const satisfies Registry` declaration. The registry supplies both TypeScript-types and runtime validation; unknown properties are rejected, not silently removed.+Keep the registry's existing `as const satisfies` declaration. Register the actual+producer (`studio`, `mcp` or `worker`) on the event; only include `studio` for an+event that browsers may submit. The registry supplies both TypeScript types and+runtime validation; unknown properties are rejected, not silently removed. A new+Studio event automatically enters `studioEvents` without another list edit.+This metadata controls Studio exposure and admission; Node's tracker still owns+the domain/worker call sites and entrypoint mapping.In the owning Studio component, import the existing wrapper using the correctrelative path. For a component directly in `studio/src/motion/`:@@ -131,7 +137,7 @@ function reportRestore(tracking: OmTracking | undefined, projectId: string) {Reuse an existing tracker; do not create an identity/tracker per interaction. In anew process only, follow `createAppTracking`/`closeTracking` lifecycle wiring. Do notawait delivery in a business operation. `track()` returning `queued` means local-acceptance; `trackMotion()` resolves without an ingestion receipt. Neither proves+acceptance; `trackMotion()` resolves with a local queue/configuration status. Neither provesthat the event is queryable in PostHog. Normal calls do not need an explicit flush.Current field rules are closed enums, booleans, UUIDv4 values, safe-code strings or@@ -167,14 +173,59 @@ collection for the installation, including MCP and Studio across restarts.`OPENMOTION_TELEMETRY=0` or `DO_NOT_TRACK=1` forces it off; browser Do Not Track alsosuppresses browser collection. An added event must respect those controls.+## Diagnose without logging event contents++Normal component calls remain `void trackMotion(...)`. Tests or a local debugger+can inspect the returned status without changing feature behavior:++```ts+const status = await trackMotion('ui_click', {+ page_name: 'home', area: 'workspace', element: 'new_creation',+});+// queued | invalid | full | duplicate | disabled | config_unavailable+```++`queued` means browser-local acceptance, not service or PostHog ingestion.+`invalid` means schema rejection; `full` means the bounded browser queue is full.+`disabled` covers policy/preference controls and a service opt-out response.+`config_unavailable` means configuration could not be confirmed; the event is+not queued. Do not retry a business operation because its tracking failed.++Studio shares one in-flight configuration load across callers. Each request has+a one-second timeout. Transient HTTP/network/JSON/shape failures get at most+three attempts, with one- and two-second delays. Collection stays off until a+valid boolean configuration arrives. After exhaustion, calls return+`config_unavailable` for 30 seconds; the next call after that cooldown starts a+new attempt group. Events rejected during the cooldown are not replayed. There+is no permanent background polling. A valid `enabled: false` is not a transient+failure and does not trigger retries. Opt-out aborts pending configuration work,+cancels retry delays and clears queued events; a late response cannot re-enable it.+`setMotionTrackingEnabled(true)` is for the existing control after the service+confirms the preference change, not a bypass around initialization or policy.++For a snapshot, import `getMotionTrackingStatus` from the same Studio wrapper.+It exposes only `configuration` (`uninitialized`, `loading`, `ready`, `disabled`+or `unavailable`), effective `enabled`, `pending` count and `retryAfterMs`.+Browser Do Not Track can keep effective `enabled` false even with a ready+configuration. No event properties, identity, tokens or raw errors are exposed.++`flushMotionTracking()` returns `accepted`, `retry`, `drop`, `disabled` or `empty`.+This describes the browser-to-local-service boundary; `accepted` does not prove+downstream PostHog ingestion. The existing core/Node tracker similarly returns+local queue statuses from `track()` and transport receipts from `flush()`.+Use fake senders/fetch in tests and assert these results; do not enable raw+payload logging or build assertions around production data.+## Verify meaning before checking ingestionExtend the existing tests nearest the changed boundary:- `tests/tracking.test.ts`: schema/privacy, local ingress, domain completion, replay,- export terminal state and installation-wide opt-out.+ export terminal state and installation-wide opt-out. It also compiles+ `tests/tracking-types.ts` to check Studio-only event exposure and field types.- `studio/src/motion/tracking.test.ts`: browser sender, common-field isolation and- browser opt-out. Also test the owning component's real completion/handler so a+ browser opt-out, bounded configuration recovery and safe diagnostic statuses.+ Also test the owning component's real completion/handler so amissing call site cannot pass on schema tests alone.- `tests/source-install.test.ts`, `tests/package.test.ts` and`tests/npm-package.test.ts`: public boundary and distributed content when affected.diff --git a/tracking/README.md b/tracking/README.mdindex 1ea8ff08..0967351d 100644--- a/tracking/README.md+++ b/tracking/README.md@@ -50,6 +50,14 @@ to PostHog `/batch/`. Browser Do Not Track suppresses browser collection. Networreporting is asynchronous, with a bounded timeout; local business results never waitfor PostHog. A collector receipt confirms acceptance, not queryable ingestion.+Event `producers` and closed property schemas live together in `events.ts`.+Studio's typed API and the service's browser-admission registry are derived from+that definition; server-side validation remains mandatory. Studio configuration+loading retries transient failures with bounded backoff, stays disabled until+confirmed, and never treats a valid opt-out as a retryable failure. Callers can+inspect local queue/configuration statuses and a content-free status snapshot;+see [diagnostics and retry semantics](INTEGRATION.md#diagnose-without-logging-event-contents).+## Identity, properties and privacyOne random UUID is persisted atomically in `tracking/identity.json` under the owneddiff --git a/tracking/browser.ts b/tracking/browser.tsindex 36f5f066..31a3504f 100644--- a/tracking/browser.ts+++ b/tracking/browser.ts@@ -1,6 +1,6 @@import { createTracker } from './core.ts';import type { Registry } from './core.ts';-export function createBrowserTracking<const R extends Registry>(options: { endpoint: string; registry: R; enabled: boolean; flushIntervalMs?: number }) {+export function createBrowserTracking<const R extends Registry>(options: { endpoint: string; registry: R; enabled: boolean; flushIntervalMs?: number; isEnabled?: () => boolean }) {const endpoint = new URL(options.endpoint, window.location.href);if (endpoint.origin !== window.location.origin || endpoint.username || endpoint.password) throw new Error('SAME_ORIGIN_REQUIRED');const tracking = createTracker({ ...options, entrypoint: 'studio', send: async (events, signal) => {diff --git a/tracking/events.ts b/tracking/events.tsindex 34cf74bb..b2ec8f2f 100644--- a/tracking/events.ts+++ b/tracking/events.ts@@ -1,4 +1,4 @@-import type { Registry } from './core.ts';+import type { Entry, Registry } from './core.ts';export const toolNames = ['motion_list_templates', 'motion_get_template', 'motion_create_project', 'motion_open_preview','motion_import_assets', 'motion_get_project', 'motion_edit_project', 'motion_export_request', 'motion_list_versions',@@ -8,21 +8,25 @@ const tool = { tool_name: toolNames, call_id: 'uuid', operation_id: 'uuid', acceconst business = { outcome, project_id: 'uuid', operation_id: 'uuid', replayed: 'boolean', error_code: 'code' } as const;export const omEvents = {- mcp_tool_started: { fields: tool, required: ['tool_name', 'call_id', 'accepted'] },- mcp_tool_finished: { fields: { ...tool, outcome, duration_ms: 'integer', error_code: 'code', replayed: 'boolean' },+ mcp_tool_started: { producers: ['mcp'], fields: tool, required: ['tool_name', 'call_id', 'accepted'] },+ mcp_tool_finished: { producers: ['mcp'], fields: { ...tool, outcome, duration_ms: 'integer', error_code: 'code', replayed: 'boolean' },required: ['tool_name', 'call_id', 'accepted', 'outcome', 'duration_ms'] },- project_create_result: { fields: { ...business, creation_route: ['natural_language', 'template', 'existing_project'], effect_status: ['applied', 'not_applied', 'unknown'] }, required: ['outcome'] },- project_open_result: { fields: { ...business, opened_by_host_status: ['unknown', 'opened', 'not_opened'] }, required: ['outcome'] },- project_edit_result: { fields: { ...business, changed_file_count: 'integer' }, required: ['outcome'] },- version_restore_result: { fields: business, required: ['outcome'] },- asset_import_result: { fields: { ...business, requested_count: 'integer', added_count: 'integer', reused_count: 'integer', failed_count: 'integer' }, required: ['outcome'] },- export_request_result: { fields: { ...business, job_id: 'uuid', queue_state: ['pending', 'running', 'cancelling', 'cancelled', 'completed', 'failed'] }, required: ['outcome'] },- export_cancel_result: { fields: { ...business, job_id: 'uuid', state_after: ['pending', 'running', 'cancelling', 'cancelled', 'completed', 'failed'] }, required: ['outcome'] },- export_result: { fields: { job_id: 'uuid', job_state: ['completed', 'failed', 'cancelled'], duration_ms: 'integer', technical_check: ['passed', 'failed', 'unknown'] }, required: ['job_id', 'job_state', 'duration_ms', 'technical_check'] },- page_view: { fields: { page_name: ['home', 'studio'], view_id: 'uuid', embedded: 'boolean', has_project: 'boolean' }, required: ['page_name', 'view_id', 'embedded', 'has_project'] },- studio_load_result: { fields: { load_id: 'uuid', outcome, duration_ms: 'integer', embedded: 'boolean' }, required: ['load_id', 'outcome', 'duration_ms', 'embedded'] },- ui_click: { fields: { page_name: ['home', 'studio'], area: ['workspace', 'templates'], element: ['new_creation', 'recent_session', 'select_template', 'copy_template'], interaction_method: ['pointer', 'keyboard'] }, required: ['page_name', 'area', 'element'] },- template_instruction_copy_result: { fields: { host_product: ['codex', 'claude', 'deepseek', 'chatgpt', 'mcp'], copy_status: ['clipboard_written', 'manual_fallback_shown', 'failed'] }, required: ['host_product', 'copy_status'] },-} as const satisfies Registry;+ project_create_result: { producers: ['mcp'], fields: { ...business, creation_route: ['natural_language', 'template', 'existing_project'], effect_status: ['applied', 'not_applied', 'unknown'] }, required: ['outcome'] },+ project_open_result: { producers: ['mcp'], fields: { ...business, opened_by_host_status: ['unknown', 'opened', 'not_opened'] }, required: ['outcome'] },+ project_edit_result: { producers: ['mcp'], fields: { ...business, changed_file_count: 'integer' }, required: ['outcome'] },+ version_restore_result: { producers: ['mcp'], fields: business, required: ['outcome'] },+ asset_import_result: { producers: ['mcp'], fields: { ...business, requested_count: 'integer', added_count: 'integer', reused_count: 'integer', failed_count: 'integer' }, required: ['outcome'] },+ export_request_result: { producers: ['mcp'], fields: { ...business, job_id: 'uuid', queue_state: ['pending', 'running', 'cancelling', 'cancelled', 'completed', 'failed'] }, required: ['outcome'] },+ export_cancel_result: { producers: ['mcp'], fields: { ...business, job_id: 'uuid', state_after: ['pending', 'running', 'cancelling', 'cancelled', 'completed', 'failed'] }, required: ['outcome'] },+ export_result: { producers: ['worker'], fields: { job_id: 'uuid', job_state: ['completed', 'failed', 'cancelled'], duration_ms: 'integer', technical_check: ['passed', 'failed', 'unknown'] }, required: ['job_id', 'job_state', 'duration_ms', 'technical_check'] },+ page_view: { producers: ['studio'], fields: { page_name: ['home', 'studio'], view_id: 'uuid', embedded: 'boolean', has_project: 'boolean' }, required: ['page_name', 'view_id', 'embedded', 'has_project'] },+ studio_load_result: { producers: ['studio'], fields: { load_id: 'uuid', outcome, duration_ms: 'integer', embedded: 'boolean' }, required: ['load_id', 'outcome', 'duration_ms', 'embedded'] },+ ui_click: { producers: ['studio'], fields: { page_name: ['home', 'studio'], area: ['workspace', 'templates'], element: ['new_creation', 'recent_session', 'select_template', 'copy_template'], interaction_method: ['pointer', 'keyboard'] }, required: ['page_name', 'area', 'element'] },+ template_instruction_copy_result: { producers: ['studio'], fields: { host_product: ['codex', 'claude', 'deepseek', 'chatgpt', 'mcp'], copy_status: ['clipboard_written', 'manual_fallback_shown', 'failed'] }, required: ['host_product', 'copy_status'] },+} as const satisfies Registry & Record<string, { producers: readonly Entry[] }>;-export const browserEvents = ['page_view', 'studio_load_result', 'ui_click', 'template_instruction_copy_result'] as const;+export type StudioEvent = { [E in keyof typeof omEvents]:+ 'studio' extends typeof omEvents[E]['producers'][number] ? E : never+}[keyof typeof omEvents];+export const studioEvents = Object.fromEntries(Object.entries(omEvents)+ .filter(([, spec]) => (spec.producers as readonly Entry[]).includes('studio'))) as Pick<typeof omEvents, StudioEvent>;