Files
openmotion/tracking/tool-fields.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

151 lines
13 KiB
TypeScript

const legacyAssetActions = ['list', 'get', 'import', 'update', 'generate', 'jobs', 'status', 'cancel', 'retry_save', 'resume', 'import_to_project'] as const;
export const assetActions = [...legacyAssetActions, 'read', 'brand_kit', 'transcript', 'scenario'] as const;
const actionSets = {
openmotion_game_trailer: ['start', 'status'],
openmotion_assets_use: assetActions,
openmotion_assets: legacyAssetActions,
openmotion_media_use: ['inspect', 'reference', 'models', 'generate', 'status', 'cancel', 'retry_save', 'resume'],
openmotion_open_preview: ['open', 'record_review', 'record_display', 'begin', 'complete_generation'],
openmotion_export_request: ['request', 'record_review'],
openmotion_project_archive: ['export', 'import'],
openmotion_manage_project: ['comments', 'info', 'rename', 'duplicate', 'reveal', 'trash', 'restore', 'delete'],
openmotion_design_catalog: ['list_scenarios', 'list_templates', 'get_template', 'list_skills', 'get_skill', 'list_design_systems', 'get_design_system', 'get_craft'],
openmotion_design_project: ['create', 'list', 'get', 'rename', 'duplicate', 'trash', 'restore', 'delete', 'open', 'open_in', 'export', 'import'],
openmotion_design_edit: ['read_file', 'write', 'list_versions', 'restore_version', 'import_asset'],
openmotion_design_comments: ['list', 'create', 'update', 'delete'],
} as const;
const targets = ['project', 'templates', 'providers'] as const;
export const toolDimensions = { action: [...new Set(Object.values(actionSets).flat())], target: targets } as const;
export function toolInputFields(tool: string, input: unknown) {
const args = input && typeof input === 'object' && !Array.isArray(input) ? input as { action?: unknown; target?: unknown } : {};
const actions: readonly typeof toolDimensions.action[number][] = Object.hasOwn(actionSets, tool) ? actionSets[tool as keyof typeof actionSets] : [];
const defaultAction = tool === 'openmotion_export_request' ? 'request' : tool === 'openmotion_open_preview' ? 'open' : undefined;
const action = actions.find(value => value === (args.action === undefined ? defaultAction : args.action));
const target = tool === 'openmotion_open_preview'
? targets.find(value => value === (args.target === undefined ? 'project' : args.target)) : undefined;
return { ...(action ? { action } : {}), ...(target ? { target } : {}) };
}
export const validationRules = ['missing', 'invalid_type', 'invalid_enum', 'invalid_format', 'out_of_range', 'unknown_field', 'invalid_combination'] as const;
// Keep the ingress allowlist independent of the app and its schema implementation.
const invalidFields = [
'operation', 'commentId', 'expectedCommentRevision', 'text', 'status', 'anchor', 'anchor.scope',
'anchor.compositionPath', 'anchor.time', 'anchor.element', 'anchor.element.handle', 'anchor.element.sourceFile',
'anchor.element.label', 'anchor.element.tagName', 'anchor.element.hfId', 'anchor.element.domId',
'anchor.element.selector', 'anchor.element.selectorIndex', 'anchor.element.text', 'anchor.element.box',
'anchor.element.box.x', 'anchor.element.box.y', 'anchor.element.box.width', 'anchor.element.box.height',
'anchor.annotation', 'anchor.annotation.version', 'anchor.annotation.coordinateSpace', 'anchor.annotation.width',
'anchor.annotation.height', 'anchor.annotation.marks', 'anchor.annotation.marks[]', 'anchor.annotation.marks[].kind',
'anchor.annotation.marks[].text', 'anchor.annotation.marks[].points', 'anchor.annotation.marks[].points[]',
'anchor.annotation.marks[].points[].x', 'anchor.annotation.marks[].points[].y',
'action', 'all', 'arguments', 'assetId', 'assetNames', 'assetNames[]', 'assetNames[].name',
'assetNames[].path', 'audio', 'brandKit', 'brandKit.catalogId', 'brandKit.expectedUpdatedAt', 'brandKit.file',
'brandKit.file.data', 'brandKit.file.name', 'brandKit.kitId', 'brandKit.name', 'brandKit.operation',
'brandKit.query', 'brandKit.remove', 'brandKit.requestId', 'brandKit.rules', 'brandKit.rules[]', 'brandKit.style',
'brandKit.style.background', 'brandKit.style.bodyFont', 'brandKit.style.foreground', 'brandKit.style.gradient',
'brandKit.style.headingFont', 'brandKit.style.onPrimary', 'brandKit.style.primary', 'brandKit.style.radius',
'brandKit.style.surface', 'brandKit.url', 'changes', 'changes.currentVersionId', 'changes.name',
'changes.trashed', 'compositionPath', 'conversationId', 'cursor', 'display', 'display.contentVerified',
'display.evidence', 'display.hostStatus', 'display.hostTabId', 'display.previewUrl', 'display.revision',
'display.versionId', 'display.visibility', 'duration', 'embedded', 'entry', 'expectedRevision',
'expectedRevisions', 'expectedTitle', 'expectedVersionId', 'exportJobId', 'file', 'file.length',
'file.offset', 'file.path', 'files', 'files[]', 'files[].content', 'files[].path', 'generation',
'includeVideo', 'items', 'items[]', 'items[].itemId', 'items[].licensePath', 'items[].name',
'items[].sourcePath', 'jobId', 'language', 'limit', 'modality', 'mode', 'model', 'name', 'namingLanguage',
'offset', 'onboarding', 'parameters', 'parentVersionId', 'presentation', 'projectId', 'projectIds',
'projectIds[]', 'projectType', 'prompt', 'provider', 'query', 'referenceAsset', 'referenceUrl',
'referenceVideoId', 'references', 'references[]', 'references[].assetId', 'references[].versionId', 'refresh',
'requestId', 'requirements', 'review', 'review.conclusion', 'review.evidence', 'review.objectId',
'review.range', 'review.range.end', 'review.range.start', 'review.source', 'review.versionId', 'sessionId',
'sort', 'source', 'sourcePath', 'start', 'summary', 'target', 'templateId', 'templateIds', 'templateIds[]',
'timestamps', 'timestamps[]', 'title', 'transcript', 'transcript.captionSettings',
'transcript.captionSettings.pacing', 'transcript.captionSettings.position',
'transcript.captionSettings.preset', 'transcript.captionSettings.scale', 'transcript.captionSettings.visible',
'transcript.command', 'transcript.compositionPath', 'transcript.expectedRevision',
'transcript.expectedTranscriptRevision', 'transcript.expectedVersionId', 'transcript.format',
'transcript.jobId', 'transcript.language', 'transcript.model', 'transcript.parameters',
'transcript.playbackRate', 'transcript.projectId', 'transcript.remove', 'transcript.requestId',
'transcript.segments', 'transcript.segments[]', 'transcript.segments[].end', 'transcript.segments[].id',
'transcript.segments[].speaker', 'transcript.segments[].start', 'transcript.segments[].text',
'transcript.segments[].words', 'transcript.segments[].words[]', 'transcript.segments[].words[].end',
'transcript.segments[].words[].start', 'transcript.segments[].words[].text', 'transcript.sourceEnd',
'transcript.sourcePath', 'transcript.sourceStart', 'transcript.subtitles', 'transcript.textKind',
'transcript.timelineStart', 'transcript.transcriptId', 'trash', 'trashed', 'unknown_field', 'versionId',
'workId',
'id', 'scenario', 'category', 'q', 'referencePath', 'designSystemId', 'editorId', 'format', 'filePath',
'outputPath', 'path', 'deletes', 'deletes[]', 'anchor.filePath', 'anchor.viewport', 'anchor.viewport.id',
'anchor.viewport.width', 'anchor.viewport.height', 'anchor.slideIndex', 'anchor.element.elementId',
'anchor.element.htmlHint', 'anchor.region', 'anchor.region.x', 'anchor.region.y', 'anchor.region.width',
'anchor.region.height',
'scenario.command', 'scenario.runId', 'scenario.expectedRevision', 'scenario.requestId', 'scenario.scenarioId',
'scenario.includeArchived', 'scenario.offset', 'scenario.limit', 'scenario.title', 'scenario.locale',
'scenario.brief', 'scenario.changes', 'scenario.changes.title', 'scenario.changes.archived',
'scenario.changes.activeStepId', 'scenario.changes.label', 'scenario.changes.tags', 'scenario.changes.tags[]',
'scenario.changes.pinned', 'scenario.stepId', 'scenario.status', 'scenario.draft', 'scenario.bindings',
'scenario.activeIterationId', 'scenario.iterationNote', 'scenario.iterationNote.iterationId',
'scenario.iterationNote.note', 'scenario.items', 'scenario.items[]', 'scenario.items[].ref',
'scenario.items[].label', 'scenario.items[].tags', 'scenario.items[].tags[]', 'scenario.items[].stepId',
'scenario.items[].source', 'scenario.poolItemId', 'scenario.iteration', 'scenario.iteration.source',
'scenario.iteration.prompt', 'scenario.iteration.settings', 'scenario.iteration.inputs',
'scenario.iteration.inputs[]', 'scenario.iteration.outputs', 'scenario.iteration.outputs[]',
'scenario.iteration.note', 'scenario.iterationId', 'scenario.modality', 'scenario.model', 'scenario.mode',
'scenario.prompt', 'scenario.parameters', 'scenario.referencePoolItemIds', 'scenario.referencePoolItemIds[]',
'scenario.scene', 'scenario.templateId', 'scenario.designProjectId', 'scenario.expectedDesignRevision',
'scenario.target', 'scenario.alt', 'scenario.projectType', 'scenario.requirements', 'scenario.poolItemIds',
'scenario.poolItemIds[]', 'scenario.projectId', 'scenario.stepIds', 'scenario.stepIds[]',
'scenario.activeOnly', 'scenario.includeStandaloneHtml', 'scenario.includeMotionSource',
] as const;
export const toolErrorCodes = [
'COMMENT_TARGET_NOT_FOUND', 'COMMENT_NOT_FOUND', 'COMMENT_CONFLICT', 'COMMENT_LIMIT', 'NOT_FOUND', 'UNSUPPORTED',
'INVALID_ARGUMENT', 'VERSION_CONFLICT', 'PROJECT_NOT_BOUND', 'PROJECT_NOT_FOUND', 'PROJECT_SESSION_MISMATCH',
'REQUEST_ID_CONFLICT', 'REQUEST_STATE_UNKNOWN', 'MCP_TOOL_NOT_EXPOSED', 'EXPORT_BUSY', 'EXPORT_NOT_FOUND',
'EXPORT_NOT_COMPLETED', 'TEMPLATE_NOT_FOUND', 'TEMPLATE_NOT_EDITABLE', 'SOURCE_BATCH_TOO_LARGE',
'INVALID_FILE_TYPE_OR_RESERVED_PATH', 'PROJECT_VALIDATION_FAILED', 'VERSION_NOT_FOUND',
'WORK_CLOSED', 'WORK_NOT_FOUND', 'WORK_VERSION_MISMATCH', 'WORK_GENERATION_UNTRACKED', 'GENERATION_CONTENT_UNCHANGED',
'GENERATION_ARTIFACT_INVALID', 'VERSION_NOT_RESTORABLE', 'REVIEW_VERSION_MISMATCH', 'REVIEW_OBJECT_MISMATCH',
'PREVIEW_TARGET_MISMATCH', 'NATIVE_RUNTIME_NOT_READY', 'EDITOR_RUNTIME_INCOMPATIBLE', 'RUNTIME_NOT_READY',
'SESSION_NOT_FOUND', 'PROJECT_TRASHED', 'INVALID_CURSOR', 'INVALID_PROJECT_ARCHIVE', 'PROJECT_ARCHIVE_TOO_LARGE',
'TEMPLATE_NOT_COPYABLE', 'INVALID_REFERENCE_URL', 'INVALID_REVIEW_RANGE', 'UNSUPPORTED_TEXT_TYPE',
'INVALID_FILE_OFFSET', 'INVALID_UTF8_OFFSET', 'READ_WINDOW_TOO_SMALL', 'TRANSCRIPT_CONFLICT',
'PROJECT_ARCHIVE_VALIDATION_UNAVAILABLE', 'PROJECT_NOT_READY', 'REVEAL_UNAVAILABLE', 'GENERATION_NOT_FOUND',
'ASSET_JOB_NOT_FOUND', 'ASSET_NOT_FOUND', 'ASSET_VERSION_NOT_FOUND', 'ASSET_IMPORT_FAILED', 'DUPLICATE_ITEM_ID',
'FINAL_VIDEO_NOT_READY', 'TEMPLATE_PRESENTATION_INVALID', 'WEBMCP_TRANSPORT_ERROR', 'WEBMCP_CALL_FAILED',
'STUDIO_TOOL_BLOCKED', 'STUDIO_TOOL_INTERNAL', 'ABORTED', 'TOOL_FAILED',
] as const;
export const toolFailureDimensions = { error_code: toolErrorCodes, invalid_field: invalidFields, validation_rule: validationRules } as const;
export function trackingError(error: unknown) {
const explicit = error && typeof error === 'object' && 'code' in error ? error.code : undefined;
const code = typeof explicit === 'string' ? explicit : error instanceof Error ? /^([A-Z_]+)(?::|$)/.exec(error.message)?.[1] : undefined;
return toolErrorCodes.find(value => value === code) ?? 'TOOL_FAILED';
}
export function toolFailureFields(error: unknown) {
const error_code = trackingError(error);
if (error_code === 'INVALID_ARGUMENT' && error && typeof error === 'object') {
const fields = error as { invalid_field?: unknown; validation_rule?: unknown };
const invalid_field = invalidFields.find(value => value === fields.invalid_field);
const validation_rule = validationRules.find(value => value === fields.validation_rule);
if (invalid_field && validation_rule) return { error_code, invalid_field, validation_rule };
}
return { error_code };
}
export const assetImportErrorCodes = ['ATTACHMENT_NOT_READABLE', 'ASSET_TOO_LARGE_OR_NOT_FILE', 'INVALID_MEDIA',
'ITEM_ID_CONFLICT', 'ASSET_NOT_IN_CURRENT_VERSION', 'ASSET_CONTENT_CHANGED', 'FONT_LICENSE_REQUIRES_FONT'] as const;
export function assetImportError(error: unknown) {
const explicit = error && typeof error === 'object' && 'code' in error ? error.code : undefined;
if (['ENOENT', 'EACCES', 'EPERM', 'ENOTDIR'].some(value => value === explicit)) return 'ATTACHMENT_NOT_READABLE';
const code = explicit ?? (error instanceof Error ? /^([A-Z_]+)(?::|$)/.exec(error.message)?.[1] : undefined);
return assetImportErrorCodes.find(value => value === code) ?? trackingError(error);
}
export const exportFailureStages = ['queued', 'lint', 'render', 'output', 'verification', 'finalize', 'unknown'] as const;
export const exportFailureCodes = ['EXPORT_LINT_FAILED', 'EXPORT_RENDER_FAILED', 'EXPORT_RENDER_TIMEOUT',
'EXPORT_OUTPUT_MISSING', 'EXPORT_OUTPUT_INVALID', 'EXPORT_VERIFICATION_FAILED', 'EXPORT_VERIFICATION_BLOCKED',
'EXPORT_FINALIZE_FAILED', 'EXPORT_DEADLINE_EXCEEDED', 'EXPORT_WORKER_INTERRUPTED', 'EXPORT_FAILED'] as const;
export type ExportFailure = { failureStage: typeof exportFailureStages[number]; failureCode: typeof exportFailureCodes[number] };