Skip to content

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.

feat(tracking): enable collection by default with persistent opt-out and coarse GeoIP

罗高73960818ed78
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a1602995..39014b99 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -38,6 +38,7 @@ jobs:
run:
shell: bash
env:
+ OPENMOTION_TELEMETRY: '0'
HYPERFRAMES_BROWSER_PATH: /usr/bin/chromium
HYPERFRAMES_FFMPEG_PATH: /usr/bin/ffmpeg
HYPERFRAMES_FFPROBE_PATH: /usr/bin/ffprobe
diff --git a/README.md b/README.md
index 92532b08..0ee8a3e3 100644
--- a/README.md
+++ b/README.md
@@ -82,6 +82,10 @@ The [lightweight npm installer](docs/npm-installation.md) installs eleven MCP To
The five entries are [motion-production](skills/motion-production/SKILL.md), [motion-director](skills/motion-director/SKILL.md), [motion-template-to-video](skills/motion-template-to-video/SKILL.md), [motion-recreate](skills/motion-recreate/SKILL.md), and [motion-video-to-template](skills/motion-video-to-template/SKILL.md). Reference recreation is implemented. Product UI follows the [OpenDesign visual system](docs/design-system.md); video artwork keeps its own styles.
+## Usage data and privacy
+
+OpenMotion collects feature usage, safe error categories, device information and coarse country/region/timezone by default. Prompts and project contents are excluded; raw IP addresses are discarded after GeoIP enrichment. Turn collection off in **Privacy settings → Share usage data**, or set `OPENMOTION_TELEMETRY=0` / `DO_NOT_TRACK=1` when launching the MCP. The saved preference covers MCP and Studio and survives restarts. See [tracking and user controls](tracking/README.md).
+
## What's next
**Motion Benchmark / Arena** is a proposed way to compare recreations: give each workflow the same reference and brand assets, then inspect the outputs for timing, brand fidelity and editability. The method and public leaderboard are still under discussion.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index af56dfbd..128374b6 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -3,3 +3,5 @@
完整中文介绍已移至 [中文项目首页](docs/README.zh-CN.md)。
[English](README.md) · [安装与首次体验](docs/usage.md) · [Motion MD](docs/motion-md.zh-CN.md) · [贡献流程](CONTRIBUTING.zh-CN.md)
+
+默认采集功能使用情况、受控错误类别、设备信息和大致国家/地区及时区;不会发送提示词或工程内容,GeoIP 解析后丢弃原始 IP。可在工作室「隐私设置 → 分享使用数据」关闭,或在启动 MCP 时设置 `OPENMOTION_TELEMETRY=0` / `DO_NOT_TRACK=1`。关闭设置同时作用于 MCP 和 Studio,重启后保留。详见[追踪与用户控制](tracking/README.md)。
diff --git a/docs/product/architecture.md b/docs/product/architecture.md
index 198da0f5..c4458300 100644
--- a/docs/product/architecture.md
+++ b/docs/product/architecture.md
@@ -163,7 +163,7 @@ flowchart LR
当前交付标准:连接可验证、模板可定位、工程可继续编辑、预览与源文件一致、导出存在真实文件、检查结果有证据。相关实现由 `tests/`、`npm run test:studio` 的原生单元/DOM 与宿主回归、类型检查、设计检查和按需浏览器验证覆盖;没有执行的检查不能记为通过。
-The runtime now includes an opt-in, explicit-event tracking package shared by MCP and Studio. Studio submits allowlisted events to the local service; Node enriches them with a persisted random installation identity before asynchronous PostHog ingestion. The implementation covers tool results, selected domain operations and selected Studio interactions. It does not establish a product analytics baseline or implement every proposed event. See [tracking configuration, privacy and coverage](../../tracking/README.md).
+The runtime includes a default-on, explicit-event tracking package shared by MCP and Studio. A persistent user preference and environment overrides can disable collection for the whole installation. Studio submits allowlisted events to the local service; Node adds a random installation identity before asynchronous ingestion into the isolated OpenMotion PostHog project. That project enriches coarse country/region/timezone and then discards raw IP addresses. The implementation covers tool results, selected domain operations and selected Studio interactions; it does not establish a product analytics baseline or implement every proposed event. See [tracking configuration, privacy and coverage](../../tracking/README.md).
The following product measures still require agreed observation windows and validated evidence:
diff --git a/mcp.ts b/mcp.ts
index 54dbcbd1..a8c8af9d 100644
--- a/mcp.ts
+++ b/mcp.ts
@@ -93,6 +93,7 @@ async function invokeRpc(message: any, store: WorkspaceStore, registry: ReturnTy
}
if (isMain(import.meta.url)) {
const store = new WorkspaceStore();
+ if ((await trackingFor(store)).enabled()) process.stderr.write('OpenMotion shares usage data and coarse region. Disable in Studio Privacy settings or set OPENMOTION_TELEMETRY=0.\n');
const connection = sharedEditorEnabled ? { selection: {} } : undefined;
const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
for await (const line of lines) {
diff --git a/scripts/distribution.ts b/scripts/distribution.ts
index b092c700..c89d354f 100644
--- a/scripts/distribution.ts
+++ b/scripts/distribution.ts
@@ -8,7 +8,7 @@ const root = fileURLToPath(new URL('../', import.meta.url));
// New documentation and developer scripts require an explicit distribution decision.
export const distributionDocuments = [
'README.md', 'README.zh-CN.md', 'CONTRIBUTING.md', 'CONTRIBUTING.zh-CN.md', 'AGENTS.md', 'CLAUDE.md', 'docs/README.md',
- 'docs/product/architecture.md', 'docs/product/media-generation-design.md', 'tracking/README.md',
+ 'docs/product/architecture.md', 'docs/product/media-generation-design.md', 'tracking/README.md', 'tracking/posthog-geoip.hog',
'docs/agent-adapters.md', 'docs/browser-runtime.md', 'docs/design-system.md', 'docs/editor-fork.md',
'docs/hyperframes.md', 'docs/mcp-phase1-tools.md', 'docs/model-gateway.md', 'docs/motion-director.md',
'docs/motion-extension-scope.md', 'docs/npm-installation.md', 'docs/project-workspace.md',
diff --git a/server.ts b/server.ts
index 7764953f..27b5d4da 100644
--- a/server.ts
+++ b/server.ts
@@ -24,7 +24,7 @@ import { WorkspaceBrowser } from './browser.ts';
import { Phase1Service } from './phase1.ts';
import { recoverProjectTransactions } from './phase1-versions.ts';
import { verifyExport } from './scripts/verify-export.ts';
-import { createAppTracking, closeTracking, type OmTracking } from './shared/tracking.ts';
+import { createAppTracking, closeTracking, saveTrackingPreference, trackingPreference, trackingLocked, type OmTracking } from './shared/tracking.ts';
import { browserEvents } from './tracking/events.ts';
import { validPending } from './tracking/core.ts';
import { omEvents } from './tracking/events.ts';
@@ -251,9 +251,19 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =
}
if (motionRequest) url.pathname = url.pathname.replace(/^\/(?:motion|design)-api\//, '/api/');
const editorUrl = `http://${host || 'localhost'}/#project/${store.projectId}`;
+ if (motionRequest && url.pathname === '/api/tracking/preferences' && ['GET', 'PUT'].includes(req.method!)) {
+ const directory = (store.workspaceStore ?? store).directory;
+ if (req.method === 'PUT') {
+ if (trackingLocked()) return json(res, 403, { error: 'TRACKING_DISABLED_BY_ENVIRONMENT' });
+ const data = await input(req, 1024);
+ if (!data || Object.keys(data).length !== 1 || typeof data.enabled !== 'boolean') return json(res, 400, { error: 'INVALID_TRACKING_PREFERENCE' });
+ await saveTrackingPreference(directory, data.enabled);
+ }
+ return json(res, 200, { enabled: context.tracking?.enabled() ?? false, preference: trackingPreference(directory), locked: trackingLocked() });
+ }
if (motionRequest && url.pathname === '/api/tracking' && req.method === 'GET') return json(res, 200, { enabled: context.tracking?.enabled() ?? false });
if (motionRequest && url.pathname === '/api/tracking' && req.method === 'POST') {
- if (!context.tracking?.enabled()) return json(res, 200, { accepted: 0 });
+ 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'
diff --git a/shared/tracking-config.json b/shared/tracking-config.json
new file mode 100644
index 00000000..d9e40f8f
--- /dev/null
+++ b/shared/tracking-config.json
@@ -0,0 +1,6 @@
+{
+ "projectId": 722078,
+ "host": "https://us.i.posthog.com",
+ "token": "phc_km8e76b2uwbAEEZ8wF3pmxSQ9b5s9izFsaZsktie3Qsq",
+ "geoip": true
+}
diff --git a/shared/tracking.ts b/shared/tracking.ts
index f34ff31c..9c173d90 100644
--- a/shared/tracking.ts
+++ b/shared/tracking.ts
@@ -1,4 +1,6 @@
import path from 'node:path';
+import { readFileSync, watch } from 'node:fs';
+import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
import { createTracker, uuid } from '../tracking/core.ts';
import type { Entry } from '../tracking/core.ts';
import { createNodeTracking, loadIdentity } from '../tracking/node.ts';
@@ -6,18 +8,45 @@ import { omEvents } from '../tracking/events.ts';
import { VERSION } from '../preview.ts';
export type OmTracking = ReturnType<typeof createTracker<typeof omEvents>>;
+export function trackingLocked() {
+ return ['0', 'false', 'off'].includes(process.env.OPENMOTION_TELEMETRY?.toLowerCase() ?? '') || process.env.DO_NOT_TRACK === '1';
+}
+export function trackingPreference(directory: string): boolean {
+ try { return JSON.parse(readFileSync(path.join(directory, 'tracking/preferences.json'), 'utf8')).enabled === true; }
+ catch (error) { return (error as NodeJS.ErrnoException).code === 'ENOENT'; }
+}
+export async function saveTrackingPreference(directory: string, enabled: boolean) {
+ const folder = path.join(directory, 'tracking'); await mkdir(folder, { recursive: true, mode: 0o700 });
+ const temporary = path.join(folder, 'preferences.' + crypto.randomUUID() + '.tmp');
+ try {
+ await writeFile(temporary, JSON.stringify({ enabled }), { mode: 0o600, flag: 'wx' });
+ await rename(temporary, path.join(folder, 'preferences.json'));
+ } finally { await rm(temporary, { force: true }); }
+}
export async function createAppTracking(directory: string, entrypoint: Entry): Promise<OmTracking> {
const disabled = () => createTracker({ registry: omEvents, entrypoint, enabled: false, send: async () => 'drop' });
- if (process.env.OPENMOTION_TELEMETRY !== '1' || process.env.DO_NOT_TRACK === '1'
- || !process.env.OPENMOTION_POSTHOG_KEY || !process.env.OPENMOTION_POSTHOG_HOST) return disabled();
+ if (trackingLocked()) return disabled();
try {
- const env = process.env.OPENMOTION_TRACKING_ENV ?? 'production';
+ const testing = Boolean(process.env.NODE_TEST_CONTEXT) || process.env.NODE_ENV === 'test';
+ if (testing && !process.env.OPENMOTION_TRACKING_TEST_RUN_ID) return disabled();
+ const env = process.env.OPENMOTION_TRACKING_ENV ?? (testing ? 'test' : 'production');
if (!['development', 'test', 'production'].includes(env)) return disabled();
- return createNodeTracking({ registry: omEvents, entrypoint, enabled: true,
+ const custom = process.env.OPENMOTION_POSTHOG_HOST !== undefined || process.env.OPENMOTION_POSTHOG_KEY !== undefined;
+ // Public write-only configuration only; malformed/missing configuration disables telemetry, not the application.
+ const config = custom ? { host: process.env.OPENMOTION_POSTHOG_HOST, token: process.env.OPENMOTION_POSTHOG_KEY,
+ geoip: process.env.OPENMOTION_GEOIP === '1' } : JSON.parse(readFileSync(new URL('./tracking-config.json', import.meta.url), 'utf8'));
+ if (!config.host || !config.token) return disabled();
+ const tracking = createNodeTracking({ registry: omEvents, entrypoint, enabled: true,
identity: await loadIdentity(path.join(directory, 'tracking')), appVersion: VERSION,
- host: process.env.OPENMOTION_POSTHOG_HOST, token: process.env.OPENMOTION_POSTHOG_KEY,
+ host: config.host, token: config.token, geoip: config.geoip,
+ isEnabled: () => !trackingLocked() && trackingPreference(directory),
env: env as 'development' | 'test' | 'production', testRunId: process.env.OPENMOTION_TRACKING_TEST_RUN_ID });
+ const changes = watch(path.join(directory, 'tracking'), { persistent: false }, () => { tracking.enabled(); });
+ changes.on('error', () => tracking.setEnabled(false));
+ const close = tracking.close;
+ tracking.close = () => { changes.close(); close(); };
+ return tracking;
} catch { return disabled(); }
}
diff --git a/studio/src/i18n/de.json b/studio/src/i18n/de.json
index bc80dbdb..e635c31a 100644
--- a/studio/src/i18n/de.json
+++ b/studio/src/i18n/de.json
@@ -1753,5 +1753,12 @@
"Get the template catalogue and local index.": "Vorlagenkatalog und lokalen Index abrufen.",
"Read the details and files for one template.": "Details und Dateien einer Vorlage lesen.",
"Template cache unavailable; downloading again": "Vorlagencache nicht verfügbar; erneuter Download",
- "Template update failed; using cached catalogue: {message}": "Vorlagenaktualisierung fehlgeschlagen; zwischengespeicherter Katalog wird verwendet: {message}"
+ "Template update failed; using cached catalogue: {message}": "Vorlagenaktualisierung fehlgeschlagen; zwischengespeicherter Katalog wird verwendet: {message}",
+ "Privacy settings": "Datenschutzeinstellungen",
+ "Share usage data": "Nutzungsdaten teilen",
+ "Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "Funktionsnutzung, Fehlerkategorien und ungefähre Region zur Verbesserung von OpenMotion senden. Prompts und Projektinhalte sind ausgeschlossen.",
+ "This setting applies to MCP and Studio on this installation and is kept after restart.": "Diese Einstellung gilt für MCP und Studio dieser Installation und bleibt nach einem Neustart erhalten.",
+ "Disabled by your environment settings.": "Durch Ihre Umgebungseinstellungen deaktiviert.",
+ "Could not load privacy settings.": "Datenschutzeinstellungen konnten nicht geladen werden.",
+ "Could not save privacy settings.": "Datenschutzeinstellungen konnten nicht gespeichert werden."
}
diff --git a/studio/src/i18n/es.json b/studio/src/i18n/es.json
index 22f16b51..da7627ce 100644
--- a/studio/src/i18n/es.json
+++ b/studio/src/i18n/es.json
@@ -1753,5 +1753,12 @@
"Get the template catalogue and local index.": "Obtener el catálogo de plantillas y el índice local.",
"Read the details and files for one template.": "Leer los detalles y archivos de una plantilla.",
"Template cache unavailable; downloading again": "Caché de plantillas no disponible; descargando de nuevo",
- "Template update failed; using cached catalogue: {message}": "Error al actualizar las plantillas; se usa el catálogo en caché: {message}"
+ "Template update failed; using cached catalogue: {message}": "Error al actualizar las plantillas; se usa el catálogo en caché: {message}",
+ "Privacy settings": "Configuración de privacidad",
+ "Share usage data": "Compartir datos de uso",
+ "Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "Enviar el uso de funciones, categorías de errores y región aproximada para mejorar OpenMotion. Se excluyen los prompts y el contenido de los proyectos.",
+ "This setting applies to MCP and Studio on this installation and is kept after restart.": "Este ajuste se aplica a MCP y Studio de esta instalación y se conserva tras reiniciar.",
+ "Disabled by your environment settings.": "Desactivado por la configuración del entorno.",
+ "Could not load privacy settings.": "No se pudo cargar la configuración de privacidad.",
+ "Could not save privacy settings.": "No se pudo guardar la configuración de privacidad."
}
diff --git a/studio/src/i18n/fr.json b/studio/src/i18n/fr.json
index c752a113..93ed1d71 100644
--- a/studio/src/i18n/fr.json
+++ b/studio/src/i18n/fr.json
@@ -1753,5 +1753,12 @@
"Get the template catalogue and local index.": "Obtenir le catalogue de modèles et son index local.",
"Read the details and files for one template.": "Lire les détails et les fichiers d’un modèle.",
"Template cache unavailable; downloading again": "Cache des modèles indisponible ; nouveau téléchargement",
- "Template update failed; using cached catalogue: {message}": "Échec de la mise à jour des modèles ; utilisation du catalogue en cache : {message}"
+ "Template update failed; using cached catalogue: {message}": "Échec de la mise à jour des modèles ; utilisation du catalogue en cache : {message}",
+ "Privacy settings": "Paramètres de confidentialité",
+ "Share usage data": "Partager les données d’utilisation",
+ "Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "Envoyer l’utilisation des fonctions, les catégories d’erreurs et la région approximative pour améliorer OpenMotion. Les prompts et le contenu des projets sont exclus.",
+ "This setting applies to MCP and Studio on this installation and is kept after restart.": "Ce réglage s’applique à MCP et Studio pour cette installation et reste enregistré après un redémarrage.",
+ "Disabled by your environment settings.": "Désactivé par vos paramètres d’environnement.",
+ "Could not load privacy settings.": "Impossible de charger les paramètres de confidentialité.",
+ "Could not save privacy settings.": "Impossible d’enregistrer les paramètres de confidentialité."
}
diff --git a/studio/src/i18n/it.json b/studio/src/i18n/it.json
index 840b729f..b85389a6 100644
--- a/studio/src/i18n/it.json
+++ b/studio/src/i18n/it.json
@@ -1753,5 +1753,12 @@
"Get the template catalogue and local index.": "Ottieni il catalogo dei modelli e l’indice locale.",
"Read the details and files for one template.": "Leggi i dettagli e i file di un modello.",
"Template cache unavailable; downloading again": "Cache dei modelli non disponibile; nuovo download",
- "Template update failed; using cached catalogue: {message}": "Aggiornamento dei modelli non riuscito; utilizzo del catalogo in cache: {message}"
+ "Template update failed; using cached catalogue: {message}": "Aggiornamento dei modelli non riuscito; utilizzo del catalogo in cache: {message}",
+ "Privacy settings": "Impostazioni privacy",
+ "Share usage data": "Condividi dati di utilizzo",
+ "Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "Invia l’utilizzo delle funzioni, le categorie di errore e la regione approssimativa per migliorare OpenMotion. I prompt e i contenuti dei progetti sono esclusi.",
+ "This setting applies to MCP and Studio on this installation and is kept after restart.": "Questa impostazione si applica a MCP e Studio di questa installazione e viene mantenuta dopo il riavvio.",
+ "Disabled by your environment settings.": "Disattivato dalle impostazioni dell’ambiente.",
+ "Could not load privacy settings.": "Impossibile caricare le impostazioni privacy.",
+ "Could not save privacy settings.": "Impossibile salvare le impostazioni privacy."
}
diff --git a/studio/src/i18n/ja.json b/studio/src/i18n/ja.json
index 7d3478eb..07a25472 100644
--- a/studio/src/i18n/ja.json
+++ b/studio/src/i18n/ja.json
@@ -1717,5 +1717,12 @@
"Get the template catalogue and local index.": "テンプレートカタログとローカルインデックスを取得します。",
"Read the details and files for one template.": "テンプレートの詳細とファイルを読み取ります。",
"Template cache unavailable; downloading again": "テンプレートのキャッシュを利用できません。再ダウンロードします",
- "Template update failed; using cached catalogue: {message}": "テンプレートの更新に失敗しました。キャッシュ済みのカタログを使用します:{message}"
+ "Template update failed; using cached catalogue: {message}": "テンプレートの更新に失敗しました。キャッシュ済みのカタログを使用します:{message}",
+ "Privacy settings": "プライバシー設定",
+ "Share usage data": "利用データを共有",
+ "Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "OpenMotion の改善のため、機能の利用状況、エラーの種類、おおよその地域を送信します。プロンプトやプロジェクト内容は送信しません。",
+ "This setting applies to MCP and Studio on this installation and is kept after restart.": "この設定は同じインストールの MCP と Studio に適用され、再起動後も保持されます。",
+ "Disabled by your environment settings.": "環境設定により無効になっています。",
+ "Could not load privacy settings.": "プライバシー設定を読み込めませんでした。",
+ "Could not save privacy settings.": "プライバシー設定を保存できませんでした。"
}
diff --git a/studio/src/i18n/ko.json b/studio/src/i18n/ko.json
index 094da4e1..7c78c9b3 100644
--- a/studio/src/i18n/ko.json
+++ b/studio/src/i18n/ko.json
@@ -1717,5 +1717,12 @@
"Get the template catalogue and local index.": "템플릿 카탈로그와 로컬 인덱스를 가져옵니다.",
"Read the details and files for one template.": "템플릿 하나의 세부 정보와 파일을 읽습니다.",
"Template cache unavailable; downloading again": "템플릿 캐시를 사용할 수 없어 다시 다운로드합니다",
- "Template update failed; using cached catalogue: {message}": "템플릿 업데이트에 실패하여 캐시된 카탈로그를 사용합니다: {message}"
+ "Template update failed; using cached catalogue: {message}": "템플릿 업데이트에 실패하여 캐시된 카탈로그를 사용합니다: {message}",
+ "Privacy settings": "개인정보 설정",
+ "Share usage data": "사용 데이터 공유",
+ "Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "OpenMotion 개선을 위해 기능 사용 현황, 오류 유형, 대략적인 지역을 전송합니다. 프롬프트와 프로젝트 내용은 제외됩니다.",
+ "This setting applies to MCP and Studio on this installation and is kept after restart.": "이 설정은 이 설치의 MCP와 Studio에 적용되며 다시 시작해도 유지됩니다.",
+ "Disabled by your environment settings.": "환경 설정으로 비활성화되었습니다.",
+ "Could not load privacy settings.": "개인정보 설정을 불러오지 못했습니다.",
+ "Could not save privacy settings.": "개인정보 설정을 저장하지 못했습니다."
}
diff --git a/studio/src/i18n/pt-BR.json b/studio/src/i18n/pt-BR.json
index 788f6363..a9c348eb 100644
--- a/studio/src/i18n/pt-BR.json
+++ b/studio/src/i18n/pt-BR.json
@@ -1753,5 +1753,12 @@
"Get the template catalogue and local index.": "Obter o catálogo de modelos e o índice local.",
"Read the details and files for one template.": "Ler os detalhes e os arquivos de um modelo.",
"Template cache unavailable; downloading again": "Cache de modelos indisponível; baixando novamente",
- "Template update failed; using cached catalogue: {message}": "Falha ao atualizar os modelos; usando o catálogo em cache: {message}"
+ "Template update failed; using cached catalogue: {message}": "Falha ao atualizar os modelos; usando o catálogo em cache: {message}",
+ "Privacy settings": "Configurações de privacidade",
+ "Share usage data": "Compartilhar dados de uso",
+ "Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "Enviar uso de recursos, categorias de erros e região aproximada para melhorar o OpenMotion. Prompts e conteúdo dos projetos são excluídos.",
+ "This setting applies to MCP and Studio on this installation and is kept after restart.": "Esta configuração se aplica ao MCP e ao Studio desta instalação e é mantida após reiniciar.",
+ "Disabled by your environment settings.": "Desativado pelas configurações do ambiente.",
+ "Could not load privacy settings.": "Não foi possível carregar as configurações de privacidade.",
+ "Could not save privacy settings.": "Não foi possível salvar as configurações de privacidade."
}
diff --git a/studio/src/i18n/ru.json b/studio/src/i18n/ru.json
index 6718a9d3..dc395692 100644
--- a/studio/src/i18n/ru.json
+++ b/studio/src/i18n/ru.json
@@ -1777,5 +1777,12 @@
"Get the template catalogue and local index.": "Получить каталог шаблонов и локальный индекс.",
"Read the details and files for one template.": "Прочитать сведения и файлы одного шаблона.",
"Template cache unavailable; downloading again": "Кэш шаблонов недоступен; повторная загрузка",
- "Template update failed; using cached catalogue: {message}": "Не удалось обновить шаблоны; используется кэшированный каталог: {message}"
+ "Template update failed; using cached catalogue: {message}": "Не удалось обновить шаблоны; используется кэшированный каталог: {message}",
+ "Privacy settings": "Настройки конфиденциальности",
+ "Share usage data": "Делиться данными об использовании",
+ "Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "Отправлять данные об использовании функций, категориях ошибок и примерном регионе для улучшения OpenMotion. Запросы и содержимое проектов не отправляются.",
+ "This setting applies to MCP and Studio on this installation and is kept after restart.": "Настройка действует для MCP и Studio этой установки и сохраняется после перезапуска.",
+ "Disabled by your environment settings.": "Отключено настройками окружения.",
+ "Could not load privacy settings.": "Не удалось загрузить настройки конфиденциальности.",
+ "Could not save privacy settings.": "Не удалось сохранить настройки конфиденциальности."
}
diff --git a/studio/src/i18n/tr.json b/studio/src/i18n/tr.json
index 73235810..164f4fcf 100644
--- a/studio/src/i18n/tr.json
+++ b/studio/src/i18n/tr.json
@@ -1717,5 +1717,12 @@
"Get the template catalogue and local index.": "Şablon kataloğunu ve yerel dizini alın.",
"Read the details and files for one template.": "Bir şablonun ayrıntılarını ve dosyalarını okuyun.",
"Template cache unavailable; downloading again": "Şablon önbelleği kullanılamıyor; yeniden indiriliyor",
- "Template update failed; using cached catalogue: {message}": "Şablonlar güncellenemedi; önbellekteki katalog kullanılıyor: {message}"
+ "Template update failed; using cached catalogue: {message}": "Şablonlar güncellenemedi; önbellekteki katalog kullanılıyor: {message}",
+ "Privacy settings": "Gizlilik ayarları",
+ "Share usage data": "Kullanım verilerini paylaş",
+ "Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "OpenMotion’ı geliştirmek için özellik kullanımı, hata kategorileri ve yaklaşık bölgeyi gönderin. İstemler ve proje içerikleri dahil edilmez.",
+ "This setting applies to MCP and Studio on this installation and is kept after restart.": "Bu ayar, bu kurulumdaki MCP ve Studio için geçerlidir ve yeniden başlatıldıktan sonra korunur.",
+ "Disabled by your environment settings.": "Ortam ayarlarınız tarafından devre dışı bırakıldı.",
+ "Could not load privacy settings.": "Gizlilik ayarları yüklenemedi.",
+ "Could not save privacy settings.": "Gizlilik ayarları kaydedilemedi."
}
diff --git a/studio/src/i18n/zh-CN.json b/studio/src/i18n/zh-CN.json
index e7d55bd4..a41903e8 100644
--- a/studio/src/i18n/zh-CN.json
+++ b/studio/src/i18n/zh-CN.json
@@ -1717,5 +1717,12 @@
"Get the template catalogue and local index.": "获取模板目录和本地索引。",
"Read the details and files for one template.": "读取单个模板的详情和文件。",
"Template cache unavailable; downloading again": "模板缓存不可用,重新下载",
- "Template update failed; using cached catalogue: {message}": "模板更新失败,使用已缓存目录:{message}"
+ "Template update failed; using cached catalogue: {message}": "模板更新失败,使用已缓存目录:{message}",
+ "Privacy settings": "隐私设置",
+ "Share usage data": "分享使用数据",
+ "Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "发送功能使用情况、错误类别和大致地区,帮助改进 OpenMotion。不会发送提示词或工程内容。",
+ "This setting applies to MCP and Studio on this installation and is kept after restart.": "此设置同时适用于本次安装的 MCP 和 Studio,重启后仍然保留。",
+ "Disabled by your environment settings.": "已由环境设置关闭。",
+ "Could not load privacy settings.": "无法加载隐私设置。",
+ "Could not save privacy settings.": "无法保存隐私设置。"
}
diff --git a/studio/src/motion/PrivacySettings.test.tsx b/studio/src/motion/PrivacySettings.test.tsx
new file mode 100644
index 00000000..46985b5c
--- /dev/null
+++ b/studio/src/motion/PrivacySettings.test.tsx
@@ -0,0 +1,44 @@
+// @vitest-environment happy-dom
+import React, { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, expect, it, vi } from 'vitest';
+import { I18nProvider } from '../i18n/I18n';
+import { PrivacySettings } from './PrivacySettings';
+
+const hooks = vi.hoisted(() => ({ enabled: vi.fn() }));
+vi.mock('./tracking', () => ({ setMotionTrackingEnabled: hooks.enabled }));
+let root: Root | undefined;
+afterEach(() => { act(() => root?.unmount()); root = undefined; document.body.innerHTML = ''; vi.unstubAllGlobals(); vi.clearAllMocks(); });
+async function open() {
+ const container = document.createElement('div'); document.body.append(container); root = createRoot(container);
+ await act(async () => root!.render(<I18nProvider initialLocale="en"><PrivacySettings onClose={() => {}} /></I18nProvider>));
+ return container.querySelector<HTMLInputElement>('input[type=checkbox]')!;
+}
+
+it('shows the enabled default and persists a user opt-out while stopping browser collection', async () => {
+ const requests: RequestInit[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (_url: string, init?: RequestInit) => {
+ requests.push(init ?? {});
+ const enabled = init?.body ? JSON.parse(String(init.body)).enabled : true;
+ return Response.json({ enabled, preference: enabled, locked: false });
+ }));
+ const toggle = await open(); expect(toggle.checked).toBe(true); expect(toggle.disabled).toBe(false);
+ await act(async () => toggle.click());
+ expect(toggle.checked).toBe(false);
+ expect(requests[1].method).toBe('PUT'); expect(JSON.parse(String(requests[1].body))).toEqual({ enabled: false });
+ expect(hooks.enabled).toHaveBeenCalledWith(false);
+});
+
+it('shows an environment lock and never offers to override it', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => Response.json({ enabled: false, preference: true, locked: true })));
+ const toggle = await open(); expect(toggle.checked).toBe(false); expect(toggle.disabled).toBe(true);
+ expect(document.body.textContent).toContain('Disabled by your environment settings.');
+});
+
+it('reports save failure without falsely claiming the installation has opted out', async () => {
+ vi.stubGlobal('fetch', vi.fn(async (_url: string, init?: RequestInit) => init?.method === 'PUT'
+ ? Response.json({ error: 'failed' }, { status: 500 }) : Response.json({ enabled: true, preference: true, locked: false })));
+ const toggle = await open(); await act(async () => toggle.click());
+ expect(toggle.checked).toBe(true); expect(document.querySelector('[role=alert]')?.textContent).toContain('Could not save');
+ expect(hooks.enabled).toHaveBeenCalledWith(false);
+});
diff --git a/studio/src/motion/PrivacySettings.tsx b/studio/src/motion/PrivacySettings.tsx
new file mode 100644
index 00000000..727b2ee3
--- /dev/null
+++ b/studio/src/motion/PrivacySettings.tsx
@@ -0,0 +1,35 @@
+import { useEffect, useRef, useState } from 'react';
+import { useI18n } from '../i18n/I18n';
+import { motionApi } from './useWorkspace';
+import { setMotionTrackingEnabled } from './tracking';
+
+type Status = { enabled: boolean; preference: boolean; locked: boolean };
+export function PrivacySettings({ onClose }: { onClose: () => void }) {
+ const { t } = useI18n(), dialog = useRef<HTMLDialogElement>(null);
+ const [status, setStatus] = useState<Status | null>(null), [busy, setBusy] = useState(false), [error, setError] = useState('');
+ useEffect(() => { dialog.current?.showModal(); return () => dialog.current?.close(); }, []);
+ useEffect(() => {
+ const controller = new AbortController();
+ void motionApi<Status>('/tracking/preferences', { signal: controller.signal }).then(setStatus)
+ .catch(() => { if (!controller.signal.aborted) setError(t('Could not load privacy settings.')); });
+ return () => controller.abort();
+ }, [t]);
+ async function change(enabled: boolean) {
+ if (!enabled) setMotionTrackingEnabled(false);
+ setBusy(true); setError('');
+ try {
+ const next = await motionApi<Status>('/tracking/preferences', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ enabled }) });
+ setStatus(next); setMotionTrackingEnabled(next.enabled);
+ } catch { setError(t('Could not save privacy settings.')); }
+ finally { setBusy(false); }
+ }
+ return <dialog ref={dialog} className="motion-model-dialog motion-media-surface motion-privacy-dialog" aria-labelledby="privacy-settings-title" onCancel={event => { event.preventDefault(); onClose(); }}>
+ <header><h2 id="privacy-settings-title">{t('Privacy settings')}</h2><button className="motion-media-close" aria-label={t('Close')} onClick={onClose}>×</button></header>
+ <section><label className="motion-media-toggle"><input type="checkbox" checked={status?.enabled ?? false} disabled={!status || busy || status.locked} onChange={event => void change(event.target.checked)} />{t('Share usage data')}</label>
+ <p>{t('Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.')}</p>
+ <p className="motion-media-muted">{t('This setting applies to MCP and Studio on this installation and is kept after restart.')}</p>
+ {status?.locked && <p role="status">{t('Disabled by your environment settings.')}</p>}
+ {error && <p role="alert">{error}</p>}
+ </section>
+ </dialog>;
+}
diff --git a/studio/src/motion/WorkspaceFrame.tsx b/studio/src/motion/WorkspaceFrame.tsx
index 5d621236..e97c2379 100644
--- a/studio/src/motion/WorkspaceFrame.tsx
+++ b/studio/src/motion/WorkspaceFrame.tsx
@@ -8,6 +8,7 @@ import { LanguageMenu } from '../i18n/LanguageMenu';
import { workspacePresentation } from '../../../shared/workspace-url';
const ModelSettings = lazy(() => import('./ModelSettings').then(module => ({ default: module.ModelSettings })));
+const PrivacySettings = lazy(() => import('./PrivacySettings').then(module => ({ default: module.PrivacySettings })));
type WorkspaceChrome = {
workspace: ReturnType<typeof useWorkspace>;
@@ -98,6 +99,12 @@ function ModelSettingsButton() {
return <button className="motion-icon-button" aria-label={t('Model settings')} title={t('Model settings')} onClick={openModelSettings}><MotionIcon name="sliders" /></button>;
}
+function PrivacySettingsButton() {
+ const { t } = useI18n(); const [open, setOpen] = useState(false);
+ return <><button className="motion-icon-button" aria-label={t('Privacy settings')} title={t('Privacy settings')} onClick={() => setOpen(true)}><MotionIcon name="eye" /></button>
+ {open && <Suspense fallback={null}><PrivacySettings onClose={() => setOpen(false)} /></Suspense>}</>;
+}
+
function WorkspaceSidebar({ currentId, close }: { currentId?: string; close: () => void }) {
const { t, formatDate } = useI18n();
const { workspace, switchingDisabled, openConnections } = useWorkspaceChrome();
@@ -128,7 +135,7 @@ function WorkspaceSidebar({ currentId, close }: { currentId?: string; close: ()
</nav>
<footer className="motion-sidebar-footer">
<div className="motion-sidebar-identity"><MotionIcon name="folder" /><span><strong>{t('My workspace')}</strong><small>{t('Saved on this device')}</small></span></div>
- <div className="motion-sidebar-settings"><ModelSettingsButton /><ThemeToggle /><LanguageMenu /></div>
+ <div className="motion-sidebar-settings"><ModelSettingsButton /><PrivacySettingsButton /><ThemeToggle /><LanguageMenu /></div>
</footer>
</aside>;
}
diff --git a/studio/src/motion/media-gateway.css b/studio/src/motion/media-gateway.css
index 5c8d5ea5..66e3b602 100644
--- a/studio/src/motion/media-gateway.css
+++ b/studio/src/motion/media-gateway.css
@@ -23,6 +23,7 @@
.motion-media-surface summary { cursor: pointer; color: var(--motion-muted); font-size: 12px; padding: 4px 0; }
.motion-media-surface details[open] summary { margin-bottom: 8px; }
.motion-model-dialog { position: fixed; inset: 0; margin: auto; width: min(960px, calc(100vw - 40px)); max-height: calc(100dvh - 48px); padding: 24px; overflow: auto; }
+.motion-privacy-dialog { width: min(520px, calc(100vw - 40px)); }
.motion-model-dialog::backdrop { background: var(--motion-overlay); backdrop-filter: blur(3px); }
.motion-model-dialog section + section { border-top: 1px solid var(--motion-border); margin-top: 24px; padding-top: 20px; }
.motion-model-routes select { min-height: 36px; }
@@ -30,8 +31,8 @@
.motion-provider-card { background: var(--motion-panel); border: 1px solid var(--motion-border); border-radius: 12px; padding: 16px; }
.motion-provider-card .motion-media-row { gap: 6px; flex-wrap: wrap; }
.motion-provider-card p { min-height: 38px; margin: 10px 0; }
-.motion-provider-card .motion-media-toggle { display: flex; flex-direction: row; align-items: center; gap: 5px; }
-.motion-provider-card input[type=checkbox] { accent-color: var(--motion-accent); }
+.motion-provider-card .motion-media-toggle, .motion-privacy-dialog .motion-media-toggle { display: flex; flex-direction: row; align-items: center; gap: 5px; }
+.motion-provider-card input[type=checkbox], .motion-privacy-dialog input[type=checkbox] { accent-color: var(--motion-accent); }
.motion-provider-card label + .motion-media-row { margin: 10px 0; }
.motion-capability-badge { display: inline-block; border-radius: 4px; padding: 2px 6px; margin-top: 10px; font-size: 11px; background: var(--motion-inset); color: var(--motion-muted); }
.motion-capability-badge[data-available=true] { color: var(--motion-accent); background: var(--motion-accent-soft); }
diff --git a/studio/src/motion/tracking.test.ts b/studio/src/motion/tracking.test.ts
index c58d45ae..b5d0dbd7 100644
--- a/studio/src/motion/tracking.test.ts
+++ b/studio/src/motion/tracking.test.ts
@@ -34,3 +34,12 @@ it('honors both local disablement and browser Do Not Track', async () => {
}
Reflect.deleteProperty(navigator, 'doNotTrack');
});
+
+it('does not let a stale configuration response undo a user opt-out', async () => {
+ let resolve!: (value: Response) => void;
+ const fetcher = vi.fn(() => new Promise<Response>(done => { resolve = done; })); vi.stubGlobal('fetch', fetcher);
+ const tracking = await import('./tracking'), pending = tracking.initializeTracking();
+ tracking.setMotionTrackingEnabled(false); resolve(Response.json({ enabled: true })); await pending;
+ await tracking.trackMotion('ui_click', { page_name: 'home', area: 'workspace', element: 'new_creation' });
+ await tracking.flushMotionTracking(); expect(fetcher).toHaveBeenCalledTimes(1);
+});
diff --git a/studio/src/motion/tracking.ts b/studio/src/motion/tracking.ts
index 13da4350..4b88f70b 100644
--- a/studio/src/motion/tracking.ts
+++ b/studio/src/motion/tracking.ts
@@ -4,11 +4,12 @@ import type { EventFields } from '../../../tracking/core.ts';
const tracking = createBrowserTracking({ registry: omEvents, endpoint: '/motion-api/tracking', enabled: false });
let initialization: Promise<void> | undefined;
+let preference: boolean | undefined;
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(config.enabled === true && navigator.doNotTrack !== '1');
+ tracking.setEnabled((preference ?? config.enabled === true) && navigator.doNotTrack !== '1');
}).catch(() => {});
return initialization;
}
@@ -17,6 +18,7 @@ export async function trackMotion<E extends keyof typeof omEvents>(event: E, pro
tracking.track(event, properties);
}
export function flushMotionTracking() { return tracking.flush(); }
+export function setMotionTrackingEnabled(enabled: boolean) { preference = enabled; tracking.setEnabled(enabled && navigator.doNotTrack !== '1'); }
window.addEventListener('pagehide', () => { void tracking.flush(); });
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') void tracking.flush(); });
diff --git a/tests/source-install.test.ts b/tests/source-install.test.ts
index fe8da41a..7019b13b 100644
--- a/tests/source-install.test.ts
+++ b/tests/source-install.test.ts
@@ -17,7 +17,12 @@ test('public Motion sources contain no company endpoints, workstation paths or e
catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue; throw error; }
// Report the filename only: an accidentally introduced secret must not reach CI logs.
assert(!/https?:\/\/[^\s/]*(?:powerformer\.(?:net|com)|powerformer\.feishu\.cn)(?:[/:]|$)/i.test(content), 'Company endpoint in ' + file);
- assert(!/phc_[A-Za-z0-9]{20,}/.test(content), 'Embedded upstream ingest identifier in ' + file);
+ if (file === 'shared/tracking-config.json') {
+ const config = JSON.parse(content);
+ assert.deepEqual(Object.keys(config).sort(), ['geoip', 'host', 'projectId', 'token']);
+ assert.equal(config.projectId, 722078); assert.equal(config.host, 'https://us.i.posthog.com');
+ assert.equal(config.geoip, true); assert.match(config.token, /^phc_[A-Za-z0-9_]+$/);
+ } else assert(!/phc_[A-Za-z0-9]{20,}/.test(content), 'Embedded upstream ingest identifier in ' + file);
const users = [...content.matchAll(/\/Users\/([\w.-]+)\//g)].map(match => match[1]);
assert(users.every(name => ['me', 'a', 'someone'].includes(name)), 'Workstation path in ' + file);
}
diff --git a/tests/tracking.test.ts b/tests/tracking.test.ts
index 8870e822..41c5b04d 100644
--- a/tests/tracking.test.ts
+++ b/tests/tracking.test.ts
@@ -5,7 +5,7 @@ import path from 'node:path';
import { createTracker, deviceContext } from '../tracking/core.ts';
import { createPosthogSender, loadIdentity } from '../tracking/node.ts';
import { omEvents } from '../tracking/events.ts';
-import { closeTracking, createAppTracking, trackingError } from '../shared/tracking.ts';
+import { closeTracking, createAppTracking, saveTrackingPreference, trackingError } from '../shared/tracking.ts';
import { Phase1Service } from '../phase1.ts';
import { renderNext } from '../server.ts';
import { pluginRoot } from '../hyperframes.ts';
@@ -86,6 +86,11 @@ test('PostHog adapter uses public ingest only, privacy fields and real receipt s
response = new Response('{}', { status: 400 }); assert.equal(await sender([event], new AbortController().signal), 'drop');
response = new Response('not json'); assert.equal(await sender([event], new AbortController().signal), 'retry');
assert.equal(trackingError(new Error('private user prompt and /local/path')), 'TOOL_FAILED');
+ const enriched: any[] = [];
+ const geoip = createPosthogSender({ ...options, geoip: true, fetch: async (_url, init) => { enriched.push(JSON.parse(String(init?.body))); return Response.json({ status: 'Ok' }); } });
+ await geoip([event], new AbortController().signal);
+ assert.equal(enriched[0].batch[0].properties.$geoip_disable, false);
+ assert.equal(Object.hasOwn(enriched[0].batch[0].properties, '$ip'), false);
});
test('browser ingress rejects forged identity, worker events and oversized batches', () => fixture(async store => {
@@ -127,7 +132,7 @@ test('domain events follow real commits, skip replay and retain safe failure wit
assert.doesNotMatch(JSON.stringify(events), /PRIVATE_|private\.txt/); tracking.close();
}, false));
-test('missing configuration and DO_NOT_TRACK create no identity and send nothing', () => fixture(async store => {
+test('DO_NOT_TRACK creates no identity and sends nothing', () => fixture(async store => {
const before = process.env.DO_NOT_TRACK; process.env.DO_NOT_TRACK = '1';
try {
const tracking = await createAppTracking(store.directory, 'mcp');
@@ -137,6 +142,39 @@ test('missing configuration and DO_NOT_TRACK create no identity and send nothing
} finally { if (before === undefined) delete process.env.DO_NOT_TRACK; else process.env.DO_NOT_TRACK = before; }
}, false));
+test('default configuration reports without opt-in; saved opt-out covers runtimes, restart and re-enable', t => fixture(async store => {
+ const keys = ['OPENMOTION_TELEMETRY', 'DO_NOT_TRACK', 'OPENMOTION_POSTHOG_HOST', 'OPENMOTION_POSTHOG_KEY', 'OPENMOTION_TRACKING_ENV', 'OPENMOTION_TRACKING_TEST_RUN_ID'];
+ const before = Object.fromEntries(keys.map(key => [key, process.env[key]]));
+ const bodies: any[] = [];
+ t.mock.method(globalThis, 'fetch', async (_url: any, init: RequestInit) => { bodies.push(JSON.parse(String(init.body))); return Response.json({ status: 'Ok' }); });
+ const runtimes: Awaited<ReturnType<typeof createAppTracking>>[] = [];
+ try {
+ for (const key of keys) delete process.env[key];
+ process.env.OPENMOTION_TRACKING_ENV = 'test'; process.env.OPENMOTION_TRACKING_TEST_RUN_ID = crypto.randomUUID();
+ const mcp = await createAppTracking(store.directory, 'mcp'), worker = await createAppTracking(store.directory, 'worker'); runtimes.push(mcp, worker);
+ assert.equal(mcp.enabled(), true); assert.equal(worker.enabled(), true);
+ mcp.ingest(packet()); assert.equal(await mcp.flush(), 'accepted'); assert.equal(bodies.length, 1);
+ assert.equal(bodies[0].batch[0].properties.$geoip_disable, false);
+ const request = transport(store, { tracking: worker });
+ mcp.ingest(packet()); worker.ingest(packet());
+ const set = (enabled: unknown) => request('/motion-api/tracking/preferences', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ enabled }) });
+ assert.equal((await set('false')).status, 400);
+ assert.equal((await set(false)).status, 200);
+ assert.equal(await mcp.flush(), 'disabled'); assert.equal(await worker.flush(), 'disabled');
+ assert.equal(mcp.pending(), 0); assert.equal(worker.pending(), 0); assert.equal(bodies.length, 1);
+ const restarted = await createAppTracking(store.directory, 'mcp'); runtimes.push(restarted);
+ assert.equal(restarted.enabled(), false); assert.equal(restarted.ingest(packet()), 'disabled');
+ await saveTrackingPreference(store.directory, true); assert.equal(restarted.enabled(), true);
+ process.env.OPENMOTION_TELEMETRY = '0'; assert.equal(restarted.ingest(packet()), 'disabled');
+ assert.equal((await set(true)).status, 403); delete process.env.OPENMOTION_TELEMETRY;
+ await writeFile(path.join(store.directory, 'tracking/preferences.json'), 'corrupted');
+ assert.equal(restarted.ingest(packet()), 'disabled');
+ } finally {
+ for (const runtime of runtimes) runtime.close();
+ for (const key of keys) { if (before[key] === undefined) delete process.env[key]; else process.env[key] = before[key]; }
+ }
+}, false));
+
test('worker reports a real terminal render failure once, separately from queue acceptance', () => fixture(async store => {
const events: PendingEvent[] = [], tracking = core(async batch => { events.push(...batch); return 'accepted'; });
const current = await store.get(), job = await store.requestExport(current.revision);
diff --git a/tracking/README.md b/tracking/README.md
index b1f6a9fd..17026a1e 100644
--- a/tracking/README.md
+++ b/tracking/README.md
@@ -5,18 +5,35 @@ It has no runtime dependencies. The application consumes its TypeScript sources;
`npm run build:tracking` emits JavaScript and declarations for a local `npm pack`
from this directory. The package remains private; this change does not publish it.
-## Enable reporting
+## Reporting and user control
-Reporting is **off by default**. Configure the process launching the MCP and local
-service with `OPENMOTION_TELEMETRY=1`, `OPENMOTION_POSTHOG_HOST` (the project's HTTPS
-ingestion origin) and `OPENMOTION_POSTHOG_KEY` (a public `phc_` project token).
-`DO_NOT_TRACK=1` overrides enablement. Restart existing local services after changing
-configuration. Missing/invalid configuration fails closed and never blocks creation.
+Reporting is **on by default** using the isolated OpenMotion project. The single
+public, write-only project token and ingestion host are distributed in
+`shared/tracking-config.json`; it contains no read/admin credentials and is never
+included in the browser bundle. Users do not need to supply a key or opt-in flag.
+
+Users can turn collection off in Studio's **Privacy settings → Share usage data**.
+This preference is persisted under the installation's data directory and applies
+to both MCP and Studio, including already-running processes and future restarts.
+Disabling clears pending queues and aborts in-flight delivery; accepted events
+cannot be recalled. A filesystem watcher propagates preference changes, and each
+enqueue/flush also checks the saved preference. Corrupt preference files fail closed.
+
+`OPENMOTION_TELEMETRY=0` (also `false`/`off`) or `DO_NOT_TRACK=1` forces all collection
+off and locks the Studio switch. Restart services after changing launch environment
+variables. Browser Do Not Track suppresses browser collection. The environment
+override takes priority over the saved preference.
+
+For another collector, supply both `OPENMOTION_POSTHOG_HOST` and
+`OPENMOTION_POSTHOG_KEY`. Partial or invalid configuration fails closed. Custom
+collectors default to zero-IP mode; `OPENMOTION_GEOIP=1` requires that collector to
+discard IP after enrichment. Never supply a personal `phx_` API key.
Use `OPENMOTION_TRACKING_ENV=test` and a UUID in
`OPENMOTION_TRACKING_TEST_RUN_ID` for isolated ingestion checks; filter these records
out of product dashboards. Normal environments are `production` and `development`.
-Do not commit deployment keys or put personal `phx_` API keys in this package.
+Node/Vitest tests suppress collection unless explicitly given a test run ID; CI
+also forces collection off. No test should silently report into production funnels.
Studio retrieves only an enabled flag and submits semantic events to the same-origin
`/motion-api/tracking` endpoint. The server validates the complete batch, rejects
@@ -37,12 +54,16 @@ a separate change. Unknown source remains null.
Common fields include schema/product/app version, environment, entrypoint/runtime,
platform/architecture, OS/version, runtime locale, device IANA timezone and UTC offset
-(east of UTC is positive). GeoIP is disabled and `$ip` is the fixed value `0.0.0.0`;
-null is insufficient because ingestion can replace it with the request's IP.
-The fixed value suppresses real IP storage in event properties; network intermediaries
-still see the connection address. Country/region and
-GeoIP timezone remain unknown until ingress geolocation and IP-discard policy are
-implemented together. Device timezone is not a country inference. Person profiles,
+(east of UTC is positive). The default project runs [coarse GeoIP](./posthog-geoip.hog)
+before the **Discard client IP data** setting removes the IP from stored events.
+Only country code/name, first-level region code/name and geographic timezone are
+added. No city, postal code, coordinates or person-location updates are generated.
+Lookup failures leave geographic fields unknown. GeoIP describes the observable
+network egress; VPNs/proxies can change it. Device timezone is a separate setting.
+Network intermediaries still see the connection address. Operators must keep the
+project's IP-discard policy enabled; it is a receiver requirement, not a guarantee
+enforced by a public capture token. Custom zero-IP mode retains the fixed address
+`0.0.0.0`, because a null property is replaced with the request IP. Person profiles,
autocapture, session replay and upstream engine telemetry are not enabled.
Runtime and TypeScript event contracts whitelist required fields, enums, UUIDs and
diff --git a/tracking/browser.ts b/tracking/browser.ts
index 00b58f56..36f5f066 100644
--- a/tracking/browser.ts
+++ b/tracking/browser.ts
@@ -3,11 +3,15 @@ import type { Registry } from './core.ts';
export function createBrowserTracking<const R extends Registry>(options: { endpoint: string; registry: R; enabled: boolean; flushIntervalMs?: number }) {
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');
- return createTracker({ ...options, entrypoint: 'studio', send: async (events, signal) => {
+ const tracking = createTracker({ ...options, entrypoint: 'studio', send: async (events, signal) => {
try {
const response = await fetch(endpoint, { method: 'POST', redirect: 'error', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ events }), keepalive: true, signal: AbortSignal.any([signal, AbortSignal.timeout(1000)]) });
- return response.ok ? 'accepted' : response.status >= 500 || response.status === 429 ? 'retry' : 'drop';
+ if (!response.ok) return response.status >= 500 || response.status === 429 ? 'retry' : 'drop';
+ const receipt = await response.json() as { enabled?: boolean };
+ if (receipt.enabled === false) tracking.setEnabled(false);
+ return 'accepted';
} catch { return 'retry'; }
} });
+ return tracking;
}
diff --git a/tracking/core.ts b/tracking/core.ts
index cbfd671d..251f7020 100644
--- a/tracking/core.ts
+++ b/tracking/core.ts
@@ -49,19 +49,26 @@ export function validPending(registry: Registry, value: unknown): value is Pendi
export function createTracker<const R extends Registry>(options: {
registry: R; entrypoint: Entry; enabled: boolean;
send: (events: readonly PendingEvent[], signal: AbortSignal) => Promise<Receipt>;
- maxQueue?: number; flushIntervalMs?: number;
+ maxQueue?: number; flushIntervalMs?: number; isEnabled?: () => boolean;
}) {
let enabled = options.enabled, queue: PendingEvent[] = [], timer: ReturnType<typeof setTimeout> | undefined;
let inFlight: Promise<Receipt | 'disabled' | 'empty'> | undefined, controller: AbortController | undefined;
const seen = new Set<string>(), maxQueue = options.maxQueue ?? 64;
let failures = 0;
+ function discard() { queue = []; seen.clear(); if (timer) clearTimeout(timer); timer = undefined; controller?.abort(); }
+ function active() {
+ let allowed = enabled;
+ try { allowed = allowed && (options.isEnabled?.() ?? true); } catch { allowed = false; }
+ if (!allowed) discard();
+ return allowed;
+ }
function schedule() {
- if (!enabled || timer || options.flushIntervalMs === 0) return;
+ if (!active() || timer || options.flushIntervalMs === 0) return;
timer = setTimeout(() => { timer = undefined; void flush(); }, Math.min(60_000, (options.flushIntervalMs ?? 1000) * 2 ** failures));
(timer as unknown as { unref?: () => void }).unref?.();
}
function ingest(raw: unknown) {
- if (!enabled) return 'disabled';
+ if (!active()) return 'disabled';
if (!validPending(options.registry, raw)) return 'invalid';
if (seen.has(raw.event_id)) return 'duplicate';
if (queue.length >= maxQueue) return 'full';
@@ -71,17 +78,17 @@ export function createTracker<const R extends Registry>(options: {
schedule(); return 'queued';
}
function track<E extends keyof R & string>(event: E, properties: EventFields<R[E]>, eventId: string = crypto.randomUUID(), entrypoint: Entry = options.entrypoint) {
- if (!enabled) return 'disabled';
+ if (!active()) return 'disabled';
try { return ingest({ event, properties, event_id: eventId, occurred_at: new Date().toISOString(),
entrypoint, ...deviceContext() }); } catch { return 'invalid'; }
}
function setEnabled(next: boolean) {
enabled = next;
- if (!next) { queue = []; seen.clear(); if (timer) clearTimeout(timer); timer = undefined; controller?.abort(); }
+ if (!next) discard();
}
function flush(): Promise<Receipt | 'disabled' | 'empty'> {
+ if (!active()) return Promise.resolve('disabled');
if (inFlight) return inFlight;
- if (!enabled) return Promise.resolve('disabled');
if (!queue.length) return Promise.resolve('empty');
if (timer) clearTimeout(timer); timer = undefined;
queue = queue.filter(event => Date.now() - Date.parse(event.occurred_at) <= 86_400_000);
@@ -90,13 +97,13 @@ export function createTracker<const R extends Registry>(options: {
inFlight = (async () => {
let receipt: Receipt;
try { receipt = await options.send(snapshot, request.signal); } catch { receipt = 'retry'; }
- if (!enabled) return 'disabled' as const;
+ if (!active()) return 'disabled' as const;
failures = receipt === 'retry' ? Math.min(6, failures + 1) : 0;
if (receipt !== 'retry') { const ids = new Set(snapshot.map(e => e.event_id)); queue = queue.filter(e => !ids.has(e.event_id)); }
return receipt;
})().finally(() => { inFlight = undefined; controller = undefined; if (queue.length) schedule(); });
return inFlight;
}
- return { track, ingest, flush, setEnabled, enabled: () => enabled, pending: () => queue.length,
+ return { track, ingest, flush, setEnabled, enabled: active, pending: () => queue.length,
close: () => { setEnabled(false); } };
}
diff --git a/tracking/node.ts b/tracking/node.ts
index f74c8860..1fdd233e 100644
--- a/tracking/node.ts
+++ b/tracking/node.ts
@@ -32,7 +32,7 @@ export async function loadIdentity(directory: string, source?: string): Promise<
export function createPosthogSender(options: {
host: string; token: string; identity: Identity; appVersion: string;
- env: 'development' | 'test' | 'production'; testRunId?: string; timeoutMs?: number; fetch?: typeof fetch;
+ env: 'development' | 'test' | 'production'; testRunId?: string; timeoutMs?: number; fetch?: typeof fetch; geoip?: boolean;
}) {
const url = new URL(options.host);
if (url.username || url.password || url.search || url.hash || url.pathname !== '/') throw new Error('INVALID_INGEST_HOST');
@@ -52,8 +52,9 @@ export function createPosthogSender(options: {
platform: os.platform(), arch: os.arch(), $os: os.type(), $os_version: os.release(),
locale: Intl.DateTimeFormat().resolvedOptions().locale,
device_timezone: event.device_timezone, utc_offset_minutes: event.utc_offset_minutes,
- // Null is replaced with the request IP by ingestion; a fixed zero address prevents that fallback.
- location_source: 'unknown', $geoip_disable: true, $ip: '0.0.0.0', $process_person_profile: false } }));
+ // GeoIP requires an ingress that discards IP after enrichment; custom collectors default to zero-IP mode.
+ ...(options.geoip ? { location_source: 'geoip', $geoip_disable: false }
+ : { location_source: 'unknown', $geoip_disable: true, $ip: '0.0.0.0' }), $process_person_profile: false } }));
const body = JSON.stringify({ api_key: options.token, batch });
if (Buffer.byteLength(body) > 64 * 1024) return 'drop';
try {
@@ -73,7 +74,7 @@ export function createPosthogSender(options: {
export function createNodeTracking<const R extends Registry>(options: {
registry: R; identity: Identity; host: string; token?: string; appVersion: string;
env: 'development' | 'test' | 'production'; testRunId?: string; entrypoint: Entry;
- enabled: boolean; timeoutMs?: number; flushIntervalMs?: number; maxQueue?: number;
+ enabled: boolean; timeoutMs?: number; flushIntervalMs?: number; maxQueue?: number; geoip?: boolean; isEnabled?: () => boolean;
}) {
const enabled = options.enabled && !!options.token;
const send = enabled ? createPosthogSender({ ...options, token: options.token! }) : async () => 'drop' as const;
diff --git a/tracking/package.json b/tracking/package.json
index b7bade41..9de89016 100644
--- a/tracking/package.json
+++ b/tracking/package.json
@@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"type": "module",
- "files": ["dist", "README.md"],
+ "files": ["dist", "README.md", "posthog-geoip.hog"],
"exports": {
"./core": { "types": "./dist/core.d.ts", "default": "./dist/core.js" },
"./node": { "types": "./dist/node.d.ts", "default": "./dist/node.js" },
diff --git a/tracking/posthog-geoip.hog b/tracking/posthog-geoip.hog
new file mode 100644
index 00000000..e4287551
--- /dev/null
+++ b/tracking/posthog-geoip.hog
@@ -0,0 +1,27 @@
+// OpenMotion GeoIP: coarse region only. Project IP discard must be enabled.
+if (event.properties?.$geoip_disable or empty(event.properties?.$ip)) {
+ return event
+}
+let location := geoipLookup(event.properties.$ip)
+if (not location) {
+ return event
+}
+let returnEvent := event
+if (location.country) {
+ returnEvent.properties.$geoip_country_code := location.country.isoCode
+ returnEvent.properties.$geoip_country_name := location.country.names?.en
+}
+if (location.location) {
+ returnEvent.properties.$geoip_time_zone := location.location.timeZone
+}
+let regionSet := false
+if (location.subdivisions) {
+ for (let index, region in location.subdivisions) {
+ if (not regionSet) {
+ returnEvent.properties.$geoip_subdivision_1_code := region.isoCode
+ returnEvent.properties.$geoip_subdivision_1_name := region.names?.en
+ regionSet := true
+ }
+ }
+}
+return returnEvent