From 6b732d1fe9b0e7b7bc7fd22ad8f58a13e50a9a8e Mon Sep 17 00:00:00 2001 From: qiqi Date: Wed, 18 Nov 2026 21:22:48 +0800 Subject: [PATCH 1/6] feat(templates): unify interactive motion guide previews --- docs/mcp-phase1-tools.md | 6 + docs/product/architecture.md | 2 +- editor-server.ts | 4 +- gateway/template-guide.ts | 37 +++ package.json | 2 +- packages/design-system/README.md | 2 + packages/design-system/controls.css | 4 + phase1.ts | 14 +- scripts/build-template-guide.mjs | 14 + scripts/distribution.ts | 2 +- server.ts | 14 +- shared/phase1-tools.ts | 5 +- shared/template-guide-ui.json | 266 ++++++++++++++++++ shared/template-guide.ts | 54 ++++ .../src/motion/TemplateMotionGuide.test.tsx | 16 ++ studio/src/motion/TemplateMotionGuide.tsx | 36 ++- .../src/motion/templateMotionGuideDocument.ts | 3 +- studio/src/template-guide/actions.test.ts | 68 +++++ studio/src/template-guide/actions.ts | 66 +++++ studio/src/template-guide/page.css | 93 ++++++ studio/src/template-guide/page.ts | 213 ++++++++++++++ tests/hosted-template-catalog.test.ts | 5 +- tests/repository-template-runtime.test.ts | 6 +- tests/template-guide.test.ts | 98 +++++++ tracking/README.md | 2 + tracking/events.ts | 3 + 26 files changed, 1019 insertions(+), 16 deletions(-) create mode 100644 gateway/template-guide.ts create mode 100644 scripts/build-template-guide.mjs create mode 100644 shared/template-guide-ui.json create mode 100644 shared/template-guide.ts create mode 100644 studio/src/template-guide/actions.test.ts create mode 100644 studio/src/template-guide/actions.ts create mode 100644 studio/src/template-guide/page.css create mode 100644 studio/src/template-guide/page.ts create mode 100644 tests/template-guide.test.ts diff --git a/docs/mcp-phase1-tools.md b/docs/mcp-phase1-tools.md index 19331d34a..055bb9295 100644 --- a/docs/mcp-phase1-tools.md +++ b/docs/mcp-phase1-tools.md @@ -7,6 +7,12 @@ Skill 是指导文档,与公开 Tool 数量分开。本次后续命名与分发对齐后,一期装入 openmotion-production、openmotion-director、openmotion-template-to-video、openmotion-recreate、openmotion-video-to-template 五个创作入口及其参考,以及按需支撑多模态素材生成的 openmotion-media。模板使用与视频转模板保留已有实际流程;openmotion-recreate 包含实际复刻流程,规则与测量脚本随 Skill 分发,不新增自动创作算法或 Tool。原九个工程 Tool 保留,本次新增目录获取和模板详情入口;详见 [Skill 路由与能力边界](skills.md)。 +## Shared template guide pages + +Every catalog `preview.html` URL uses the maintained guide interface. It preserves that entry's own authored sequence, declared parameters, timing, reference film, rules and frames. The authored examples are motion illustrations, not verified reconstructions of the reference films. Entries without the supported declaration retain their own source preview and Agent handoff; no substitute film or unsupported trial fields are inserted. `?raw=1` and `motion.md` preserve the original source bytes. + +`openmotion_create_project` accepts optional `guideDraft: { title, accent }` with `projectType=template` and the exact catalog `templateId`. It validates the selected guide's declaration and copies that guide's own canvas code, duration and motion document into an independent native project. Title and accent are declared as native variables for Agent editing; the JavaScript source remains available for deeper edits. The current Studio layout does not expose a Variables panel, so the guide does not promise that control. The original reference is not automatically recreated, no export is started, and the source catalog is not modified. Existing request-id deduplication and version/history protection apply. Studio's direct and sandbox-embedded guide actions use the same authority. + ## Optional native template presentation The sixteen registered domain names (including one asset compatibility alias) share the same HTTP authority; `openmotion_assets_use` with its `openmotion_assets` compatibility name provides workspace assets without changing existing project calls. A phase-one stdio connection may additionally discover `openmotion_show_template_recommendations` when its `initialize` capabilities declare `extensions["io.modelcontextprotocol/ui"].mimeTypes` containing `text/html;profile=mcp-app`, the feature is enabled and the local presentation assets are valid. Do not infer this capability from a client name or protocol date. Clients without that declaration, including the installed direct CLI client, still discover exactly sixteen names; the legacy profile remains twenty-eight. diff --git a/docs/product/architecture.md b/docs/product/architecture.md index f775a8d24..da8d1958a 100644 --- a/docs/product/architecture.md +++ b/docs/product/architecture.md @@ -36,7 +36,7 @@ Model Gateway is the shared media-generation backend for Studio and MCP. Generat - An empty, loaded root composition shows a centered import/drop prompt over the mounted preview and hides transport controls, including the placeholder duration. The empty state requires both no timeline clips and no authored preview content; loading, failed previews and nested compositions retain their existing states. Import uses the existing timeline gateway and file-drop pipeline. The empty timeline retains its drop target and ruler, with a muted dashed track sketch instead of a duplicate import prompt or button. Empty timelines disable zoom controls. A confirmed empty composition blocks new exports at both the settings button and the shared editor render-start handler, while existing export history remains available. Properties distinguish no content from no selection and show guidance when a selected layer has no available controls. Composition reference hosts resolve to their parent source file, while their internal layers resolve to the referenced file; small panel empty states share muted text and icon sizing. Preview zoom percentage and Fit sit in the MVP preview header, outside the picture. Clicking the percentage opens 50%, 75%, 100%, 150% and 200% presets in a compact opaque menu. The MVP hides the corner position navigator; existing zoom gestures and Fit remain available. Browser fullscreen is unavailable in the MVP, including its playback button and keyboard entry; workspace preview expansion remains available as Immersive preview, with Escape restoring the editing layout. Playback controls respond to their own container width: secondary-button gaps narrow below 420px; below 300px they move to a second row so timecode, playback, volume, speed and loop remain reachable. Preview and track volume use upward floating vertical sliders, opened by hover or keyboard focus; clicking the speaker still toggles mute. Editor controls share one neutral hover background for both ordinary and selected states, including visible keyboard focus and highlighted menu items. Primary Export actions retain their dark action hover surface. Disabled controls share one foreground token without per-control opacity, and never gain hover feedback. Official animation-library controls use shared semantic theme roles; template artwork and timeline clip bodies retain their content presentation. The enabled play/pause icon uses the same action-color token as the header Export background, including hover. - The composition list places the full video first, preserves the remaining clip order, and marks the live preview target. Queued, loading, missing and failed covers share a muted gray OD placeholder without failure text; decoded covers replace it automatically. A confirmed empty root is omitted from this list using the same loaded-preview content check; when no clips remain, the panel shows a brief empty state. The MVP omits the duplicate preview breadcrumb; composition switching and existing return shortcuts remain available. - The application header owns the sidebar control, clickable 104px OpenMotion wordmark that switches to the shared compact symbol in narrow headers, with shared hover/focus feedback, Back to home action in settings, localized community link, GitHub star badge with a 10K fallback and provider/model selector. The nested editor toolbar is 32px high, with a content-sized editable project name centered independently of the controls on either side, automatic-save status on the left, and undo/redo, version history, layout and export on the right. The template library has one entry in the left application rail, identified by a clapperboard; the provider entry uses the same sparkle icon as the model picker, while a separate plug opens MCP onboarding. The toolbar does not repeat either the template entry or sidebar toggle, and shares the preview transport’s flat panel surface and subtle separators. Clearing the title and committing with blur or Enter saves the localized Untitled default; Escape cancels. The community link and GitHub star badge with a 10K fallback sit beside the model selector in the application header; the community link opens the public Feishu group for Simplified Chinese and the public Discord community for the other supported interface languages, with the matching logo, while the star badge opens the OpenMotion repository. External links open separately from the editor. The GitHub badge uses the official circular mark, a border and the same 28px height as Export. Application and editor header controls share a 6px radius. Narrow layouts retain the link icons while hiding the star count and model-selector text. Undo, redo and version history form one visual group with 4px internal gaps, followed by Export. A decorative 1px by 16px divider in the shared border color sits between history and Export without moving the buttons; it hides with the history group on narrow screens. Version-history empty text reads No edits yet in a subdued tone. Save status is event-driven and project-scoped: confirmed native file writes update the displayed save time, existing history supplies its initial value, and failed writes retain an unsaved state until the affected write recovers or the user discards it. Existing edit queues save incrementally; a 15-second check drains staged source, property and DOM edits without blurring the active input, overlapping an active edit/flush, or rewriting clean files. Rendering, history restoration and write guards suspend this check. Hidden pages stop periodic work and attempt one pending-only drain when backgrounded; abrupt browser termination cannot guarantee completion. This is an additional drain of the existing native save path, not a parallel project snapshot or history store. Workspace and export failures show concise causes and available next steps, with raw diagnostics behind expandable, copyable details. Workspace connection failures show one brief feedback toast per outage at the top center with a Reconnecting message and no buttons or diagnostic details. The notice expires after three seconds, or disappears earlier on recovery; repeated failed polls do not renew it. Automatic polling continues independently, waits 1.8 seconds after each completed attempt, has no overall retry limit or explicit per-request timeout and does not start a stopped service. Other notice dismissal does not bypass write guards. Editor toasts stack at the top center; editor, connection and template-copy feedback share a top-layer host inside the active native/shared modal focus boundary and above ordinary overlays, without taking focus. Template-copy feedback uses the shared top-center placement and three-second lifetime; identical notices replace their previous instance. Error toasts use the compact neutral feedback surface and concise recognized causes, with a dismiss button and no details icon or expandable diagnostics. Detailed error panels retain their diagnostic controls. Every toast without an operation expires after three seconds followed by the shared exit animation, regardless of error/info tone or feedback presentation; a close button alone does not make it persistent. Only toasts with explicit actions such as Undo, Retry or Download have no automatic timeout and remain dismissible until completed or displaced by the bounded stack, isolate action identities and prevent duplicate execution while pending. Action failures produce timed error feedback while leaving the original action retryable. Save-queue pauses use a brief, localized feedback toast without paths, diagnostics or a retry action; it expires after three seconds without clearing the write guard or claiming that failed edits were saved. Help also offers both README invitations, with Feishu first in Simplified Chinese and Discord first in other languages. -- The template library fills the current browser viewport with a single immersive video gallery, an introductory random-discovery action, persistent search, horizontal video-purpose categories, industry browsing, shared design-system radio menus for sorting and an icon-only, right-aligned multi-facet dropdown beside sorting. The non-modal grouped panel uses category tabs and a two-column grid, preserves draft choices across groups, previews their match count, and commits through Apply; dismissal discards the draft. Group clearing and clear-all retain the independent search. The TOP 100 brands capsule immediately after All filters the gallery to templates with published brand metadata without opening a menu. It shares the existing capsule surfaces and uses the design system’s bold serif collection title, green-to-theme-foreground text gradient and semibold brand label, with the full label set in italics. It switches directly with All and the video-purpose capsules; search and other facets still narrow the results. Purpose labels emphasize product launches, company introductions, fundraising, demos and campaigns. Localized catalog use cases normalize to stable discovery labels; reviewed funding entries retain a distinct purpose across locales. Published industry metadata takes precedence over a conservative brand-based browsing map; unknown brands remain unclassified. These discovery groupings do not rewrite source catalog metadata. It does not duplicate featured entries. Cards retain author avatars and reveal title, creator, duration and editability on hover or keyboard focus. One intersection observer budgets at most eight visible, muted looping previews (four on narrow screens); offscreen cards, hidden tabs and open detail dialogs release media sources. Autoplay has no toolbar toggle. Reduced-motion preferences disable gallery autoplay; data-saving connections require deliberate hover or focus. Surprise me samples the current results without consecutive repeats when alternatives exist. Published brand metadata supplies catalog logos in repository, hosted and CMS modes, with bundled legacy fallbacks and an initial when a logo fails. Repository metadata drives the source-checkout list; hosted main snapshots and cache updates drive NPM installations without the source catalog, while the website retains its CMS publication. The catalog selects the editor locale from a shared multilingual publication, falling back to English and then the Resource default; template-copy prompts support the same eleven UI languages. Previews, author/source links and editable-project opening remain available. Filters use non-modal shared dropdown menus with immediate results and individually removable condition chips; selecting multiple values keeps the menu open and leaves gallery playback active. A full-window detail dialog places a large video over a blurred poster backdrop beside an independently scrolling information panel; narrow screens stack these regions. It includes author/source, duration, template instructions, clickable metadata, related templates and previous/next navigation within the current result order. Related entries are ranked by shared brand, styles, use cases and tags. Hovering or keyboard-focusing a related card opens one enlarged, muted looping preview over the stage, with its title overlaid; clicking still opens the selected detail. The floating preview stays within the native dialog and viewport, moves above or below its trigger on narrow screens, and releases its video source on dismissal, scrolling, backgrounding or template changes. Reduced-motion preferences and missing video URLs retain the poster; failed or timed-out playback offers a retry without changing the selected template. The motion.md download action (`motionDocumentUrl`) remains above the collapsible guide content (`styleDescription`, `reviewFocus`, `motionGuideUrl`), with the guide iframe mounted only on expansion. Readable HTML guides adopt shared light/dark chrome inside the opaque-origin sandbox; nested demo artwork remains unchanged. Relative resources resolve against the final response URL and any authored base URL. Hosts that disallow CORS retain the original remote iframe. Template instructions remain separate from authored guidance. Recreate copies its Agent brief directly and reports success through the shared floating Toast viewport without changing detail layout; clipboard failure exposes selectable text in the same detail panel and a floating failure notice. A quieter Recreate and submit action copies a contribution brief for the exact selected template. A highlighted Submit video link opens the existing GitHub contribution guide. Every detail links to its repository source directory when registered, and the gallery and editor headers share a GitHub badge. Star counts come from the public repository API through a single in-flight request, a five-minute persisted cache and a one-minute failure cooldown; fresh cached counts remain usable; a 10K fallback is shown when no valid count is available. No action uploads media or creates a PR automatically. Gallery surfaces, controls, borders and frosted media surroundings use the shared design system in both light and dark editor themes. Shared semantic skeleton tokens reserve catalog, poster and instruction geometry while content loads; failed posters keep a title fallback, and failed detail video or instruction loads offer inline retry. Video duration stays in metadata without a duplicate stage badge. Catalog metadata is not represented as an original author prompt or publication date when those fields are absent. +- The template library fills the current browser viewport with a single immersive video gallery, an introductory random-discovery action, persistent search, horizontal video-purpose categories, industry browsing, shared design-system radio menus for sorting and an icon-only, right-aligned multi-facet dropdown beside sorting. The non-modal grouped panel uses category tabs and a two-column grid, preserves draft choices across groups, previews their match count, and commits through Apply; dismissal discards the draft. Group clearing and clear-all retain the independent search. The TOP 100 brands capsule immediately after All filters the gallery to templates with published brand metadata without opening a menu. It shares the existing capsule surfaces and uses the design system’s bold serif collection title, green-to-theme-foreground text gradient and semibold brand label, with the full label set in italics. It switches directly with All and the video-purpose capsules; search and other facets still narrow the results. Purpose labels emphasize product launches, company introductions, fundraising, demos and campaigns. Localized catalog use cases normalize to stable discovery labels; reviewed funding entries retain a distinct purpose across locales. Published industry metadata takes precedence over a conservative brand-based browsing map; unknown brands remain unclassified. These discovery groupings do not rewrite source catalog metadata. It does not duplicate featured entries. Cards retain author avatars and reveal title, creator, duration and editability on hover or keyboard focus. One intersection observer budgets at most eight visible, muted looping previews (four on narrow screens); offscreen cards, hidden tabs and open detail dialogs release media sources. Autoplay has no toolbar toggle. Reduced-motion preferences disable gallery autoplay; data-saving connections require deliberate hover or focus. Surprise me samples the current results without consecutive repeats when alternatives exist. Published brand metadata supplies catalog logos in repository, hosted and CMS modes, with bundled legacy fallbacks and an initial when a logo fails. Repository metadata drives the source-checkout list; hosted main snapshots and cache updates drive NPM installations without the source catalog, while the website retains its CMS publication. The catalog selects the editor locale from a shared multilingual publication, falling back to English and then the Resource default; template-copy prompts support the same eleven UI languages. Previews, author/source links and editable-project opening remain available. Filters use non-modal shared dropdown menus with immediate results and individually removable condition chips; selecting multiple values keeps the menu open and leaves gallery playback active. A full-window detail dialog places a large video over a blurred poster backdrop beside an independently scrolling information panel; narrow screens stack these regions. It includes author/source, duration, template instructions, clickable metadata, related templates and previous/next navigation within the current result order. Related entries are ranked by shared brand, styles, use cases and tags. Hovering or keyboard-focusing a related card opens one enlarged, muted looping preview over the stage, with its title overlaid; clicking still opens the selected detail. The floating preview stays within the native dialog and viewport, moves above or below its trigger on narrow screens, and releases its video source on dismissal, scrolling, backgrounding or template changes. Reduced-motion preferences and missing video URLs retain the poster; failed or timed-out playback offers a retry without changing the selected template. The motion.md download action (`motionDocumentUrl`) remains above the collapsible guide content (`styleDescription`, `reviewFocus`, `motionGuideUrl`), with the guide iframe mounted only on expansion. Readable HTML guides adopt shared light/dark chrome inside the opaque-origin sandbox; nested demo artwork remains unchanged. Every local catalog preview URL uses the shared guide viewer while preserving its authored sequence, chapters, rules, frames and reference media. Supported guides expose only their declared title/accent trials, isolate drafts by exact template ID, and use the public template-create operation with guideDraft to open an independent native canvas example with the selected values and original timing. Copy retains the exact template and draft without sending a task. Guides without supported trial declarations retain their own preview and Agent handoff. Full motion.md downloads retain source bytes; raw=1 retains the original preview. The opaque sandbox delegates storage, copy, download and navigation to its identity-pinned parent. Trial examples remain distinct from reference-film reconstruction. Relative resources resolve against the final response URL and any authored base URL. Hosts that disallow CORS retain the original remote iframe. Template instructions remain separate from authored guidance. Recreate copies its Agent brief directly and reports success through the shared floating Toast viewport without changing detail layout; clipboard failure exposes selectable text in the same detail panel and a floating failure notice. A quieter Recreate and submit action copies a contribution brief for the exact selected template. A highlighted Submit video link opens the existing GitHub contribution guide. Every detail links to its repository source directory when registered, and the gallery and editor headers share a GitHub badge. Star counts come from the public repository API through a single in-flight request, a five-minute persisted cache and a one-minute failure cooldown; fresh cached counts remain usable; a 10K fallback is shown when no valid count is available. No action uploads media or creates a PR automatically. Gallery surfaces, controls, borders and frosted media surroundings use the shared design system in both light and dark editor themes. Shared semantic skeleton tokens reserve catalog, poster and instruction geometry while content loads; failed posters keep a title fallback, and failed detail video or instruction loads offer inline retry. Video duration stays in metadata without a duplicate stage badge. Catalog metadata is not represented as an original author prompt or publication date when those fields are absent. - The asset panel shows only the current project, with compact search/import controls, type filters, and a dedicated scrollable list. Image and video thumbnails reveal a compact lower-right quick-add button on hover or keyboard focus (always available on touch), with a 95%-opaque dark surface and no artwork scrim; audio and font rows offer the same shortcut at the right edge, with a smaller 24px button and 14px plus icon for compact font rows. Fonts insert an editable three-second text clip bearing the font name, with a unique local font-face alias, through the shared serialized insertion/history path. The shortcut it uses the existing add-at-playhead operation without opening preview, blocks duplicate pending clicks and reports failures through the shared Toast layer. Delete remains in the asset actions menu. User-uploaded audio rows in My assets retain filenames with their original extensions, wrap within the panel for at most two lines and ellipsize overflow; hovering reveals the complete name only when truncated; the generic Audio label is omitted, while duration and specific BGM/SFX/Voice labels remain when available. Official library sources are unchanged. Official animation-library cards reuse the composition list’s muted gray OD placeholder when preview media is absent or all available preview media fail; healthy posters and videos retain their existing behavior, and catalog entries remain available. Assets referenced by the current composition carry an In use badge (已使用 in Chinese); unused assets have no badge. MVP My assets deletion invokes the existing file-deletion handler directly from the menu, without a second confirmation; the full editor retains its confirmation. This does not introduce a new undo mechanism or alter official catalog assets. Usage filtering is omitted; used assets sort first within each type, with the latest explicit library import temporarily revealed first. The single upload menu offers local upload and exact-version library import. Library import refreshes and verifies the owning project’s native file list, clears hiding filters and shows a floating success notice only after the imported path is available. Refresh failures remain retryable without repeating the copy; late completions cannot update another project. The picker preserves the sidebar layout. In both My assets and the official animation library, hover plays only the card thumbnail, while clicking opens a centered modal preview over a gray full-editor backdrop. The modal reuses Studio-styled playback, volume and speed controls; its play button stays centered, and secondary controls wrap in very narrow players to avoid overlap. Volume and loop icons are 16px inside 28px buttons, and playback speed text is 12px; closing it restores access to the paused composition; previewing media does not add it to the project. The global cache view remains in source but has no editor entry in the MVP. - All supported content-insertion drops share persistent timeline feedback, including project images/video/audio, the composition list, official catalog items dropped on the timeline or preview, and local files dropped on the timeline or editor shell. Accepted drops immediately show a transient loading clip, including in an empty timeline; it remains until the saved clip appears, and failures remain dismissible at the placement. New loading rows reserve display space but remain unavailable as edit targets until discovery supplies their authored identity. Selected trim grips sit on the clip borders, with distinct hit targets even on short clips. A local-file batch immediately creates one loading clip per file, retains matching identities for accepted uploads, and refreshes the preview once after the batch saves; rejected files retain the upload handler's existing error feedback. Uploads retain the existing single multipart request. Catalog insertion buttons and overlays use the same state instead of progress toasts. Feedback resolves known row collisions before its first paint, reserves row geometry and scroll extent while loading, and settles to the saved host identity and measured duration. Unknown media durations can still require collision resolution when probing completes. Drop times come from the pointer on occupied, empty and newly opened lanes, using the same measured origin and centered row geometry as the ruler and clips. Editing a displayed spill row materializes distinct authored tracks within its source file and media zone in the same save transaction; existing visible lanes, timings and canvas stacking remain unchanged. A locked peer that would need renumbering refuses the operation. Discovery alone never rewrites authored tracks. Repeated drops remain independent. Composition insertions and catalog installs queue their writes; switching composition or project invalidates queued insertions and old selection changes. Known drag metadata bypasses duration probing, and concurrent requests for the same project asset share one in-flight probe without coalescing insertions. Unreadable durations fail visibly instead of inserting a five-second clip. Placeholders never enter project source or undo history. Drops on the Assets panel import files without inserting timeline content and retain that panel's importing state. - Panel positions are fixed. The workspace uses continuous flat surfaces with thin resizable dividers, without outer panel padding, gaps or rounded card borders. A horizontal divider separates the main header from the panel tabs. Export settings and render history live in a compact popover below the header Export button, outside the right panel. Both side groups can temporarily collapse into 48px vertical icon rails, giving their width to preview; the rail toggle restores the previous width and tab, while a module icon opens that module. Collapse does not remove panels or remount the player. The MVP initially shows collapsed sides and sizes the timeline to its track content, toolbar and footer, capped at 42% of the dock height while reserving preview space. Wrapped narrow-screen controls contribute to the measured height. A deliberate pointer or keyboard divider resize stores a per-project pixel height; resizing the host clamps that preference without replacing it. Fit timeline to content returns to automatic sizing. Side visibility records user intent independently from responsive fitting. Newly opened sides use fixed defaults of 200px for the library and 230px for the inspector when no saved preference exists. Collapsing and reopening a side restores its last manually chosen width; temporary responsive compression does not replace that preference. Width fitting accounts for each actual expanded column and only 48px for a collapsed rail, then compresses expanded sides before preview when space is insufficient. As the editor narrows, expanded sides shrink proportionally through their available slack to a 160px library minimum and a 200px inspector minimum before preview gives up width. Manual divider drags may reduce preview to 240px independently of its preferred responsive width. Composition badges wrap beside thumbnails; narrow inspector names use the default arrow cursor and wrap to at most two lines with ellipsis. Full-label tooltips appear only while the text is truncated and disappear when resizing makes it fit; controls retain their alignment. Font names truncate and narrow slider labels sit above the track. Long translated dock tabs truncate within the scrollable strip and expose their full titles in tooltips only when clipped; composition names, paths and audio metadata use the same overflow check. If both expanded columns cannot leave 240px for preview, the less recently opened side temporarily becomes an icon rail. Below a 448px dock width, both icon rails remain visible with disabled expansion controls and a screen-too-small tooltip; the timeline retains its requested visibility. At widths that fit one side, both rails remain enabled: opening one automatically collapses the other when both cannot fit. Between 448px and 487px, the wider inspector may reduce preview to 200–239px so switching remains available. Collapsed groups retain their tabs, manual widths and state. Enlarging the editor restores the requested sides and preferred widths, while deliberate collapses remain collapsed. Resizing preserves the same mounted player and open modules. Divider hover and drag change only the thin line to green. The header Panels and layout menu remains available at every width. It activates or collapses each side module, independently shows or hides preview and timeline without unmounting them, offers Focus preview and Restore default layout, and restores the timeline to its content height. Hiding preview distributes its space between the open side panels; hiding all upper panels leaves the timeline available. Hiding the last visible timeline restores preview so the workspace cannot become empty. Restore default layout also resets side widths. The default editing preset expands both sides only when space permits. Explicit visibility and manual timeline height are remembered per project; responsive rearrangement does not overwrite those stored preferences. Panel positions remain fixed and tabs are not removed. Preview alone can temporarily expand within the editor workspace, keeping the host chat visible and the player mounted. Its header button or Escape restores the previous layout and playback position; expansion is not persisted across reloads. diff --git a/editor-server.ts b/editor-server.ts index dc3410558..9db99958f 100644 --- a/editor-server.ts +++ b/editor-server.ts @@ -16,13 +16,15 @@ export async function serveEditorFile(url: URL, res: ServerResponse): Promise value.replace(/&/g, '&').replace(/'/g, ''').replace(/"/g, '"'); +/** Convert the selected guide's actual canvas example, never a different built-in film. */ +export async function materializeTemplateGuide(catalog: TemplateCatalog, templateId: string, directory: string, runtimeRoot: string, input: TemplateGuideDraft) { + const draft = parseTemplateGuideDraft(input); + const guide = authoredTemplateGuide((await catalog.sourceFile(templateId, 'preview.html')).toString()); + if (!guide) throw new Error('GUIDE_NOT_EDITABLE: this guide has no supported authored example'); + const sequence = (await catalog.sourceFile(templateId, guide.src)).toString(); + const canvas = sequence.match(/ 4096 || Number(canvas[2]) > 4096) throw new Error('GUIDE_CANVAS_UNAVAILABLE'); + const [width, height] = canvas.slice(1).map(Number); + const files = await Promise.all(['data.js', 'common.js', 'scene.js'].map(async name => [name, await catalog.sourceFile(templateId, 'demos/' + name)] as const)); + const motion = await catalog.sourceFile(templateId, 'motion.md'); + await createBlankProject(directory, runtimeRoot, draft.title); + await mkdir(path.join(directory, 'demos'), { recursive: true }); + for (const [name, bytes] of files) await writeFile(path.join(directory, 'demos', name), bytes); + await writeFile(path.join(directory, 'motion.md'), motion); + await writeFile(path.join(directory, 'guide-draft.json'), jsonForHtml({ templateId, ...draft })); + const variables = [{ id: 'title', label: 'Title', type: 'string', default: draft.title }, { id: 'accent', label: 'Accent color', type: 'color', default: draft.accent }]; + const html = `
+`; + await writeFile(path.join(directory, 'index.html'), html); + return { draft, source: { id: templateId, provenance: 'authored-motion-guide-example', durationSeconds: guide.duration, width, height, + editing: 'Canvas example. Title and accent are declared as native variables for Agent editing; change demos/*.js for deeper edits; the reference film is not reconstructed.' } }; +} diff --git a/package.json b/package.json index 50580b690..b74b0074e 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ "package:phase1": "npm run build:studio && node --experimental-strip-types scripts/package.ts --mcp-profile=phase1", "package:test": "node scripts/test-package.mjs", "package:npm": "npm run build:studio && node scripts/package-npm.mjs", - "build:studio": "npm run build:inline && npm run build:template-cards && vite build --config studio/vite.config.ts", + "build:studio": "npm run build:inline && npm run build:template-cards && vite build --config studio/vite.config.ts && node scripts/build-template-guide.mjs", "build:tracking": "tsc -p tracking/tsconfig.json", "typecheck:studio": "tsc -p studio/tsconfig.json", "design:tokens": "node --experimental-strip-types scripts/design-tokens.ts", diff --git a/packages/design-system/README.md b/packages/design-system/README.md index 7aeb89e4e..da2318f1a 100644 --- a/packages/design-system/README.md +++ b/packages/design-system/README.md @@ -49,6 +49,8 @@ Ordinary HTML pages load `/design-system/ui.css` and set `data-motion-ui` on the ``` +Use `ui-text-link` for quiet inline resource actions such as source links and document downloads. It shares the theme, focus and disabled roles with the other portable controls. + Studio imports `tailwind.css` from its stylesheet and `studio.css` from its application entry. Its existing `data-motion-studio` root maps `paper` to light and the default to dark. Both adapters consume the same `--motion-*` roles. For example, `--color-surface`, catalog surfaces and ordinary control backgrounds derive from shared surface roles; they do not carry separate palettes. Theme-specific recipes belong here, not in component overrides. `studio/application.css`, included by `studio.css`, supplies the reusable `om-*` navigation, buttons, fields, cards, badges, avatars, switches and dialogs used by the application shell and settings. Load consumer geometry after this entry so responsive visibility and measured sizes can override the primitive defaults. The `shell` role supplies the continuous top/left backdrop; `workspace` supplies the inset content surface. The `chrome-icon`, `chrome-hover` and `chrome-active` roles distinguish quiet navigation from the main content; shared transition recipes respect reduced motion. Provider artwork uses a neutral `brand-surface` tile, with identical local assets shared by lists, details and model choices. Keep colors, materials, focus and disabled states in the package. Composite fields use one visible focus ring around the whole control. diff --git a/packages/design-system/controls.css b/packages/design-system/controls.css index 0e7e43bb8..e6c4f69ef 100644 --- a/packages/design-system/controls.css +++ b/packages/design-system/controls.css @@ -19,6 +19,10 @@ :where([data-motion-ui]) .ui-button--danger:hover:not(:disabled) { background: var(--motion-danger-soft); color: var(--motion-danger); border-color: var(--motion-danger); } :where([data-motion-ui]) .ui-button--sm { min-height: var(--motion-control-sm); padding: var(--motion-space-4) var(--motion-space-8); font-size: var(--motion-text-sm); } :where([data-motion-ui]) .ui-button--icon { width: var(--motion-icon-button); min-height: var(--motion-icon-button); padding: var(--motion-space-6); } +/* Quiet resource actions shared by ordinary HTML guides and other portable surfaces. */ +:where([data-motion-ui]) .ui-text-link { display: inline-flex; align-items: center; gap: var(--motion-space-6); min-height: var(--motion-control-sm); padding: 0; border: 0; background: transparent; color: var(--motion-muted); font-size: var(--motion-text-sm); font-weight: var(--motion-weight-regular); line-height: var(--motion-leading-body); text-decoration: none; white-space: nowrap; cursor: pointer; } +:where([data-motion-ui]) .ui-text-link:hover:not(:disabled):not([aria-disabled="true"]) { text-decoration: underline; } +:where([data-motion-ui]) .ui-text-link:is(:disabled,[aria-disabled="true"]) { color: var(--motion-control-disabled); cursor: default; } :where([data-motion-ui]) .ui-field { display: flex; flex-direction: column; gap: var(--motion-space-8); font-size: var(--motion-text-sm); color: var(--motion-muted); } :where([data-motion-ui]) .ui-input { width: 100%; min-width: 0; min-height: var(--motion-control); diff --git a/phase1.ts b/phase1.ts index f26e788e6..b2dc00448 100644 --- a/phase1.ts +++ b/phase1.ts @@ -21,6 +21,8 @@ import { copyFile, lstat, mkdir, open, readFile, readdir, rm, stat, writeFile } import path from 'node:path'; import { WorkspaceStore, createBlankProject, projectPath, validateProjectTitle } from './workspace.ts'; import { templateCatalogFor } from './prism-templates.ts'; +import { materializeTemplateGuide } from './gateway/template-guide.ts'; +import { parseTemplateGuideDraft } from './shared/template-guide.ts'; import { isEditableTemplate } from './shared/catalog.ts'; import { getTemplate } from './template-catalog.ts'; import { execute, inspectProject, pluginRoot } from './hyperframes.ts'; @@ -455,17 +457,21 @@ export class Phase1Service { if (args.projectType === 'natural_language' && (args.templateId || args.referenceVideoId || args.referenceUrl) || args.projectType === 'template' && (args.referenceVideoId || args.referenceUrl) || args.projectType === 'reference_video' && (args.templateId || args.referenceVideoId && args.referenceUrl)) throw new Error('INVALID_ARGUMENT: creation source must match projectType'); if (args.projectType === 'template' && !args.templateId || args.projectType === 'reference_video' && !args.referenceVideoId && !args.referenceUrl) throw new Error('INVALID_ARGUMENT: creation source is required'); const source = args.templateId ? await templateCatalogFor(this.store.directory).get(args.templateId) : args.referenceVideoId ? getTemplate(args.referenceVideoId) : null; - if (args.projectType === 'template' && (!source || !isEditableTemplate(source))) throw new Error('TEMPLATE_NOT_COPYABLE: 请在 Studio 选择可编辑原生模板;参考视频需由 Agent 重建'); + const guideDraft = args.guideDraft === undefined ? undefined : parseTemplateGuideDraft(args.guideDraft); + if (guideDraft && (args.projectType !== 'template' || !source)) throw new Error('INVALID_GUIDE_DRAFT: a catalog template is required'); + if (args.projectType === 'template' && (!source || !isEditableTemplate(source)) && !guideDraft) throw new Error('TEMPLATE_NOT_COPYABLE: 请在 Studio 选择可编辑原生模板;参考视频需由 Agent 重建'); if (args.referenceUrl && !['https:', 'http:'].includes(new URL(args.referenceUrl).protocol)) throw new Error('INVALID_REFERENCE_URL'); validateInstruction(args.requirements); const language = args.namingLanguage === undefined ? undefined : namingLanguage(args.namingLanguage); const title = validateProjectTitle(args.title), directory = this.store.projectDirectoryFor(record.projectId); let registered = false; try { - if (args.projectType === 'template') await templateCatalogFor(this.store.directory).copy(source!, directory, this.runtimeRoot); - else await createBlankProject(directory, this.runtimeRoot, title); + const appliedGuide = guideDraft ? await materializeTemplateGuide(templateCatalogFor(this.store.directory), source!.id, directory, this.runtimeRoot, guideDraft) : undefined; + if (args.projectType === 'template' && !guideDraft) await templateCatalogFor(this.store.directory).copy(source!, directory, this.runtimeRoot); + else if (!guideDraft) await createBlankProject(directory, this.runtimeRoot, title); const meta = { schemaVersion: 1, namingLanguage: language, projectType: args.projectType, requirements: args.requirements, creationRequestId: args.requestId, - source: source ? { id: source.id, kind: source.kind, catalogVersion: 'catalogVersion' in source ? source.catalogVersion : undefined, previewUrl: source.previewUrl, sourceUrl: source.sourceUrl } : args.referenceUrl ? { url: args.referenceUrl, inspected: false } : null }; + ...(appliedGuide ? { guideDraft: appliedGuide.draft } : {}), + source: source ? { id: source.id, kind: source.kind, catalogVersion: 'catalogVersion' in source ? source.catalogVersion : undefined, previewUrl: source.previewUrl, sourceUrl: source.sourceUrl, ...appliedGuide?.source } : args.referenceUrl ? { url: args.referenceUrl, inspected: false } : null }; await atomicJson(path.join(directory, metadataPath), meta); await atomicJson(path.join(directory, assetIndexPath), []); await this.store.lock(async () => { diff --git a/scripts/build-template-guide.mjs b/scripts/build-template-guide.mjs new file mode 100644 index 000000000..f82c2d2cb --- /dev/null +++ b/scripts/build-template-guide.mjs @@ -0,0 +1,14 @@ +import { build } from 'esbuild'; +import { copyFile, mkdir, readFile } from 'node:fs/promises'; +const root = new URL('../', import.meta.url); +// Inline the maintained symbol paths so the same icons work inside opaque-origin guide sandboxes. +const sprite = await readFile(new URL('packages/design-system/icons.svg', root), 'utf8'); +const icons = Object.fromEntries(['arrow-left-line', 'arrow-right-line', 'refresh-line', 'file-copy-line', 'file-text-line', 'download-2-line', 'external-link-line'].map(name => { + const symbol = sprite.match(new RegExp(']*>([\\s\\S]*?)')); + if (!symbol) throw new Error('Missing shared guide icon: ' + name); + return [name, symbol[1]]; +})); +await mkdir(new URL('studio/build/guide-assets/', root), { recursive: true }); +await build({ entryPoints: [new URL('studio/src/template-guide/page.ts', root).pathname], outfile: new URL('studio/build/guide-assets/viewer.js', root).pathname, + bundle: true, format: 'iife', platform: 'browser', target: 'es2022', minify: true, define: { __OPENMOTION_GUIDE_ICONS__: JSON.stringify(icons) } }); +await copyFile(new URL('studio/src/template-guide/page.css', root), new URL('studio/build/guide-assets/viewer.css', root)); diff --git a/scripts/distribution.ts b/scripts/distribution.ts index ad9be488a..9f2b64ce5 100644 --- a/scripts/distribution.ts +++ b/scripts/distribution.ts @@ -705,7 +705,7 @@ export async function distributionFiles(profile: string, include: (file: string) 'scripts/npm-installer.mjs', 'scripts/npm-hosts.mjs', 'scripts/install-public-skill.ts', 'scripts/recover-workspace-lock.ts', 'scripts/cleanup-harness-bundles.mjs', 'scripts/check-installed-mcp.mjs', 'scripts/mcp-client.mjs', 'scripts/install-onboarding.mjs', 'scripts/inline-onboarding.mjs', 'scripts/codex-host-handoff.mjs', 'scripts/onboarding-catalog.ts', 'scripts/open-template-library.ts', 'scripts/install-library-skill.mjs', 'scripts/diagnostics.mjs', 'scripts/diagnostic-redaction.mjs', 'scripts/zip.mjs', - 'scripts/verify-export.ts', 'scripts/export-adapters.ts', 'scripts/package.ts', 'scripts/distribution.ts', + 'scripts/verify-export.ts', 'scripts/export-adapters.ts', 'scripts/package.ts', 'scripts/distribution.ts', 'scripts/build-template-guide.mjs', 'scripts/repository-media.ts', 'scripts/prepare-font.ts', 'scripts/font-specimen.ts', 'scripts/build-template-cards.mjs', 'shared/asset-name-ui.json', 'shared/workflow-entry.js', 'shared/inline-video-result.js', 'shared/provider-registry-LICENSE.txt', 'shared/provider-registry-NOTICE.md', 'studio/LICENSE', 'studio/README.md', 'template-library/LICENSE', 'shared/editor-launch.pl', 'gateway/brand-capture/LICENSE', 'gateway/brand-capture/NOTICE.md', diff --git a/server.ts b/server.ts index fe721fa38..493f69c90 100644 --- a/server.ts +++ b/server.ts @@ -18,6 +18,7 @@ import { VERSION } from './preview.ts'; import { templates } from './template-library.ts'; import { templateRecipe } from './template-catalog.ts'; import { templateCatalogFor } from './prism-templates.ts'; +import { upgradeTemplateGuidePage, compactNativeGuideStage, authoredTemplateGuide } from './shared/template-guide.ts'; import { isEditableTemplate } from './shared/catalog.ts'; import { proxyStudio, renderDownloadDisposition, serveEditorFile } from './editor-server.ts'; import { publicTools as mcpTools } from './mcp.ts'; @@ -613,8 +614,17 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store = const mime: Record = { '.html': 'text/html', '.md': 'text/plain', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp', '.avif': 'image/avif', '.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.woff': 'font/woff', '.ttf': 'font/ttf', '.otf': 'font/otf', '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.webm': 'video/webm', '.m4v': 'video/mp4', '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.ogg': 'audio/ogg', '.m4a': 'audio/mp4', '.aac': 'audio/aac', '.flac': 'audio/flac' }; const type = mime[path.extname(name).toLowerCase()] || 'application/octet-stream'; try { - const bytes = await templateCatalogFor(store.directory).sourceFile(templateSource[1], name); - res.writeHead(200, { 'Content-Type': type, 'Content-Length': bytes.length }); res.end(bytes); return; + const catalog = templateCatalogFor(store.directory); + let bytes = await catalog.sourceFile(templateSource[1], name); + if (name === 'preview.html' && url.searchParams.get('raw') !== '1') { + const template = await catalog.get(templateSource[1]); + bytes = Buffer.from(upgradeTemplateGuidePage(bytes.toString(), { id: template.id, title: template.title, brand: template.brand, + sourceUrl: template.sourceUrl, previewUrl: template.previewUrl, posterUrl: template.posterUrl, hasHtmlProject: template.hasHtmlProject, + ...(!authoredTemplateGuide(bytes.toString()) ? { motionDocument: (await catalog.sourceFile(template.id, 'motion.md')).toString() } : {}) })); + } + else if (name === 'preview.html' && url.searchParams.get('stage') === '1') bytes = Buffer.from(compactNativeGuideStage(bytes.toString())); + res.writeHead(200, { 'Content-Type': type, 'Content-Length': bytes.length, + ...(name === 'motion.md' && url.searchParams.get('download') === '1' ? { 'Content-Disposition': 'attachment; filename="motion.md"' } : {}) }); res.end(bytes); return; } catch (error) { if ((error as { code?: string }).code === 'TEMPLATE_LFS_NOT_FETCHED') return json(res, 409, { code: 'TEMPLATE_LFS_NOT_FETCHED', error: (error as Error).message }); diff --git a/shared/phase1-tools.ts b/shared/phase1-tools.ts index 4f08b4249..bcd1b2e4e 100644 --- a/shared/phase1-tools.ts +++ b/shared/phase1-tools.ts @@ -1,4 +1,5 @@ import { inlineVideoUri } from './inline-video.ts'; +import { templateGuideDraftSchema } from './template-guide.ts'; import { publicToolName, legacyToolName } from './public-names.mjs'; import { templateDiscoveryGuide } from './workflow-entry.js'; import { projectArchiveTool } from './project-archive.ts'; @@ -34,10 +35,10 @@ export const phase1Tools = [ offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 100 } }, ['action']), annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true } }, { name: 'openmotion_list_templates', title: 'OpenMotion · List Templates', description: 'Index templates from the loaded local repository; NPM installations without repository catalog files read the latest OpenMotion hosted `main` catalog, while explicit CMS mode uses the configured publication. Returns source, indexPath (local JSONL, one summary per template), total and catalogVersion, not search results. Read or grep/jq the file to select a template, then call openmotion_get_template. Repository summaries include localSource paths and hosted entries do not expose local paths. No query or pagination arguments. ' + templateDiscoveryGuide, inputSchema: object({}), annotations: { ...read, openWorldHint: true } }, - { name: 'openmotion_get_template', title: 'OpenMotion · Get Template', description: 'Read one exact template ID and its TEMPLATE.md guidance. Repository entries include localSource absolute paths and local motionDocument content; hosted catalog entries return motionDocument without localSource paths. Built-in examples resolve locally without a catalog request. Guidance-only examples remain distinct from editable Studio projects. Follow the returned workflowGuide: template means openmotion_create_project with projectType=template copies the editable project; recreate means openmotion-recreate rebuilds from the guidance package and its linked reference video. Known IDs do not require listing first.', inputSchema: object({ templateId: id }, ['templateId']), annotations: { ...read, openWorldHint: true } }, + { name: 'openmotion_get_template', title: 'OpenMotion · Get Template', description: 'Read one exact template ID and its TEMPLATE.md guidance. Repository entries include localSource absolute paths and local motionDocument content; hosted catalog entries return motionDocument without localSource paths. Built-in examples resolve locally without a catalog request. Guidance-only examples remain distinct from editable Studio projects. Follow the returned workflowGuide: template means openmotion_create_project with projectType=template copies the editable project; recreate means openmotion-recreate rebuilds from the guidance package and its linked reference video. An explicit guideDraft can instead create this entry’s declared title/accent motion example; this does not reconstruct its reference film or change the default workflowGuide. Known IDs do not require listing first.', inputSchema: object({ templateId: id }, ['templateId']), annotations: { ...read, openWorldHint: true } }, { name: 'openmotion_create_project', title: 'OpenMotion · Create Project', description: 'Create an independent editable native OpenMotion project from a prompt, an editable template ID or reference-video ID. The host Agent authors the film; creation does not generate a finished video. Persist requirements, namingLanguage and source, return project/session IDs and the initial content version. A requestId is required for safe retries.', inputSchema: object({ requestId: id, projectType: { enum: ['natural_language', 'template', 'reference_video'] }, title: { type: 'string', minLength: 1, maxLength: 100 }, requirements: text, namingLanguage: { type: 'string', minLength: 2, maxLength: 50, description: 'BCP 47 language for newly assigned asset names. Choose explicit user preference, otherwise initial brief language, otherwise interface language. Saved once; existing meaningful names remain unchanged.' }, - sessionId: projectId, templateId: id, referenceVideoId: id, referenceUrl: { type: 'string', maxLength: 2000 } }, ['requestId', 'projectType', 'title', 'requirements']), annotations: write }, + sessionId: projectId, templateId: id, guideDraft: { ...templateGuideDraftSchema, description: 'Optional title and accent for this catalog entry’s own authored motion-guide example. Creates that canvas example with native Variables, not a reconstruction of its reference film. Requires projectType=template and templateId.' }, referenceVideoId: id, referenceUrl: { type: 'string', maxLength: 2000 } }, ['requestId', 'projectType', 'title', 'requirements']), annotations: write }, { name: 'openmotion_open_preview', title: 'OpenMotion · Open Preview', description: 'For video production, action=begin with explicit projectId, stable requestId and mode=create|modify creates a business work round silently before authoring. No production or editor action mounts an inline component. Open the editor only after the final authored video is ready for preview; after MP4 verification, prefer the host-native video preview (Codex: one final-reply embed). Use the separately discovered openmotion_show_video only if the host cannot preview the video; never combine both players for the same export. Once the requested video artifact exists, call action=complete_generation with workId, expectedRevision and expectedVersionId. This independently validates the completed artifact and records generation once, including background work, without saving, opening preview or rendering. Carry its workId through saves and the final export; begin does not open Studio or render. Explicit editor-only requests, unchanged template browsing and review flows do not begin a round. Prepare the named project in the shared editable Studio; this Tool does not open the host browser. Use target=templates for the template library or target=providers for Settings > Model providers without creating/selecting a project; target=templates accepts only action=open, embedded and presentation, while target=providers also accepts optional entry, and both return a page handoff without a project/version identity. Without projectId use only an explicitly bound OpenMotion session, never the global most-recent project. Follow previewHandoff to present the native panel and verify visibility plus latest content for first delivery and continued edits. Default foreground shows the active calling chat panel without switching chats; wait for return only when the host confirms that chat is inactive. A queued acknowledgment, hidden automation tab or markDeliverable does not complete delivery. Only an explicit show-now request uses presentation=now to permit switching for this turn. action=record_display records the current revision/version observation; queued or unverified content stays pending. Report a still-hidden panel as a display failure. action=record_review records evidence about a previously viewed frozen version without changing source.', inputSchema: object({ target: { enum: ['project', 'templates', 'providers'] }, action: { enum: ['open', 'record_review', 'record_display', 'begin', 'complete_generation'] }, mode: { enum: ['create', 'modify'] }, generation: { type: 'boolean', description: 'Begin defaults to a generation attempt. Set false only for export-only playback of already accepted content.' }, projectId, sessionId: projectId, workId, embedded: { type: 'boolean' }, presentation, entry: providerEntry, expectedRevision: revision, expectedVersionId: id, requestId: id, review, display }, []), annotations: write }, { name: 'openmotion_import_assets', title: 'OpenMotion · Import Assets', description: 'Persist a batch of real local attachments into this project, at most 500 MB (500000000 bytes) per file. Probe media or parse TTF/OTF/TTC/WOFF fonts and return per-item asset IDs, types, sizes, paths and errors. Fonts include actual family/weight/style and project-relative @font-face CSS; an optional licensePath is copied in the same version. Successful items survive other failures. Existing history is not overwritten. Import does not place media on the timeline. Reuse the same requestId/itemId to retry without duplicate assets.', diff --git a/shared/template-guide-ui.json b/shared/template-guide-ui.json new file mode 100644 index 000000000..503c81c6b --- /dev/null +++ b/shared/template-guide-ui.json @@ -0,0 +1,266 @@ +{ + "en": { + "make": "Make it your own", + "hint": "Change the fields to update this example instantly.", + "edit": "Continue in editor", + "copy": "Copy production requirements", + "reset": "Restore example", + "example": "Example", + "reference": "Reference video", + "breakdown": "Reference and breakdown", + "download": "Download motion.md", + "document": "View full document", + "source": "View original source", + "chapters": "Choose a moment to try", + "notice": "This authored example illustrates the reference motion; it is not the reference film.", + "saved": "Draft saved on this device", + "failed": "Could not open the project. Your draft is kept; try again.", + "opening": "Preparing editable project...", + "copied": "Production requirements copied.", + "manual": "Copy failed. Select and copy the production requirements below.", + "variables": "Your trial text and color carry into the new project. Continue with your Agent.", + "unavailable": "This guide has no trial fields. Copy the requirements to continue with your Agent.", + "library": "Template library", + "pending": "Changes stay on this device" + }, + "zh-CN": { + "make": "做成你的版本", + "hint": "修改内容,画面会即时更新。", + "edit": "进入编辑器", + "copy": "复制制作要求", + "reset": "还原示例", + "example": "示例", + "reference": "参考原片", + "breakdown": "参考与拆解", + "download": "下载 motion.md", + "document": "查看完整文档", + "source": "查看原作来源", + "chapters": "选一个画面,看看能改什么", + "notice": "这是根据参考整理的动作与构图示意,并非参考原片。", + "saved": "草稿已保存在本机", + "failed": "未能打开工程,草稿已保留,请重试。", + "opening": "正在准备可编辑工程…", + "copied": "制作要求已复制", + "manual": "复制失败,请选中下方制作要求手动复制。", + "variables": "试改的文字和颜色会带入新工程,可交给 Agent 继续修改。", + "unavailable": "此页暂未提供试改参数。可复制制作要求,交给 Agent 继续制作。", + "library": "模板库", + "pending": "试改内容保留在本机" + }, + "ja": { + "make": "自分の作品にする", + "hint": "項目を変更すると、サンプルにすぐ反映されます。", + "edit": "エディターで続ける", + "copy": "制作要件をコピー", + "reset": "サンプルに戻す", + "example": "サンプル", + "reference": "参考動画", + "breakdown": "参考作品と分析", + "download": "motion.mdをダウンロード", + "document": "完全なドキュメントを表示", + "source": "原作の出典を見る", + "chapters": "場面を選んで試す", + "notice": "参考作品をもとに作成した動きと構図のサンプルで、参考動画そのものではありません。", + "saved": "下書きをこの端末に保存しました", + "failed": "プロジェクトを開けませんでした。下書きは保持されています。再試行してください。", + "opening": "編集可能なプロジェクトを準備中…", + "copied": "制作要件をコピーしました", + "manual": "コピーできませんでした。以下の制作要件を選択して手動でコピーしてください。", + "variables": "変更した文字と色は新しいプロジェクトに引き継がれます。Agentで編集を続けられます。", + "unavailable": "このガイドには試用項目がありません。制作要件をコピーしてAgentで続けてください。", + "library": "テンプレートライブラリ", + "pending": "変更内容はこの端末に保持されます" + }, + "ko": { + "make": "나만의 버전 만들기", + "hint": "항목을 변경하면 예시에 바로 반영됩니다.", + "edit": "편집기에서 계속", + "copy": "제작 요구 사항 복사", + "reset": "예시 복원", + "example": "예시", + "reference": "참고 영상", + "breakdown": "참고 자료와 분석", + "download": "motion.md 다운로드", + "document": "전체 문서 보기", + "source": "원작 출처 보기", + "chapters": "장면을 선택해 바꿔 보세요", + "notice": "참고 작품을 바탕으로 만든 모션과 구도 예제이며 원본 영상은 아닙니다.", + "saved": "초안을 이 기기에 저장했습니다", + "failed": "프로젝트를 열지 못했습니다. 초안은 유지됩니다. 다시 시도하세요.", + "opening": "편집 가능한 프로젝트 준비 중…", + "copied": "제작 요구사항이 복사됨", + "manual": "복사하지 못했습니다. 아래 제작 요구 사항을 선택해 직접 복사하세요.", + "variables": "변경한 글자와 색상이 새 프로젝트에 유지됩니다. Agent로 편집을 계속하세요.", + "unavailable": "이 가이드에는 체험 항목이 없습니다. 제작 요구사항을 복사하여 Agent에서 계속하세요.", + "library": "템플릿 라이브러리", + "pending": "변경 사항은 이 기기에 보관됩니다" + }, + "de": { + "make": "Mach es zu deiner Version", + "hint": "Ändere die Felder, um das Beispiel sofort zu aktualisieren.", + "edit": "Im Editor fortfahren", + "copy": "Produktionsvorgaben kopieren", + "reset": "Beispiel wiederherstellen", + "example": "Beispiel", + "reference": "Referenzfilm", + "breakdown": "Referenz und Analyse", + "download": "motion.md herunterladen", + "document": "Vollständiges Dokument ansehen", + "source": "Originalquelle ansehen", + "chapters": "Wähle einen Moment zum Ausprobieren", + "notice": "Dieses Bewegungsbeispiel basiert auf der Referenz. Es ist nicht der Originalfilm.", + "saved": "Entwurf auf diesem Gerät gespeichert", + "failed": "Projekt konnte nicht geöffnet werden. Dein Entwurf bleibt erhalten; versuche es erneut.", + "opening": "Bearbeitbares Projekt wird vorbereitet…", + "copied": "Produktionsvorgaben kopiert", + "manual": "Kopieren fehlgeschlagen. Markiere und kopiere die Produktionsvorgaben unten.", + "variables": "Dein Text und deine Farbe werden ins neue Projekt übernommen. Bearbeite es mit deinem Agent weiter.", + "unavailable": "Diese Anleitung hat keine Testfelder. Kopiere die Vorgaben und fahre mit deinem Agent fort.", + "library": "Vorlagenbibliothek", + "pending": "Änderungen bleiben auf diesem Gerät" + }, + "fr": { + "make": "Personnalisez-le", + "hint": "Modifiez les champs pour actualiser immédiatement cet exemple.", + "edit": "Continuer dans l’éditeur", + "copy": "Copier les consignes de production", + "reset": "Rétablir l’exemple", + "example": "Exemple", + "reference": "Film de référence", + "breakdown": "Référence et analyse", + "download": "Télécharger motion.md", + "document": "Voir le document complet", + "source": "Voir la source originale", + "chapters": "Choisissez un moment à modifier", + "notice": "Cet exemple animé s’inspire de la référence. Ce n’est pas le film original.", + "saved": "Brouillon enregistré sur cet appareil", + "failed": "Impossible d’ouvrir le projet. Votre brouillon est conservé ; réessayez.", + "opening": "Préparation du projet modifiable…", + "copied": "Consignes de production copiées", + "manual": "Échec de la copie. Sélectionnez et copiez les consignes de production ci-dessous.", + "variables": "Le texte et la couleur sont conservés dans le nouveau projet. Continuez avec votre Agent.", + "unavailable": "Ce guide n’a pas de champs d’essai. Copiez les consignes et continuez avec votre Agent.", + "library": "Bibliothèque de modèles", + "pending": "Les modifications restent sur cet appareil" + }, + "ru": { + "make": "Создайте свою версию", + "hint": "Меняйте поля, чтобы сразу увидеть результат в примере.", + "edit": "Продолжить в редакторе", + "copy": "Скопировать требования к ролику", + "reset": "Восстановить пример", + "example": "Пример", + "reference": "Видео-референс", + "breakdown": "Референс и разбор", + "download": "Скачать motion.md", + "document": "Открыть полный документ", + "source": "Открыть оригинальный источник", + "chapters": "Выберите момент для изменения", + "notice": "Это авторский пример анимации по референсу, а не оригинальный фильм.", + "saved": "Черновик сохранён на этом устройстве", + "failed": "Не удалось открыть проект. Черновик сохранён; попробуйте ещё раз.", + "opening": "Подготовка редактируемого проекта…", + "copied": "Требования скопированы", + "manual": "Не удалось скопировать. Выделите и скопируйте требования к ролику ниже.", + "variables": "Изменённые текст и цвет сохранятся в новом проекте. Продолжайте с Agent.", + "unavailable": "В руководстве нет пробных полей. Скопируйте требования и продолжите с Agent.", + "library": "Библиотека шаблонов", + "pending": "Изменения остаются на этом устройстве" + }, + "es": { + "make": "Hazlo tuyo", + "hint": "Cambia los campos para actualizar el ejemplo al instante.", + "edit": "Continuar en el editor", + "copy": "Copiar requisitos de producción", + "reset": "Restaurar ejemplo", + "example": "Ejemplo", + "reference": "Vídeo de referencia", + "breakdown": "Referencia y análisis", + "download": "Descargar motion.md", + "document": "Ver documento completo", + "source": "Ver la fuente original", + "chapters": "Elige un momento para probar", + "notice": "Este ejemplo de movimiento se basa en la referencia. No es el vídeo original.", + "saved": "Borrador guardado en este dispositivo", + "failed": "No se pudo abrir el proyecto. Se conserva tu borrador; inténtalo de nuevo.", + "opening": "Preparando proyecto editable…", + "copied": "Requisitos de producción copiados", + "manual": "La copia falló. Selecciona y copia los requisitos de producción de abajo.", + "variables": "El texto y el color se conservan en el nuevo proyecto. Continúa con tu Agent.", + "unavailable": "Esta guía no tiene campos de prueba. Copia los requisitos y continúa con tu Agent.", + "library": "Biblioteca de plantillas", + "pending": "Los cambios se guardan en este dispositivo" + }, + "pt-BR": { + "make": "Deixe com a sua cara", + "hint": "Altere os campos para atualizar o exemplo na hora.", + "edit": "Continuar no editor", + "copy": "Copiar requisitos de produção", + "reset": "Restaurar exemplo", + "example": "Exemplo", + "reference": "Vídeo de referência", + "breakdown": "Referência e análise", + "download": "Baixar motion.md", + "document": "Ver documento completo", + "source": "Ver a fonte original", + "chapters": "Escolha um momento para testar", + "notice": "Este exemplo de movimento foi criado com base na referência. Não é o vídeo original.", + "saved": "Rascunho salvo neste dispositivo", + "failed": "Não foi possível abrir o projeto. Seu rascunho foi mantido; tente novamente.", + "opening": "Preparando projeto editável…", + "copied": "Requisitos de produção copiados", + "manual": "A cópia falhou. Selecione e copie os requisitos de produção abaixo.", + "variables": "O texto e a cor serão mantidos no novo projeto. Continue com seu Agent.", + "unavailable": "Este guia não tem campos de teste. Copie os requisitos e continue com seu Agent.", + "library": "Biblioteca de modelos", + "pending": "As alterações ficam neste dispositivo" + }, + "it": { + "make": "Rendilo tuo", + "hint": "Modifica i campi per aggiornare subito l’esempio.", + "edit": "Continua nell’editor", + "copy": "Copia i requisiti di produzione", + "reset": "Ripristina esempio", + "example": "Esempio", + "reference": "Video di riferimento", + "breakdown": "Riferimento e analisi", + "download": "Scarica motion.md", + "document": "Apri il documento completo", + "source": "Visualizza la fonte originale", + "chapters": "Scegli un momento da provare", + "notice": "Questo esempio animato si basa sul riferimento. Non è il video originale.", + "saved": "Bozza salvata su questo dispositivo", + "failed": "Impossibile aprire il progetto. La bozza è conservata; riprova.", + "opening": "Preparazione del progetto modificabile…", + "copied": "Requisiti di produzione copiati", + "manual": "Copia non riuscita. Seleziona e copia i requisiti di produzione qui sotto.", + "variables": "Il testo e il colore vengono mantenuti nel nuovo progetto. Continua con il tuo Agent.", + "unavailable": "Questa guida non ha campi di prova. Copia i requisiti e continua con il tuo Agent.", + "library": "Libreria modelli", + "pending": "Le modifiche restano su questo dispositivo" + }, + "tr": { + "make": "Kendinize uyarlayın", + "hint": "Örneği anında güncellemek için alanları değiştirin.", + "edit": "Düzenleyicide devam et", + "copy": "Yapım gereksinimlerini kopyala", + "reset": "Örneği geri yükle", + "example": "Örnek", + "reference": "Referans video", + "breakdown": "Referans ve inceleme", + "download": "motion.md indir", + "document": "Tam belgeyi görüntüle", + "source": "Özgün kaynağı görüntüle", + "chapters": "Denemek için bir an seçin", + "notice": "Bu hareket örneği referanstan yola çıkılarak hazırlanmıştır. Özgün video değildir.", + "saved": "Taslak bu cihaza kaydedildi", + "failed": "Proje açılamadı. Taslağınız korunuyor; yeniden deneyin.", + "opening": "Düzenlenebilir proje hazırlanıyor…", + "copied": "Üretim gereksinimleri kopyalandı", + "manual": "Kopyalama başarısız. Aşağıdaki yapım gereksinimlerini seçip kopyalayın.", + "variables": "Denediğiniz metin ve renk yeni projeye aktarılır. Agent ile düzenlemeye devam edin.", + "unavailable": "Bu kılavuzda deneme alanları yok. Gereksinimleri kopyala ve Agent ile devam et.", + "library": "Şablon kitaplığı", + "pending": "Değişiklikler bu cihazda kalır" + } +} diff --git a/shared/template-guide.ts b/shared/template-guide.ts new file mode 100644 index 000000000..f1b8db424 --- /dev/null +++ b/shared/template-guide.ts @@ -0,0 +1,54 @@ +/** Portable draft contract for each catalog entry's own authored motion example. */ +export type TemplateGuideDraft = { title: string; accent: string }; +export const templateGuideActions = ['shown', 'edit', 'chapter', 'reference', 'reset', 'copy', 'open_editor', 'download'] as const; +export type TemplateGuideEvent = { action: typeof templateGuideActions[number]; view_id: string; field?: 'title' | 'accent'; outcome?: 'success' | 'failure' | 'manual_fallback'; project_id?: string }; +export function isTemplateGuideEvent(input: unknown): input is TemplateGuideEvent { + const value = input as TemplateGuideEvent; + return Boolean(value && templateGuideActions.includes(value.action) && /^[a-f0-9-]{36}$/i.test(value.view_id) + && (value.field === undefined || ['title', 'accent'].includes(value.field)) + && (value.outcome === undefined || ['success', 'failure', 'manual_fallback'].includes(value.outcome)) + && (value.project_id === undefined || value.action === 'open_editor' && value.outcome === 'success' && /^[a-f0-9-]{36}$/i.test(value.project_id)) + && Object.keys(value).every(key => ['action', 'view_id', 'field', 'outcome', 'project_id'].includes(key))); +} +export const templateGuideDraftSchema = { type: 'object', additionalProperties: false, + properties: { title: { type: 'string', minLength: 1, maxLength: 60 }, accent: { type: 'string', pattern: '^#[a-fA-F0-9]{6}$' } }, + required: ['title', 'accent'] }; +export function parseTemplateGuideDraft(input: unknown): TemplateGuideDraft { + const value = input as TemplateGuideDraft; + if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !['title', 'accent'].includes(key)) + || typeof value.title !== 'string' || !value.title.trim() || value.title.length > 60 || /[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(value.title) + || typeof value.accent !== 'string' || !/^#[a-fA-F0-9]{6}$/.test(value.accent)) throw new Error('INVALID_GUIDE_DRAFT'); + return { title: value.title, accent: value.accent.toLowerCase() }; +} +export const jsonForHtml = (value: unknown) => JSON.stringify(value).replace(/ value.replace(/&(quot|apos|lt|gt|amp|#39);/g, (_, key: string) => + ({ quot: '"', apos: "'", lt: '<', gt: '>', amp: '&', '#39': "'" }[key]!)); +export type AuthoredGuide = { src: 'demos/sequence.html'; duration: number; defaults: TemplateGuideDraft }; +/** Read declarations only; catalog scripts and prose are never executed on the server. */ +export function authoredTemplateGuide(source: string): AuthoredGuide | undefined { + for (const match of source.matchAll(/\bdata-demo="([^"]+)"/g)) { + let data; + try { data = JSON.parse(decodeAttribute(match[1])); } catch { continue; } + if (data.id !== 'sequence') continue; + if (data.src !== 'demos/sequence.html' || data.status !== 'authored' || !Number.isFinite(data.duration) || data.duration <= 0 || data.duration > 600) return; + if (!Array.isArray(data.params) || data.params.length !== 2) return; + const title = data.params.find((item: any) => item.key === 'title' && item.type === 'text'); + const accent = data.params.find((item: any) => item.key === 'accent' && item.type === 'color'); + if (!title || !accent || title.maxLength !== 60) return; + try { return { src: data.src, duration: data.duration, defaults: parseTemplateGuideDraft({ title: title.value, accent: accent.value }) }; } catch { return; } + } +} + +export type TemplateGuidePage = { id: string; title: string; brand?: string; sourceUrl?: string; previewUrl?: string; posterUrl?: string; hasHtmlProject?: boolean; motionDocument?: string; authored: boolean }; +export function compactNativeGuideStage(source: string): string { + return source.replace(/<\/head>/i, ''); +} +/** Serve one maintained interface at every existing preview URL, preserving each entry's source and resource base. */ +export function upgradeTemplateGuidePage(source: string, template: Omit): string { + const config = { ...template, authored: Boolean(authoredTemplateGuide(source)) }; + const head = ''; + const scripts = ''; + if (!config.authored) return '' + head + '' + scripts + ''; + const html = source.replace(/]*href=["']viewer\/(?:guide|board)\.css["'][^>]*>/gi, ''); + return html.replace(/<\/head>/i, head + '').replace(/<\/body>/i, scripts + ''); +} diff --git a/studio/src/motion/TemplateMotionGuide.test.tsx b/studio/src/motion/TemplateMotionGuide.test.tsx index 5e0b523e5..5f1960345 100644 --- a/studio/src/motion/TemplateMotionGuide.test.tsx +++ b/studio/src/motion/TemplateMotionGuide.test.tsx @@ -4,6 +4,7 @@ import { createRoot, type Root } from 'react-dom/client'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import { TemplateMotionGuide } from './TemplateMotionGuide'; import { prepareMotionGuide, type GuideAppearance } from './templateMotionGuideDocument'; +import * as guideActions from '../template-guide/actions'; globalThis.IS_REACT_ACT_ENVIRONMENT = true; const appearance: GuideAppearance = { theme: 'light', background: '#f5f5f5', text: '#494949', muted: '#5c5c5c', surface: '#fafafa', border: '#dbdbdb' }; @@ -93,3 +94,18 @@ it('revokes prepared guide documents on selection changes and unmount', async () await act(async () => root.render(null)); expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:http://localhost/2'); }); + +it('delegates only the current local guide frame and pins its template identity', async () => { + const id = 'motion-be2a4af0-0183-4979-ab05-2a68413c0890'; + vi.stubGlobal('fetch', vi.fn(async () => new Response(source, { headers: { 'content-type': 'text/html' } }))); + const action = vi.spyOn(guideActions, 'handleGuideAction').mockResolvedValue(null); + await act(async () => root.render()); + const frame = host.querySelector('iframe')!; + const rpc = { type: 'openmotion:guide-action', templateId: id, viewId: crypto.randomUUID(), requestId: 'load-1', action: 'load', locale: 'en' }; + await act(async () => window.dispatchEvent(new MessageEvent('message', { data: rpc, source: window }))); + expect(action).not.toHaveBeenCalled(); + await act(async () => window.dispatchEvent(new MessageEvent('message', { data: { ...rpc, templateId: 'motion-another-template' }, source: frame.contentWindow }))); + expect(action).not.toHaveBeenCalled(); + await act(async () => window.dispatchEvent(new MessageEvent('message', { data: rpc, source: frame.contentWindow }))); + expect(action).toHaveBeenCalledExactlyOnceWith(id, 'load', undefined, expect.any(String)); +}); diff --git a/studio/src/motion/TemplateMotionGuide.tsx b/studio/src/motion/TemplateMotionGuide.tsx index 2c57e78a4..9b4453996 100644 --- a/studio/src/motion/TemplateMotionGuide.tsx +++ b/studio/src/motion/TemplateMotionGuide.tsx @@ -1,10 +1,15 @@ import { useEffect, useRef, useState } from 'react'; import { useShownStudioTheme } from '../utils/studioTheme'; import { prepareMotionGuide, type GuideAppearance } from './templateMotionGuideDocument'; +import { handleGuideAction, validGuideRpc } from '../template-guide/actions'; +import { useI18n } from '../i18n/I18n'; +import { isTemplateGuideEvent } from '../../../shared/template-guide'; +import { send } from './reporting'; export function TemplateMotionGuide({ url, title }: { url: string; title: string }) { const frame = useRef(null); const theme = useShownStudioTheme(); + const { locale } = useI18n(); const latestTheme = useRef(theme); latestTheme.current = theme; const [document, setDocument] = useState<{ url: string; src: string }>({ url: '', src: 'about:blank' }); @@ -24,6 +29,35 @@ export function TemplateMotionGuide({ url, title }: { url: string; title: string frame.current?.contentWindow?.postMessage({ type: 'openmotion:guide-appearance', appearance: appearance() }, '*'); } useEffect(() => { syncAppearance(); }, [theme]); + useEffect(() => { + const path = new URL(url, location.href); + const id = path.origin === location.origin && path.pathname.match(/^\/api\/template-source\/([a-z][a-z0-9-]+)\/preview\.html$/)?.[1]; + if (!id) return; + let active = true; + const receive = async (event: MessageEvent) => { + if (event.source !== frame.current?.contentWindow) return; + if (event.data?.type === 'openmotion:guide-event' && event.data.templateId === id && isTemplateGuideEvent(event.data.event)) { + send('template_guide_interaction', { page_name: 'studio', template_id: id, ...event.data.event }); return; + } + if (!validGuideRpc(event.data) || event.data.templateId !== id) return; + const message = event.data; + try { + const result = await handleGuideAction(id, message.action, message.value, locale); + if (!active) return; + frame.current?.contentWindow?.postMessage({ type: 'openmotion:guide-action-result', requestId: message.requestId, result }, '*'); + if (message.action === 'library' && result && typeof result === 'object' && 'url' in result) location.assign(String(result.url)); + if (message.action === 'open' && result && typeof result === 'object' && 'url' in result && 'projectId' in result) { + send('template_guide_interaction', { page_name: 'studio', template_id: id, view_id: message.viewId, action: 'open_editor', outcome: 'success', project_id: String(result.projectId) }); + location.assign(String(result.url)); + } + } catch (error) { if (active) { + if (message.action === 'open') send('template_guide_interaction', { page_name: 'studio', template_id: id, view_id: message.viewId, action: 'open_editor', outcome: 'failure' }); + frame.current?.contentWindow?.postMessage({ type: 'openmotion:guide-action-result', requestId: message.requestId, error: (error as Error).message }, '*'); + } } + }; + window.addEventListener('message', receive); + return () => { active = false; window.removeEventListener('message', receive); }; + }, [url, locale]); useEffect(() => { const controller = new AbortController(); let objectUrl: string | undefined; @@ -35,7 +69,7 @@ export function TemplateMotionGuide({ url, title }: { url: string; title: string if (!controller.signal.aborted) { // A blob retains the parent's URL origin for authored postMessage calls. // The sandbox still gives its script an opaque security origin. - const html = prepareMotionGuide(source, response.url || url, appearance()); + const html = prepareMotionGuide(source, response.url || url, appearance(), locale); objectUrl = URL.createObjectURL(new Blob([html], { type: 'text/html' })); setDocument({ url, src: objectUrl }); } diff --git a/studio/src/motion/templateMotionGuideDocument.ts b/studio/src/motion/templateMotionGuideDocument.ts index f784c9641..744ed9afc 100644 --- a/studio/src/motion/templateMotionGuideDocument.ts +++ b/studio/src/motion/templateMotionGuideDocument.ts @@ -24,13 +24,14 @@ html[data-openmotion-guide="dark"] :is(.identity, .palette, .overview, .type-bas `; /** Keep the remote document and its resource base intact inside the existing opaque-origin sandbox. */ -export function prepareMotionGuide(source: string, url: string, appearance: GuideAppearance): string { +export function prepareMotionGuide(source: string, url: string, appearance: GuideAppearance, locale?: string): string { const doc = new DOMParser().parseFromString(source, 'text/html'); const base = doc.querySelector('base[href]') ?? doc.createElement('base'); base.href = new URL(base.getAttribute('href') ?? url, url).href; if (!base.parentNode) doc.head.prepend(base); const root = doc.documentElement; root.dataset.openmotionGuide = appearance.theme; + if (locale) root.dataset.guideLocale = locale; root.style.setProperty('--om-guide-scheme', appearance.theme); for (const key of ['background', 'text', 'muted', 'surface', 'border'] as const) { root.style.setProperty(`--om-guide-${key}`, appearance[key]); diff --git a/studio/src/template-guide/actions.test.ts b/studio/src/template-guide/actions.test.ts new file mode 100644 index 000000000..17ee0185f --- /dev/null +++ b/studio/src/template-guide/actions.test.ts @@ -0,0 +1,68 @@ +// @vitest-environment happy-dom +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { guideDraftKey, handleGuideAction, validGuideRpc } from './actions'; +const lovable = 'motion-be2a4af0-0183-4979-ab05-2a68413c0890'; +const stripe = 'motion-80dceb1d-5219-4e1f-9394-6baacf5d0166'; +const draft = { title: 'My product', accent: '#7050da' }; +beforeEach(() => localStorage.clear()); +afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); }); +const api = () => vi.stubGlobal('fetch', vi.fn(async (_url: string, init: RequestInit) => { + const { name } = JSON.parse(init.body as string); + if (_url !== '/motion-api/phase1/call') return new Response(JSON.stringify({ error: 'Wrong service route' }), { status: 503 }); + return new Response(JSON.stringify(name === 'openmotion_get_template' ? { title: 'Lovable', hasHtmlProject: false } : name === 'openmotion_create_project' + ? { projectId: '11111111-1111-4111-8111-111111111111', previewUrl: location.origin + '/?project=11111111-1111-4111-8111-111111111111' } : {})); +})); + +it('keeps draft storage separate for every exact template and rejects corrupt values', async () => { + await handleGuideAction(lovable, 'save', draft, 'en'); + expect(await handleGuideAction(lovable, 'load', undefined, 'en')).toEqual(draft); + expect(await handleGuideAction(stripe, 'load', undefined, 'en')).toBeNull(); + localStorage.setItem(guideDraftKey(stripe), JSON.stringify({ ...draft, path: '/private' })); + expect(await handleGuideAction(stripe, 'load', undefined, 'en')).toBeNull(); +}); +it('copies the selected template and current values without creating or sending a project', async () => { + api(); const write = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(); + expect(await handleGuideAction(lovable, 'copy', draft, 'en')).toEqual({ copied: true }); + const text = write.mock.calls[0][0]; expect(text).toContain(lovable); expect(text).toContain('My product'); expect(text).not.toContain(stripe); + expect(fetch).toHaveBeenCalledTimes(1); + write.mockRejectedValue(new Error('Clipboard denied')); + expect(await handleGuideAction(lovable, 'copy', draft, 'en')).toEqual({ copied: false, text }); +}); +it('reuses one creation request for the same draft and opens the returned project', async () => { + api(); + await handleGuideAction(lovable, 'open', draft, 'en'); await handleGuideAction(lovable, 'open', draft, 'en'); + const calls = vi.mocked(fetch).mock.calls.map(([, init]) => JSON.parse(init!.body as string)); + const creates = calls.filter(call => call.name === 'openmotion_create_project'); + expect(creates[0].arguments.requestId).toBe(creates[1].arguments.requestId); + expect(creates[0].arguments).toEqual(expect.objectContaining({ templateId: lovable, guideDraft: draft })); + expect(calls.filter(call => call.name === 'openmotion_open_preview').map(call => call.arguments.projectId)).toEqual(['11111111-1111-4111-8111-111111111111', '11111111-1111-4111-8111-111111111111']); +}); +it('accepts only bounded requests tied to a concrete template', () => { + const rpc = { type: 'openmotion:guide-action', templateId: lovable, viewId: crypto.randomUUID(), requestId: 'copy-1', action: 'copy', locale: 'en', value: draft }; + expect(validGuideRpc(rpc)).toBe(true); expect(validGuideRpc({ ...rpc, action: 'fetch_private_file' })).toBe(false); + expect(validGuideRpc({ ...rpc, templateId: '../private' })).toBe(false); +}); + +it('downloads only the current template document through the unsandboxed host', async () => { + const bytes = '# Exact document\n'; + vi.stubGlobal('fetch', vi.fn(async () => new Response(bytes))); + vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:guide-document'); + vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}); + const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}); + vi.useFakeTimers(); + try { + expect(await handleGuideAction(lovable, 'download', undefined, 'en')).toBe(true); + expect(fetch).toHaveBeenCalledExactlyOnceWith(`/api/template-source/${lovable}/motion.md`); + expect(click).toHaveBeenCalledOnce(); + expect(click.mock.instances[0].download).toBe('motion.md'); + await vi.runAllTimersAsync(); + expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:guide-document'); + } finally { vi.useRealTimers(); } +}); +it('opens only the catalog-owned original source and constructs a pinned library route', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ sourceUrl: 'https://x.com/Lovable/status/2056389414381879461' })))); + const open = vi.spyOn(window, 'open').mockReturnValue(null); + await handleGuideAction(lovable, 'source', undefined, 'en'); + expect(open).toHaveBeenCalledExactlyOnceWith('https://x.com/Lovable/status/2056389414381879461', '_blank', 'noopener,noreferrer'); + expect(await handleGuideAction(lovable, 'library', undefined, 'en')).toEqual({ url: `${location.origin}/?templates=1&template=${lovable}` }); +}); diff --git a/studio/src/template-guide/actions.ts b/studio/src/template-guide/actions.ts new file mode 100644 index 000000000..b624725f5 --- /dev/null +++ b/studio/src/template-guide/actions.ts @@ -0,0 +1,66 @@ +import { parseTemplateGuideDraft, type TemplateGuideDraft } from '../../../shared/template-guide'; +import { formatTemplatePrompt } from '../../../shared/template-prompts'; +import { gatewayRequest } from '../motion/gatewayClient'; + +export type GuideAction = 'load' | 'save' | 'copy' | 'open' | 'download' | 'source' | 'library'; +export const guideDraftKey = (id: string) => `openmotion.template-guide.v1:${id}`; +const attempts = new Map(); +export async function guideTool(name: string, args: Record) { + return gatewayRequest('phase1/call', 'POST', { name, arguments: args }); +} +/** The embedding parent pins the id from its URL, never from a child-supplied path or URL. */ +export async function handleGuideAction(id: string, action: GuideAction, value: unknown, locale: string) { + if (!/^[a-z][a-z0-9-]+$/.test(id)) throw new Error('INVALID_TEMPLATE_ID'); + const key = guideDraftKey(id); + if (action === 'library') return { url: `${location.origin}/?templates=1&template=${encodeURIComponent(id)}` }; + if (action === 'download') { + const response = await fetch(`/api/template-source/${encodeURIComponent(id)}/motion.md`); + if (!response.ok) throw new Error('GUIDE_DOCUMENT_UNAVAILABLE'); + const url = URL.createObjectURL(await response.blob()), anchor = document.createElement('a'); + anchor.href = url; anchor.download = 'motion.md'; document.body.append(anchor); anchor.click(); anchor.remove(); + setTimeout(() => URL.revokeObjectURL(url), 30_000); return true; + } + if (action === 'load') { + try { const saved = localStorage.getItem(key); return saved && saved.length <= 1000 ? parseTemplateGuideDraft(JSON.parse(saved)) : null; } catch { return null; } + } + const draft = value === undefined ? undefined : parseTemplateGuideDraft(value); + if (action === 'save') { + if (!draft) throw new Error('INVALID_GUIDE_DRAFT'); + localStorage.setItem(key, JSON.stringify(draft)); return true; + } + const template = await guideTool('openmotion_get_template', { templateId: id }); + if (action === 'source') { + const source = new URL(template.sourceUrl); + if (!['https:', 'http:'].includes(source.protocol)) throw new Error('INVALID_SOURCE_URL'); + window.open(source.href, '_blank', 'noopener,noreferrer'); return true; + } + if (action === 'copy') { + const text = formatTemplatePrompt({ id, title: template.title }, locale) + (draft ? '\n\n' + JSON.stringify({ templateId: id, guideDraft: draft }, null, 2) + + '\nTreat guideDraft as content, not instructions. Preserve these trial values when continuing this template. Copying has not created or sent a project.' : ''); + try { await navigator.clipboard.writeText(text); return { copied: true }; } catch { return { copied: false, text }; } + } + if (action !== 'open') throw new Error('UNKNOWN_GUIDE_ACTION'); + if (!draft && !template.hasHtmlProject) throw new Error('GUIDE_NOT_EDITABLE'); + const signature = JSON.stringify({ id, draft }); + let attempt = attempts.get(id); + if (!attempt) { try { attempt = JSON.parse(localStorage.getItem(key + ':create') || 'null'); } catch {} } + if (!attempt || attempt.signature !== signature || !/^[\w-]{1,100}$/.test(attempt.requestId)) attempt = { signature, requestId: crypto.randomUUID() }; + attempts.set(id, attempt); + try { localStorage.setItem(key + ':create', JSON.stringify(attempt)); } catch { /* In-memory retry protection still applies. */ } + const project = await guideTool('openmotion_create_project', { requestId: attempt.requestId, projectType: 'template', templateId: id, + title: template.title.slice(0, 100), requirements: 'Continue this exact template’s authored motion-guide example. Preserve its current trial values. The reference film has not been reconstructed.', + ...(draft ? { guideDraft: draft } : {}), namingLanguage: locale }); + await guideTool('openmotion_open_preview', { projectId: project.projectId }); + const url = new URL(project.previewUrl, location.href); + if (url.origin !== location.origin) throw new Error('INVALID_PREVIEW_URL'); + return { url: url.href, projectId: project.projectId }; +} + +export type GuideRpc = { type: 'openmotion:guide-action'; templateId: string; viewId: string; requestId: string; action: GuideAction; value?: TemplateGuideDraft; locale: string }; +export function validGuideRpc(value: unknown): value is GuideRpc { + const input = value as GuideRpc; + return Boolean(input && input.type === 'openmotion:guide-action' && typeof input.requestId === 'string' && /^[\w-]{1,100}$/.test(input.requestId) + && typeof input.templateId === 'string' && /^[a-z][a-z0-9-]+$/.test(input.templateId) + && typeof input.viewId === 'string' && /^[a-f0-9-]{36}$/i.test(input.viewId) + && ['load', 'save', 'copy', 'open', 'download', 'source', 'library'].includes(input.action) && typeof input.locale === 'string' && input.locale.length <= 16); +} diff --git a/studio/src/template-guide/page.css b/studio/src/template-guide/page.css new file mode 100644 index 000000000..be45680a5 --- /dev/null +++ b/studio/src/template-guide/page.css @@ -0,0 +1,93 @@ +html[data-template-guide] { color-scheme: light; scroll-behavior: auto; } +html[data-template-guide][data-theme=dark] { color-scheme: dark; } +html[data-template-guide] body { margin: 0; background: var(--motion-workspace); color: var(--motion-text); font: var(--motion-weight-regular) var(--motion-text-body)/var(--motion-leading-body) var(--motion-font-sans); } +[data-template-guide] :is(h1,h2,h3,p,figure) { margin: 0; } +[data-template-guide] .omg-top { height: var(--motion-space-64); padding-inline: var(--motion-space-24); display: flex; align-items: center; gap: var(--motion-space-16); border-bottom: 1px solid var(--motion-border-subtle); } +.omg-top img { width: calc(3 * var(--motion-space-32)); height: var(--motion-space-24); object-fit: contain; } +.omg-top-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: var(--motion-weight-semibold); } +.omg-layout { display: grid; grid-template-columns: minmax(0,1fr) 400px; } +.omg-preview { min-width: 0; padding: var(--motion-space-24) var(--motion-space-32); } +.omg-first { min-height: 570px; height: calc(100dvh - var(--motion-space-64) - var(--motion-space-48)); display: flex; flex-direction: column; } +.omg-first > :not(.omg-card) { flex: none; } +.omg-heading { display: grid; gap: var(--motion-space-8); margin-bottom: var(--motion-space-20); } +.omg-eyebrow { font-size: var(--motion-text-sm); color: var(--motion-muted); } +[data-template-guide] h1 { font-size: var(--motion-text-section); font-weight: var(--motion-weight-semibold); line-height: var(--motion-leading-tight); overflow-wrap: anywhere; } +.intro-copy { color: var(--motion-muted); line-height: var(--motion-leading-prose); } +.omg-tabs { display: flex; gap: var(--motion-space-8); margin-bottom: var(--motion-space-12); } +.omg-tabs [aria-pressed=true] { background: var(--motion-hover); } +.omg-card { display: flex; flex-direction: column; min-height: 0; flex: 1; gap: var(--motion-space-12); } +.omg-stage-box { display: grid; place-items: center; flex: 1; min-height: 0; container-type: size; } +.omg-stage,.omg-original { width: min(100cqw, calc(100cqh * 5 / 3)); aspect-ratio: 5 / 3; overflow: hidden; border-radius: var(--motion-radius-xl); border: 1px solid var(--motion-border-subtle); background: var(--motion-panel); } +.omg-stage iframe { display: block; width: 100%; height: 100%; border: 0; } +.omg-original { object-fit: contain; } +.demo-controls { display: flex; align-items: center; gap: var(--motion-space-8); flex: none; min-height: var(--motion-space-32); } +.demo-controls .seek { flex: 1; min-width: 20px; accent-color: var(--motion-action); } +.demo-controls output { white-space: nowrap; font-size: var(--motion-text-xs); color: var(--motion-muted); font-family: var(--motion-font-mono); } +.demo-controls select { width: var(--motion-space-64); min-height: var(--motion-control-sm); padding: var(--motion-space-4); } +.omg-chapter-heading { font-size: var(--motion-text-md); margin-block: var(--motion-space-20) var(--motion-space-12) !important; } +.beats { display: flex; gap: var(--motion-space-8); overflow-x: auto; padding-bottom: var(--motion-space-4); } +.beats .beat { display: grid; gap: var(--motion-space-6); align-content: start; flex: 1 0 100px; min-width: 0; max-width: 220px; white-space: normal; text-align: left; padding: var(--motion-space-10); background: transparent; font-weight: var(--motion-weight-regular); } +.beat > span { font: var(--motion-text-xs) var(--motion-font-mono); color: var(--motion-muted); } +.beat b { font-size: var(--motion-text-sm); font-weight: var(--motion-weight-medium); } +.beat small { margin-left: var(--motion-space-4); } +.beat[aria-pressed=true] { background: var(--motion-hover); border-color: var(--motion-selected); } +.omg-notice { color: var(--motion-muted); font-size: var(--motion-text-sm); line-height: var(--motion-leading-prose); } +.omg-preview > .omg-notice { margin-block: var(--motion-space-16); } +.omg-inspector { height: calc(100dvh - var(--motion-space-64)); position: sticky; top: 0; display: flex; flex-direction: column; border-left: 1px solid var(--motion-border-subtle); min-height: 0; } +.omg-inspector-heading { display: flex; align-items: start; justify-content: space-between; gap: var(--motion-space-16); padding: var(--motion-space-24); } +.omg-inspector-heading > div { display: grid; gap: var(--motion-space-12); } +.omg-inspector-heading h2 { font-size: var(--motion-text-section); font-weight: var(--motion-weight-semibold); } +.omg-inspector-heading p { color: var(--motion-muted); line-height: var(--motion-leading-prose); } +.omg-inspector-heading > button { flex: none; padding-inline: var(--motion-space-8); } +.omg-inspector-body { flex: 1; min-height: 0; overflow: auto; padding-inline: var(--motion-space-24); } +.demo-params { display: grid; gap: var(--motion-space-24); padding-block: var(--motion-space-24); border-top: 1px solid var(--motion-border-subtle); } +.omg-color { display: flex; align-items: center; justify-content: space-between; gap: var(--motion-space-12); } +.demo-params input[type=color] { width: var(--motion-space-32); height: var(--motion-space-24); padding: 0; border: 0; background: transparent; cursor: pointer; } +.omg-color-code { min-width: 0; width: calc(3 * var(--motion-space-32)); padding: 0; text-align: right; font: var(--motion-text-sm) var(--motion-font-mono); background: transparent; border: 0; color: var(--motion-text); } +.omg-actions { display: grid; gap: var(--motion-space-12); padding: var(--motion-space-24); border-top: 1px solid var(--motion-border-subtle); } +.omg-status { color: var(--motion-muted); } +.omg-actions > .ui-button { width: 100%; min-height: var(--motion-space-40); } +.omg-actions > small { line-height: var(--motion-leading-prose); } +.omg-actions textarea { resize: vertical; font: var(--motion-text-xs) var(--motion-font-mono); } +.omg-breakdown { border-top: 1px solid var(--motion-border-subtle); padding-block: var(--motion-space-24); display: grid; gap: var(--motion-space-32); } +.omg-reference-heading { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--motion-space-16); } +.omg-reference-heading h2 { font-size: var(--motion-text-title); font-weight: var(--motion-weight-semibold); } +.omg-resources { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--motion-space-8) var(--motion-space-16); padding-top: var(--motion-space-12); border-top: 1px solid var(--motion-border-subtle); } +.rule-grid { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: var(--motion-space-32); align-items: start; } +.rule { min-width: 0; } +.rule-label { display: flex; align-items: baseline; gap: var(--motion-space-12); margin-bottom: var(--motion-space-12); } +.rule-label > span { color: var(--motion-muted); font: var(--motion-text-xs) var(--motion-font-mono); } +.rule-label h2,.production h2 { font-size: var(--motion-text-body); font-weight: var(--motion-weight-semibold); } +.rule-copy { display: grid; gap: var(--motion-space-12); color: var(--motion-muted); line-height: var(--motion-leading-prose); } +.rule-copy ul,.production ul { padding-left: var(--motion-space-20); } +.rule .demo { margin-block: var(--motion-space-16); } +.rule .demo-stage { aspect-ratio: 5 / 3; background: var(--motion-panel); border-radius: var(--motion-radius-md); overflow: hidden; } +.rule iframe { width: 100%; height: 100%; border: 0; } +.rule .demo-params,.demo-source { display: none; } +.rule figcaption { font-size: var(--motion-text-xs); color: var(--motion-muted); margin-top: var(--motion-space-8); } +.rule figcaption a { margin-left: var(--motion-space-12); } +.rule .reference { width: 100%; object-fit: contain; } +.identity { display: grid; gap: var(--motion-space-16); padding-top: var(--motion-space-24); border-top: 1px solid var(--motion-border-subtle); } +.tile-label { font-weight: var(--motion-weight-medium); margin-bottom: var(--motion-space-12); } +.tile-label span { color: var(--motion-muted); font-size: var(--motion-text-xs); margin-left: var(--motion-space-12); } +.type-sheet p { color: var(--motion-muted); } +.swatches { display: flex; flex-wrap: wrap; gap: var(--motion-space-24); } +.swatch { background: transparent; border: 0; padding: 0; display: grid; gap: var(--motion-space-8); text-align: left; } +.swatch > span { display: block; width: var(--motion-space-32); height: var(--motion-space-32); border-radius: var(--motion-radius-full); background: var(--swatch); border: 1px solid var(--motion-border); } +.swatch code { font-size: var(--motion-text-xs); color: var(--motion-muted); } +.filmstrip { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: var(--motion-space-16); } +.filmstrip img { width: 100%; aspect-ratio: 16 / 9; object-fit: contain; border-radius: var(--motion-radius-md); background: var(--motion-panel); } +.filmstrip figcaption { color: var(--motion-muted); font: var(--motion-text-xs) var(--motion-font-mono); margin-top: var(--motion-space-6); } +.production { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: var(--motion-space-32); padding-top: var(--motion-space-24); border-top: 1px solid var(--motion-border-subtle); color: var(--motion-muted); line-height: var(--motion-leading-prose); } +.production h3 { font-size: var(--motion-text-body); font-weight: var(--motion-weight-medium); } +.production-rules > p { display: none; } +.eyebrow { display: none; } +#source-view pre { font: var(--motion-text-sm)/var(--motion-leading-prose) var(--motion-font-mono); white-space: pre-wrap; overflow-wrap: anywhere; padding: var(--motion-space-24); border: 1px solid var(--motion-border-subtle); border-radius: var(--motion-radius-md); } +.table-wrap { overflow: auto; } +.omg-document { display: grid; gap: var(--motion-space-16); color: var(--motion-muted); line-height: var(--motion-leading-prose); overflow-wrap: anywhere; } +.omg-document h3 { font-size: var(--motion-text-body); color: var(--motion-text); font-weight: var(--motion-weight-semibold); } +.omg-document ul { margin: 0; padding-left: var(--motion-space-24); } +th,td { text-align: left; padding: var(--motion-space-8); border-bottom: 1px solid var(--motion-border-subtle); } +@media(max-width:1199px) { .omg-layout { grid-template-columns: minmax(0,1fr) 360px; } } +@media(max-width:999px) { .omg-layout { grid-template-columns: minmax(0,1fr) 320px; } .omg-preview { padding: var(--motion-space-20); } .rule-grid { grid-template-columns: minmax(0,1fr); } } +@media(max-width:749px) { .omg-layout { display: flex; flex-direction: column; } .omg-preview { display: contents; } .omg-first { height: auto; min-height: 0; padding: var(--motion-space-16); } .omg-stage-box { display: block; container-type: normal; } .omg-stage,.omg-original { width: 100%; } .omg-card { flex: none; } .omg-inspector { height: auto; position: static; border-left: 0; border-block: 1px solid var(--motion-border-subtle); } .omg-preview > .omg-notice { order: 1; padding-inline: var(--motion-space-16); } .omg-inspector { order: 2; } .omg-breakdown { order: 3; padding: var(--motion-space-24) var(--motion-space-16); } .omg-top { padding-inline: var(--motion-space-16) !important; } .omg-top-title { font-size: var(--motion-text-sm); } .omg-top > a:last-child { font-size: var(--motion-text-xs); } .rule-grid,.production { grid-template-columns: minmax(0,1fr); } .filmstrip { grid-template-columns: repeat(2,minmax(0,1fr)); } .demo-controls { flex-wrap: wrap; } } diff --git a/studio/src/template-guide/page.ts b/studio/src/template-guide/page.ts new file mode 100644 index 000000000..cbdc39302 --- /dev/null +++ b/studio/src/template-guide/page.ts @@ -0,0 +1,213 @@ +import { parseTemplateGuideDraft, type TemplateGuideDraft, type TemplateGuidePage, type TemplateGuideEvent } from '../../../shared/template-guide'; +import labels from '../../../shared/template-guide-ui.json'; +import { handleGuideAction, type GuideAction } from './actions'; +import { readStudioUiPreferences } from '../utils/studioUiPreferences'; + +type Label = keyof typeof labels.en; +declare const __OPENMOTION_GUIDE_ICONS__: Record; +const config = JSON.parse(document.querySelector('#openmotion-guide-page')!.textContent!) as TemplateGuidePage; +const viewId = crypto.randomUUID(); +function report(action: TemplateGuideEvent['action'], details: Partial> = {}) { + const event = { action, view_id: viewId, ...details }; + if (parent !== window) parent.postMessage({ type: 'openmotion:guide-event', templateId: config.id, event }, '*'); + else return import('../motion/tracking').then(({ trackMotion }) => trackMotion('template_guide_interaction', { page_name: 'studio', template_id: config.id, ...event })).catch(() => {}); +} +let locale = 'zh-CN'; +try { locale = localStorage.getItem('motion.studio.locale') || locale; } catch {} +locale = document.documentElement.dataset.guideLocale || locale; +const messages = labels as Record>; +const t = (key: Label) => messages[locale]?.[key] || messages.en[key]; +const element = (tag: K, className = '', text = '') => { + const node = document.createElement(tag); node.className = className; if (text) node.textContent = text; return node; +}; +const icon = (name: string) => ``; +const button = (text: string, name?: string, quiet = false) => { + const node = element('button', 'ui-button' + (quiet ? ' ui-button--ghost' : ''), text); node.type = 'button'; + if (name) { const box = element('span'); box.innerHTML = icon(name); node.append(box); } return node; +}; +const link = (text: string, url: string, name?: string) => { + const node = element('a', 'ui-button ui-button--ghost', text); node.href = url; node.target = '_blank'; node.rel = 'noreferrer'; + if (name) { const box = element('span'); box.innerHTML = icon(name); node.append(box); } return node; +}; +const pending = new Map void; reject: (error: Error) => void; timer: ReturnType }>(); +window.addEventListener('message', event => { + if (event.source !== parent || parent === window) return; + if (event.data?.type === 'openmotion:guide-action-result') { + const callback = pending.get(event.data.requestId); if (!callback) return; + clearTimeout(callback.timer); pending.delete(event.data.requestId); + if (event.data.error) callback.reject(new Error(event.data.error)); else callback.resolve(event.data.result); + } + if (event.data?.type === 'openmotion:guide-appearance') document.documentElement.dataset.theme = event.data.appearance?.theme === 'dark' ? 'dark' : 'light'; +}); +function host(action: GuideAction, value?: TemplateGuideDraft): Promise { + if (parent === window) return handleGuideAction(config.id, action, value, locale); + const requestId = crypto.randomUUID(); + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { pending.delete(requestId); reject(new Error('GUIDE_HOST_UNAVAILABLE')); }, action === 'open' ? 120_000 : 8_000); + pending.set(requestId, { resolve, reject, timer }); + parent.postMessage({ type: 'openmotion:guide-action', templateId: config.id, viewId, requestId, action, value, locale }, '*'); + }); +} + +async function mount() { + const root = document.documentElement; + root.dataset.motionUi = ''; root.dataset.templateGuide = config.id; + const syncTheme = () => { + const theme = readStudioUiPreferences().theme || 'light'; + root.dataset.theme = root.dataset.openmotionGuide || (theme === 'system' ? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') : theme); + }; + syncTheme(); window.addEventListener('storage', syncTheme); + const original = document.querySelector('#board-view'); + const source = document.querySelector('#source-view') || (config.motionDocument ? element('section') : null); + if (source && !source.id) { source.id = 'source-view'; source.hidden = true; source.append(element('pre', '', config.motionDocument)); } + const sequence = document.querySelector('#demo-sequence'); + const intro = original?.querySelector('.intro'); + const summary = intro?.querySelector('.intro-copy'); + const card = sequence || element('figure', 'demo'); + const stage = sequence?.querySelector('.demo-stage') || element('div', 'demo-stage'); + if (!sequence) { + const frame = element('iframe'); frame.src = `?raw=1&stage=1`; frame.title = config.title; frame.sandbox.add('allow-scripts'); stage.append(frame); card.append(stage); + } + const defaults = sequence ? JSON.parse(sequence.dataset.demo!).params : []; + const values = () => sequence ? parseTemplateGuideDraft(Object.fromEntries([...params.querySelectorAll('input[data-key]')].map(input => [input.dataset.key, input.value]))) : undefined; + const params = sequence?.querySelector('.demo-params') || element('div', 'demo-params'); + const controls = sequence?.querySelector('.demo-controls'); + const beats = original?.querySelector('.beats'); + const shell = element('header', 'omg-top'); + const home = link('', `/?templates=1&template=${encodeURIComponent(config.id)}`); home.target = '_self'; home.setAttribute('aria-label', t('library')); + home.onclick = event => { if (parent !== window) { event.preventDefault(); void host('library'); } }; + const logo = element('img'); logo.src = '/design-system/brand/openmotion-logo.svg'; logo.alt = 'OpenMotion'; home.append(logo); + shell.append(home, element('span', 'omg-top-title', config.title)); + const back = link(t('library'), `/?templates=1&template=${encodeURIComponent(config.id)}`, 'arrow-left-line'); back.target = '_self'; back.onclick = home.onclick; shell.append(back); + const layout = element('main', 'omg-layout'), preview = element('section', 'omg-preview'), first = element('div', 'omg-first'); + const heading = element('header', 'omg-heading'); + heading.append(element('span', 'omg-eyebrow', config.brand || 'MOTION'), element('h1', '', config.title)); + if (summary) heading.append(summary); + const tabs = element('div', 'omg-tabs'), own = button(t('example'), undefined, true), reference = button(t('reference'), undefined, true); + own.setAttribute('aria-pressed', 'true'); reference.setAttribute('aria-pressed', 'false'); tabs.append(own); + if (config.previewUrl) tabs.append(reference); + card.classList.add('omg-card'); stage.classList.add('omg-stage'); + const stageBox = element('div', 'omg-stage-box'); stage.before(stageBox); stageBox.append(stage); + card.querySelector('.demo-heading')?.remove(); card.querySelector('figcaption')?.remove(); + const originalFilm = element('video', 'omg-original'); originalFilm.controls = true; originalFilm.preload = 'none'; originalFilm.hidden = true; + if (config.posterUrl) originalFilm.poster = config.posterUrl; + stageBox.append(originalFilm); + const showReference = (show: boolean) => { + own.setAttribute('aria-pressed', String(!show)); reference.setAttribute('aria-pressed', String(show)); + stage.hidden = show; originalFilm.hidden = !show; if (controls) controls.hidden = show; + if (show && config.previewUrl && !originalFilm.getAttribute('src')) originalFilm.src = config.previewUrl; + if (show && sequence?.querySelector('.play')?.textContent === '暂停') sequence.querySelector('.play')!.click(); + if (!show) originalFilm.pause(); + }; + own.onclick = () => showReference(false); reference.onclick = () => { showReference(true); report('reference'); }; + first.append(heading, tabs, card); + if (beats) { const title = element('h2', 'omg-chapter-heading', t('chapters')); first.append(title, beats); } + preview.append(first); if (sequence) preview.append(element('p', 'omg-notice', t('notice'))); + const breakdown = element('section', 'omg-breakdown'); breakdown.setAttribute('aria-label', t('breakdown')); + const referenceHeading = element('header', 'omg-reference-heading'); referenceHeading.append(element('h2', '', t('breakdown'))); + const downloads = element('nav', 'omg-resources'), download = link(t('download'), 'motion.md?download=1', 'download-2-line'); download.download = 'motion.md'; download.target = '_self'; + downloads.setAttribute('aria-label', t('document')); downloads.append(download); + download.addEventListener('click', event => { if (parent !== window) { event.preventDefault(); void host('download').catch(() => notice(t('failed'))); } report('download'); }); + if (source) { const doc = button(t('document'), 'file-text-line', true); doc.setAttribute('aria-expanded', 'false'); doc.onclick = () => { source.hidden = !source.hidden; doc.setAttribute('aria-expanded', String(!source.hidden)); if (!source.hidden) source.scrollIntoView({ block: 'start' }); }; downloads.append(doc); } + if (config.sourceUrl) { const sourceLink = link(t('source'), config.sourceUrl, 'external-link-line'); sourceLink.onclick = event => { if (parent !== window) { event.preventDefault(); void host('source').catch(() => notice(t('failed'))); } }; downloads.append(sourceLink); } + for (const control of downloads.children) { control.className = 'ui-text-link'; const glyph = control.querySelector('span'); if (glyph) control.prepend(glyph); } + breakdown.append(referenceHeading); + const rules = original?.querySelector('.rule-grid'), identity = original?.querySelector('.identity'), filmstrip = original?.querySelector('.filmstrip'), production = original?.querySelector('.production'); + if (rules) breakdown.append(rules); + if (identity) { identity.querySelector('.type-brand')?.remove(); identity.querySelector('.type-sample')?.remove(); identity.querySelector('.type-baseline')?.remove(); breakdown.append(identity); } + if (filmstrip) breakdown.append(filmstrip); + if (production) { + const authoredCopy = new Set([...(rules?.querySelectorAll('.rule-copy p,.rule-copy li') || []), ...(summary ? [summary] : [])].map(node => node.textContent?.trim())); + // The source repeats its rule paragraphs as production bullets; retain only distinct constraints. + for (const item of production.querySelectorAll('.production-rules li')) if (authoredCopy.has(item.textContent?.trim())) item.remove(); + if (!production.querySelector('.production-rules li')) production.querySelector('.production-rules')?.remove(); + breakdown.append(production); + } + if (source) breakdown.append(source); + if (!sequence && config.motionDocument) { + const content = element('div', 'omg-document'); + for (const paragraph of config.motionDocument.split(/\n\s*\n/)) { + if (/^#{1,3} /.test(paragraph)) content.append(element('h3', '', paragraph.replace(/^#{1,3} /, ''))); + else if (/^- /.test(paragraph)) { const list = element('ul'); for (const item of paragraph.split('\n')) list.append(element('li', '', item.replace(/^- /, ''))); content.append(list); } + else if (/^\|/.test(paragraph)) { + const table = element('table'), wrap = element('div', 'table-wrap'); + paragraph.split('\n').filter(line => !/^\|[\s:|-]+\|$/.test(line)).forEach((line, index) => { const row = element('tr'); + for (const cell of line.replace(/^\||\|$/g, '').split('|')) row.append(element(index === 0 ? 'th' : 'td', '', cell.trim())); table.append(row); + }); wrap.append(table); content.append(wrap); + } + else content.append(element('p', '', paragraph)); + } + breakdown.append(content); + } + preview.append(breakdown); + const inspector = element('aside', 'omg-inspector'); inspector.setAttribute('aria-label', t('make')); + const inspectorHeading = element('header', 'omg-inspector-heading'), reset = button('', 'refresh-line', true); reset.setAttribute('aria-label', t('reset')); reset.title = t('reset'); + const inspectorTitles = element('div'); inspectorTitles.append(element('h2', '', t('make'))); if (sequence) inspectorTitles.append(element('p', '', t('hint'))); inspectorHeading.append(inspectorTitles); + if (sequence) inspectorHeading.append(reset); + const inspectorBody = element('div', 'omg-inspector-body'); params.querySelector('.demo-presets')?.remove(); + for (const label of params.querySelectorAll('label')) { label.classList.add('ui-field'); label.querySelector('input')?.classList.add('ui-input'); } + const color = params.querySelector('input[type=color]'); + if (color) { const control = element('span', 'ui-input omg-color'), code = element('input', 'omg-color-code'); code.type = 'text'; code.value = color.value.toUpperCase(); code.maxLength = 7; + code.setAttribute('aria-label', (defaults.find((item: { key: string }) => item.key === 'accent')?.label || 'Accent') + ' HEX'); + color.before(control); color.classList.remove('ui-input'); control.append(color, code); + color.addEventListener('input', () => { code.value = color.value.toUpperCase(); }); + code.addEventListener('input', () => { if (/^#[a-fA-F0-9]{6}$/.test(code.value)) { code.removeAttribute('aria-invalid'); color.value = code.value; color.dispatchEvent(new Event('input', { bubbles: true })); } + else code.setAttribute('aria-invalid', 'true'); }); + code.addEventListener('change', () => { if (!code.hasAttribute('aria-invalid')) report('edit', { field: 'accent' }); }); + code.addEventListener('blur', () => { code.value = color.value.toUpperCase(); code.removeAttribute('aria-invalid'); }); + } + inspectorBody.append(params); + if (!sequence) inspectorBody.append(element('p', 'omg-notice', t('unavailable'))); + const footer = element('footer', 'omg-actions'), status = element('small', 'omg-status', t('pending')); + status.setAttribute('role', 'status'); + const open = button(t('edit'), 'arrow-right-line'); open.classList.add('ui-button--primary'); open.disabled = !sequence && !config.hasHtmlProject; + const copy = button(t('copy'), 'file-copy-line', true), manual = element('textarea', 'ui-input'); manual.hidden = true; manual.readOnly = true; manual.rows = 7; manual.setAttribute('aria-label', t('manual')); + if (sequence) footer.append(status); if (sequence || config.hasHtmlProject) footer.append(open); else { copy.classList.remove('ui-button--ghost'); copy.classList.add('ui-button--primary'); } + if (sequence) footer.append(element('small', 'omg-notice', t('variables'))); footer.append(copy, manual, downloads); + inspector.append(inspectorHeading, inspectorBody, footer); layout.append(preview, inspector); + document.body.replaceChildren(shell, layout); + const feedback = element('div', 'motion-inline-toast'); feedback.hidden = true; feedback.setAttribute('role', 'status'); document.body.append(feedback); + let feedbackTimer: ReturnType; + const notice = (text: string) => { feedback.textContent = text; feedback.hidden = false; clearTimeout(feedbackTimer); feedbackTimer = setTimeout(() => { feedback.hidden = true; }, 3000); }; + for (const swatch of document.querySelectorAll('[data-color]')) swatch.onclick = async () => { + try { await navigator.clipboard.writeText(swatch.dataset.color!); notice(swatch.dataset.color!); } catch { notice(swatch.dataset.color!); } + }; + const apply = (draft: TemplateGuideDraft) => { + for (const input of params.querySelectorAll('input[data-key]')) { input.value = draft[input.dataset.key as keyof TemplateGuideDraft]; input.dispatchEvent(new Event('input', { bubbles: true })); } + }; + let saveTimer: ReturnType, dirty = false; + params.addEventListener('input', () => { dirty = true; showReference(false); clearTimeout(saveTimer); saveTimer = setTimeout(() => { let draft; try { draft = values(); } catch { return; } + void host('save', draft).then(() => { status.textContent = t('saved'); }).catch(() => { status.textContent = t('pending'); }); }, 180); }); + params.addEventListener('change', event => { const key = (event.target as HTMLInputElement).dataset.key; if (key === 'title' || key === 'accent') { try { values(); report('edit', { field: key }); } catch {} } }); + reset.onclick = () => { if (sequence) { apply(parseTemplateGuideDraft(Object.fromEntries(defaults.map((item: { key: string; value: string }) => [item.key, item.value])))); report('reset'); } }; + if (sequence) { + void host('load').then(saved => { if (saved && !dirty) { apply(parseTemplateGuideDraft(saved)); status.textContent = t('saved'); } }).catch(() => { /* An unavailable host never prevents playback. */ }); + } + copy.onclick = async () => { + try { copy.disabled = true; const result = await host('copy', values()); if (result.copied) notice(t('copied')); else { manual.value = result.text; manual.hidden = false; manual.focus(); manual.select(); } report('copy', { outcome: result.copied ? 'success' : 'manual_fallback' }); } + catch { notice(t('failed')); report('copy', { outcome: 'failure' }); } finally { copy.disabled = false; } + }; + open.onclick = async () => { + try { open.disabled = true; copy.disabled = true; open.textContent = t('opening'); const result = await host('open', values()); + if (parent === window) { await report('open_editor', { outcome: 'success', project_id: result.projectId }); location.assign(result.url); } + } catch { notice(t('failed')); if (parent === window) report('open_editor', { outcome: 'failure' }); } finally { open.disabled = false; copy.disabled = false; open.textContent = t('edit'); } + }; + controls?.querySelectorAll('button').forEach(node => node.classList.add('ui-button', 'ui-button--ghost')); + controls?.querySelector('select')?.classList.add('ui-input'); + beats?.querySelectorAll('button').forEach(node => { node.classList.add('ui-button'); node.onclick = () => { + showReference(false); const seek = sequence?.querySelector('.seek'); if (!seek) return; seek.value = node.dataset.time!; seek.dispatchEvent(new Event('input')); + for (const other of beats.querySelectorAll('button')) other.setAttribute('aria-pressed', String(other === node)); + report('chapter'); + }; }); + // Restore semantic keyboard labels missing from older authored controls. + const play = controls?.querySelector('.play'); + if (play) { const label = () => play.setAttribute('aria-label', play.textContent || 'Play'); label(); new MutationObserver(label).observe(play, { childList: true, characterData: true, subtree: true }); } + document.title = config.title + ' · OpenMotion'; + let exposure: ReturnType | undefined, shown = false, visible = false, ready = !sequence || sequence.dataset.ready === 'true'; + const measure = () => { clearTimeout(exposure); if (!shown && ready && visible && !document.hidden) exposure = setTimeout(() => { shown = true; report('shown'); observer.disconnect(); }, 1000); }; + const observer = new IntersectionObserver(entries => { visible = Boolean(entries[0]?.isIntersecting && entries[0].intersectionRatio >= .5); measure(); }, { threshold: [.5] }); + observer.observe(stageBox); + document.addEventListener('visibilitychange', measure); + window.addEventListener('message', event => { if (!ready && event.source === stage.querySelector('iframe')?.contentWindow && event.data?.type === 'motion-demo:ready') { ready = true; measure(); } }); +} +void mount(); diff --git a/tests/hosted-template-catalog.test.ts b/tests/hosted-template-catalog.test.ts index f0ff61dab..842bf5ab9 100644 --- a/tests/hosted-template-catalog.test.ts +++ b/tests/hosted-template-catalog.test.ts @@ -139,7 +139,10 @@ test('published repository files serve the HTTP gallery, public MCP and arbitrar assert.equal(detail.motionDocument.content, motion.toString()); assert.equal(detail.localSource, undefined); assert.equal(detail.workflowGuide.workflow, 'template'); - assert.equal(await (await request(item.motionGuideUrl)).text(), contents['preview.html'].toString()); + const guide = await (await request(item.motionGuideUrl)).text(); + assert(guide.includes('/guide-assets/viewer.js')); + assert(guide.includes('"id":"' + id + '"')); + assert.equal(await (await request(item.motionGuideUrl + '?raw=1')).text(), contents['preview.html'].toString()); assert.equal(await (await request(`/api/template-source/${id}/style.css`)).text(), contents['style.css'].toString()); const downloaded = await request(`/api/template-source/${id}/${encodeURIComponent('工程.custom')}`); assert.equal(downloaded.status, 200); diff --git a/tests/repository-template-runtime.test.ts b/tests/repository-template-runtime.test.ts index 321e9ebfc..4b0ae4692 100644 --- a/tests/repository-template-runtime.test.ts +++ b/tests/repository-template-runtime.test.ts @@ -9,6 +9,7 @@ import { createHash } from 'node:crypto'; import { mediaKey, mediaOrigin } from '../shared/repository-media.ts'; import { TemplateCatalog } from '../prism-templates.ts'; import { templateRecipe } from '../template-catalog.ts'; +import { authoredTemplateGuide } from '../shared/template-guide.ts'; import { repositoryCatalogRoot, readRepositoryFile } from '../shared/repository-template-catalog.ts'; import { WorkspaceStore } from '../workspace.ts'; import { transport } from './http.ts'; @@ -122,7 +123,10 @@ test('HTTP gallery and guide routes use the same repository source; copied promp const template = page.items.find(item => item.id === firstId); assert(template); assert.equal(template.localSource.directory, path.join(repositoryCatalogRoot, firstId)); const response = await request(template.motionGuideUrl); assert.equal(response.status, 200); - assert.equal(await response.text(), await readFile(template.localSource.previewPath, 'utf8')); + const shown = await response.text(); + assert(shown.includes('"id":"' + template.id + '"')); + assert(shown.includes('/guide-assets/viewer.js')); + assert.deepEqual(authoredTemplateGuide(shown), authoredTemplateGuide(await readFile(template.localSource.previewPath, 'utf8'))); const css = await request(`/api/template-source/${firstId}/viewer/board.css`); assert.equal(css.status, 200); assert.match(css.headers.get('content-type')!, /text\/css/); assert.equal((await request(`/api/template-source/${firstId}/%2e%2e%2f%2e%2e%2fpackage.json`)).status, 404); assert.equal((await request(`/api/template-source/${firstId}/missing.md`)).status, 404); diff --git a/tests/template-guide.test.ts b/tests/template-guide.test.ts new file mode 100644 index 000000000..52263da3d --- /dev/null +++ b/tests/template-guide.test.ts @@ -0,0 +1,98 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile, readdir } from 'node:fs/promises'; +import path from 'node:path'; +import { authoredTemplateGuide, isTemplateGuideEvent, parseTemplateGuideDraft, upgradeTemplateGuidePage } from '../shared/template-guide.ts'; +import { repositoryCatalogRoot } from '../shared/repository-template-catalog.ts'; +import { materializeTemplateGuide } from '../gateway/template-guide.ts'; +import { TemplateCatalog } from '../prism-templates.ts'; +import { pluginRoot, inspectProject } from '../hyperframes.ts'; +import { Phase1Service } from '../phase1.ts'; +import { fixture } from './fixtures.ts'; +import { transport } from './http.ts'; + +const lovable = 'motion-be2a4af0-0183-4979-ab05-2a68413c0890'; +const stripe = 'motion-80dceb1d-5219-4e1f-9394-6baacf5d0166'; + +test('every catalog preview receives the common interface and retains its own authored content', async () => { + const manifest = JSON.parse(await readFile(path.join(repositoryCatalogRoot, 'catalog.json'), 'utf8')); + let authored = 0; + const examples = new Set(); + for (const id of manifest.templateIds) { + const source = await readFile(path.join(repositoryCatalogRoot, id, 'source/preview.html'), 'utf8'); + const guide = authoredTemplateGuide(source); if (guide) { authored++; examples.add(JSON.stringify(guide)); } + const result = upgradeTemplateGuidePage(source, { id, title: 'This template ' }); + assert.equal((result.match(/id="openmotion-guide-page"/g) || []).length, 1, id); + assert(result.includes('"id":"' + id + '"'), id); + assert(result.includes('/guide-assets/viewer.js'), id); + assert(!result.includes(''), id); + if (guide) { + assert(result.includes('data-demo='), id); + assert(result.includes('viewer/guide.js'), id); + assert(!result.includes('href="viewer/board.css"'), id); + assert(!result.includes('openmotion-product-flow'), id); + } + } + assert.equal(manifest.templateIds.length, 287); + assert.equal(authored, 286); + assert(examples.size > 250, 'entries must retain distinct defaults and durations'); +}); + +test('guide drafts and analytics reject arbitrary fields and never collect changed text', () => { + assert.deepEqual(parseTemplateGuideDraft({ title: 'My own launch', accent: '#ABCDEF' }), { title: 'My own launch', accent: '#abcdef' }); + for (const value of [{ title: '', accent: '#ffffff' }, { title: 'x'.repeat(61), accent: '#ffffff' }, { title: 'x', accent: 'url(private)' }, { title: 'x', accent: '#ffffff', templateId: stripe }]) + assert.throws(() => parseTemplateGuideDraft(value), /INVALID_GUIDE_DRAFT/); + const event = { action: 'edit', view_id: crypto.randomUUID(), field: 'title' }; + assert(isTemplateGuideEvent(event)); assert(!isTemplateGuideEvent({ ...event, text: 'Private draft' })); + assert(!isTemplateGuideEvent({ ...event, field: 'brand' })); +}); + +test('each selected guide materializes its own native canvas, timing and variables', () => fixture(async store => { + const catalog = new TemplateCatalog(store.directory, { source: 'repository' }); + for (const id of [lovable, stripe]) { + const directory = path.join(store.directory, id); + const draft = { title: 'A "launch" ', accent: '#8dff5c' }; + const result = await materializeTemplateGuide(catalog, id, directory, pluginRoot, draft); + assert.equal(result.source.id, id); assert.equal(result.source.width, 1000); assert.equal(result.source.height, 600); + assert.equal(result.source.provenance, 'authored-motion-guide-example'); + assert.deepEqual(await readFile(path.join(directory, 'demos/scene.js')), await catalog.sourceFile(id, 'demos/scene.js')); + const index = await readFile(path.join(directory, 'index.html'), 'utf8'); + assert(!index.includes(draft.title)); assert(index.includes('\\u003cwith content>')); + assert(index.includes('data-composition-variables=')); + const lint = await inspectProject(pluginRoot, directory, 'lint'); assert.equal(lint.exitCode, 0, JSON.stringify(lint)); + const info = await inspectProject(pluginRoot, directory, 'info'); assert.equal(info.result.duration, result.source.durationSeconds); + assert.equal(info.result.width, 1000); assert.equal(info.result.height, 600); + const timeline = await inspectProject(pluginRoot, directory, 'timeline'); + const clips = timeline.result.timeline.tracks.flatMap((track: any) => track.rows).filter((clip: any) => !clip.nested); + assert.deepEqual(clips.map((clip: any) => [clip.id, clip.absStart, clip.absEnd]), [['guide-example', 0, Number(result.source.durationSeconds.toFixed(3))]]); + } +}, false)); + +test('MCP guide creation reuses the request, keeps the original template and rejects unsupported source', () => fixture(async store => { + const service = new Phase1Service(store, pluginRoot, { origin: () => 'http://127.0.0.1:4173', nativeUrl: () => undefined, + openProject: async () => {}, mutation: async task => task(), cancel: async () => {} }); + const args = { requestId: 'lovable-guide-draft', projectType: 'template', templateId: lovable, title: 'My version', requirements: 'Continue the selected motion example', guideDraft: { title: 'My launch', accent: '#7050da' } }; + const created = await service.call('openmotion_create_project', args); + const retried = await service.call('openmotion_create_project', args); + assert.equal(created.projectId, retried.projectId); + assert.equal(created.source.id, lovable); assert.equal(created.source.provenance, 'authored-motion-guide-example'); + assert.deepEqual(JSON.parse(await readFile(path.join(store.projectDirectoryFor(created.projectId), 'motion-project.json'), 'utf8')).guideDraft, args.guideDraft); + await assert.rejects(service.call('openmotion_create_project', { ...args, guideDraft: { ...args.guideDraft, title: 'Other draft' } }), /REQUEST_ID_CONFLICT/); + await assert.rejects(service.call('openmotion_create_project', { ...args, requestId: 'unsupported-guide', templateId: 'motion-orbit-launch' }), /GUIDE_NOT_EDITABLE/); + assert.equal(store.projectCatalog().projects.filter(item => item.id === created.projectId).length, 1); +}, false)); + +test('the exact requested URLs serve upgraded pages, while raw source and downloads stay byte-identical', () => fixture(async store => { + const request = transport(store); + for (const id of [lovable, stripe, 'motion-orbit-launch']) { + const pathName = `/api/template-source/${id}/preview.html`; + const response = await request(pathName); assert.equal(response.status, 200); + assert((await response.text()).includes('openmotion-guide-page')); + assert.equal(await (await request(pathName + '?raw=1')).text(), await readFile(path.join(repositoryCatalogRoot, id, 'source/preview.html'), 'utf8')); + const motion = await readFile(path.join(repositoryCatalogRoot, id, 'source/motion.md'), 'utf8'); + assert.equal(await (await request(`/api/template-source/${id}/motion.md`)).text(), motion); + const download = await request(`/api/template-source/${id}/motion.md?download=1`); + assert.equal(download.headers.get('content-disposition'), 'attachment; filename="motion.md"'); + assert.equal(await download.text(), motion); + } +}, false)); diff --git a/tracking/README.md b/tracking/README.md index 44e29ae4b..0b694e220 100644 --- a/tracking/README.md +++ b/tracking/README.md @@ -1,5 +1,7 @@ # OpenMotion tracking +Catalog guide pages emit `template_guide_interaction` through the existing Studio transport and privacy preference. `template_id` always identifies the page being used, with a fresh `view_id`; actions are `shown`, `edit`, `chapter`, `reference`, `reset`, `copy`, `open_editor` and `download`. `shown` requires at least half of the preview visible for one continuous foreground second. Edits report only `title` or `accent`, never their values. Copy and editor actions report success, failure or manual fallback separately. The embedding parent pins the template identity and validates the closed event fields. This measures interaction and handoff, not user acceptance, export or reference-recreation completion. Local tests do not establish production collection. + An explicit-event package shared by the standalone MCP runtime and Motion Studio. It has no runtime dependencies. The application consumes its TypeScript sources; `npm run build:tracking` emits JavaScript and declarations for a local `npm pack` diff --git a/tracking/events.ts b/tracking/events.ts index c3169f345..e20d7121f 100644 --- a/tracking/events.ts +++ b/tracking/events.ts @@ -220,6 +220,9 @@ export const omEvents = { resource_download_result: { producers: ['studio'], fields: { page_name: pages, resource_kind: ['motion_guide', 'brand_kit_package'], download_attempt_id: 'uuid', delivery_status: ['browser_save_requested', 'fetch_failed', 'unknown'], error_code: 'code', detail_view_id: 'uuid', detail_mode: ['modal'], ...template, ...brand, ...templateSeries }, required: ['resource_kind', 'download_attempt_id', 'delivery_status'] }, + template_guide_interaction: { producers: ['studio'], fields: { page_name: ['studio'], template_id: 'code', view_id: 'uuid', project_id: 'uuid', + action: ['shown', 'edit', 'chapter', 'reference', 'reset', 'copy', 'open_editor', 'download'], + field: ['title', 'accent'], outcome: ['success', 'failure', 'manual_fallback'] }, required: ['page_name', 'template_id', 'view_id', 'action'] }, template_instruction_copy_result: { producers: ['studio'], fields: { host_product: hosts, copy_status: ['clipboard_written', 'manual_fallback_shown', 'failed'], page_name: ['home', 'studio'], copy_attempt_id: 'uuid', ...templateDetail, ...project, ...template, ...templateSeries }, required: ['host_product', 'copy_status'] }, // Skills page. One search result per settled query; the brief itself is reduced to its choices and two yes/no flags. From 0e2048bcf354585a8b8fb5939f734b3214b8de63 Mon Sep 17 00:00:00 2001 From: qiqi Date: Wed, 18 Nov 2026 21:43:13 +0800 Subject: [PATCH 2/6] fix(tracking): complete template guide resource and handoff signals --- shared/template-guide.ts | 8 +++++--- studio/src/template-guide/page.ts | 7 ++++--- tests/template-guide.test.ts | 34 +++++++++++++++++++++++++++++++ tracking/README.md | 2 +- tracking/events.ts | 3 ++- 5 files changed, 46 insertions(+), 8 deletions(-) diff --git a/shared/template-guide.ts b/shared/template-guide.ts index f1b8db424..d45d8b366 100644 --- a/shared/template-guide.ts +++ b/shared/template-guide.ts @@ -1,14 +1,16 @@ /** Portable draft contract for each catalog entry's own authored motion example. */ export type TemplateGuideDraft = { title: string; accent: string }; -export const templateGuideActions = ['shown', 'edit', 'chapter', 'reference', 'reset', 'copy', 'open_editor', 'download'] as const; -export type TemplateGuideEvent = { action: typeof templateGuideActions[number]; view_id: string; field?: 'title' | 'accent'; outcome?: 'success' | 'failure' | 'manual_fallback'; project_id?: string }; +export const templateGuideActions = ['shown', 'edit', 'chapter', 'reference', 'reset', 'copy', 'open_editor', 'download', 'document', 'source'] as const; +export type TemplateGuideEvent = { action: typeof templateGuideActions[number]; view_id: string; field?: 'title' | 'accent'; outcome?: 'success' | 'failure' | 'manual_fallback'; project_id?: string; expanded?: boolean; delivery_status?: 'browser_save_requested' | 'fetch_failed' }; export function isTemplateGuideEvent(input: unknown): input is TemplateGuideEvent { const value = input as TemplateGuideEvent; return Boolean(value && templateGuideActions.includes(value.action) && /^[a-f0-9-]{36}$/i.test(value.view_id) && (value.field === undefined || ['title', 'accent'].includes(value.field)) && (value.outcome === undefined || ['success', 'failure', 'manual_fallback'].includes(value.outcome)) && (value.project_id === undefined || value.action === 'open_editor' && value.outcome === 'success' && /^[a-f0-9-]{36}$/i.test(value.project_id)) - && Object.keys(value).every(key => ['action', 'view_id', 'field', 'outcome', 'project_id'].includes(key))); + && (value.expanded === undefined || value.action === 'document' && typeof value.expanded === 'boolean') + && (value.delivery_status === undefined || value.action === 'download' && ['browser_save_requested', 'fetch_failed'].includes(value.delivery_status)) + && Object.keys(value).every(key => ['action', 'view_id', 'field', 'outcome', 'project_id', 'expanded', 'delivery_status'].includes(key))); } export const templateGuideDraftSchema = { type: 'object', additionalProperties: false, properties: { title: { type: 'string', minLength: 1, maxLength: 60 }, accent: { type: 'string', pattern: '^#[a-fA-F0-9]{6}$' } }, diff --git a/studio/src/template-guide/page.ts b/studio/src/template-guide/page.ts index cbdc39302..3b1b367c6 100644 --- a/studio/src/template-guide/page.ts +++ b/studio/src/template-guide/page.ts @@ -107,9 +107,9 @@ async function mount() { const referenceHeading = element('header', 'omg-reference-heading'); referenceHeading.append(element('h2', '', t('breakdown'))); const downloads = element('nav', 'omg-resources'), download = link(t('download'), 'motion.md?download=1', 'download-2-line'); download.download = 'motion.md'; download.target = '_self'; downloads.setAttribute('aria-label', t('document')); downloads.append(download); - download.addEventListener('click', event => { if (parent !== window) { event.preventDefault(); void host('download').catch(() => notice(t('failed'))); } report('download'); }); - if (source) { const doc = button(t('document'), 'file-text-line', true); doc.setAttribute('aria-expanded', 'false'); doc.onclick = () => { source.hidden = !source.hidden; doc.setAttribute('aria-expanded', String(!source.hidden)); if (!source.hidden) source.scrollIntoView({ block: 'start' }); }; downloads.append(doc); } - if (config.sourceUrl) { const sourceLink = link(t('source'), config.sourceUrl, 'external-link-line'); sourceLink.onclick = event => { if (parent !== window) { event.preventDefault(); void host('source').catch(() => notice(t('failed'))); } }; downloads.append(sourceLink); } + download.addEventListener('click', event => { event.preventDefault(); void host('download').then(() => report('download', { delivery_status: 'browser_save_requested' })).catch(() => { notice(t('failed')); report('download', { delivery_status: 'fetch_failed' }); }); }); + if (source) { const doc = button(t('document'), 'file-text-line', true); doc.setAttribute('aria-expanded', 'false'); doc.onclick = () => { source.hidden = !source.hidden; doc.setAttribute('aria-expanded', String(!source.hidden)); if (!source.hidden) source.scrollIntoView({ block: 'start' }); report('document', { expanded: !source.hidden }); }; downloads.append(doc); } + if (config.sourceUrl) { const sourceLink = link(t('source'), config.sourceUrl, 'external-link-line'); sourceLink.onclick = event => { report('source'); if (parent !== window) { event.preventDefault(); void host('source').catch(() => notice(t('failed'))); } }; downloads.append(sourceLink); } for (const control of downloads.children) { control.className = 'ui-text-link'; const glyph = control.querySelector('span'); if (glyph) control.prepend(glyph); } breakdown.append(referenceHeading); const rules = original?.querySelector('.rule-grid'), identity = original?.querySelector('.identity'), filmstrip = original?.querySelector('.filmstrip'), production = original?.querySelector('.production'); @@ -188,6 +188,7 @@ async function mount() { catch { notice(t('failed')); report('copy', { outcome: 'failure' }); } finally { copy.disabled = false; } }; open.onclick = async () => { + report('open_editor'); try { open.disabled = true; copy.disabled = true; open.textContent = t('opening'); const result = await host('open', values()); if (parent === window) { await report('open_editor', { outcome: 'success', project_id: result.projectId }); location.assign(result.url); } } catch { notice(t('failed')); if (parent === window) report('open_editor', { outcome: 'failure' }); } finally { open.disabled = false; copy.disabled = false; open.textContent = t('edit'); } diff --git a/tests/template-guide.test.ts b/tests/template-guide.test.ts index 52263da3d..143c8da6d 100644 --- a/tests/template-guide.test.ts +++ b/tests/template-guide.test.ts @@ -10,6 +10,8 @@ import { pluginRoot, inspectProject } from '../hyperframes.ts'; import { Phase1Service } from '../phase1.ts'; import { fixture } from './fixtures.ts'; import { transport } from './http.ts'; +import { createTracker, deviceContext, type PendingEvent } from '../tracking/core.ts'; +import { omEvents } from '../tracking/events.ts'; const lovable = 'motion-be2a4af0-0183-4979-ab05-2a68413c0890'; const stripe = 'motion-80dceb1d-5219-4e1f-9394-6baacf5d0166'; @@ -45,6 +47,10 @@ test('guide drafts and analytics reject arbitrary fields and never collect chang const event = { action: 'edit', view_id: crypto.randomUUID(), field: 'title' }; assert(isTemplateGuideEvent(event)); assert(!isTemplateGuideEvent({ ...event, text: 'Private draft' })); assert(!isTemplateGuideEvent({ ...event, field: 'brand' })); + assert(isTemplateGuideEvent({ action: 'document', view_id: event.view_id, expanded: true })); + assert(!isTemplateGuideEvent({ ...event, expanded: true })); + assert(isTemplateGuideEvent({ action: 'download', view_id: event.view_id, delivery_status: 'browser_save_requested' })); + assert(!isTemplateGuideEvent({ action: 'download', view_id: event.view_id, delivery_status: 'saved_to_disk' })); }); test('each selected guide materializes its own native canvas, timing and variables', () => fixture(async store => { @@ -96,3 +102,31 @@ test('the exact requested URLs serve upgraded pages, while raw source and downlo assert.equal(await download.text(), motion); } }, false)); + + +test('guide actions cross real Studio admission with closed metadata and respect opt-out', () => fixture(async store => { + const received: PendingEvent[] = []; + const tracking = createTracker({ registry: omEvents, entrypoint: 'mcp', enabled: true, flushIntervalMs: 0, + send: async events => { received.push(...events); return 'accepted'; } }); + const request = transport(store, { tracking }); + const view = crypto.randomUUID(); + const properties = [ + { action: 'shown' }, { action: 'edit', field: 'title' }, { action: 'chapter' }, { action: 'reference' }, + { action: 'document', expanded: true }, { action: 'source' }, + { action: 'download', delivery_status: 'browser_save_requested' }, { action: 'download', delivery_status: 'fetch_failed' }, + { action: 'open_editor' }, { action: 'open_editor', outcome: 'success', project_id: crypto.randomUUID() }, + { action: 'copy', outcome: 'manual_fallback' }, + ].map(value => ({ page_name: 'studio', template_id: lovable, view_id: view, ...value })); + const packet = (value: Record): PendingEvent => ({ event: 'template_guide_interaction', properties: value, + event_id: crypto.randomUUID(), occurred_at: new Date().toISOString(), entrypoint: 'studio', ...deviceContext() }); + const send = (value: Record) => request('/motion-api/tracking', { method: 'POST', + headers: { 'content-type': 'application/json' }, body: JSON.stringify({ events: [packet(value)] }) }); + for (const value of properties) assert.equal((await send(value)).status, 200); + assert.equal(await tracking.flush(), 'accepted'); assert.equal(received.length, properties.length); + assert(received.every(event => event.properties.template_id === lovable && event.properties.view_id === view)); + assert.equal((await send({ ...properties[1], title: 'PRIVATE_COPY' })).status, 400); + assert.equal((await send({ ...properties[6], delivery_status: 'saved_to_disk' })).status, 400); + tracking.setEnabled(false); + assert.equal((await send(properties[0])).status, 200); assert.equal(tracking.pending(), 0); + assert.equal(received.length, properties.length); tracking.close(); +}, false)); diff --git a/tracking/README.md b/tracking/README.md index 0b694e220..1126f8e90 100644 --- a/tracking/README.md +++ b/tracking/README.md @@ -1,6 +1,6 @@ # OpenMotion tracking -Catalog guide pages emit `template_guide_interaction` through the existing Studio transport and privacy preference. `template_id` always identifies the page being used, with a fresh `view_id`; actions are `shown`, `edit`, `chapter`, `reference`, `reset`, `copy`, `open_editor` and `download`. `shown` requires at least half of the preview visible for one continuous foreground second. Edits report only `title` or `accent`, never their values. Copy and editor actions report success, failure or manual fallback separately. The embedding parent pins the template identity and validates the closed event fields. This measures interaction and handoff, not user acceptance, export or reference-recreation completion. Local tests do not establish production collection. +Catalog guide pages emit `template_guide_interaction` through the existing Studio transport and privacy preference. `template_id` always identifies the page being used, with a fresh `view_id`; actions are `shown`, `edit`, `chapter`, `reference`, `reset`, `copy`, `open_editor`, `download`, `document` and `source`. Document toggles include `expanded`; source links record intent. Download results distinguish `browser_save_requested` from `fetch_failed`, and never confirm disk persistence. Editor entry reports intent separately from its result. `shown` requires at least half of the preview visible for one continuous foreground second. Edits report only `title` or `accent`, never their values. Copy and editor actions report success, failure or manual fallback separately. The embedding parent pins the template identity and validates the closed event fields. This measures interaction and handoff, not user acceptance, export or reference-recreation completion. Local tests do not establish production collection. An explicit-event package shared by the standalone MCP runtime and Motion Studio. It has no runtime dependencies. The application consumes its TypeScript sources; diff --git a/tracking/events.ts b/tracking/events.ts index e20d7121f..29e2a358c 100644 --- a/tracking/events.ts +++ b/tracking/events.ts @@ -221,7 +221,8 @@ export const omEvents = { delivery_status: ['browser_save_requested', 'fetch_failed', 'unknown'], error_code: 'code', detail_view_id: 'uuid', detail_mode: ['modal'], ...template, ...brand, ...templateSeries }, required: ['resource_kind', 'download_attempt_id', 'delivery_status'] }, template_guide_interaction: { producers: ['studio'], fields: { page_name: ['studio'], template_id: 'code', view_id: 'uuid', project_id: 'uuid', - action: ['shown', 'edit', 'chapter', 'reference', 'reset', 'copy', 'open_editor', 'download'], + action: ['shown', 'edit', 'chapter', 'reference', 'reset', 'copy', 'open_editor', 'download', 'document', 'source'], + expanded: 'boolean', delivery_status: ['browser_save_requested', 'fetch_failed'], field: ['title', 'accent'], outcome: ['success', 'failure', 'manual_fallback'] }, required: ['page_name', 'template_id', 'view_id', 'action'] }, template_instruction_copy_result: { producers: ['studio'], fields: { host_product: hosts, copy_status: ['clipboard_written', 'manual_fallback_shown', 'failed'], page_name: ['home', 'studio'], copy_attempt_id: 'uuid', ...templateDetail, ...project, ...template, ...templateSeries }, required: ['host_product', 'copy_status'] }, From 79ebc2f2c6bf7dd3dd3ca3b62ee30ec7fd6a7c79 Mon Sep 17 00:00:00 2001 From: qiqi Date: Wed, 18 Nov 2026 22:05:30 +0800 Subject: [PATCH 3/6] test(templates): run shared guide contracts in CI --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 751c1c415..0e3516ef2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -312,7 +312,7 @@ jobs: node --test tests/brand-extraction.browser.test.ts tests/brand-showcase.browser.test.ts - name: Repository template runtime regression if: steps.scope.outputs.full == 'true' - run: node --test tests/repository-template-runtime.test.ts tests/hosted-template-catalog.test.ts tests/template-prompts.test.ts tests/integration-setup.test.ts + run: node --test tests/repository-template-runtime.test.ts tests/hosted-template-catalog.test.ts tests/template-guide.test.ts tests/template-prompts.test.ts tests/integration-setup.test.ts - name: Workspace, wrapper and session regression if: steps.scope.outputs.full == 'true' timeout-minutes: 10 From 89bb638c276ad8f34ca8b35994f079c22d1d0234 Mon Sep 17 00:00:00 2001 From: qiqi Date: Wed, 18 Nov 2026 22:27:52 +0800 Subject: [PATCH 4/6] fix(templates): preserve guide retries and complete handbook discovery --- docs/mcp-phase1-tools.md | 2 +- mcp.ts | 4 +- phase1.ts | 33 +++++++++------ scripts/build-template-guide.mjs | 3 +- server.ts | 2 +- shared/template-guide.ts | 1 + studio/src/i18n/mcp-ui.json | 50 ++++++++++++++++++----- studio/src/motion/gatewayClient.ts | 2 +- studio/src/motion/mcpCapabilities.ts | 6 +++ studio/src/template-guide/actions.test.ts | 31 ++++++++++++++ studio/src/template-guide/actions.ts | 30 ++++++++++---- tests/mcp-onboarding.test.ts | 13 +++++- tests/mcp-runtime.test.ts | 13 ++++++ tests/template-guide.test.ts | 21 ++++++++++ 14 files changed, 174 insertions(+), 37 deletions(-) diff --git a/docs/mcp-phase1-tools.md b/docs/mcp-phase1-tools.md index 055bb9295..172fad0b8 100644 --- a/docs/mcp-phase1-tools.md +++ b/docs/mcp-phase1-tools.md @@ -11,7 +11,7 @@ Skill 是指导文档,与公开 Tool 数量分开。本次后续命名与分 Every catalog `preview.html` URL uses the maintained guide interface. It preserves that entry's own authored sequence, declared parameters, timing, reference film, rules and frames. The authored examples are motion illustrations, not verified reconstructions of the reference films. Entries without the supported declaration retain their own source preview and Agent handoff; no substitute film or unsupported trial fields are inserted. `?raw=1` and `motion.md` preserve the original source bytes. -`openmotion_create_project` accepts optional `guideDraft: { title, accent }` with `projectType=template` and the exact catalog `templateId`. It validates the selected guide's declaration and copies that guide's own canvas code, duration and motion document into an independent native project. Title and accent are declared as native variables for Agent editing; the JavaScript source remains available for deeper edits. The current Studio layout does not expose a Variables panel, so the guide does not promise that control. The original reference is not automatically recreated, no export is started, and the source catalog is not modified. Existing request-id deduplication and version/history protection apply. Studio's direct and sandbox-embedded guide actions use the same authority. +`openmotion_create_project` accepts optional `guideDraft: { title, accent }` with `projectType=template` and the exact catalog `templateId`. It validates the selected guide's declaration and copies that guide's own canvas code, duration and motion document into an independent native project. Title and accent are declared as native variables for Agent editing; the JavaScript source remains available for deeper edits. The current Studio layout does not expose a Variables panel, so the guide does not promise that control. The original reference is not automatically recreated, no export is started, and the source catalog is not modified. Existing request-id deduplication and version/history protection apply. Replay the complete original creation payload, including namingLanguage, when retrying the same draft. Creation errors explicitly marked applied=false confirm that the unregistered project was cleaned up; only those permit a fresh requestId. Transport loss and unknown outcomes must retain the original request. The Studio MCP handbook exposes the same copyable guide-example scenario with its prerequisites and limits. Studio's direct and sandbox-embedded guide actions use the same authority. ## Optional native template presentation diff --git a/mcp.ts b/mcp.ts index 3b8db9a0d..069c09d6e 100644 --- a/mcp.ts +++ b/mcp.ts @@ -178,7 +178,7 @@ async function invokeRpc(message: any, store: WorkspaceStore, registry: ReturnTy const raw = await response.json(); const normalized = response.ok && transportName === 'openmotion_get_project' && transportArgs.workId ? normalizeInlineResult(raw) : undefined; const value = publicToolResult(normalized?.structuredContent ?? raw); - if (!response.ok) throw Object.assign(new Error(value.error || 'Tool failed'), { code: value.code, details: value.runtime }); + if (!response.ok) throw Object.assign(new Error(value.error || 'Tool failed'), { code: value.code, details: value.runtime, ...(value.applied === false ? { applied: false } : {}) }); if (finalVideo && (!value.inlineWork?.playable || value.inlineWork.state !== 'completed' || !normalized?._meta?.inlineVideo?.video)) throw new Error('FINAL_VIDEO_NOT_READY: Display only after the MP4 export completes and passes verification'); if (value.projectId && value.sessionId) selections.set(store, { projectId: value.projectId, sessionId: value.sessionId }); @@ -208,7 +208,7 @@ async function invokeRpc(message: any, store: WorkspaceStore, registry: ReturnTy const runtimeFailure = ['MCP_RUNTIME_RELOAD_REQUIRED', 'EDITOR_RUNTIME_INCOMPATIBLE', 'NATIVE_RUNTIME_NOT_READY'].includes(code); return result({ isError: true, content: [{ type: 'text', text: message }], structuredContent: { error: { code, message, ...(runtimeFailure && (error as any).details ? { details: (error as any).details } : {}), - applied: runtimeFailure || /^(NATIVE_RUNTIME_NOT_READY|INVALID_|VERSION_CONFLICT|VERSION_NOT_RESTORABLE|PROJECT_NOT_|PROJECT_SESSION_|REQUEST_ID_CONFLICT|MCP_TOOL_NOT_EXPOSED|EXPORT_NOT_|TEMPLATE_NOT_)/.test(code) ? false : 'unknown' } } }); + applied: (error as any).applied === false || runtimeFailure || /^(NATIVE_RUNTIME_NOT_READY|INVALID_|VERSION_CONFLICT|VERSION_NOT_RESTORABLE|PROJECT_NOT_|PROJECT_SESSION_|REQUEST_ID_CONFLICT|MCP_TOOL_NOT_EXPOSED|EXPORT_NOT_|TEMPLATE_NOT_)/.test(code) ? false : 'unknown' } } }); } } return { jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } }; diff --git a/phase1.ts b/phase1.ts index b2dc00448..a88339d19 100644 --- a/phase1.ts +++ b/phase1.ts @@ -171,7 +171,7 @@ export class Phase1Service { if (previous) { if (previous.inputHash !== inputHash) throw new Error('REQUEST_ID_CONFLICT: 相同 requestId 不能使用不同输入'); if (previous.state === 'completed') return { ...previous.result, ...(previous.result.job ? { job: await this.publicJob(previous.result.job.id) } : {}), replayed: true }; - if (previous.state === 'failed') throw new Error(previous.error); + if (previous.state === 'failed') throw Object.assign(new Error(previous.error), previous.applied === false ? { applied: false } : {}); if (name === 'motion_open_preview' && args.action === 'complete_generation') { const work = await this.workRounds.get(args.projectId, args.workId); if (work.generation?.completionRequestId === args.requestId) { @@ -225,7 +225,7 @@ export class Phase1Service { } catch (error) { if (workAccepted) await this.workRounds.failed(args.projectId, args.workId, errorText(error)); - await atomicJson(file, { ...record, state: 'failed', error: errorText(error) }); throw error; + await atomicJson(file, { ...record, state: 'failed', error: errorText(error), ...((error as any)?.applied === false ? { applied: false } : {}) }); throw error; } await atomicJson(file, { ...record, state: 'completed', result }); return result; } @@ -454,18 +454,19 @@ export class Phase1Service { }, 30_000); } if (name === 'motion_create_project') return this.writeRequest(name, args, async record => { - if (args.projectType === 'natural_language' && (args.templateId || args.referenceVideoId || args.referenceUrl) || args.projectType === 'template' && (args.referenceVideoId || args.referenceUrl) || args.projectType === 'reference_video' && (args.templateId || args.referenceVideoId && args.referenceUrl)) throw new Error('INVALID_ARGUMENT: creation source must match projectType'); - if (args.projectType === 'template' && !args.templateId || args.projectType === 'reference_video' && !args.referenceVideoId && !args.referenceUrl) throw new Error('INVALID_ARGUMENT: creation source is required'); - const source = args.templateId ? await templateCatalogFor(this.store.directory).get(args.templateId) : args.referenceVideoId ? getTemplate(args.referenceVideoId) : null; - const guideDraft = args.guideDraft === undefined ? undefined : parseTemplateGuideDraft(args.guideDraft); - if (guideDraft && (args.projectType !== 'template' || !source)) throw new Error('INVALID_GUIDE_DRAFT: a catalog template is required'); - if (args.projectType === 'template' && (!source || !isEditableTemplate(source)) && !guideDraft) throw new Error('TEMPLATE_NOT_COPYABLE: 请在 Studio 选择可编辑原生模板;参考视频需由 Agent 重建'); - if (args.referenceUrl && !['https:', 'http:'].includes(new URL(args.referenceUrl).protocol)) throw new Error('INVALID_REFERENCE_URL'); - validateInstruction(args.requirements); - const language = args.namingLanguage === undefined ? undefined : namingLanguage(args.namingLanguage); - const title = validateProjectTitle(args.title), directory = this.store.projectDirectoryFor(record.projectId); + const directory = this.store.projectDirectoryFor(record.projectId); let registered = false; try { + if (args.projectType === 'natural_language' && (args.templateId || args.referenceVideoId || args.referenceUrl) || args.projectType === 'template' && (args.referenceVideoId || args.referenceUrl) || args.projectType === 'reference_video' && (args.templateId || args.referenceVideoId && args.referenceUrl)) throw new Error('INVALID_ARGUMENT: creation source must match projectType'); + if (args.projectType === 'template' && !args.templateId || args.projectType === 'reference_video' && !args.referenceVideoId && !args.referenceUrl) throw new Error('INVALID_ARGUMENT: creation source is required'); + const source = args.templateId ? await templateCatalogFor(this.store.directory).get(args.templateId) : args.referenceVideoId ? getTemplate(args.referenceVideoId) : null; + const guideDraft = args.guideDraft === undefined ? undefined : parseTemplateGuideDraft(args.guideDraft); + if (guideDraft && (args.projectType !== 'template' || !source)) throw new Error('INVALID_GUIDE_DRAFT: a catalog template is required'); + if (args.projectType === 'template' && (!source || !isEditableTemplate(source)) && !guideDraft) throw new Error('TEMPLATE_NOT_COPYABLE: 请在 Studio 选择可编辑原生模板;参考视频需由 Agent 重建'); + if (args.referenceUrl && !['https:', 'http:'].includes(new URL(args.referenceUrl).protocol)) throw new Error('INVALID_REFERENCE_URL'); + validateInstruction(args.requirements); + const language = args.namingLanguage === undefined ? undefined : namingLanguage(args.namingLanguage); + const title = validateProjectTitle(args.title); const appliedGuide = guideDraft ? await materializeTemplateGuide(templateCatalogFor(this.store.directory), source!.id, directory, this.runtimeRoot, guideDraft) : undefined; if (args.projectType === 'template' && !guideDraft) await templateCatalogFor(this.store.directory).copy(source!, directory, this.runtimeRoot); else if (!guideDraft) await createBlankProject(directory, this.runtimeRoot, title); @@ -492,7 +493,13 @@ export class Phase1Service { }); const detail = await this.detail(record.projectId); return { ...detail, created: true, previewUrl: this.context.origin() + sessionPath(detail.sessionId, detail.projectId, { embedded: true }), creationComplete: true, filmComplete: false }; - } catch (error) { if (!registered) await rm(directory, { recursive: true, force: true }); throw error; } + } catch (error) { + if (!registered) { + await rm(directory, { recursive: true, force: true }); + throw Object.assign(error instanceof Error ? error : new Error(errorText(error)), { applied: false }); + } + throw error; + } }); if (name === 'motion_open_preview') { if (args.action === 'record_display') { diff --git a/scripts/build-template-guide.mjs b/scripts/build-template-guide.mjs index f82c2d2cb..c8bc71978 100644 --- a/scripts/build-template-guide.mjs +++ b/scripts/build-template-guide.mjs @@ -1,5 +1,6 @@ import { build } from 'esbuild'; import { copyFile, mkdir, readFile } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; const root = new URL('../', import.meta.url); // Inline the maintained symbol paths so the same icons work inside opaque-origin guide sandboxes. const sprite = await readFile(new URL('packages/design-system/icons.svg', root), 'utf8'); @@ -9,6 +10,6 @@ const icons = Object.fromEntries(['arrow-left-line', 'arrow-right-line', 'refres return [name, symbol[1]]; })); await mkdir(new URL('studio/build/guide-assets/', root), { recursive: true }); -await build({ entryPoints: [new URL('studio/src/template-guide/page.ts', root).pathname], outfile: new URL('studio/build/guide-assets/viewer.js', root).pathname, +await build({ entryPoints: [fileURLToPath(new URL('studio/src/template-guide/page.ts', root))], outfile: fileURLToPath(new URL('studio/build/guide-assets/viewer.js', root)), bundle: true, format: 'iife', platform: 'browser', target: 'es2022', minify: true, define: { __OPENMOTION_GUIDE_ICONS__: JSON.stringify(icons) } }); await copyFile(new URL('studio/src/template-guide/page.css', root), new URL('studio/build/guide-assets/viewer.css', root)); diff --git a/server.ts b/server.ts index 493f69c90..4be3c2460 100644 --- a/server.ts +++ b/server.ts @@ -481,7 +481,7 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store = } catch (error) { const message = error instanceof Error ? error.message : 'Tool failed'; - return json(res, 400, { error: message, applied: message.startsWith('VERSION_NOT_RESTORABLE:') ? false : 'unknown' }); + return json(res, 400, { error: message, applied: (error as any)?.applied === false || message.startsWith('VERSION_NOT_RESTORABLE:') ? false : 'unknown' }); } } if (req.method === 'GET' && ['/api/integration', '/connect/guide', '/connect/config'].includes(url.pathname)) { diff --git a/shared/template-guide.ts b/shared/template-guide.ts index d45d8b366..419462bfa 100644 --- a/shared/template-guide.ts +++ b/shared/template-guide.ts @@ -1,5 +1,6 @@ /** Portable draft contract for each catalog entry's own authored motion example. */ export type TemplateGuideDraft = { title: string; accent: string }; +export const templateGuideContinuationInstruction = 'Continue the authored guide example using the exact templateId and guideDraft from my copied requirements. First call openmotion_get_template and confirm this entry declares the title/accent example. Use openmotion_create_project with projectType=template, that templateId, guideDraft and a stable requestId; preserve the complete creation payload when retrying. If creation confirms applied=false, retry with a new requestId; keep the original request for unknown outcomes. Open the returned project with openmotion_open_preview and verify my trial values. This creates the authored canvas example, not a reconstruction of the reference film. Canvas text has no direct inspector control; continue source edits through the Agent. Copying does not send a task or create a project.'; export const templateGuideActions = ['shown', 'edit', 'chapter', 'reference', 'reset', 'copy', 'open_editor', 'download', 'document', 'source'] as const; export type TemplateGuideEvent = { action: typeof templateGuideActions[number]; view_id: string; field?: 'title' | 'accent'; outcome?: 'success' | 'failure' | 'manual_fallback'; project_id?: string; expanded?: boolean; delivery_status?: 'browser_save_requested' | 'fetch_failed' }; export function isTemplateGuideEvent(input: unknown): input is TemplateGuideEvent { diff --git a/studio/src/i18n/mcp-ui.json b/studio/src/i18n/mcp-ui.json index db38305ec..c33673d6e 100644 --- a/studio/src/i18n/mcp-ui.json +++ b/studio/src/i18n/mcp-ui.json @@ -231,7 +231,10 @@ "DSH workspace plugin": "DSH 工作台插件", "The final video loads automatically. If loading fails, choose Reload to read the same completed export without rendering again.": "成片会自动加载。如果加载失败,点击“重新加载”即可重新读取同一份已完成的成片,不会重新渲染。", "How do I find where project audio is used?": "如何查找项目音频用在哪里?", - "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "在「我的素材」中,音频显示使用状态和可点击的应用区间。点击区间会选中片段并定位到起点;嵌套音频会先打开所属合成。已使用音频不重复显示文件时长,窄面板将使用信息单独显示一行。详细预览保留试听与可视化。" + "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "在「我的素材」中,音频显示使用状态和可点击的应用区间。点击区间会选中片段并定位到起点;嵌套音频会先打开所属合成。已使用音频不重复显示文件时长,窄面板将使用信息单独显示一行。详细预览保留试听与可视化。", + "Continue a guide example": "继续制作讲解示例", + "Open a template’s motion guide and try its declared text and accent controls, then copy the requirements or enter the editor. Keep the exact template and draft. This creates the authored example, not the reference film; only confirmed unapplied failures permit a new creation request.": "打开模板动效说明,试改已声明的文案和强调色,再复制要求或进入编辑器。保留准确模板与草稿;创建的是编排示例,并非参考原片复刻。仅确认未生效的失败允许重新发起创建。", + "Continue the authored guide example using the exact templateId and guideDraft from my copied requirements. First call openmotion_get_template and confirm this entry declares the title/accent example. Use openmotion_create_project with projectType=template, that templateId, guideDraft and a stable requestId; preserve the complete creation payload when retrying. If creation confirms applied=false, retry with a new requestId; keep the original request for unknown outcomes. Open the returned project with openmotion_open_preview and verify my trial values. This creates the authored canvas example, not a reconstruction of the reference film. Canvas text has no direct inspector control; continue source edits through the Agent. Copying does not send a task or create a project.": "使用我复制要求中的准确 templateId 和 guideDraft 继续制作讲解示例。先调用 openmotion_get_template,确认该模板声明了文案/强调色示例。用 openmotion_create_project,携带 projectType=template、原 templateId、guideDraft 和稳定 requestId;重试时完整保留首次创建参数。仅当创建明确返回 applied=false 时换新 requestId,结果未知时继续用原请求。调用 openmotion_open_preview 打开返回的工程,核对试改值。创建的是编排 canvas 示例,并非参考原片复刻;canvas 文字没有普通属性编辑控件,可由 Agent 续改源码。复制不会发送任务或创建工程。" }, "ja": { "Create and reuse assets": "アセットを作成して再利用", @@ -257,7 +260,10 @@ "DSH workspace plugin": "DSH ワークスペースプラグイン", "The final video loads automatically. If loading fails, choose Reload to read the same completed export without rendering again.": "完成した動画は自動で読み込まれます。失敗した場合は「再読み込み」を選択すると、再レンダリングせずに同じ完成済み動画を読み込みます。", "How do I find where project audio is used?": "プロジェクトの音声が使われている場所を確認するには?", - "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "「マイアセット」の音声には使用状況とクリック可能な使用区間が表示されます。区間をクリックするとクリップを選択し、開始位置に移動します。入れ子の音声は所属するコンポジションを先に開きます。使用中はファイルの長さを重複表示せず、狭いパネルでは使用情報を別の行に表示します。詳細プレビューの試聴と可視化は引き続き利用できます。" + "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "「マイアセット」の音声には使用状況とクリック可能な使用区間が表示されます。区間をクリックするとクリップを選択し、開始位置に移動します。入れ子の音声は所属するコンポジションを先に開きます。使用中はファイルの長さを重複表示せず、狭いパネルでは使用情報を別の行に表示します。詳細プレビューの試聴と可視化は引き続き利用できます。", + "Continue a guide example": "解説サンプルを続けて制作", + "Open a template’s motion guide and try its declared text and accent controls, then copy the requirements or enter the editor. Keep the exact template and draft. This creates the authored example, not the reference film; only confirmed unapplied failures permit a new creation request.": "テンプレートの動きの解説で、対応する文字とアクセント色を試し、要件をコピーするかエディターへ進みます。テンプレートと下書きを保持します。作成するのは解説用サンプルです。未適用と確認できた失敗だけ、新規リクエストで再試行できます。", + "Continue the authored guide example using the exact templateId and guideDraft from my copied requirements. First call openmotion_get_template and confirm this entry declares the title/accent example. Use openmotion_create_project with projectType=template, that templateId, guideDraft and a stable requestId; preserve the complete creation payload when retrying. If creation confirms applied=false, retry with a new requestId; keep the original request for unknown outcomes. Open the returned project with openmotion_open_preview and verify my trial values. This creates the authored canvas example, not a reconstruction of the reference film. Canvas text has no direct inspector control; continue source edits through the Agent. Copying does not send a task or create a project.": "コピーした要件の正確な templateId と guideDraft で解説サンプルを続けてください。openmotion_get_template で文字とアクセント色の対応を確認し、openmotion_create_project に projectType=template、templateId、guideDraft、固定 requestId を渡します。再試行では作成引数をすべて保持します。applied=false が確定した場合だけ新しい requestId を使い、結果不明なら元のリクエストを保持します。openmotion_open_preview で返された工程を開き、試した値を確認します。参照映像の再現ではなく、作成済み canvas サンプルです。canvas 文字は属性パネルで直接編集できないため、Agent がソースを編集します。コピーだけではタスク送信も工程作成も行いません。" }, "ko": { "Create and reuse assets": "에셋 생성 및 재사용", @@ -283,7 +289,10 @@ "DSH workspace plugin": "DSH 워크스페이스 플러그인", "The final video loads automatically. If loading fails, choose Reload to read the same completed export without rendering again.": "완성된 동영상은 자동으로 로드됩니다. 실패하면 다시 로드를 선택하세요. 다시 렌더링하지 않고 동일한 완성된 동영상을 불러옵니다.", "How do I find where project audio is used?": "프로젝트 오디오가 사용된 위치는 어떻게 찾나요?", - "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "내 에셋의 오디오 행에서 사용 상태와 클릭 가능한 적용 구간을 확인할 수 있습니다. 구간을 클릭하면 클립을 선택하고 시작점으로 이동하며, 중첩된 오디오는 해당 컴포지션을 먼저 엽니다. 사용 중인 오디오는 파일 길이를 중복 표시하지 않고 좁은 패널에서는 사용 정보를 별도 줄에 표시합니다. 상세 미리보기의 재생과 시각화는 유지됩니다." + "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "내 에셋의 오디오 행에서 사용 상태와 클릭 가능한 적용 구간을 확인할 수 있습니다. 구간을 클릭하면 클립을 선택하고 시작점으로 이동하며, 중첩된 오디오는 해당 컴포지션을 먼저 엽니다. 사용 중인 오디오는 파일 길이를 중복 표시하지 않고 좁은 패널에서는 사용 정보를 별도 줄에 표시합니다. 상세 미리보기의 재생과 시각화는 유지됩니다.", + "Continue a guide example": "가이드 예제 이어서 제작", + "Open a template’s motion guide and try its declared text and accent controls, then copy the requirements or enter the editor. Keep the exact template and draft. This creates the authored example, not the reference film; only confirmed unapplied failures permit a new creation request.": "템플릿 동작 가이드에서 지원하는 문구와 강조색을 바꾼 뒤 요구사항을 복사하거나 편집기로 이동합니다. 정확한 템플릿과 초안을 유지합니다. 참조 영상 재현이 아닌 가이드 예제를 만들며, 적용되지 않았다고 확인된 실패만 새 요청으로 재시도합니다.", + "Continue the authored guide example using the exact templateId and guideDraft from my copied requirements. First call openmotion_get_template and confirm this entry declares the title/accent example. Use openmotion_create_project with projectType=template, that templateId, guideDraft and a stable requestId; preserve the complete creation payload when retrying. If creation confirms applied=false, retry with a new requestId; keep the original request for unknown outcomes. Open the returned project with openmotion_open_preview and verify my trial values. This creates the authored canvas example, not a reconstruction of the reference film. Canvas text has no direct inspector control; continue source edits through the Agent. Copying does not send a task or create a project.": "복사한 요구사항의 정확한 templateId와 guideDraft로 가이드 예제를 이어서 제작하세요. openmotion_get_template으로 문구와 강조색 지원을 확인하고, openmotion_create_project에 projectType=template, templateId, guideDraft와 고정 requestId를 전달하세요. 재시도 시 최초 생성 인수를 모두 유지하세요. applied=false가 확인된 경우만 새 requestId를 쓰고, 결과가 불확실하면 원래 요청을 유지하세요. openmotion_open_preview로 반환된 프로젝트를 열어 시험한 값을 확인하세요. 참조 영상 재현이 아닌 작성된 canvas 예제입니다. canvas 문구는 속성 패널에서 직접 편집할 수 없으며 Agent가 소스를 수정합니다. 복사는 작업 전송이나 프로젝트 생성을 실행하지 않습니다." }, "de": { "Create and reuse assets": "Assets erstellen und wiederverwenden", @@ -309,7 +318,10 @@ "DSH workspace plugin": "DSH-Workspace-Plugin", "The final video loads automatically. If loading fails, choose Reload to read the same completed export without rendering again.": "Das fertige Video wird automatisch geladen. Falls das Laden fehlschlägt, wählen Sie Neu laden. Derselbe fertige Export wird erneut geladen, ohne neu zu rendern.", "How do I find where project audio is used?": "Wie finde ich, wo Projektaudio verwendet wird?", - "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "Unter Meine Assets zeigen Audiozeilen den Nutzungsstatus und anklickbare Zeitbereiche. Ein Klick wählt den Clip und springt zum Anfang; verschachteltes Audio öffnet zuerst seine Komposition. Verwendetes Audio zeigt die Dateidauer nicht doppelt. Schmale Panels zeigen die Nutzung in einer eigenen Zeile. Vorhören und Visualisierung bleiben in der Detailvorschau verfügbar." + "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "Unter Meine Assets zeigen Audiozeilen den Nutzungsstatus und anklickbare Zeitbereiche. Ein Klick wählt den Clip und springt zum Anfang; verschachteltes Audio öffnet zuerst seine Komposition. Verwendetes Audio zeigt die Dateidauer nicht doppelt. Schmale Panels zeigen die Nutzung in einer eigenen Zeile. Vorhören und Visualisierung bleiben in der Detailvorschau verfügbar.", + "Continue a guide example": "Ein Anleitungsbeispiel fortsetzen", + "Open a template’s motion guide and try its declared text and accent controls, then copy the requirements or enter the editor. Keep the exact template and draft. This creates the authored example, not the reference film; only confirmed unapplied failures permit a new creation request.": "Öffne die Bewegungsanleitung, teste die vorgesehenen Texte und Akzentfarben und kopiere die Anforderungen oder öffne den Editor. Vorlage und Entwurf bleiben erhalten. Erstellt wird das Beispiel, keine Rekonstruktion des Referenzfilms. Nur ein nachweislich nicht angewandter Fehler erlaubt eine neue Erstellungsanfrage.", + "Continue the authored guide example using the exact templateId and guideDraft from my copied requirements. First call openmotion_get_template and confirm this entry declares the title/accent example. Use openmotion_create_project with projectType=template, that templateId, guideDraft and a stable requestId; preserve the complete creation payload when retrying. If creation confirms applied=false, retry with a new requestId; keep the original request for unknown outcomes. Open the returned project with openmotion_open_preview and verify my trial values. This creates the authored canvas example, not a reconstruction of the reference film. Canvas text has no direct inspector control; continue source edits through the Agent. Copying does not send a task or create a project.": "Setze das Anleitungsbeispiel mit templateId und guideDraft aus meinen kopierten Anforderungen fort. Prüfe mit openmotion_get_template die Text-/Akzent-Unterstützung. Nutze openmotion_create_project mit projectType=template, templateId, guideDraft und einer festen requestId. Wiederhole stets die vollständigen ursprünglichen Parameter. Nur bei bestätigtem applied=false ist eine neue requestId erlaubt; bei unbekanntem Ausgang bleibt die ursprüngliche Anfrage bestehen. Öffne das zurückgegebene Projekt mit openmotion_open_preview und prüfe die Testwerte. Es entsteht das erstellte Canvas-Beispiel, keine Filmrekonstruktion. Canvas-Text hat kein direktes Eigenschaftsfeld; der Agent bearbeitet den Quelltext. Kopieren sendet keinen Auftrag und erstellt kein Projekt." }, "fr": { "Create and reuse assets": "Créer et réutiliser des ressources", @@ -335,7 +347,10 @@ "DSH workspace plugin": "Plugin de travail DSH", "The final video loads automatically. If loading fails, choose Reload to read the same completed export without rendering again.": "La vidéo finale se charge automatiquement. En cas d’échec, choisissez Recharger pour relire le même export terminé sans effectuer un nouveau rendu.", "How do I find where project audio is used?": "Comment trouver où un fichier audio est utilisé dans le projet ?", - "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "Dans Mes médias, les lignes audio affichent leur utilisation et des plages cliquables. Cliquez sur une plage pour sélectionner le clip et rejoindre son début ; un audio imbriqué ouvre d’abord sa composition. La durée du fichier n’est pas répétée pour les audios utilisés. Les panneaux étroits affichent l’utilisation sur une ligne séparée. L’écoute et la visualisation restent disponibles dans l’aperçu détaillé." + "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "Dans Mes médias, les lignes audio affichent leur utilisation et des plages cliquables. Cliquez sur une plage pour sélectionner le clip et rejoindre son début ; un audio imbriqué ouvre d’abord sa composition. La durée du fichier n’est pas répétée pour les audios utilisés. Les panneaux étroits affichent l’utilisation sur une ligne séparée. L’écoute et la visualisation restent disponibles dans l’aperçu détaillé.", + "Continue a guide example": "Poursuivre un exemple du guide", + "Open a template’s motion guide and try its declared text and accent controls, then copy the requirements or enter the editor. Keep the exact template and draft. This creates the authored example, not the reference film; only confirmed unapplied failures permit a new creation request.": "Ouvrez le guide animé, essayez le texte et la couleur prévus, puis copiez les consignes ou ouvrez l’éditeur. Conservez le modèle exact et le brouillon. Il s’agit de l’exemple, sans reconstruction du film de référence. Seul un échec confirmé sans effet permet une nouvelle requête de création.", + "Continue the authored guide example using the exact templateId and guideDraft from my copied requirements. First call openmotion_get_template and confirm this entry declares the title/accent example. Use openmotion_create_project with projectType=template, that templateId, guideDraft and a stable requestId; preserve the complete creation payload when retrying. If creation confirms applied=false, retry with a new requestId; keep the original request for unknown outcomes. Open the returned project with openmotion_open_preview and verify my trial values. This creates the authored canvas example, not a reconstruction of the reference film. Canvas text has no direct inspector control; continue source edits through the Agent. Copying does not send a task or create a project.": "Poursuivez l’exemple avec les templateId et guideDraft exacts de mes consignes copiées. Vérifiez la prise en charge du texte et de la couleur avec openmotion_get_template. Appelez openmotion_create_project avec projectType=template, templateId, guideDraft et un requestId stable. Conservez tous les paramètres initiaux lors des reprises. Un nouveau requestId est permis uniquement si applied=false est confirmé ; si le résultat est inconnu, gardez la requête initiale. Ouvrez le projet retourné avec openmotion_open_preview et vérifiez mes valeurs. Cela crée l’exemple canvas, sans reconstruire le film de référence. Le texte canvas ne se modifie pas directement dans les propriétés ; l’Agent peut modifier le code. Copier n’envoie aucune tâche et ne crée aucun projet." }, "ru": { "Create and reuse assets": "Создавайте и используйте ресурсы повторно", @@ -361,7 +376,10 @@ "DSH workspace plugin": "Плагин рабочего пространства DSH", "The final video loads automatically. If loading fails, choose Reload to read the same completed export without rendering again.": "Готовое видео загружается автоматически. При ошибке выберите «Загрузить снова»: будет прочитан тот же готовый файл без повторного рендеринга.", "How do I find where project audio is used?": "Как найти место использования аудио в проекте?", - "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "В разделе «Мои ресурсы» строки аудио показывают статус использования и доступные для нажатия интервалы. Нажмите интервал, чтобы выбрать клип и перейти к его началу; для вложенного аудио сначала откроется его композиция. Длительность используемого файла не дублируется. В узких панелях сведения об использовании идут отдельной строкой. Прослушивание и визуализация остаются в подробном просмотре." + "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "В разделе «Мои ресурсы» строки аудио показывают статус использования и доступные для нажатия интервалы. Нажмите интервал, чтобы выбрать клип и перейти к его началу; для вложенного аудио сначала откроется его композиция. Длительность используемого файла не дублируется. В узких панелях сведения об использовании идут отдельной строкой. Прослушивание и визуализация остаются в подробном просмотре.", + "Continue a guide example": "Продолжить пример из руководства", + "Open a template’s motion guide and try its declared text and accent controls, then copy the requirements or enter the editor. Keep the exact template and draft. This creates the authored example, not the reference film; only confirmed unapplied failures permit a new creation request.": "Откройте руководство шаблона, измените доступные текст и акцентный цвет, затем скопируйте требования или перейдите в редактор. Сохраните точный шаблон и черновик. Создаётся пример, а не реконструкция референса. Новый запрос допустим лишь после подтверждённой ошибки без изменений.", + "Continue the authored guide example using the exact templateId and guideDraft from my copied requirements. First call openmotion_get_template and confirm this entry declares the title/accent example. Use openmotion_create_project with projectType=template, that templateId, guideDraft and a stable requestId; preserve the complete creation payload when retrying. If creation confirms applied=false, retry with a new requestId; keep the original request for unknown outcomes. Open the returned project with openmotion_open_preview and verify my trial values. This creates the authored canvas example, not a reconstruction of the reference film. Canvas text has no direct inspector control; continue source edits through the Agent. Copying does not send a task or create a project.": "Продолжите пример с точными templateId и guideDraft из скопированных требований. Через openmotion_get_template проверьте поддержку текста и акцентного цвета. Вызовите openmotion_create_project с projectType=template, templateId, guideDraft и постоянным requestId. При повторе сохраняйте все исходные параметры. Новый requestId допустим только при подтверждённом applied=false; при неизвестном результате сохраните исходный запрос. Откройте полученный проект через openmotion_open_preview и проверьте значения. Это canvas-пример, а не реконструкция референсного фильма. Текст canvas нельзя править в обычной панели свойств; Agent продолжает редактировать исходники. Копирование не отправляет задачу и не создаёт проект." }, "es": { "Create and reuse assets": "Crear y reutilizar recursos", @@ -387,7 +405,10 @@ "DSH workspace plugin": "Plugin de espacio de trabajo DSH", "The final video loads automatically. If loading fails, choose Reload to read the same completed export without rendering again.": "El vídeo final se carga automáticamente. Si falla, selecciona Recargar para leer la misma exportación terminada sin volver a renderizar.", "How do I find where project audio is used?": "¿Cómo encuentro dónde se utiliza el audio del proyecto?", - "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "En Mis recursos, las filas de audio muestran su uso e intervalos seleccionables. Haz clic en un intervalo para seleccionar el clip e ir al inicio; el audio anidado abre primero su composición. El audio utilizado no repite la duración del archivo y los paneles estrechos muestran el uso en una línea independiente. La escucha y la visualización siguen disponibles en la vista detallada." + "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "En Mis recursos, las filas de audio muestran su uso e intervalos seleccionables. Haz clic en un intervalo para seleccionar el clip e ir al inicio; el audio anidado abre primero su composición. El audio utilizado no repite la duración del archivo y los paneles estrechos muestran el uso en una línea independiente. La escucha y la visualización siguen disponibles en la vista detallada.", + "Continue a guide example": "Continuar un ejemplo de la guía", + "Open a template’s motion guide and try its declared text and accent controls, then copy the requirements or enter the editor. Keep the exact template and draft. This creates the authored example, not the reference film; only confirmed unapplied failures permit a new creation request.": "Abra la guía de movimiento, pruebe el texto y el color de acento disponibles y copie las instrucciones o abra el editor. Mantenga la plantilla exacta y el borrador. Se crea el ejemplo, sin reconstruir el vídeo de referencia. Solo un fallo confirmado sin cambios permite otra solicitud de creación.", + "Continue the authored guide example using the exact templateId and guideDraft from my copied requirements. First call openmotion_get_template and confirm this entry declares the title/accent example. Use openmotion_create_project with projectType=template, that templateId, guideDraft and a stable requestId; preserve the complete creation payload when retrying. If creation confirms applied=false, retry with a new requestId; keep the original request for unknown outcomes. Open the returned project with openmotion_open_preview and verify my trial values. This creates the authored canvas example, not a reconstruction of the reference film. Canvas text has no direct inspector control; continue source edits through the Agent. Copying does not send a task or create a project.": "Continúa el ejemplo con los templateId y guideDraft exactos de mis instrucciones copiadas. Comprueba con openmotion_get_template que admite texto y color de acento. Usa openmotion_create_project con projectType=template, templateId, guideDraft y un requestId estable. Conserva todos los argumentos originales al reintentar. Usa otro requestId solo si se confirma applied=false; si el resultado es desconocido, mantén la solicitud original. Abre el proyecto devuelto con openmotion_open_preview y verifica mis valores. Se crea el ejemplo canvas, sin reconstruir el vídeo de referencia. El texto canvas no tiene control directo en propiedades; el Agent puede editar el código. Copiar no envía tareas ni crea proyectos." }, "pt-BR": { "Create and reuse assets": "Crie e reutilize recursos", @@ -413,7 +434,10 @@ "DSH workspace plugin": "Plugin de workspace DSH", "The final video loads automatically. If loading fails, choose Reload to read the same completed export without rendering again.": "O vídeo final é carregado automaticamente. Se houver falha, selecione Recarregar para ler a mesma exportação concluída sem renderizar novamente.", "How do I find where project audio is used?": "Como encontrar onde o áudio do projeto é usado?", - "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "Em Meus recursos, as linhas de áudio mostram o uso e intervalos clicáveis. Clique em um intervalo para selecionar o clipe e ir ao início; o áudio aninhado abre primeiro sua composição. O áudio em uso não repete a duração do arquivo, e painéis estreitos mostram o uso em uma linha própria. A reprodução e a visualização continuam na prévia detalhada." + "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "Em Meus recursos, as linhas de áudio mostram o uso e intervalos clicáveis. Clique em um intervalo para selecionar o clipe e ir ao início; o áudio aninhado abre primeiro sua composição. O áudio em uso não repete a duração do arquivo, e painéis estreitos mostram o uso em uma linha própria. A reprodução e a visualização continuam na prévia detalhada.", + "Continue a guide example": "Continuar um exemplo do guia", + "Open a template’s motion guide and try its declared text and accent controls, then copy the requirements or enter the editor. Keep the exact template and draft. This creates the authored example, not the reference film; only confirmed unapplied failures permit a new creation request.": "Abra o guia de movimento, experimente o texto e a cor de destaque disponíveis e copie as instruções ou abra o editor. Mantenha o modelo exato e o rascunho. É criado o exemplo, sem reconstruir o vídeo de referência. Só uma falha confirmada sem alterações permite outra solicitação de criação.", + "Continue the authored guide example using the exact templateId and guideDraft from my copied requirements. First call openmotion_get_template and confirm this entry declares the title/accent example. Use openmotion_create_project with projectType=template, that templateId, guideDraft and a stable requestId; preserve the complete creation payload when retrying. If creation confirms applied=false, retry with a new requestId; keep the original request for unknown outcomes. Open the returned project with openmotion_open_preview and verify my trial values. This creates the authored canvas example, not a reconstruction of the reference film. Canvas text has no direct inspector control; continue source edits through the Agent. Copying does not send a task or create a project.": "Continue o exemplo com os templateId e guideDraft exatos das minhas instruções copiadas. Verifique com openmotion_get_template o suporte a texto e cor de destaque. Use openmotion_create_project com projectType=template, templateId, guideDraft e um requestId fixo. Preserve todos os argumentos originais ao tentar novamente. Use outro requestId apenas se applied=false for confirmado; se o resultado for desconhecido, mantenha a solicitação original. Abra o projeto retornado com openmotion_open_preview e confira meus valores. Isso cria o exemplo canvas, sem reconstruir o vídeo de referência. O texto canvas não tem controle direto no painel de propriedades; o Agent pode editar o código. Copiar não envia tarefas nem cria projetos." }, "it": { "Create and reuse assets": "Crea e riutilizza risorse", @@ -439,7 +463,10 @@ "DSH workspace plugin": "Plugin spazio di lavoro DSH", "The final video loads automatically. If loading fails, choose Reload to read the same completed export without rendering again.": "Il video finale si carica automaticamente. In caso di errore, scegli Ricarica per leggere la stessa esportazione completata senza eseguire un nuovo rendering.", "How do I find where project audio is used?": "Come trovo dove viene usato l’audio del progetto?", - "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "In Le mie risorse, le righe audio mostrano lo stato di utilizzo e intervalli cliccabili. Un clic seleziona la clip e ne raggiunge l’inizio; l’audio annidato apre prima la composizione a cui appartiene. L’audio utilizzato non ripete la durata del file e i pannelli stretti mostrano l’utilizzo su una riga separata. Ascolto e visualizzazione restano nell’anteprima dettagliata." + "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "In Le mie risorse, le righe audio mostrano lo stato di utilizzo e intervalli cliccabili. Un clic seleziona la clip e ne raggiunge l’inizio; l’audio annidato apre prima la composizione a cui appartiene. L’audio utilizzato non ripete la durata del file e i pannelli stretti mostrano l’utilizzo su una riga separata. Ascolto e visualizzazione restano nell’anteprima dettagliata.", + "Continue a guide example": "Continuare un esempio della guida", + "Open a template’s motion guide and try its declared text and accent controls, then copy the requirements or enter the editor. Keep the exact template and draft. This creates the authored example, not the reference film; only confirmed unapplied failures permit a new creation request.": "Apri la guida al movimento, prova il testo e il colore di accento disponibili, poi copia le istruzioni o apri l’editor. Mantieni modello e bozza esatti. Viene creato l’esempio, senza ricostruire il filmato di riferimento. Solo un errore confermato senza modifiche consente una nuova richiesta di creazione.", + "Continue the authored guide example using the exact templateId and guideDraft from my copied requirements. First call openmotion_get_template and confirm this entry declares the title/accent example. Use openmotion_create_project with projectType=template, that templateId, guideDraft and a stable requestId; preserve the complete creation payload when retrying. If creation confirms applied=false, retry with a new requestId; keep the original request for unknown outcomes. Open the returned project with openmotion_open_preview and verify my trial values. This creates the authored canvas example, not a reconstruction of the reference film. Canvas text has no direct inspector control; continue source edits through the Agent. Copying does not send a task or create a project.": "Continua l’esempio con templateId e guideDraft esatti delle istruzioni copiate. Verifica il supporto di testo e colore con openmotion_get_template. Usa openmotion_create_project con projectType=template, templateId, guideDraft e un requestId stabile. Nei tentativi successivi conserva tutti i parametri originali. Usa un nuovo requestId solo con applied=false confermato; se l’esito è ignoto, mantieni la richiesta originale. Apri il progetto restituito con openmotion_open_preview e verifica i valori provati. Si crea l’esempio canvas, senza ricostruire il filmato di riferimento. Il testo canvas non si modifica direttamente nelle proprietà; l’Agent può modificare il codice. Copiare non invia attività e non crea progetti." }, "tr": { "Create and reuse assets": "Varlık oluşturun ve yeniden kullanın", @@ -465,6 +492,9 @@ "DSH workspace plugin": "DSH çalışma alanı eklentisi", "The final video loads automatically. If loading fails, choose Reload to read the same completed export without rendering again.": "Son video otomatik olarak yüklenir. Yükleme başarısız olursa Yeniden yükle seçeneğini kullanın. Aynı tamamlanmış dışa aktarım, yeniden işlenmeden okunur.", "How do I find where project audio is used?": "Proje sesinin nerede kullanıldığını nasıl bulurum?", - "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "Varlıklarım bölümünde ses satırları kullanım durumunu ve tıklanabilir aralıkları gösterir. Bir aralığa tıklamak klibi seçer ve başlangıcına gider; iç içe ses önce ait olduğu kompozisyonu açar. Kullanılan sesin dosya süresi yinelenmez; dar paneller kullanım bilgisini ayrı satırda gösterir. Dinleme ve görselleştirme ayrıntılı önizlemede kalır." + "In My assets, audio rows show usage status and clickable application intervals. Click a range to select the clip and seek to its start; nested audio opens its owning composition first. Used audio omits duplicate file duration, and narrow panels keep usage on its own line. Detailed previews retain audition and visualization.": "Varlıklarım bölümünde ses satırları kullanım durumunu ve tıklanabilir aralıkları gösterir. Bir aralığa tıklamak klibi seçer ve başlangıcına gider; iç içe ses önce ait olduğu kompozisyonu açar. Kullanılan sesin dosya süresi yinelenmez; dar paneller kullanım bilgisini ayrı satırda gösterir. Dinleme ve görselleştirme ayrıntılı önizlemede kalır.", + "Continue a guide example": "Kılavuz örneğini sürdür", + "Open a template’s motion guide and try its declared text and accent controls, then copy the requirements or enter the editor. Keep the exact template and draft. This creates the authored example, not the reference film; only confirmed unapplied failures permit a new creation request.": "Şablonun hareket kılavuzunu açın, desteklenen metin ve vurgu rengini deneyin; ardından gereksinimleri kopyalayın veya düzenleyiciyi açın. Şablonu ve taslağı koruyun. Referans film yeniden oluşturulmaz, kılavuz örneği oluşturulur. Yalnızca uygulanmadığı doğrulanan hatada yeni oluşturma isteği kullanılabilir.", + "Continue the authored guide example using the exact templateId and guideDraft from my copied requirements. First call openmotion_get_template and confirm this entry declares the title/accent example. Use openmotion_create_project with projectType=template, that templateId, guideDraft and a stable requestId; preserve the complete creation payload when retrying. If creation confirms applied=false, retry with a new requestId; keep the original request for unknown outcomes. Open the returned project with openmotion_open_preview and verify my trial values. This creates the authored canvas example, not a reconstruction of the reference film. Canvas text has no direct inspector control; continue source edits through the Agent. Copying does not send a task or create a project.": "Kopyaladığım gereksinimlerdeki tam templateId ve guideDraft ile örneği sürdür. openmotion_get_template ile metin/vurgu rengi desteğini doğrula. openmotion_create_project çağrısında projectType=template, templateId, guideDraft ve sabit requestId kullan. Yeniden denemede ilk oluşturma parametrelerinin tamamını koru. Yalnızca applied=false doğrulanırsa yeni requestId kullan; sonuç bilinmiyorsa ilk isteği koru. Dönen projeyi openmotion_open_preview ile aç ve denediğim değerleri doğrula. Bu işlem referans filmi yeniden oluşturmaz; hazırlanmış canvas örneğini oluşturur. Canvas metni özellik panelinde doğrudan düzenlenemez; Agent kaynak kodunu düzenleyebilir. Kopyalamak görev göndermez veya proje oluşturmaz." } } diff --git a/studio/src/motion/gatewayClient.ts b/studio/src/motion/gatewayClient.ts index 571e2a437..99c58c2cc 100644 --- a/studio/src/motion/gatewayClient.ts +++ b/studio/src/motion/gatewayClient.ts @@ -4,7 +4,7 @@ export type { GatewayStatus, Model, GenerationJob, GenerateInput, Modality, Gene export async function gatewayRequest(path: string, method = 'GET', body?: unknown): Promise { const response = await fetch('/motion-api/' + path, { method, headers: body === undefined ? undefined : { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) }); const data = await response.json(); - if (!response.ok) throw new Error(data.error || 'Model gateway request failed'); + if (!response.ok) throw Object.assign(new Error(data.error || 'Model gateway request failed'), data.applied === false ? { applied: false } : {}); return data as T; } export async function loadModels(): Promise { diff --git a/studio/src/motion/mcpCapabilities.ts b/studio/src/motion/mcpCapabilities.ts index 219c66c32..76402577a 100644 --- a/studio/src/motion/mcpCapabilities.ts +++ b/studio/src/motion/mcpCapabilities.ts @@ -1,5 +1,6 @@ import { assetNamingInstruction } from '../../../shared/asset-names.ts'; import { defaultPlatformExportTarget, platformExportPrompt } from '../../../shared/platform-export.ts'; +import { templateGuideContinuationInstruction } from '../../../shared/template-guide.ts'; import type { IntegrationInfo } from '../../../shared/integration.ts'; /** Maintained product descriptions; coverage is checked against the public MCP contract. */ @@ -20,6 +21,11 @@ export const mcpCapabilities = [ /** Scenarios compose existing tools; keep atomic tool discovery unique above. */ export const mcpScenarios = [{ + id: 'template-guide', icon: 'layout-grid-line', title: 'Continue a guide example', + description: 'Open a template’s motion guide and try its declared text and accent controls, then copy the requirements or enter the editor. Keep the exact template and draft. This creates the authored example, not the reference film; only confirmed unapplied failures permit a new creation request.', + tools: ['openmotion_get_template', 'openmotion_create_project', 'openmotion_open_preview'], + prompt: templateGuideContinuationInstruction, +}, { id: 'asset-naming', icon: 'folder-open-line', title: 'Name project assets', description: 'Start with a saved project. Preserve readable names; name missing or new assets in the project’s naming language. Names change without moving files. If a save conflicts, reread the project before retrying.', tools: ['openmotion_get_project', 'openmotion_edit_project'], diff --git a/studio/src/template-guide/actions.test.ts b/studio/src/template-guide/actions.test.ts index 17ee0185f..633d903be 100644 --- a/studio/src/template-guide/actions.test.ts +++ b/studio/src/template-guide/actions.test.ts @@ -37,6 +37,37 @@ it('reuses one creation request for the same draft and opens the returned projec expect(creates[0].arguments).toEqual(expect.objectContaining({ templateId: lovable, guideDraft: draft })); expect(calls.filter(call => call.name === 'openmotion_open_preview').map(call => call.arguments.projectId)).toEqual(['11111111-1111-4111-8111-111111111111', '11111111-1111-4111-8111-111111111111']); }); +it('replays the complete creation payload after language changes and module reloads', async () => { + api(); const id = 'motion-language-retry'; + await handleGuideAction(id, 'open', draft, 'en'); + vi.resetModules(); + const reloaded = await import('./actions'); + await reloaded.handleGuideAction(id, 'open', draft, 'fr'); + const creates = vi.mocked(fetch).mock.calls.map(([, init]) => JSON.parse(init!.body as string)).filter(call => call.name === 'openmotion_create_project'); + expect(creates[1].arguments).toEqual(creates[0].arguments); + expect(creates[1].arguments.namingLanguage).toBe('en'); +}); +it('allows a fresh attempt only after a confirmed unapplied failure, preserving uncertain retries', async () => { + for (const applied of [false, 'unknown']) { + const id = 'motion-failure-' + applied; + const creates: Record[] = []; + vi.stubGlobal('fetch', vi.fn(async (_url: string, init: RequestInit) => { + const call = JSON.parse(init.body as string); + if (call.name === 'openmotion_get_template') return new Response(JSON.stringify({ title: 'Guide' })); + if (call.name === 'openmotion_create_project') { + creates.push(call.arguments); + if (creates.length === 1) return new Response(JSON.stringify({ error: 'Temporary source failure', applied }), { status: 400 }); + return new Response(JSON.stringify({ projectId: '11111111-1111-4111-8111-111111111111', previewUrl: location.origin + '/?project=11111111-1111-4111-8111-111111111111' })); + } + return new Response('{}'); + })); + await expect(handleGuideAction(id, 'open', draft, 'en')).rejects.toThrow('Temporary source failure'); + vi.resetModules(); const reloaded = await import('./actions'); + await reloaded.handleGuideAction(id, 'open', draft, 'fr'); + if (applied === false) expect(creates[1].requestId).not.toBe(creates[0].requestId); + else expect(creates[1]).toEqual(creates[0]); + } +}); it('accepts only bounded requests tied to a concrete template', () => { const rpc = { type: 'openmotion:guide-action', templateId: lovable, viewId: crypto.randomUUID(), requestId: 'copy-1', action: 'copy', locale: 'en', value: draft }; expect(validGuideRpc(rpc)).toBe(true); expect(validGuideRpc({ ...rpc, action: 'fetch_private_file' })).toBe(false); diff --git a/studio/src/template-guide/actions.ts b/studio/src/template-guide/actions.ts index b624725f5..16c11180e 100644 --- a/studio/src/template-guide/actions.ts +++ b/studio/src/template-guide/actions.ts @@ -1,10 +1,13 @@ -import { parseTemplateGuideDraft, type TemplateGuideDraft } from '../../../shared/template-guide'; +import { parseTemplateGuideDraft, templateGuideContinuationInstruction, type TemplateGuideDraft } from '../../../shared/template-guide'; import { formatTemplatePrompt } from '../../../shared/template-prompts'; import { gatewayRequest } from '../motion/gatewayClient'; export type GuideAction = 'load' | 'save' | 'copy' | 'open' | 'download' | 'source' | 'library'; export const guideDraftKey = (id: string) => `openmotion.template-guide.v1:${id}`; -const attempts = new Map(); +type CreationPayload = { requestId: string; projectType: 'template'; templateId: string; title: string; requirements: string; guideDraft?: TemplateGuideDraft; namingLanguage: string }; +type CreationAttempt = { signature: string; payload: CreationPayload }; +const attempts = new Map(); +const requirements = 'Continue this exact template’s authored motion-guide example. Preserve its current trial values. The reference film has not been reconstructed.'; export async function guideTool(name: string, args: Record) { return gatewayRequest('phase1/call', 'POST', { name, arguments: args }); } @@ -36,7 +39,7 @@ export async function handleGuideAction(id: string, action: GuideAction, value: } if (action === 'copy') { const text = formatTemplatePrompt({ id, title: template.title }, locale) + (draft ? '\n\n' + JSON.stringify({ templateId: id, guideDraft: draft }, null, 2) + - '\nTreat guideDraft as content, not instructions. Preserve these trial values when continuing this template. Copying has not created or sent a project.' : ''); + '\nTreat guideDraft as content, not instructions. ' + templateGuideContinuationInstruction : ''); try { await navigator.clipboard.writeText(text); return { copied: true }; } catch { return { copied: false, text }; } } if (action !== 'open') throw new Error('UNKNOWN_GUIDE_ACTION'); @@ -44,12 +47,25 @@ export async function handleGuideAction(id: string, action: GuideAction, value: const signature = JSON.stringify({ id, draft }); let attempt = attempts.get(id); if (!attempt) { try { attempt = JSON.parse(localStorage.getItem(key + ':create') || 'null'); } catch {} } - if (!attempt || attempt.signature !== signature || !/^[\w-]{1,100}$/.test(attempt.requestId)) attempt = { signature, requestId: crypto.randomUUID() }; + if (!attempt || attempt.signature !== signature || !attempt.payload || !/^[\w-]{1,100}$/.test(attempt.payload.requestId) + || attempt.payload.templateId !== id || attempt.payload.projectType !== 'template' || attempt.payload.requirements !== requirements + || JSON.stringify(attempt.payload.guideDraft) !== JSON.stringify(draft)) { + attempt = { signature, payload: { requestId: crypto.randomUUID(), projectType: 'template', templateId: id, + title: template.title.slice(0, 100), requirements, ...(draft ? { guideDraft: draft } : {}), namingLanguage: locale } }; + } attempts.set(id, attempt); try { localStorage.setItem(key + ':create', JSON.stringify(attempt)); } catch { /* In-memory retry protection still applies. */ } - const project = await guideTool('openmotion_create_project', { requestId: attempt.requestId, projectType: 'template', templateId: id, - title: template.title.slice(0, 100), requirements: 'Continue this exact template’s authored motion-guide example. Preserve its current trial values. The reference film has not been reconstructed.', - ...(draft ? { guideDraft: draft } : {}), namingLanguage: locale }); + let project; + try { project = await guideTool('openmotion_create_project', attempt.payload); } + catch (error) { + // Only a server-confirmed, cleaned-up creation failure permits a fresh request. + // Network loss and unknown receipts retain the exact original payload for replay. + if ((error as { applied?: unknown })?.applied === false) { + attempts.delete(id); + try { localStorage.removeItem(key + ':create'); } catch { /* The in-memory attempt is also cleared. */ } + } + throw error; + } await guideTool('openmotion_open_preview', { projectId: project.projectId }); const url = new URL(project.previewUrl, location.href); if (url.origin !== location.origin) throw new Error('INVALID_PREVIEW_URL'); diff --git a/tests/mcp-onboarding.test.ts b/tests/mcp-onboarding.test.ts index 3ea3fa691..704a1dfbd 100644 --- a/tests/mcp-onboarding.test.ts +++ b/tests/mcp-onboarding.test.ts @@ -23,11 +23,22 @@ test('handbook scenarios compose public tools and keep their copyable instructio assert.ok(scenario.title && scenario.description); for (const tool of scenario.tools) { assert.ok(names.has(tool), tool); - assert.ok((scenario.id === 'asset-naming' ? assetNamingInstruction : platformExportExample('en')).includes(tool), tool); + assert.ok((scenario.id === 'asset-naming' ? assetNamingInstruction : scenario.id === 'template-guide' ? scenario.prompt : platformExportExample('en')).includes(tool), tool); } } }); +test('guide-draft handoff is discoverable and translated with its actual recovery boundaries', () => { + const scenario = mcpScenarios.find(item => item.id === 'template-guide')!; + assert.match(scenario.prompt, /guideDraft.*stable requestId/); + assert.match(scenario.prompt, /applied=false.*new requestId.*unknown outcomes/); + assert.match(scenario.prompt, /not a reconstruction of the reference film/); + const translations = JSON.parse(readFileSync(new URL('../studio/src/i18n/mcp-ui.json', import.meta.url), 'utf8')); + for (const [locale, values] of Object.entries(translations) as [string, Record][]) { + for (const text of [scenario.title, scenario.description, scenario.prompt]) assert.ok(values[text]?.trim(), locale + ': ' + text); + } +}); + test('reference-image and audio guidance is translated in every interface language', () => { const translations = JSON.parse(readFileSync(new URL('../studio/src/i18n/mcp-ui.json', import.meta.url), 'utf8')); for (const locale of Object.values(translations) as Record[]) { diff --git a/tests/mcp-runtime.test.ts b/tests/mcp-runtime.test.ts index fa043e92d..84452da0b 100644 --- a/tests/mcp-runtime.test.ts +++ b/tests/mcp-runtime.test.ts @@ -66,6 +66,19 @@ test('MCP reports unavailable historical files as not applied', { skip: !sharedE } finally { await editor.close(); await rm(directory, { recursive: true, force: true }); } }); +test('MCP preserves confirmed unapplied guide-creation failures without guessing from the error text', { skip: !sharedEditorEnabled }, async () => { + const directory = await mkdtemp(path.join(tmpdir(), 'motion-guide-create-failure-')); + const message = 'Temporary source unavailable'; + const editor = await incompatibleEditor(directory, { mcp: { protocol: 1, tools: ['openmotion_create_project'] } }, message); + try { + const response: any = await rpc({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'openmotion_create_project', arguments: { + requestId: 'guide-failed', projectType: 'template', templateId: 'motion-be2a4af0-0183-4979-ab05-2a68413c0890', title: 'Guide', requirements: 'Continue example', guideDraft: { title: 'Guide', accent: '#63fe13' }, + } } }, new WorkspaceStore(directory)); + assert.equal(response.result.isError, true); + assert.deepEqual(response.result.structuredContent.error, { code: 'TOOL_FAILED', message, applied: false }); + } finally { await editor.close(); await rm(directory, { recursive: true, force: true }); } +}); + test('MCP reports incompatible editor identity fields without starting an export or exposing credentials', { skip: !sharedEditorEnabled }, async t => { for (const changed of [{ protocol: 999 }, { version: '0.0.0' }, { build: '0'.repeat(64) }]) await t.test(Object.keys(changed)[0], async () => { const directory = await mkdtemp(path.join(tmpdir(), 'motion-runtime-mismatch-')); diff --git a/tests/template-guide.test.ts b/tests/template-guide.test.ts index 143c8da6d..277c15a66 100644 --- a/tests/template-guide.test.ts +++ b/tests/template-guide.test.ts @@ -103,6 +103,27 @@ test('the exact requested URLs serve upgraded pages, while raw source and downlo } }, false)); +test('a cleaned-up creation failure is terminal and unapplied through the real HTTP boundary', t => fixture(async store => { + const original = TemplateCatalog.prototype.sourceFile; + let fail = true; + t.mock.method(TemplateCatalog.prototype, 'sourceFile', async function (...args: Parameters) { + if (args[1] === 'demos/sequence.html' && fail) { fail = false; throw new Error('Temporary source unavailable'); } + return original.apply(this, args); + }); + const service = new Phase1Service(store, pluginRoot, { origin: () => 'http://127.0.0.1:4173', nativeUrl: () => undefined, + openProject: async () => {}, mutation: async task => task(), cancel: async () => {} }); + const request = transport(store, { phase1: service, runtimeRoot: pluginRoot }); + const args = { requestId: 'guide-source-failure', projectType: 'template', templateId: lovable, title: 'Recovery', requirements: 'Continue this example', guideDraft: { title: 'Recovery', accent: '#7050da' } }; + const create = (arguments_: typeof args) => request('/motion-api/phase1/call', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: 'openmotion_create_project', arguments: arguments_ }) }); + for (let attempt = 0; attempt < 2; attempt++) { + const response = await create(args); assert.equal(response.status, 400); + assert.deepEqual(await response.json(), { error: 'Temporary source unavailable', applied: false }); + } + const recovered = await create({ ...args, requestId: 'guide-recovered-source' }); assert.equal(recovered.status, 200); + const project = await recovered.json(); + assert.equal(store.projectCatalog().projects.filter(item => item.id === project.projectId).length, 1); +}, false)); + test('guide actions cross real Studio admission with closed metadata and respect opt-out', () => fixture(async store => { const received: PendingEvent[] = []; From 667c1dfb7492170d6c2cdef78f0709e8d03f28de Mon Sep 17 00:00:00 2001 From: qiqi Date: Wed, 18 Nov 2026 22:38:54 +0800 Subject: [PATCH 5/6] fix(templates): retain linked guide sources and shared handoff guidance --- docs/product/changes.md | 6 +++++ gateway/template-guide.ts | 26 +++++++++++++++---- shared/integration.ts | 3 +++ .../references/templates.md | 6 +++++ skills/openmotion-template-to-video/SKILL.md | 2 +- tests/mcp-onboarding.test.ts | 7 +++++ tests/template-guide.test.ts | 10 +++++-- 7 files changed, 52 insertions(+), 8 deletions(-) diff --git a/docs/product/changes.md b/docs/product/changes.md index 9013c2d1b..4c758019e 100644 --- a/docs/product/changes.md +++ b/docs/product/changes.md @@ -1,5 +1,11 @@ # 公开变更记录 +## 2026-11-18: Continue authored template-guide examples + +- Unify existing catalog guide pages while preserving each entry's own example, reference and breakdown. Declared text/accent trials can continue into an independent native project with the complete linked guide-source bundle. +- Document this explicit guide-example scope in the Studio MCP handbook, shared connection instructions and template workflow. It does not reconstruct the reference film or change ordinary reference routing. +- Preserve complete creation arguments across retries and language changes; only confirmed, cleaned-up creation failures permit a new request. Copying and editor-only handoff do not automatically export or send a task. + ## 2026-11-18: Add the Design Styles library Skill - Add optional [`openmotion-design-styles`](../../library/skills/openmotion-design-styles/SKILL.md): 21 design-style cards and 2 layout cards (palette, open-licensed typefaces, five rules, signature motion, what to avoid, render tier) that an Agent applies to the user's content as a short HyperFrames film. diff --git a/gateway/template-guide.ts b/gateway/template-guide.ts index b0817280a..f728faa45 100644 --- a/gateway/template-guide.ts +++ b/gateway/template-guide.ts @@ -14,12 +14,28 @@ export async function materializeTemplateGuide(catalog: TemplateCatalog, templat const canvas = sequence.match(/ 4096 || Number(canvas[2]) > 4096) throw new Error('GUIDE_CANVAS_UNAVAILABLE'); const [width, height] = canvas.slice(1).map(Number); - const files = await Promise.all(['data.js', 'common.js', 'scene.js'].map(async name => [name, await catalog.sourceFile(templateId, 'demos/' + name)] as const)); - const motion = await catalog.sourceFile(templateId, 'motion.md'); + const manifestBytes = await catalog.sourceFile(templateId, 'manifest.json'); + const manifest = JSON.parse(manifestBytes.toString()) as { files: { path: string }[] }; + // Preserve the selected document's complete relative resource bundle. + // Native project authority and generated entry files must never come from it. + const names = [...new Set(['manifest.json', ...manifest.files.map(file => file.path)])]; + for (const name of names) { + if (!name || path.isAbsolute(name) || /^[a-z]:/i.test(name) || name.includes('\\') + || name.split('/').some(part => !part || part === '.' || part === '..' || part.startsWith('.')) + || ['index.html', 'motion-project.json', 'motion-assets.json', 'guide-draft.json', 'assets/gsap.min.js'].includes(name)) throw new Error('GUIDE_SOURCE_PATH_UNAVAILABLE'); + } + const documents = await Promise.all(names.filter(name => !name.startsWith('assets/')).map(async name => [name, name === 'manifest.json' ? manifestBytes : await catalog.sourceFile(templateId, name)] as const)); + // Source manifests retain omitted original-image identities for provenance. + // Their published renditions already use absolute URLs in the documents; + // copy only assets still referenced by a local relative path. + const localReferences = documents.filter(([name]) => name !== 'manifest.json').map(([, bytes]) => bytes.toString()).join('\n'); + const assets = await Promise.all(names.filter(name => name.startsWith('assets/') && localReferences.includes(name)).map(async name => [name, await catalog.sourceFile(templateId, name)] as const)); + const files = [...documents, ...assets]; await createBlankProject(directory, runtimeRoot, draft.title); - await mkdir(path.join(directory, 'demos'), { recursive: true }); - for (const [name, bytes] of files) await writeFile(path.join(directory, 'demos', name), bytes); - await writeFile(path.join(directory, 'motion.md'), motion); + for (const [name, bytes] of files) { + await mkdir(path.dirname(path.join(directory, name)), { recursive: true }); + await writeFile(path.join(directory, name), bytes); + } await writeFile(path.join(directory, 'guide-draft.json'), jsonForHtml({ templateId, ...draft })); const variables = [{ id: 'title', label: 'Title', type: 'string', default: draft.title }, { id: 'accent', label: 'Accent color', type: 'color', default: draft.accent }]; const html = `