Files
openmotion/tests/scenario-content.test.ts
Tom Huang 9060f47d0d feat(scenario): add dual-mode Workflows workspace, shared Assets, and MCP write-back (#781)
* Add scenario workflows foundation, Design asset import and Wave 1 contracts

Implement the Wave 1 scenario workflow contracts, shared domain service,
Design Studio binary asset import, ZIP bundle exporter and Studio boundary
files while preserving the 22 public MCP tools:

- Shared browser-safe contracts in shared/scenarios.ts, shared/scenario-runs.ts
  and shared/scenario-content.ts covering all five scenarios, 21 scenario
  commands, starter HTML recipes, idempotent HTML image embedding, localized
  social drafting and Agent handoff builders.
- Design Studio binary asset import via DesignProjects.importBinaryFile(),
  openmotion_design_edit action=import_asset, POST /api/design/projects/:id/import-asset
  and designClient.importAsset().
- Domain service (gateway/scenario-runs.ts), ZIP bundle builder
  (gateway/scenario-bundle.ts) and HTTP download route (gateway/scenario-http.ts),
  wired under openmotion_assets_use action=scenario with tracking schema parity.
- Studio scenario client, scenarioCovers.ts, stepContract.ts and ODUI-compliant
  boundary stubs for parallel Wave 2 UI implementation.
- Node test coverage in tests/scenario-content.test.ts, tests/scenario-runs.test.ts,
  tests/scenario-bundle.test.ts and tests/design-import-asset.test.ts registered
  in .github/workflows/ci.yml.

* Implement scenario workflow step workbenches and unit tests

- Add reusable BindingSlot with pool picker, chip removal and drag-and-drop
- Implement BriefStep with dynamic brief fields, debounced autosave, revisions, downstream prompt seeding, AI influencer script editor, Gemini 4 Neon rail/availability and Black Friday discount badge
- Implement WebPageStep with starter/template/existing project creation, live viewport preview, live HTML slot targeting, single and chained Embed all, and design version previews
- Implement MediaStep (image, video, audio) and MotionPanel with scene/audio tabs, catalog model picker, offscreen-pausing video, offline provider-setup recovery with upload/workspace import, and Motion project creation/linking
- Implement SocialPackStep with offline drafting, regeneration variants, character/title limit counters, hashtags, media reordering and token-only live card previews
- Implement ExportHubStep with step overview, pool readiness checks, ZIP bundle export with persistent download card and Agent handoff actions
- Wire StepRouter with token-only opaque steps.css and add Vitest suites for all five step workbenches

* Implement scenario workflow shell, shared asset pool, and run state

Add useScenarioRun state hook with auto-resume, lazy run creation, optimistic revision conflict recovery, visibility-aware job polling, and window focus refresh. Implement ScenarioCard, ScenarioHub, ScenarioHeader, ScenarioStepper, PoolItemPreview, AssetPoolPanel, IterationHistory, StepExportMenu, ScenarioWorkspace, opaque token-only scenario.css, and Studio unit tests.

* Wire scenario workflow navigation, routing, MCP handbook, 10-locale i18n and docs

Implements Worker D integration for end-to-end scenario workflows:
- Routing & URLs: scenario/scenarios pages with category, run UUID, and step validation plus breadcrumb labels
- Top nav & Explore: Workflows split tab with 3-column mega menu, ExploreSpotlight primary workflow CTAs + 5th AI Influencer slide, ScenarioHighlights rail, CapabilityIndex Workflows column, landing cross-links, and WorkspaceFrame host wiring
- MCP handbook: scenario-workflows capability (preserving exact 22 phase-1 tool union), scenario-black-friday and design-embed-assets recipes, and setup-prefixed Black Friday handoff
- 10-locale i18n: scenario-ui.json (526 keys x 10 locales covering shared/scenarios.ts plus all scenario-shell and scenario-steps UI keys), studio-navigation-ui.json, and mcp-ui.json updates
- Docs & tests: mcp-phase1-tools.md, product architecture, scenario-workflows.md guide, openmotion-design SKILL note, and full Vitest + Node MCP test coverage

* Register scenario stylesheets in tokenGate and complete 10-locale i18n coverage

- Register scenarioNavigation.css, scenario.css and steps.css in
  studio/src/styles/tokenGate.test.ts and define the four remaining
  token-only scenario CSS classes (.om-scenario-host,
  .om-scenario-header-category, .om-scenario-step-tab-title,
  .om-scenario-history--empty).
- Add the missing 'Download started' translation across all 10 non-English
  locales in studio/src/i18n/scenario-ui.json for 100% 10-locale coverage.

* Fix Scenario Workflows Wave 3 E2E and visual findings

- Treat full content-step selection as an unfiltered export bundle so README.md and unattached uploaded pool files are included
- Auto-activate newly saved iterations in ScenarioRuns.addIteration while preserving promote for older versions
- Suppress duplicate raw error toasts on SCENARIO_CONFLICT after useScenarioRun displays the localized conflict notice
- Map raw step statuses, pool kinds, job states, and copy tone/promo code labels through localized UI keys across all 10 locales
- Restore light/dark Explore hero CTA contrast hierarchy and make the Workflows mega menu compact so the footer is visible without clipping at 1440x900
- Stack the scenario step header vertically below 767px to avoid squeezing the step title on mobile viewports

* fix(scenario): replace alarming export-hub step warning stack with calm readiness hint

* feat(scenario): replace intimidating brief form with guided fill-in-the-blanks prompt composer

* polish(scenario): auto-size inline blank pills snugly to text content

* feat(scenario): add guided page composer, filter layouts, and codify workflow UX rules

* Enhance scenario workflows with semantic step colors, icons, and unified composers

Add consistent semantic color-coding and richer icons across the scenario
workflow shell and every step workbench without removing any capability:

- ScenarioStepper & ScenarioWorkspace: add step-type color accents (brief,
  image, web-page, video, audio, social-pack, export-hub), flow connectors,
  live progress bar, tinted step header badge, Step N / M pill, and next-step
  icon cues.
- ScenarioHeader, ScenarioCard & AssetPoolPanel: color-code category pills,
  step preview chips, shared asset pool header/filter chips, and asset kind
  badges using existing packages/design-system tokens.
- MediaStep, SocialPackStep, WebPageStep, BriefStep, MotionPanel, BindingSlot
  & ExportHubStep: unify Media and Social steps into single composer cards
  matching Brief and WebPage, render official PlatformIcon glyphs for social
  channels, add colored section/slot/stat icons, and remove redundant orphan
  toolbars while preserving all generation, upload, embed, edit, compare,
  MCP handoff, and ZIP export actions.
- Update studio/src/i18n/scenario-ui.json across all 10 non-English locales.

* Refine scenario workflows layout, controls, and dual-track MCP write-back

- Refine input and Select dropdown borders across design-system adapter/application CSS and workflow steps, eliminating thick stacked outlines and clipped option borders
- Flatten nested wireframes and unify top chrome, stepper, step composers, and open canvas sections with plain consumer-product terminology and 10-locale translations
- Add desktop drag-resizer, keyboard/double-click reset, persistence, and collapse/reopen toggle with auto-expand on pick for the right Shared assets sidebar
- Add StepCapabilityBar for in-step direct image/video generation alongside run-bound MCP write-back prompts and window focus/visibility sync across creation steps
- Consolidate workflow export actions into the header and Shared assets sidebar and fix backend text-ref type narrowing in scenario bundle generation

* feat(scenario): add dual-mode Agent mode, preview stage, draft history, and polish UX

Add Step-by-step and Agent mode workspace views with grouped Skills pipeline, concise MCP prompt generation, visual preview stage, draft history dialog, selective Assets import/export, 10-locale i18n coverage, and tokenGate CSS fixes.

* fix(i18n): remove duplicate base-dictionary overrides from scenario-ui.json

Drop duplicate '{count} selected' and 'Copied. Paste into your Agent.' entries from scenario-ui.json so ProjectArchives and TemplateLibraryDialog retain their canonical translations.

* feat(scenario): add stage preview artwork, refine Agent Teams UX and disclosure styling

* fix(scenario): address PR #781 review feedback across steps, templates, HTML embed and side-effect mutations

---------

Co-authored-by: pftom <pftom@pftomdeMacBook-Pro.local>
2026-11-21 17:21:46 +08:00

414 lines
21 KiB
TypeScript

import assert from 'node:assert/strict';
import { existsSync, statSync } from 'node:fs';
import test from 'node:test';
import {
applyImageToHtml,
briefMarkdown,
draftSocialPosts,
listHtmlImageTargets,
runReadme,
scenarioStarterPage,
scriptOutline,
socialPostsMarkdown,
} from '../shared/scenario-content.ts';
import {
scenarioConcisePrompt,
scenarioSkills,
fillScenarioTemplate,
findScenario,
scenarioAgentPrompt,
scenarioDefinitions,
scenarioRecipeTools,
scenarioRunAgentPrompt,
socialPlatforms,
type PageRecipeId,
type ScenarioSkillRef,
type ScenarioWorkspaceMode,
} from '../shared/scenarios.ts';
import { workflowResources } from '../shared/workflow.ts';
test('scenarioStarterPage escapes untrusted brief content, includes slots and valid structure for every recipe', () => {
const recipes: PageRecipeId[] = ['landing', 'sale', 'link-in-bio', 'code-animation'];
const hostile = '<script>alert("xss")</script>Nova & Co';
const brief = {
productName: hostile,
brandName: hostile,
personaName: hostile,
concept: hostile,
idea: 'Launch fast with <img src=x onerror=alert(1)> safety',
valueProps: ['Fast <b>setup</b>', 'Zero lock-in'],
originalPrice: '$199',
salePrice: '$99',
promoCode: 'BF50',
saleWindow: 'Nov 27 – Dec 1',
pageUrl: 'javascript:alert(1)',
cta: 'Buy now',
};
for (const recipe of recipes) {
const files = scenarioStarterPage(recipe, brief, 'en');
const html = files.find(f => f.path === 'index.html')?.content ?? '';
const css = files.find(f => f.path === 'styles.css')?.content ?? '';
assert.ok(html.length > 200, `${recipe} produces index.html`);
assert.ok(css.length > 200, `${recipe} produces styles.css`);
assert.ok(html.includes('<!DOCTYPE html>'), `${recipe} has doctype`);
assert.ok(html.includes('</html>') && html.includes('</body>') && html.includes('</head>'), `${recipe} has closing tags`);
assert.ok(html.includes('data-om-slot="hero"'), `${recipe} includes hero slot`);
assert.ok(html.includes('data-om-slot="gallery"'), `${recipe} includes gallery slot`);
assert.ok(!html.includes('<script>alert("xss")</script>'), `${recipe} escapes hostile script tag`);
assert.ok(!html.includes('<img src=x'), `${recipe} escapes hostile img tag`);
assert.ok(!html.includes('javascript:alert(1)'), `${recipe} blocks javascript: URL`);
assert.ok(html.includes('&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;Nova &amp; Co'), `${recipe} preserves escaped text`);
}
const saleHtml = scenarioStarterPage('sale', brief, 'en').find(f => f.path === 'index.html')!.content;
assert.ok(saleHtml.includes('$99') && saleHtml.includes('$199') && saleHtml.includes('BF50'));
assert.ok(saleHtml.includes('data-om-slot="product"'));
const bioHtml = scenarioStarterPage('link-in-bio', brief, 'en').find(f => f.path === 'index.html')!.content;
assert.ok(bioHtml.includes('data-om-slot="avatar"'));
const landingWithUrl = scenarioStarterPage('landing', { ...brief, pageUrl: 'https://example.com/launch' }, 'en').find(f => f.path === 'index.html')!.content;
assert.ok(landingWithUrl.includes('href="https://example.com/launch"'));
});
test('listHtmlImageTargets finds slots and img tags across starter and template HTML', () => {
const starterHtml = scenarioStarterPage('sale', { productName: 'Tote' }, 'en').find(f => f.path === 'index.html')!.content;
const starterTargets = listHtmlImageTargets(starterHtml);
const slotNames = starterTargets.filter(t => t.kind === 'slot').map(t => t.slot);
assert.deepEqual(slotNames, ['hero', 'product', 'gallery']);
const templateHtml = '<html><body><section data-om-slot="banner" data-om-label="Top Banner"><img src="./hero.png" alt="Hero" /><img src="./sub.jpg" alt="Detail" /></section></body></html>';
const targets = listHtmlImageTargets(templateHtml);
assert.deepEqual(targets, [
{ kind: 'slot', slot: 'banner', label: 'Top Banner' },
{ kind: 'img', index: 0, src: './hero.png', alt: 'Hero' },
{ kind: 'img', index: 1, src: './sub.jpg', alt: 'Detail' },
]);
});
test('applyImageToHtml handles slot, img-index and append targets idempotently with escaped alt', () => {
const starter = scenarioStarterPage('landing', { productName: 'Prism' }, 'en').find(f => f.path === 'index.html')!.content;
const escapedAlt = 'Hero "quoted" <tag>';
// Container slot + idempotency
const once = applyImageToHtml(starter, { kind: 'slot', slot: 'hero' }, './assets/hero-12345678.png', escapedAlt);
assert.ok(once.includes('src="./assets/hero-12345678.png"'));
assert.ok(once.includes('alt="Hero &quot;quoted&quot; &lt;tag&gt;"'));
const twice = applyImageToHtml(once, { kind: 'slot', slot: 'hero' }, './assets/hero-12345678.png', escapedAlt);
assert.equal(twice.match(/hero-12345678\.png/g)?.length, 1);
// Direct <img data-om-slot>
const directImg = '<html><body><img data-om-slot="hero" src="./old.png" alt="Old" /></body></html>';
const replacedSlotImg = applyImageToHtml(directImg, { kind: 'slot', slot: 'hero' }, './assets/new.png', 'Fresh');
assert.ok(replacedSlotImg.includes('src="./assets/new.png"') && replacedSlotImg.includes('alt="Fresh"'));
// img index replacement
const twoImgs = '<html><body><img src="./a.png" alt="A" /><img src="./b.png" alt="B" /></body></html>';
const replacedSecond = applyImageToHtml(twoImgs, { kind: 'img', index: 1 }, './assets/c.png', 'C & D');
assert.ok(replacedSecond.includes('src="./a.png"'));
assert.ok(replacedSecond.includes('src="./assets/c.png"') && replacedSecond.includes('alt="C &amp; D"'));
// append on plain HTML without gallery slot (and idempotency)
const plain = '<html><body><h1>Hello</h1></body></html>';
const appended = applyImageToHtml(plain, { kind: 'append' }, './assets/gal.png', 'Gallery');
assert.ok(appended.includes('data-om-slot="gallery"'));
assert.ok(appended.includes('src="./assets/gal.png"'));
const appendedAgain = applyImageToHtml(appended, { kind: 'append' }, './assets/gal.png', 'Gallery');
assert.equal(appendedAgain.match(/gal\.png/g)?.length, 1);
// Dollar replacement patterns ($1, $&, $') and data-src/data-alt attributes must be handled safely
const lazyHtml = '<html><body><img data-src="./lazy.png" data-alt="Lazy alt" src="./real.png" alt="Real alt" /></body></html>';
const dollarPatched = applyImageToHtml(
lazyHtml,
{ kind: 'img', index: 0 },
'./assets/hero.png',
"Save $1 off & $' deals",
);
assert.ok(dollarPatched.includes('data-src="./lazy.png"'), 'data-src must remain untouched');
assert.ok(dollarPatched.includes('data-alt="Lazy alt"'), 'data-alt must remain untouched');
assert.ok(dollarPatched.includes('src="./assets/hero.png"'), 'real src must be updated');
assert.ok(dollarPatched.includes('alt="Save $1 off &amp; $&#39; deals"'), 'alt must preserve literal $1 and $\'');
});
test('draftSocialPosts enforces platform character, hashtag and title limits, rotates variants and localizes zh-CN', () => {
const blackFriday = findScenario('black-friday')!;
const longIdea = 'Ultra-durable travel weekender built for holiday getaways '.repeat(25);
const brief = {
productName: 'Nomad Holiday Weekender Tote Deluxe Edition',
idea: longIdea,
salePrice: '$79',
originalPrice: '$149',
promoCode: 'BF40',
saleWindow: 'Nov 27 – Dec 1',
};
const allPlatforms = socialPlatforms.map(p => p.id);
const v0 = draftSocialPosts(blackFriday, brief, allPlatforms, { tone: 'bold', variant: 0, locale: 'en' });
const v1 = draftSocialPosts(blackFriday, brief, allPlatforms, { tone: 'bold', variant: 1, locale: 'en' });
assert.equal(v0.length, allPlatforms.length);
for (const post of v0) {
const spec = socialPlatforms.find(p => p.id === post.platform)!;
assert.ok(Array.from(post.text).length <= spec.maxChars, `${post.platform} respects maxChars`);
assert.ok(post.hashtags.length <= spec.maxHashtags, `${post.platform} respects maxHashtags`);
if ('maxTitleChars' in spec && spec.maxTitleChars) {
assert.ok(post.title && Array.from(post.title).length <= spec.maxTitleChars, `${post.platform} respects maxTitleChars`);
}
}
assert.notEqual(v0[0].text, v1[0].text, 'Variant rotation produces different hooks/CTAs');
const zhPosts = draftSocialPosts(blackFriday, brief, ['xiaohongshu', 'douyin'], { locale: 'zh-CN', variant: 0 });
assert.match(zhPosts[0].text, /[\u4e00-\u9fff]/, 'zh-CN draft uses Chinese phrasing');
assert.ok(zhPosts[0].title && Array.from(zhPosts[0].title).length <= 20, 'Xiaohongshu zh-CN title <= 20 chars');
const md = socialPostsMarkdown(v0);
assert.ok(md.includes('# Social posts') && md.includes('## X (16:9)'));
const scriptEn = scriptOutline({ personaName: 'Mina', topic: 'Batch filming' }, 'en');
const scriptZh = scriptOutline({ personaName: 'Mina', topic: '批量拍摄' }, 'zh-CN');
assert.ok(scriptEn.includes('[Hook') && scriptEn.includes('Mina'));
assert.match(scriptZh, /开场 Hook/);
});
test('fillScenarioTemplate handles missing fields gracefully and prompt builders include every required tool', () => {
const filledPartial = fillScenarioTemplate('Hero image for {productName}: {valueProps}, {visualStyle}', { productName: 'Nova' });
assert.equal(filledPartial, 'Hero image for Nova');
assert.ok(!filledPartial.includes('{'));
// Preserves literal words like "code" and trailing punctuation in user values while cleaning empty `code {promoCode}`
const preservedUserProse = fillScenarioTemplate('Storyboard frame for {concept}: {visualStyle}, {aspect} composition', {
concept: 'Learn to code.',
visualStyle: 'Minimal',
aspect: '16:9',
});
assert.equal(preservedUserProse, 'Storyboard frame for Learn to code.: Minimal, 16:9 composition');
const preservedTrailingColon = fillScenarioTemplate('Hero image for {productName}: {valueProps}, {visualStyle}', {
productName: 'ACME:',
});
assert.equal(preservedTrailingColon, 'Hero image for ACME:');
const cleanedEmptyPromoCode = fillScenarioTemplate(
'30s Black Friday sales film for {productName}: {salePrice}, code {promoCode}, {saleWindow}',
{ productName: 'Holiday Tote', salePrice: '$79', promoCode: '', saleWindow: 'Nov 27' },
);
assert.equal(cleanedEmptyPromoCode, '30s Black Friday sales film for Holiday Tote: $79, Nov 27');
const keptPromoCode = fillScenarioTemplate(
'30s Black Friday sales film for {productName}: {salePrice}, code {promoCode}, {saleWindow}',
{ productName: 'Holiday Tote', salePrice: '$79', promoCode: 'BF40', saleWindow: 'Nov 27' },
);
assert.equal(keptPromoCode, '30s Black Friday sales film for Holiday Tote: $79, code BF40, Nov 27');
const filledList = fillScenarioTemplate('Hero image for {productName}: {valueProps}, {visualStyle}', {
productName: 'Nova',
valueProps: ['Fast', 'Local'],
visualStyle: 'Minimalist',
});
assert.equal(filledList, 'Hero image for Nova: Fast, Local, Minimalist');
for (const scenario of scenarioDefinitions) {
const prompt = scenarioAgentPrompt(scenario, { integration: { previewUrl: 'http://127.0.0.1:4173', dataDirectory: '/fixture/data' } });
for (const tool of scenarioRecipeTools) {
assert.ok(prompt.includes(tool), `${scenario.id} prompt includes ${tool}`);
}
assert.ok(prompt.includes('openmotion_assets_use'));
assert.ok(prompt.includes('command=export'));
assert.ok(prompt.includes('/fixture/data'));
}
const bf = findScenario('black-friday')!;
const runSummary = {
id: '11111111-1111-4111-8111-111111111111',
title: 'Holiday Tote',
revision: 3,
brief: { productName: 'Holiday Tote' },
activeStepId: 'detail-page',
steps: {
brief: { stepId: 'brief', status: 'done', activeIterationId: null, links: {} },
'detail-page': { stepId: 'detail-page', status: 'in-progress', activeIterationId: null, links: { designProjectId: '22222222-2222-4222-8222-222222222222' } },
},
pool: [{
id: '33333333-3333-4333-8333-333333333333',
kind: 'image' as const,
label: 'Hero shot',
stepId: 'product-images',
pinned: true,
ref: { type: 'asset' as const, assetId: '44444444-4444-4444-8444-444444444444', versionId: '55555555-5555-4555-8555-555555555555' },
}],
};
const runPrompt = scenarioRunAgentPrompt(bf, runSummary, {
stepId: 'detail-page',
stepPrompt: 'Create a bold Black Friday landing page for Holiday Tote',
});
assert.ok(runPrompt.includes('11111111-1111-4111-8111-111111111111'));
assert.ok(runPrompt.includes('expectedRevision: 3'));
assert.ok(runPrompt.includes('44444444-4444-4444-8444-444444444444@55555555-5555-4555-8555-555555555555'));
assert.ok(runPrompt.includes('22222222-2222-4222-8222-222222222222'));
assert.ok(runPrompt.includes('Step write-back instructions:'));
assert.ok(runPrompt.includes('Current step prompt: Create a bold Black Friday landing page for Holiday Tote'));
assert.ok(runPrompt.includes('openmotion_assets_use(action="scenario", scenario={ command: "generate", runId: "11111111-1111-4111-8111-111111111111", expectedRevision: 3, stepId: "detail-page"'));
assert.ok(runPrompt.includes('command: "add_pool"'));
assert.ok(runPrompt.includes('command: "link_design"'));
const briefStepPrompt = scenarioRunAgentPrompt(bf, runSummary, {
stepId: 'brief',
stepPrompt: 'Refine Holiday Tote offer brief',
});
assert.ok(briefStepPrompt.includes('Step write-back instructions:'));
assert.ok(briefStepPrompt.includes('command: "update_brief" | "add_iteration"'));
assert.ok(briefStepPrompt.includes('stepId: "brief"'));
const videoStepPrompt = scenarioRunAgentPrompt(bf, runSummary, {
stepId: 'sales-film',
stepPrompt: '30s Holiday Tote reveal video',
});
assert.ok(videoStepPrompt.includes('command: "link_motion"'));
assert.ok(videoStepPrompt.includes('stepId: "sales-film"'));
const socialStepPrompt = scenarioRunAgentPrompt(bf, runSummary, {
stepId: 'social',
stepPrompt: 'Draft Black Friday social launch posts',
});
assert.ok(socialStepPrompt.includes('outputs: [{ type: "social", posts }]'));
assert.ok(socialStepPrompt.includes('stepId: "social"'));
assert.ok(briefMarkdown(bf, { productName: 'Tote' }).includes('## Product name'));
const readme = runReadme(bf, {
id: '11111111-1111-4111-8111-111111111111',
title: 'Holiday Tote',
revision: 3,
brief: {},
activeStepId: 'brief',
steps: {},
pool: [],
}, { origin: 'http://127.0.0.1:4173' });
assert.ok(readme.includes('# Holiday Tote') && readme.includes('manifest.json'));
});
test('every scenario step defines valid real Skills and scenarioSkills deduplicates in first-seen order', () => {
const validWorkflowUris = new Set(workflowResources().map(resource => resource.uri));
const modeCheck: ScenarioWorkspaceMode = 'agent';
assert.equal(modeCheck, 'agent');
for (const scenario of scenarioDefinitions) {
const firstSeenIds: string[] = [];
for (const step of scenario.steps) {
assert.ok(step.skills && step.skills.length >= 1, `${scenario.id}/${step.id} defines at least one Skill`);
for (const skill of step.skills as readonly ScenarioSkillRef[]) {
assert.ok(skill.id.trim().length > 0, `${scenario.id}/${step.id} skill id`);
assert.ok(skill.label.trim().length > 0, `${scenario.id}/${step.id} skill label`);
assert.ok(skill.role.trim().length > 0, `${scenario.id}/${step.id} skill role`);
if (skill.source === 'library') {
const dirUrl = new URL(`../library/skills/${skill.id}`, import.meta.url);
assert.ok(existsSync(dirUrl) && statSync(dirUrl).isDirectory(), `library skill directory exists: ${skill.id}`);
assert.ok(existsSync(new URL(`../library/skills/${skill.id}/SKILL.md`, import.meta.url)), `SKILL.md exists: ${skill.id}`);
} else {
assert.equal(skill.source, 'workflow');
assert.ok(skill.resourceUri && validWorkflowUris.has(skill.resourceUri), `valid workflow resourceUri: ${skill.resourceUri}`);
}
if (!firstSeenIds.includes(skill.id)) {
firstSeenIds.push(skill.id);
}
}
}
const deduped = scenarioSkills(scenario);
assert.deepEqual(deduped.map(skill => skill.id), firstSeenIds, `${scenario.id} preserves first-seen order`);
assert.equal(new Set(deduped.map(skill => skill.id)).size, deduped.length, `${scenario.id} deduplicates skills`);
}
// Verify specific cross-step deduplication cases (e.g. openmotion-ad-script in black-friday appears in brief then social)
const bfSkills = scenarioSkills(findScenario('black-friday')!);
assert.equal(bfSkills[0].id, 'openmotion-ad-script');
assert.equal(bfSkills[0].label, 'Campaign Script');
assert.equal(bfSkills.filter(skill => skill.id === 'openmotion-ad-script').length, 1);
});
test('scenarioConcisePrompt stays under 35 lines with metadata, assets, skills pipeline and MCP instructions', () => {
const bf = findScenario('black-friday')!;
const runSummary = {
id: '11111111-1111-4111-8111-111111111111',
title: 'Holiday Tote',
revision: 3,
brief: {
idea: 'Limited-run canvas tote campaign',
productName: 'Holiday Tote',
salePrice: '$79',
promoCode: 'BF40',
},
activeStepId: 'detail-page',
steps: {
brief: { stepId: 'brief', status: 'done', activeIterationId: null, links: {} },
'detail-page': {
stepId: 'detail-page',
status: 'in-progress',
activeIterationId: null,
links: { designProjectId: '22222222-2222-4222-8222-222222222222' },
},
},
pool: [
{
id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
kind: 'image' as const,
label: 'Secondary angle',
stepId: 'product-images',
pinned: false,
ref: { type: 'asset' as const, assetId: '66666666-6666-4666-8666-666666666666', versionId: '77777777-7777-4777-8777-777777777777' },
},
{
id: '33333333-3333-4333-8333-333333333333',
kind: 'image' as const,
label: 'Hero shot',
stepId: 'product-images',
pinned: true,
ref: { type: 'asset' as const, assetId: '44444444-4444-4444-8444-444444444444', versionId: '55555555-5555-4555-8555-555555555555' },
},
],
};
const concise = scenarioConcisePrompt(bf, runSummary, {
customPrompt: 'Create a high-contrast Black Friday tote campaign across page, video and social.',
locale: 'en',
integration: { previewUrl: 'http://127.0.0.1:4173', dataDirectory: '/fixture/data' },
});
const lines = concise.split('\n');
assert.ok(lines.length < 35, `Expected < 35 lines, got ${lines.length}`);
assert.ok(concise.includes('workflow: black-friday'));
assert.ok(concise.includes('runId: 11111111-1111-4111-8111-111111111111'));
assert.ok(concise.includes('expectedRevision: 3'));
assert.ok(concise.includes('workspace: /fixture/data'));
assert.ok(concise.includes('studioUrl: http://127.0.0.1:4173'));
assert.ok(concise.includes('locale: en'));
assert.ok(concise.includes('linkedProjects: detail-page:design=22222222-2222-4222-8222-222222222222'));
assert.ok(concise.includes('assets:'));
// Pinned item must appear before unpinned item
const heroIdx = concise.indexOf('asset:44444444-4444-4444-8444-444444444444@55555555-5555-4555-8555-555555555555 "Hero shot" (pinned)');
const secondaryIdx = concise.indexOf('asset:66666666-6666-4666-8666-666666666666@77777777-7777-4777-8777-777777777777 "Secondary angle"');
assert.ok(heroIdx > 0 && secondaryIdx > heroIdx, 'Pinned pool item comes first');
assert.ok(concise.includes('openmotion_get_skill'));
for (const tool of scenarioRecipeTools) {
assert.ok(concise.includes(tool), `concise prompt includes ${tool}`);
}
assert.ok(concise.includes('library:openmotion-sale-countdown'));
assert.ok(concise.includes('resource:openmotion://workflow/design/start'));
assert.ok(concise.includes('Create a high-contrast Black Friday tote campaign across page, video and social.'));
assert.ok(concise.includes('params: idea=Limited-run canvas tote campaign | productName=Holiday Tote | salePrice=$79 | promoCode=BF40'));
// Without customPrompt, brief.idea becomes the main task and is excluded from params
const briefMain = scenarioConcisePrompt(bf, runSummary);
assert.ok(briefMain.includes('task: Limited-run canvas tote campaign'));
assert.ok(briefMain.includes('params: productName=Holiday Tote | salePrice=$79 | promoCode=BF40'));
assert.ok(!briefMain.includes('params: idea='));
// Without run, all scenarios stay compact under 35 lines and use command=create
for (const scenario of scenarioDefinitions) {
const freshPrompt = scenarioConcisePrompt(scenario, null, {
integration: { previewUrl: 'http://127.0.0.1:4173', dataDirectory: '/fixture/data' },
});
assert.ok(freshPrompt.split('\n').length < 35, `${scenario.id} fresh concise prompt < 35 lines`);
assert.ok(freshPrompt.includes('command=create') && freshPrompt.includes('assets: none'));
assert.ok(freshPrompt.includes('command: "create"'));
}
});