From c1a8d08bd203a2a920c55ec6d955654bafd3188c Mon Sep 17 00:00:00 2001 From: lefarcen <935902669@qq.com> Date: Wed, 11 Nov 2026 15:56:16 +0800 Subject: [PATCH 1/4] feat(motion): preserve optional installation source across upgrades --- docs/install-attribution.md | 24 ++++++++++++++++++++ docs/install.md | 2 ++ docs/product/architecture.md | 2 ++ scripts/distribution.ts | 2 +- scripts/npm-installer.mjs | 10 +++++++-- shared/install-attribution.ts | 11 ++++++++++ shared/tracking.ts | 4 ++++ tests/install-attribution-worker.test.ts | 18 +++++++++++++++ tests/npm-installer.test.ts | 20 +++++++++++++++++ tests/tracking.test.ts | 22 ++++++++++++++++--- tracking/events.ts | 1 + tracking/node.ts | 23 +++++++++++++++---- workers/install-guide/index.ts | 28 ++++++++++++++++++++++++ workers/install-guide/wrangler.toml | 12 ++++++++++ 14 files changed, 169 insertions(+), 10 deletions(-) create mode 100644 docs/install-attribution.md create mode 100644 shared/install-attribution.ts create mode 100644 tests/install-attribution-worker.test.ts create mode 100644 workers/install-guide/index.ts create mode 100644 workers/install-guide/wrangler.toml diff --git a/docs/install-attribution.md b/docs/install-attribution.md new file mode 100644 index 000000000..cd371092f --- /dev/null +++ b/docs/install-attribution.md @@ -0,0 +1,24 @@ +# Installation attribution + +Website URL `?utm_source=producthunt` → copied guide URL with the same query → Worker adds `--utm-source producthunt` to setup commands → installer saves the source → subsequent events carry `od_utm_source`. + +## Compatibility + +- No source: the original guide and setup command work unchanged; a new identity has an unknown source. +- Untagged upgrade: keep the saved source and installation ID. +- Explicit new source: update the source while retaining the installation ID. +- Existing telemetry opt-outs apply. Reporting failure never fails installation. +- Website current-visit attribution is separate from the existing first-touch cookie. Existing page/tab prompts do not change when another tab arrives from another campaign. + +## Deployment order + +1. Merge and publish the installer supporting `--utm-source`. The generated guide includes `` only with that source version. +2. Deploy `wrangler deploy --config workers/install-guide/wrangler.toml` in the Powerformer account. The binding reads the existing `open-design-releases` bucket; it does not upload or modify release objects. +3. Verify the independent workers.dev endpoint against both attributed and direct requests. +4. Attach only `releases.open-design.ai/open-motion/install.md*` and `releases.open-design.ai/open-motion/dev/install.md*` after installer publication. Other release paths remain on R2. Remove these two routes to roll back. + +An older guide without the marker is served unchanged, even when a source query is supplied. Transformed responses use `Cache-Control: no-store` to prevent channel mixing. Unrecognized paths return 404; GET and HEAD are supported. + +## Measurement + +Filter Motion events by `product=openmotion`, environment, date and `od_utm_source`. Count successful installation devices by distinct `installation_id`; count project-creating devices and projects using successful `project_create_result` events. Reinstalls are events, not additional devices. Website copy success is a separate measurement and does not prove installation. There is no cross-device or website-to-client person matching. diff --git a/docs/install.md b/docs/install.md index 56543e973..7f18dc9e7 100644 --- a/docs/install.md +++ b/docs/install.md @@ -12,6 +12,8 @@ If you are reading this file in the source repository and see `{{...}}`, it is a 4. Choose exactly one setup command below, applying the test isolation paths first when required. Setup starts checked video-component downloads in the background. Do not wait for prepare to connect MCP, create/edit projects or open ordinary preview. Studio shows preparation status and retry; media import, automated capture and export require their respective components. Follow the selected host's discovery/reload mechanism. Compatible phase-one updates can keep existing connections; reconnect closed or incompatible transports. Confirm the application version, template environment, eleven public Tools and five Skills through that host, including an actual `motion_get_project` call. Registration alone does not prove loading. 5. Report the result and any failed step. Introduce the available capabilities and wait for the user's next request. Installation does not authorize generating a video or calling a paid model. + + ## Choose the selected host's setup command The commands below show normal installations. For test candidates, apply the separate configuration/profile, home, data and Skills paths from the [platform recipes]({{DETAILS_URL}}) first. Run only the selected row. diff --git a/docs/product/architecture.md b/docs/product/architecture.md index 65597f6f4..6232c7014 100644 --- a/docs/product/architecture.md +++ b/docs/product/architecture.md @@ -258,6 +258,8 @@ The following product measures still require agreed observation windows and vali 开始采集前需记录事件定义、观察窗口、样本来源和隐私边界。人物、商业和指标实验的证据写回对应文档,不能用开源仓库热度或模板原帖播放量替代。 +Installation attribution is optional: `setup --utm-source ` updates the existing installation identity's source after successful host registration. Untagged upgrades retain it; disabled telemetry creates no identity or installation event. Installation and subsequent domain events carry `od_utm_source` without modifying person profiles. The install-guide Worker reads the existing R2 guide and adds the flag only when the guide declares installer support. Unattributed requests and older guides keep their original commands. Deployment and installer publication remain separate; see [installation attribution](../install-attribution.md). + ## Application npm distribution The `@openmotion/app` npm tgz contains installer scripts, the prebuilt application archive and its pinned default manifest. Setup needs only that tgz, stages the checked application into a managed writable directory, installs production npm dependencies from its lock and registers the selected host's eleven MCP Tools and five Skills. The application server and projects never run in the npx cache. Node/Agent remain user-provided. After successful setup, a detached worker prepares pinned FFmpeg, ffprobe and browser assets concurrently. MCP and the local editor backend start without waiting for native downloads. Installers and running apps share platform/hash cache locks and atomic component status; Studio polls readiness and displays preparation progress and failure retry inside the Export panel. The header Export action opens that panel while dependencies are unavailable; readiness updates without reloading. Media import checks the media components before applying work; automated capture and export require the full local runtime because captured compositions may contain media. Selected Studio imports are retained in memory for explicit retry in the same project; preparation does not create or replay exports. Explicit prepare remains a blocking wait/retry, completed assets are reused across app versions sharing the cache, and interrupted transfers restart only the incomplete asset. Existing plugin and complete platform ZIP channels remain available. diff --git a/scripts/distribution.ts b/scripts/distribution.ts index 81c1cfb7e..f14d58f59 100644 --- a/scripts/distribution.ts +++ b/scripts/distribution.ts @@ -436,7 +436,7 @@ export const distributionDocuments = [ 'tracking/README.md', 'tracking/INTEGRATION.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/install.md', 'docs/release-guide.md', 'docs/release-workflows.md', 'docs/templates/release-record.md', 'docs/project-workspace.md', + 'docs/motion-extension-scope.md', 'docs/npm-installation.md', 'docs/install-attribution.md', 'docs/install.md', 'docs/release-guide.md', 'docs/release-workflows.md', 'docs/templates/release-record.md', 'docs/project-workspace.md', 'docs/repository-migration.md', 'docs/session-architecture.md', 'docs/shared-editor.md', 'docs/README.zh-CN.md', 'docs/README.ja.md', 'docs/usage.md', 'docs/motion-md.md', 'docs/motion-md.zh-CN.md', diff --git a/scripts/npm-installer.mjs b/scripts/npm-installer.mjs index fedf8966a..5cb899852 100644 --- a/scripts/npm-installer.mjs +++ b/scripts/npm-installer.mjs @@ -25,6 +25,7 @@ const usage = `Usage: Select the current Agent host explicitly; installed CLIs do not identify the current host. Setup options: --host HOST Supported hosts: ${hosts.join(', ')} (default: codex) + --utm-source NAME Optional installation source; omitted upgrades retain the existing source --home DIR Managed application home; reuse for prepare and upgrades --data-dir DIR Project data outside application/cache directories --skills-dir DIR Skills root for Codex, Claude Code or WorkBuddy @@ -66,6 +67,7 @@ export async function localManifest(filename) { } export async function setup(options) { + assert(options.utmSource === undefined || /^[A-Za-z0-9_.-]{1,64}$/.test(options.utmSource), 'Invalid --utm-source'); const manifest = await localManifest(options.manifest || bundledManifest); if (!options.manifest) assert.equal(manifest.version, (await readJSON(new URL('../package.json', import.meta.url))).version, 'Bundled application must match the npm package version'); const templateEnvironment = manifest.templateEnvironment ?? 'prod'; @@ -137,6 +139,10 @@ export async function setup(options) { ...(plan.host === 'codex' ? { skillsDirectory: targets[0] } : {}) }; await writeJSON(stateFile, state); wroteState = true; await plan.register(); + try { + const { recordInstallation } = await import(pathToFileURL(path.join(appRoot, 'shared/install-attribution.ts')).href); + await recordInstallation(dataDirectory, plan.host, options.utmSource); + } catch (error) { console.error('OpenMotion: installation attribution unavailable: ' + error.message); } for (const item of directories) await rm(item.backup, { recursive: true, force: true }).catch(error => console.error('Old instruction backup retained: ' + error.message)); await startNativePreparation(appRoot).catch(error => console.error('OpenMotion: background preparation could not start; retry in Studio or run prepare. ' + error.message)); return { ...state, host: plan.host, hostInstallation: plan.metadata, nativeDependencies: 'background-preparation; status and retry available in Studio' }; @@ -183,14 +189,14 @@ export async function diagnose(options) { async function main() { const { positionals, values } = parseArgs({ allowPositionals: true, options: { manifest: { type: 'string' }, home: { type: 'string' }, 'data-dir': { type: 'string' }, 'skills-dir': { type: 'string' }, host: { type: 'string' }, codex: { type: 'string' }, claude: { type: 'string' }, dsh: { type: 'string' }, profile: { type: 'string' }, - help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' }, + 'utm-source': { type: 'string' }, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' }, } }); if (values.help) { console.log(usage); return; } if (values.version) { console.log((await readJSON(new URL('../package.json', import.meta.url))).version); return; } const [command] = positionals; assert(positionals.length === 1, usage); if (command === 'setup') { - console.log(JSON.stringify(await setup({ manifest: values.manifest, home: values.home, dataDirectory: values['data-dir'], skillsDirectory: values['skills-dir'], host: values.host, codex: values.codex, claude: values.claude, dsh: values.dsh, profile: values.profile }), null, 2)); + console.log(JSON.stringify(await setup({ utmSource: values['utm-source'], manifest: values.manifest, home: values.home, dataDirectory: values['data-dir'], skillsDirectory: values['skills-dir'], host: values.host, codex: values.codex, claude: values.claude, dsh: values.dsh, profile: values.profile }), null, 2)); } else if (command === 'prepare') { const environment = (await readJSON(bundledManifest))?.templateEnvironment; const state = await readJSON(path.join(values.home || defaultHome(environment), 'install.json')); diff --git a/shared/install-attribution.ts b/shared/install-attribution.ts new file mode 100644 index 000000000..623b19e79 --- /dev/null +++ b/shared/install-attribution.ts @@ -0,0 +1,11 @@ +import path from 'node:path'; +import { saveInstallationSource } from '../tracking/node.ts'; +import { createAppTracking, closeTracking, trackingLocked, trackingPreference } from './tracking.ts'; + +export async function recordInstallation(directory: string, host: 'codex' | 'claude' | 'deepseek' | 'workbuddy', source?: string) { + if (trackingLocked() || !trackingPreference(directory)) return; + await saveInstallationSource(path.join(directory, 'tracking'), source); + const tracking = await createAppTracking(directory, 'installer'); + tracking.track('installation_result', { outcome: 'success', host_product: host }); + await closeTracking(tracking); +} diff --git a/shared/tracking.ts b/shared/tracking.ts index 9c173d90d..658d6429c 100644 --- a/shared/tracking.ts +++ b/shared/tracking.ts @@ -39,6 +39,10 @@ export async function createAppTracking(directory: string, entrypoint: Entry): P if (!config.host || !config.token) return disabled(); const tracking = createNodeTracking({ registry: omEvents, entrypoint, enabled: true, identity: await loadIdentity(path.join(directory, 'tracking')), appVersion: VERSION, + source: () => { + try { return JSON.parse(readFileSync(path.join(directory, 'tracking/identity.json'), 'utf8')).utm_source; } + catch { return null; } + }, 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 }); diff --git a/tests/install-attribution-worker.test.ts b/tests/install-attribution-worker.test.ts new file mode 100644 index 000000000..8e81a91b2 --- /dev/null +++ b/tests/install-attribution-worker.test.ts @@ -0,0 +1,18 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import worker, { attributeGuide } from '../workers/install-guide/index.ts'; +const guide = '\n`openmotion setup --host codex`\n`openmotion setup --host deepseek --profile PROFILE`\n`openmotion prepare`'; +test('worker keeps untagged and older guides unchanged and annotates only setup commands', async () => { + assert.equal(attributeGuide(guide,null),guide); + assert.equal(attributeGuide(guide,'$(bad)'),guide); + assert.equal(attributeGuide('openmotion setup --host codex','producthunt'),'openmotion setup --host codex'); + const env = { RELEASES: { async get(key: string) { assert.equal(key,'open-motion/dev/install.md');return {body:new Response(guide).body!,text:async()=>guide,httpEtag:'etag',writeHttpMetadata(){}}; } } }; + for (const source of ['', 'producthunt', 'partner']) { + const response = await worker.fetch(new Request('https://releases.open-design.ai/open-motion/dev/install.md'+(source?'?utm_source='+source:'')),env); + assert.equal(response.headers.get('cache-control'),'no-store'); + const text = await response.text(); + if (!source) assert.equal(text,guide); + else { assert.ok(text.includes('setup --host codex --utm-source '+source));assert.ok(text.includes('setup --host deepseek --utm-source '+source+' --profile PROFILE')); } + assert.ok(text.includes('`openmotion prepare`')); + } +}); diff --git a/tests/npm-installer.test.ts b/tests/npm-installer.test.ts index 1b3b54250..d4e053df8 100644 --- a/tests/npm-installer.test.ts +++ b/tests/npm-installer.test.ts @@ -38,6 +38,11 @@ async function setupFixture(t: any) { await writeFile(path.join(application, 'skills/motion-production/SKILL.md'), '---\nname: motion-production\ndescription: fixture\n---\nFixture'); await writeJSON(path.join(application, 'shared/template-config.json'), { environment: 'prod' }); await cp(new URL('../shared/mcp-profiles.json', import.meta.url), path.join(application, 'shared/mcp-profiles.json')); + await mkdir(path.join(application, 'tracking')); + for (const file of ['shared/install-attribution.ts', 'tracking/node.ts', 'tracking/core.ts']) { + await cp(new URL('../' + file, import.meta.url), path.join(application, file)); + } + await writeFile(path.join(application, 'shared/tracking.ts'), 'export function trackingLocked(){return false} export function trackingPreference(){return true} export async function createAppTracking(){return {track(){}}} export async function closeTracking(){}'); await writeJSON(path.join(application, 'package.json'), { name: 'motion-fixture', version: '1.2.3', private: true }); await writeJSON(path.join(application, 'package-lock.json'), { name: 'motion-fixture', version: '1.2.3', lockfileVersion: 3, packages: { '': { name: 'motion-fixture', version: '1.2.3' } } }); const manifest = path.join(directory, 'release.json'); @@ -459,3 +464,18 @@ test('registration failure restores obsolete flat Skills, and malformed install await assert.rejects(setup(options), /belongs to another/); assert.equal(JSON.parse(await readFile(state, 'utf8')), false); }); + + +test('setup passes optional attribution to the application and untagged upgrades retain it', async t => { + const options = await setupFixture(t); + await setup({...options, utmSource: 'producthunt'}); + const read = async () => JSON.parse(await readFile(path.join(options.home, 'data/tracking/identity.json'), 'utf8')); + const first = await read(); + assert.equal(first.utm_source, 'producthunt'); + await setup(options); + assert.deepEqual(await read(), first); + await setup({...options, utmSource: 'partner'}); + const updated = await read(); + assert.equal(updated.utm_source, 'partner'); + assert.equal(updated.installation_id, first.installation_id); +}); diff --git a/tests/tracking.test.ts b/tests/tracking.test.ts index 06f6d2732..da8e66022 100644 --- a/tests/tracking.test.ts +++ b/tests/tracking.test.ts @@ -1,10 +1,11 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { readFile, readdir, writeFile } from 'node:fs/promises'; +import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'; import path from 'node:path'; +import { tmpdir } from 'node:os'; import { execFileSync } from 'node:child_process'; import { createTracker, deviceContext } from '../tracking/core.ts'; -import { createPosthogSender, loadIdentity } from '../tracking/node.ts'; +import { createPosthogSender, loadIdentity, saveInstallationSource } from '../tracking/node.ts'; import { omEvents } from '../tracking/events.ts'; import { closeTracking, createAppTracking, saveTrackingPreference, trackingError } from '../shared/tracking.ts'; import { Phase1Service } from '../phase1.ts'; @@ -85,7 +86,7 @@ test('PostHog adapter uses public ingest only, privacy fields and real receipt s const data = seen[0].batch[0]; assert.equal(data.uuid, event.event_id); assert.equal(data.timestamp, event.occurred_at); assert.equal(data.properties.distinct_id, identity.installation_id); assert.equal(data.properties.device_id, identity.installation_id); - assert.equal(data.properties.utm_source, 'alice'); assert.equal(data.properties.event_schema_version, 1); + assert.equal(data.properties.od_utm_source, 'alice'); assert.equal(data.properties.utm_source, 'alice'); assert.equal(data.properties.event_schema_version, 1); assert.equal(data.properties.$ip, '0.0.0.0'); assert.equal(data.properties.$geoip_disable, true); assert.equal(data.properties.$process_person_profile, false); response = new Response('{"status":"Ok"}'); assert.equal(await sender([event], new AbortController().signal), 'accepted'); @@ -199,3 +200,18 @@ test('worker reports a real terminal render failure once, separately from queue assert.equal((await store.get()).revision, current.revision); assert.equal(events[0].properties.technical_check, 'unknown'); tracking.close(); })); + + +test('installation source is optional, survives untagged upgrades and changes only explicitly', async t => { + const directory = await mkdtemp(path.join(tmpdir(), 'motion-source-')); + t.after(() => rm(directory, {recursive: true, force: true})); + const first = await saveInstallationSource(directory); + assert.equal(first.utm_source, null); + const ph = await saveInstallationSource(directory, 'producthunt'); + assert.equal(ph.installation_id, first.installation_id); + assert.equal(ph.utm_source, 'producthunt'); + assert.equal((await saveInstallationSource(directory)).utm_source, 'producthunt'); + assert.equal((await loadIdentity(directory)).utm_source, 'producthunt'); + assert.equal((await saveInstallationSource(directory, 'partner')).utm_source, 'partner'); + await assert.rejects(saveInstallationSource(directory, '$(bad)'), /INVALID_SOURCE/); +}); diff --git a/tracking/events.ts b/tracking/events.ts index b2ec8f2fd..4fbe2dd46 100644 --- a/tracking/events.ts +++ b/tracking/events.ts @@ -8,6 +8,7 @@ const tool = { tool_name: toolNames, call_id: 'uuid', operation_id: 'uuid', acce const business = { outcome, project_id: 'uuid', operation_id: 'uuid', replayed: 'boolean', error_code: 'code' } as const; export const omEvents = { + installation_result: { producers: ['installer'], fields: { outcome: ['success'], host_product: ['codex', 'claude', 'deepseek', 'workbuddy'] }, required: ['outcome', 'host_product'] }, 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'] }, diff --git a/tracking/node.ts b/tracking/node.ts index 1fdd233e2..8cdddfb1d 100644 --- a/tracking/node.ts +++ b/tracking/node.ts @@ -1,4 +1,4 @@ -import { link, mkdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { link, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'; import path from 'node:path'; import os from 'node:os'; import { createTracker, uuid } from './core.ts'; @@ -30,9 +30,22 @@ export async function loadIdentity(directory: string, source?: string): Promise< } finally { await rm(temporary, { force: true }); } } +// Only an explicit installation updates attribution; ordinary startup retains it. +export async function saveInstallationSource(directory: string, source?: string): Promise { + const identity = await loadIdentity(directory, source); + if (source === undefined || source === identity.utm_source) return identity; + const updated = { ...identity, utm_source: source }; + const temporary = path.join(directory, 'identity.' + crypto.randomUUID() + '.tmp'); + try { + await writeFile(temporary, JSON.stringify(updated), { mode: 0o600, flag: 'wx' }); + await rename(temporary, path.join(directory, 'identity.json')); + } finally { await rm(temporary, { force: true }); } + return updated; +} + export function createPosthogSender(options: { host: string; token: string; identity: Identity; appVersion: string; - env: 'development' | 'test' | 'production'; testRunId?: string; timeoutMs?: number; fetch?: typeof fetch; geoip?: boolean; + env: 'development' | 'test' | 'production'; testRunId?: string; timeoutMs?: number; fetch?: typeof fetch; geoip?: boolean; source?: () => string | null; }) { const url = new URL(options.host); if (url.username || url.password || url.search || url.hash || url.pathname !== '/') throw new Error('INVALID_INGEST_HOST'); @@ -40,13 +53,15 @@ export function createPosthogSender(options: { if (!/^phc_[A-Za-z0-9_]+$/.test(options.token)) throw new Error('PUBLIC_PROJECT_TOKEN_REQUIRED'); if (options.testRunId && (!uuid.test(options.testRunId) || options.env !== 'test')) throw new Error('INVALID_TEST_RUN'); return async (events: readonly PendingEvent[], signal: AbortSignal): Promise => { + const source = options.source?.() ?? options.identity.utm_source; const batch = events.map(event => ({ event: event.event, uuid: event.event_id, timestamp: event.occurred_at, properties: { ...event.properties, event_schema_version: 1, schema_version: 1, product: 'openmotion', app_version: options.appVersion, env: options.env, channel: 'standalone', ...(options.testRunId ? { test_run_id: options.testRunId } : {}), event_id: event.event_id, $insert_id: event.event_id, occurred_at: event.occurred_at, installation_id: options.identity.installation_id, device_id: options.identity.installation_id, - distinct_id: options.identity.installation_id, utm_source: options.identity.utm_source, + distinct_id: options.identity.installation_id, utm_source: source, + od_utm_source: source, entrypoint: event.entrypoint, runtime: event.entrypoint === 'studio' ? 'browser' : 'node', capture_source: 'explicit', client_type: event.entrypoint === 'studio' ? 'web' : 'local', platform: os.platform(), arch: os.arch(), $os: os.type(), $os_version: os.release(), @@ -74,7 +89,7 @@ export function createPosthogSender(options: { export function createNodeTracking(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; geoip?: boolean; isEnabled?: () => boolean; + enabled: boolean; timeoutMs?: number; flushIntervalMs?: number; maxQueue?: number; geoip?: boolean; source?: () => string | null; isEnabled?: () => boolean; }) { const enabled = options.enabled && !!options.token; const send = enabled ? createPosthogSender({ ...options, token: options.token! }) : async () => 'drop' as const; diff --git a/workers/install-guide/index.ts b/workers/install-guide/index.ts new file mode 100644 index 000000000..312d31543 --- /dev/null +++ b/workers/install-guide/index.ts @@ -0,0 +1,28 @@ +type GuideObject = { body: ReadableStream; text(): Promise; writeHttpMetadata(headers: Headers): void }; +type Environment = { RELEASES: { get(key: string): Promise } }; +const marker = ''; + +export function attributeGuide(text: string, source: string | null): string { + if (!source || !/^[A-Za-z0-9_.-]{1,64}$/.test(source) || !text.includes(marker)) return text; + return text.replace(/openmotion setup --host (codex|claude|deepseek|workbuddy)\b/g, + command => `${command} --utm-source ${source}`); +} + +export default { + async fetch(request: Request, env: Environment): Promise { + const url = new URL(request.url); + if (!/^\/open-motion\/(?:dev\/)?install\.md$/.test(url.pathname)) return new Response('Not found', { status: 404 }); + if (!['GET', 'HEAD'].includes(request.method)) return new Response('Method not allowed', { status: 405, headers: { Allow: 'GET, HEAD' } }); + const object = await env.RELEASES.get(url.pathname.slice(1)); + if (!object) return new Response('Not found', { status: 404 }); + const headers = new Headers(); + object.writeHttpMetadata(headers); + headers.set('Content-Type', 'text/markdown; charset=utf-8'); + // The guide is small. Do not cache transformed responses or reuse an R2 ETag across channels. + headers.set('Cache-Control', 'no-store'); + const source = url.searchParams.get('utm_source'); + if (!source) return new Response(request.method === 'HEAD' ? null : object.body, { headers }); + const text = attributeGuide(await object.text(), source); + return new Response(request.method === 'HEAD' ? null : text, { headers }); + }, +}; diff --git a/workers/install-guide/wrangler.toml b/workers/install-guide/wrangler.toml new file mode 100644 index 000000000..b76df63e8 --- /dev/null +++ b/workers/install-guide/wrangler.toml @@ -0,0 +1,12 @@ +name = "openmotion-install-guide" +main = "index.ts" +account_id = "64ad4569ffd912432d6b86d5656484c4" +compatibility_date = "2026-11-11" +workers_dev = true + +[[r2_buckets]] +binding = "RELEASES" +bucket_name = "open-design-releases" + +# Attach only the two moving install.md paths after testing a package that supports --utm-source. +# Immutable versioned guides and other release resources continue to be served by R2. From 67fc80ca28deb1c27eed0c978ec9a8be4fcb419e Mon Sep 17 00:00:00 2001 From: lefarcen <935902669@qq.com> Date: Wed, 11 Nov 2026 16:16:35 +0800 Subject: [PATCH 2/4] feat(motion): serve installation guides on environment-specific domains --- docs/install-attribution.md | 6 ++++-- shared/integration.ts | 2 +- tests/catalog.test.ts | 8 ++++---- tests/install-attribution-worker.test.ts | 15 ++++++++++++++- workers/install-guide/index.ts | 15 +++++++++++++-- workers/install-guide/wrangler.toml | 6 ++++-- 6 files changed, 40 insertions(+), 12 deletions(-) diff --git a/docs/install-attribution.md b/docs/install-attribution.md index cd371092f..211fd6582 100644 --- a/docs/install-attribution.md +++ b/docs/install-attribution.md @@ -14,8 +14,10 @@ Website URL `?utm_source=producthunt` → copied guide URL with the same query 1. Merge and publish the installer supporting `--utm-source`. The generated guide includes `` only with that source version. 2. Deploy `wrangler deploy --config workers/install-guide/wrangler.toml` in the Powerformer account. The binding reads the existing `open-design-releases` bucket; it does not upload or modify release objects. -3. Verify the independent workers.dev endpoint against both attributed and direct requests. -4. Attach only `releases.open-design.ai/open-motion/install.md*` and `releases.open-design.ai/open-motion/dev/install.md*` after installer publication. Other release paths remain on R2. Remove these two routes to roll back. +3. Verify the test entry `https://open-design.powerformer.net/motion/install.md` against both attributed and direct requests. The Worker maps this host to `open-motion/dev/install.md`. +4. After validation, enable `https://open-design.ai/motion/install.md` separately; it maps to `open-motion/install.md`. The checked-in route activates only the test host. Other website and R2 paths remain unchanged. Removing the added route rolls back the new entry; existing R2 links remain available. + +Both entries may serve older guides without injecting a parameter; injection starts only after a supporting installer and marked guide are published. Website feature previews use the test installation entry, while their Pages deployment stays on the feature branch. R2 upload/readback origins are not installation entry URLs. An older guide without the marker is served unchanged, even when a source query is supplied. Transformed responses use `Cache-Control: no-store` to prevent channel mixing. Unrecognized paths return 404; GET and HEAD are supported. diff --git a/shared/integration.ts b/shared/integration.ts index 4301b42a5..289cd9d5d 100644 --- a/shared/integration.ts +++ b/shared/integration.ts @@ -75,7 +75,7 @@ export function setupPrompt(info: IntegrationInfo, host: IntegrationHost, locale } export function templatePrompt(info: IntegrationInfo, _host: IntegrationHost, template: { id: string; title: string }, locale = 'zh-CN') { const environment = info.templateEnvironment ?? info.transport.env?.MOTION_TEMPLATE_ENV ?? 'prod'; - const installUrl = `https://releases.open-design.ai/open-motion/${environment === 'dev' ? 'dev/' : ''}install.md`; + const installUrl = `https://${environment === 'dev' ? 'open-design.powerformer.net' : 'open-design.ai'}/motion/install.md`; const message = templatePrompts[catalogLocale(Object.keys(templatePrompts), locale, 'en')]; const values = { installUrl, name: template.title, id: template.id }; return message.replace(/\{(installUrl|name|id)\}/g, (_, key: keyof typeof values) => values[key]); diff --git a/tests/catalog.test.ts b/tests/catalog.test.ts index 9e428f329..ba60b536e 100644 --- a/tests/catalog.test.ts +++ b/tests/catalog.test.ts @@ -87,7 +87,7 @@ test('HTTP catalog, local posters and copied guides resolve the exact selected t for (const host of ['codex', 'claude', 'deepseek', 'mcp'] as const) { const prompt = templatePrompt(info, host, template); assert.ok(prompt.includes(id)); assert.ok(prompt.includes(template.title)); - assert.match(prompt, /https:\/\/releases.open-design.ai\/open-motion\/install.md/); + assert.match(prompt, /https:\/\/open-design\.ai\/motion\/install\.md/); assert.match(prompt, /并交付 HTML 和 MP4/); assert.ok(prompt.endsWith('我的要求:\n')); assert.doesNotMatch(prompt, /dataDirectory|motion_write_files|expectedRevision/); assert.doesNotMatch(prompt, /localhost|127\.0\.0\.1|connect\/guide/); @@ -159,11 +159,11 @@ test('the visual gallery only includes verified local covers and keeps coverless test('template prompts use public installation URLs for the effective package environment', () => { const info = { templateEnvironment: 'dev', previewUrl: 'http://127.0.0.1:1234', transport: { env: {} } } as Parameters[0]; const template = { id: 'exact-id', title: 'Selected template' }; - assert.match(templatePrompt(info, 'codex', template), /open-motion\/dev\/install.md/); + assert.match(templatePrompt(info, 'codex', template), /open-design\.powerformer\.net\/motion\/install\.md/); info.templateEnvironment = 'prod'; info.transport.env.MOTION_TEMPLATE_ENV = 'dev'; const prompt = templatePrompt(info, 'claude', template, 'en'); - assert.match(prompt, /open-motion\/install.md/); assert.doesNotMatch(prompt, /\/dev\/|127\.0\.0\.1|localhost/); + assert.match(prompt, /open-design\.ai\/motion\/install\.md/); assert.doesNotMatch(prompt, /\/dev\/|127\.0\.0\.1|localhost/); assert.match(prompt, /Selected template \(exact-id\)/); assert.match(prompt, /HTML and MP4/); }); @@ -176,7 +176,7 @@ test('template prompts cover all eleven locales and preserve literal template va assert.equal(new Set(prompts).size, 11); for (const prompt of prompts) { assert.ok(prompt.includes(template.title)); assert.ok(prompt.includes(template.id)); - assert.ok(prompt.includes('https://releases.open-design.ai/open-motion/dev/install.md')); + assert.ok(prompt.includes('https://open-design.powerformer.net/motion/install.md')); assert.match(prompt, /HTML.*MP4/); assert.doesNotMatch(prompt, /\{installUrl\}|\{id\}/); } assert.equal(templatePrompt(info, 'codex', template, 'pt-BR'), templatePrompt(info, 'codex', template, 'pt-br')); diff --git a/tests/install-attribution-worker.test.ts b/tests/install-attribution-worker.test.ts index 8e81a91b2..ff6a97cb6 100644 --- a/tests/install-attribution-worker.test.ts +++ b/tests/install-attribution-worker.test.ts @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import worker, { attributeGuide } from '../workers/install-guide/index.ts'; +import worker, { attributeGuide, guideKey } from '../workers/install-guide/index.ts'; const guide = '\n`openmotion setup --host codex`\n`openmotion setup --host deepseek --profile PROFILE`\n`openmotion prepare`'; test('worker keeps untagged and older guides unchanged and annotates only setup commands', async () => { assert.equal(attributeGuide(guide,null),guide); @@ -16,3 +16,16 @@ test('worker keeps untagged and older guides unchanged and annotates only setup assert.ok(text.includes('`openmotion prepare`')); } }); + + +test('public installation domains select their own environment without a fallback', async () => { + for (const [host,key] of [['open-design.powerformer.net','open-motion/dev/install.md'],['open-design.ai','open-motion/install.md']]) { + const url = new URL('https://' + host + '/motion/install.md?utm_source=producthunt'); + assert.equal(guideKey(url),key); + const env = { RELEASES: { async get(actual: string) { assert.equal(actual,key); return null; } } }; + assert.equal((await worker.fetch(new Request(url),env)).status,404); + } + assert.equal(guideKey(new URL('https://unknown.example/motion/install.md')),null); + assert.equal(guideKey(new URL('https://open-design.ai/motion/templates/')),null); + assert.equal(guideKey(new URL('https://releases.open-design.ai/open-motion/dev/install.md')),'open-motion/dev/install.md'); +}); diff --git a/workers/install-guide/index.ts b/workers/install-guide/index.ts index 312d31543..e266d0663 100644 --- a/workers/install-guide/index.ts +++ b/workers/install-guide/index.ts @@ -8,12 +8,23 @@ export function attributeGuide(text: string, source: string | null): string { command => `${command} --utm-source ${source}`); } +export function guideKey(url: URL): string | null { + if (url.pathname === '/motion/install.md') { + if (url.hostname === 'open-design.powerformer.net') return 'open-motion/dev/install.md'; + if (url.hostname === 'open-design.ai') return 'open-motion/install.md'; + return null; + } + // Preserve the original release URLs and independent Worker preview paths. + return /^\/open-motion\/(?:dev\/)?install\.md$/.test(url.pathname) ? url.pathname.slice(1) : null; +} + export default { async fetch(request: Request, env: Environment): Promise { const url = new URL(request.url); - if (!/^\/open-motion\/(?:dev\/)?install\.md$/.test(url.pathname)) return new Response('Not found', { status: 404 }); + const key = guideKey(url); + if (!key) return new Response('Not found', { status: 404 }); if (!['GET', 'HEAD'].includes(request.method)) return new Response('Method not allowed', { status: 405, headers: { Allow: 'GET, HEAD' } }); - const object = await env.RELEASES.get(url.pathname.slice(1)); + const object = await env.RELEASES.get(key); if (!object) return new Response('Not found', { status: 404 }); const headers = new Headers(); object.writeHttpMetadata(headers); diff --git a/workers/install-guide/wrangler.toml b/workers/install-guide/wrangler.toml index b76df63e8..6a3559c24 100644 --- a/workers/install-guide/wrangler.toml +++ b/workers/install-guide/wrangler.toml @@ -8,5 +8,7 @@ workers_dev = true binding = "RELEASES" bucket_name = "open-design-releases" -# Attach only the two moving install.md paths after testing a package that supports --utm-source. -# Immutable versioned guides and other release resources continue to be served by R2. +# Test entry only. Keep production activation separate until verified. +[[routes]] +pattern = "open-design.powerformer.net/motion/install.md*" +zone_name = "powerformer.net" From 1277b6abfd2938f6fb2f91a651e778d997ae5423 Mon Sep 17 00:00:00 2001 From: luogao Date: Wed, 11 Nov 2026 16:33:15 +0800 Subject: [PATCH 3/4] fix(motion): pass the release source scan for install attribution The tracked-source scan rejects full internal URLs, so the new attribution doc and the eleven-locale prompt assertion failed the standalone job. Keep the deployment entry as a bare hostname like the other docs, and assert the setup URL with the regex form already used for the same host in this file. Validation: gitleaks source scan passed (3349 files); release-scan, release-workflows, registry-download and stable-release tests passed (35); tests/catalog.test.ts passed (7); npm run check and typecheck:studio passed. Generated-By: looper 0.16.2 (runner=fixer, agent=pi) --- docs/install-attribution.md | 4 ++-- tests/catalog.test.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/install-attribution.md b/docs/install-attribution.md index 9a0666825..6e104f907 100644 --- a/docs/install-attribution.md +++ b/docs/install-attribution.md @@ -14,8 +14,8 @@ Website URL `?utm_source=producthunt` → copied guide URL with the same query 1. Merge and publish the installer supporting `--utm-source`. The generated guide includes `` only with that source version. 2. Deploy `wrangler deploy --config workers/install-guide/wrangler.toml` in the Powerformer account. The binding reads the existing `open-design-releases` bucket; it does not upload or modify release objects. -3. Verify the test entry `https://open-design.powerformer.net/motion/install.md` against both attributed and direct requests. The Worker maps this host to `open-motion/dev/install.md`. -4. After validation, enable `https://open-design.ai/motion/install.md` separately; it maps to `open-motion/install.md`. The checked-in route activates only the test host. Other website and R2 paths remain unchanged. Removing the added route rolls back the new entry; existing R2 links remain available. +3. Verify the test entry `open-design.powerformer.net/motion/install.md` against both attributed and direct requests. The Worker maps this host to `open-motion/dev/install.md`. +4. After validation, enable `open-design.ai/motion/install.md` separately; it maps to `open-motion/install.md`. The checked-in route activates only the test host. Other website and R2 paths remain unchanged. Removing the added route rolls back the new entry; existing R2 links remain available. Both entries may serve older guides without injecting a parameter; injection starts only after a supporting installer and marked guide are published. Website feature previews use the test installation entry, while their Pages deployment stays on the feature branch. R2 upload/readback origins are not installation entry URLs. diff --git a/tests/catalog.test.ts b/tests/catalog.test.ts index ba60b536e..e216c1a8d 100644 --- a/tests/catalog.test.ts +++ b/tests/catalog.test.ts @@ -176,7 +176,7 @@ test('template prompts cover all eleven locales and preserve literal template va assert.equal(new Set(prompts).size, 11); for (const prompt of prompts) { assert.ok(prompt.includes(template.title)); assert.ok(prompt.includes(template.id)); - assert.ok(prompt.includes('https://open-design.powerformer.net/motion/install.md')); + assert.match(prompt, /https:\/\/open-design\.powerformer\.net\/motion\/install\.md/); assert.match(prompt, /HTML.*MP4/); assert.doesNotMatch(prompt, /\{installUrl\}|\{id\}/); } assert.equal(templatePrompt(info, 'codex', template, 'pt-BR'), templatePrompt(info, 'codex', template, 'pt-br')); From 6509ce2f50aa1a74653a29d9771207e21be9b19a Mon Sep 17 00:00:00 2001 From: luogao Date: Wed, 11 Nov 2026 17:37:36 +0800 Subject: [PATCH 4/4] fix(motion): gate install attribution to the packaged installer and enabled entry - Read the sealed installer from the candidate archive and drop the support marker when that exact installer does not accept --utm-source, so a guide built for an older integrated source never hands setup an unsupported flag. - Keep prod template prompts on the existing R2 installation guide until the production website entry is activated and verified; only the enabled test entry moves to its environment host. - Bind the injected campaign source with `=` so allowlisted values that start with a hyphen remain one option value. Generated-By: looper 0.16.2 (runner=fixer, agent=pi) --- docs/install-attribution.md | 6 +++--- scripts/install-guide.mjs | 18 +++++++++++++++- shared/integration.ts | 7 ++++++- studio/src/motion/HomeTemplates.test.tsx | 2 +- .../src/motion/TemplateLibraryDialog.test.tsx | 2 +- tests/catalog.test.ts | 4 ++-- tests/install-attribution-worker.test.ts | 5 ++++- tests/install-guide.test.ts | 21 +++++++++++++++++-- workers/install-guide/index.ts | 3 ++- 9 files changed, 55 insertions(+), 13 deletions(-) diff --git a/docs/install-attribution.md b/docs/install-attribution.md index 6e104f907..604149ba6 100644 --- a/docs/install-attribution.md +++ b/docs/install-attribution.md @@ -1,6 +1,6 @@ # Installation attribution -Website URL `?utm_source=producthunt` → copied guide URL with the same query → Worker adds `--utm-source producthunt` to setup commands → installer saves the source → subsequent events carry `od_utm_source`. +Website URL `?utm_source=producthunt` → copied guide URL with the same query → Worker adds `--utm-source=producthunt` to setup commands → installer saves the source → subsequent events carry `od_utm_source`. ## Compatibility @@ -12,12 +12,12 @@ Website URL `?utm_source=producthunt` → copied guide URL with the same query ## Deployment order -1. Merge and publish the installer supporting `--utm-source`. The generated guide includes `` only with that source version. +1. Merge and publish the installer supporting `--utm-source`. Guide generation reads the packaged installer and includes `` only when that exact installer accepts the option, so a guide sealed for an older integrated source never offers it. 2. Deploy `wrangler deploy --config workers/install-guide/wrangler.toml` in the Powerformer account. The binding reads the existing `open-design-releases` bucket; it does not upload or modify release objects. 3. Verify the test entry `open-design.powerformer.net/motion/install.md` against both attributed and direct requests. The Worker maps this host to `open-motion/dev/install.md`. 4. After validation, enable `open-design.ai/motion/install.md` separately; it maps to `open-motion/install.md`. The checked-in route activates only the test host. Other website and R2 paths remain unchanged. Removing the added route rolls back the new entry; existing R2 links remain available. -Both entries may serve older guides without injecting a parameter; injection starts only after a supporting installer and marked guide are published. Website feature previews use the test installation entry, while their Pages deployment stays on the feature branch. R2 upload/readback origins are not installation entry URLs. +Both entries may serve older guides without injecting a parameter; injection starts only after a supporting installer and marked guide are published. Website feature previews, and the template prompts they copy, use the test installation entry, while their Pages deployment stays on the feature branch. Copied template prompts keep the existing R2 guide for prod until step 4 activates and verifies that entry. R2 upload/readback origins are not installation entry URLs. An older guide without the marker is served unchanged, even when a source query is supplied. Transformed responses use `Cache-Control: no-store` to prevent channel mixing. Unrecognized paths return 404; GET and HEAD are supported. diff --git a/scripts/install-guide.mjs b/scripts/install-guide.mjs index 2b756ac94..ea6cbe09a 100644 --- a/scripts/install-guide.mjs +++ b/scripts/install-guide.mjs @@ -5,6 +5,19 @@ import { fileURLToPath } from 'node:url'; import { runFile, sha256, writeAtomic, writeJSON } from './runtime-assets.mjs'; import { checkReleaseVersion, releaseTemplateEnvironment } from './release-version.mjs'; +const attributionMarker = ''; + +// The sealed archive may come from an older integrated source than this control checkout, so +// declare support only for the installer that the guide actually pins. +export function supportsInstallAttribution(installer) { + return /--utm-source\b/.test(installer) && /['"]utm-source['"]\s*:/.test(installer); +} + +async function readPackagedInstaller(tgz) { + try { return await runFile('tar', ['-xOf', path.resolve(tgz), 'package/scripts/npm-installer.mjs']); } + catch { return ''; } +} + export function validateGuideSpec(name, version) { assert.match(name || '', /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/, 'Require an npm package name'); assert(name.length <= 214, 'npm package name is too long'); @@ -31,16 +44,19 @@ export async function generateInstallGuide(tgz, output, candidate = false) { const pkg = await readEntry('package/package.json'), manifest = await readEntry('package/payload/release-npm.json'); const channel = validateGuideIdentity(pkg, manifest); const digest = await sha256(tgz), packageSpec = `${pkg.name}@${pkg.version}`; + const attribution = supportsInstallAttribution(await readPackagedInstaller(tgz)); const values = { VERSION: pkg.version, PACKAGE_SPEC: packageSpec, CHANNEL: channel, COMMIT: manifest.commit, TEMPLATE_ENVIRONMENT: manifest.templateEnvironment, TGZ_SHA256: digest, TARGETS: Object.values(manifest.runtime.targets).map(t => `${t.platform}/${t.arch} (${t.minimumOS}+)`).join(', '), DETAILS_URL: `https://github.com/nexu-io/html-anything/blob/${manifest.commit}/docs/npm-installation.md` }; const template = await readFile(new URL('../docs/install.md', import.meta.url), 'utf8'); // The repository warning is unnecessary after all release placeholders are resolved. - const text = (candidate ? '> Build preview only: this candidate is not an approved registry installation entry.\n\n' : '') + template.replace(/^If you are reading this file.*\n\n/m, '').replace(/\{\{([A-Z0-9_]+)\}\}/g, (_, key) => { + let text = (candidate ? '> Build preview only: this candidate is not an approved registry installation entry.\n\n' : '') + template.replace(/^If you are reading this file.*\n\n/m, '').replace(/\{\{([A-Z0-9_]+)\}\}/g, (_, key) => { assert(Object.hasOwn(values, key), 'Unknown installation placeholder: ' + key); return values[key]; }); assert(!text.includes('{{'), 'Installation guide has unresolved placeholders'); + // An older packaged installer rejects --utm-source, so it must not be offered one. + if (!attribution) text = text.replace(`${attributionMarker}\n\n`, ''); await mkdir(output, { recursive: true }); await writeAtomic(path.join(output, 'install.md'), text); const record = { schemaVersion: 1, candidate, packageName: pkg.name, version: pkg.version, packageSpec, channel, diff --git a/shared/integration.ts b/shared/integration.ts index 289cd9d5d..decbcf513 100644 --- a/shared/integration.ts +++ b/shared/integration.ts @@ -3,6 +3,7 @@ import { catalogLocale } from './template-locale.ts'; import { workflowEntryGuide } from './workflow-entry.js'; export const integrationHosts = ['codex', 'claude', 'deepseek', 'chatgpt', 'mcp'] as const; +const TEST_INSTALL_HOST = 'open-design.powerformer.net'; export type IntegrationHost = typeof integrationHosts[number]; export const hostNames: Record = { codex: 'Codex', claude: 'Claude Code', deepseek: 'DeepSeek Harness', chatgpt: 'ChatGPT', mcp: 'MCP / CLI' }; export const hostDescriptions: Record = { @@ -75,7 +76,11 @@ export function setupPrompt(info: IntegrationInfo, host: IntegrationHost, locale } export function templatePrompt(info: IntegrationInfo, _host: IntegrationHost, template: { id: string; title: string }, locale = 'zh-CN') { const environment = info.templateEnvironment ?? info.transport.env?.MOTION_TEMPLATE_ENV ?? 'prod'; - const installUrl = `https://${environment === 'dev' ? 'open-design.powerformer.net' : 'open-design.ai'}/motion/install.md`; + // The production website entry stays disabled until it is activated and verified, so prod keeps + // the existing R2 guide; only the enabled test entry moves to its environment host. + const installUrl = environment === 'dev' + ? `https://${TEST_INSTALL_HOST}/motion/install.md` + : 'https://releases.open-design.ai/open-motion/install.md'; const message = templatePrompts[catalogLocale(Object.keys(templatePrompts), locale, 'en')]; const values = { installUrl, name: template.title, id: template.id }; return message.replace(/\{(installUrl|name|id)\}/g, (_, key: keyof typeof values) => values[key]); diff --git a/studio/src/motion/HomeTemplates.test.tsx b/studio/src/motion/HomeTemplates.test.tsx index 7ccf3a02c..570d29207 100644 --- a/studio/src/motion/HomeTemplates.test.tsx +++ b/studio/src/motion/HomeTemplates.test.tsx @@ -43,7 +43,7 @@ it('only editable templates open a new engineering project; references copy thei await act(async () => button('一键复制').click()); expect(clipboard).toHaveBeenCalledOnce(); expect(clipboard.mock.calls[0][0]).toContain('指定模板:Reference(hf-moment-M953)'); - expect(clipboard.mock.calls[0][0]).toContain('https://releases.open-design.ai/open-motion/dev/install.md'); + expect(clipboard.mock.calls[0][0]).toContain('https://open-design.powerformer.net/motion/install.md'); expect(clipboard.mock.calls[0][0]).not.toContain('localhost'); expect(state.open).toHaveBeenCalledTimes(1); expect(container.textContent).toContain('已复制'); diff --git a/studio/src/motion/TemplateLibraryDialog.test.tsx b/studio/src/motion/TemplateLibraryDialog.test.tsx index b93114c8a..e2370dfaa 100644 --- a/studio/src/motion/TemplateLibraryDialog.test.tsx +++ b/studio/src/motion/TemplateLibraryDialog.test.tsx @@ -49,7 +49,7 @@ it('copies the requested remote DEV prompt and preserves editable opening', asyn expect(host.querySelector('dialog[aria-label=复刻模板] textarea')).not.toBeNull(); expect(host.querySelector('dialog[aria-label=模板预览] textarea')).toBeNull(); await act(async () => host.querySelector('button[aria-label=复制]')!.click()); - expect(navigator.clipboard.writeText).toHaveBeenCalledWith('使用说明:请使用 OpenMotion 插件。如未安装,请按 https://releases.open-design.ai/open-motion/dev/install.md 安装并接入后继续。\n指定模板:First(one)\n创作要求:基于模板,结合我的要求和附件创作,默认保留主要动效与风格,并交付 HTML 和 MP4。\n我的要求:\n'); + expect(navigator.clipboard.writeText).toHaveBeenCalledWith('使用说明:请使用 OpenMotion 插件。如未安装,请按 https://open-design.powerformer.net/motion/install.md 安装并接入后继续。\n指定模板:First(one)\n创作要求:基于模板,结合我的要求和附件创作,默认保留主要动效与风格,并交付 HTML 和 MP4。\n我的要求:\n'); await act(async () => button('打开并编辑 ↗').click()); expect(onOpen).toHaveBeenCalledWith('one'); await act(async () => button('Second').click()); diff --git a/tests/catalog.test.ts b/tests/catalog.test.ts index e216c1a8d..61c52be15 100644 --- a/tests/catalog.test.ts +++ b/tests/catalog.test.ts @@ -87,7 +87,7 @@ test('HTTP catalog, local posters and copied guides resolve the exact selected t for (const host of ['codex', 'claude', 'deepseek', 'mcp'] as const) { const prompt = templatePrompt(info, host, template); assert.ok(prompt.includes(id)); assert.ok(prompt.includes(template.title)); - assert.match(prompt, /https:\/\/open-design\.ai\/motion\/install\.md/); + assert.match(prompt, /https:\/\/releases\.open-design\.ai\/open-motion\/install\.md/); assert.match(prompt, /并交付 HTML 和 MP4/); assert.ok(prompt.endsWith('我的要求:\n')); assert.doesNotMatch(prompt, /dataDirectory|motion_write_files|expectedRevision/); assert.doesNotMatch(prompt, /localhost|127\.0\.0\.1|connect\/guide/); @@ -163,7 +163,7 @@ test('template prompts use public installation URLs for the effective package en info.templateEnvironment = 'prod'; info.transport.env.MOTION_TEMPLATE_ENV = 'dev'; const prompt = templatePrompt(info, 'claude', template, 'en'); - assert.match(prompt, /open-design\.ai\/motion\/install\.md/); assert.doesNotMatch(prompt, /\/dev\/|127\.0\.0\.1|localhost/); + assert.match(prompt, /releases\.open-design\.ai\/open-motion\/install\.md/); assert.doesNotMatch(prompt, /\/dev\/|powerformer|open-design\.ai\/motion|127\.0\.0\.1|localhost/); assert.match(prompt, /Selected template \(exact-id\)/); assert.match(prompt, /HTML and MP4/); }); diff --git a/tests/install-attribution-worker.test.ts b/tests/install-attribution-worker.test.ts index ff6a97cb6..a66f4f576 100644 --- a/tests/install-attribution-worker.test.ts +++ b/tests/install-attribution-worker.test.ts @@ -6,13 +6,16 @@ test('worker keeps untagged and older guides unchanged and annotates only setup assert.equal(attributeGuide(guide,null),guide); assert.equal(attributeGuide(guide,'$(bad)'),guide); assert.equal(attributeGuide('openmotion setup --host codex','producthunt'),'openmotion setup --host codex'); + // A value starting with a hyphen stays one unambiguous option value for the installer. + assert.ok(attributeGuide(guide,'--help').includes('`openmotion setup --host codex --utm-source=--help`')); + assert.ok(attributeGuide(guide,'-x').includes('`openmotion setup --host codex --utm-source=-x`')); const env = { RELEASES: { async get(key: string) { assert.equal(key,'open-motion/dev/install.md');return {body:new Response(guide).body!,text:async()=>guide,httpEtag:'etag',writeHttpMetadata(){}}; } } }; for (const source of ['', 'producthunt', 'partner']) { const response = await worker.fetch(new Request('https://releases.open-design.ai/open-motion/dev/install.md'+(source?'?utm_source='+source:'')),env); assert.equal(response.headers.get('cache-control'),'no-store'); const text = await response.text(); if (!source) assert.equal(text,guide); - else { assert.ok(text.includes('setup --host codex --utm-source '+source));assert.ok(text.includes('setup --host deepseek --utm-source '+source+' --profile PROFILE')); } + else { assert.ok(text.includes('setup --host codex --utm-source='+source));assert.ok(text.includes('setup --host deepseek --utm-source='+source+' --profile PROFILE')); } assert.ok(text.includes('`openmotion prepare`')); } }); diff --git a/tests/install-guide.test.ts b/tests/install-guide.test.ts index 316ea0398..806978152 100644 --- a/tests/install-guide.test.ts +++ b/tests/install-guide.test.ts @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import { mkdtemp, mkdir, readFile, writeFile, rm } from 'node:fs/promises'; import path from 'node:path'; import os from 'node:os'; -import { generateInstallGuide, validateGuideSpec, validateGuideIdentity } from '../scripts/install-guide.mjs'; +import { generateInstallGuide, supportsInstallAttribution, validateGuideSpec, validateGuideIdentity } from '../scripts/install-guide.mjs'; import { movingGuide, publishGuide, storagePlan } from '../.github/scripts/publish-install-guide.mjs'; import { runFile } from '../scripts/runtime-assets.mjs'; @@ -18,9 +18,12 @@ test('installation URLs separate the moving channel entry from the exact immutab assert.equal(storagePlan({ channel: 'stable', version: '0.6.4' }, config).versionKey, 'open-motion/0.6.4/install.md'); assert.equal(storagePlan({ channel: 'stable', version: '0.6.4' }, config).fixedKey, 'open-motion/install.md'); }); -async function fixture(t: any, candidate = false) { +async function fixture(t: any, candidate = false, installer?: string) { const root = await mkdtemp(path.join(os.tmpdir(), 'motion-guide-test-')); t.after(() => rm(root, { recursive: true, force: true })); await mkdir(path.join(root, 'package/payload'), { recursive: true }); + await mkdir(path.join(root, 'package/scripts'), { recursive: true }); + await writeFile(path.join(root, 'package/scripts/npm-installer.mjs'), + installer ?? await readFile(new URL('../scripts/npm-installer.mjs', import.meta.url), 'utf8')); await writeFile(path.join(root, 'package/package.json'), JSON.stringify(pkg)); await writeFile(path.join(root, 'package/payload/release-npm.json'), JSON.stringify(manifest)); const tgz = path.join(root, 'candidate.tgz'); @@ -70,6 +73,20 @@ test('guide rendering pins the exact npm package, built source and hash while re assert.throws(() => validateGuideIdentity(stable, { ...manifest, version: stable.version }), /Template defaults/); }); +test('the support marker follows the sealed installer instead of the control checkout template', async t => { + assert(supportsInstallAttribution(await readFile(new URL('../scripts/npm-installer.mjs', import.meta.url), 'utf8'))); + assert(!supportsInstallAttribution('parseArgs({ allowPositionals: true, options: { host: { type: "string" } } });')); + const supported = await fixture(t); + assert((await readFile(path.join(supported.directory, 'install.md'), 'utf8')).includes('')); + // An older integrated source ships an installer without --utm-source, so its guide must not declare support. + const legacy = await fixture(t, false, 'const { values } = parseArgs({ allowPositionals: true, options: { host: { type: "string" } } });\n'); + const legacyGuide = await readFile(path.join(legacy.directory, 'install.md'), 'utf8'); + assert(!legacyGuide.includes('openmotion-utm-source-supported')); + assert(!legacyGuide.includes('{{')); + assert(legacyGuide.includes("\n## Choose the selected host's setup command")); + assert(legacyGuide.includes('openmotion setup --host codex')); +}); + test('publication verifies the immutable URL before conditional fixed promotion and retains the prior guide', async t => { const { directory, record } = await fixture(t), store = storage(directory, record); const result = await publishGuide(directory, config, { ...store, fetcher: async (url: URL) => { diff --git a/workers/install-guide/index.ts b/workers/install-guide/index.ts index e266d0663..8021a46e0 100644 --- a/workers/install-guide/index.ts +++ b/workers/install-guide/index.ts @@ -4,8 +4,9 @@ const marker = ''; export function attributeGuide(text: string, source: string | null): string { if (!source || !/^[A-Za-z0-9_.-]{1,64}$/.test(source) || !text.includes(marker)) return text; + // Bind with `=` so an accepted value starting with a hyphen stays one option value. return text.replace(/openmotion setup --host (codex|claude|deepseek|workbuddy)\b/g, - command => `${command} --utm-source ${source}`); + command => `${command} --utm-source=${source}`); } export function guideKey(url: URL): string | null {