The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
fix(motion): cache template downloads and show neutral loading state (#181)
open-design-crew[bot]3e67e29c1ee6
diff --git a/docs/template-catalog.md b/docs/template-catalog.mdindex c08f863c..24e9563b 100644--- a/docs/template-catalog.md+++ b/docs/template-catalog.md@@ -30,6 +30,7 @@ DEV 的默认工作区另加 `-dev`,与线上后台进程、工程和缓存分- 可用 `MOTION_TEMPLATE_RESOURCE_ID`、`MOTION_TEMPLATE_LOCALE` 指定 Resource 和语言。缓存位于当前 Motion 数据目录的 `template-cache`,按来源和语言隔离,不能手工修改。- 按需用 ETag / If-None-Match 检查发布,304 复用已下载内容;DEV 最短间隔 2 秒,prod 60 秒。当前目录约 120 KB,直接缓存 main.json,不另加 manifest 下载链。- 发布成功的目录整体替换;网络或内容读取失败时保留上次有效缓存并返回 warning。首次读取无缓存时明确失败。+- Template files download with at most four concurrent requests. Verified bytes are cached locally and rechecked against the manifest before reuse; each project gets independent files. A corrupt cache entry is downloaded again. Failed copies wait for pending writes before removing the incomplete project.- 打开的模板界面每 5 秒检查目录版本,变化后更新列表,保留搜索条件,不重启编辑器或改写已有工程。保存 CMS 草稿不触发变化,需发布 DEV。### MCPdiff --git a/prism-templates.ts b/prism-templates.tsindex 2a33410b..c0a0f65f 100644--- a/prism-templates.ts+++ b/prism-templates.ts@@ -21,7 +21,7 @@ export type EditableTemplate = GalleryTemplate & { files?: TemplateFile[]; catalconst builtinTemplates = libraryTemplates.filter(template => template.kind === 'builtin');const hash = (value: string | Buffer) => createHash('sha256').update(value).digest('hex');-async function atomicWrite(filename: string, content: string): Promise<void> {+async function atomicWrite(filename: string, content: string | Buffer): Promise<void> {await mkdir(path.dirname(filename), { recursive: true });const temporary = filename + '.' + randomUUID();await writeFile(temporary, content);@@ -155,10 +155,19 @@ export class TemplateCatalog {private async downloadFile(file: TemplateFile): Promise<Buffer> {const url = new URL(file.url);if (url.protocol !== 'https:' || url.hostname !== 'r.open-design.ai' || !url.pathname.startsWith('/files/')) throw new Error('模板文件地址无效');+ const cachedPath = path.join(this.directory, 'files', hash(file.url));+ const matches = (bytes: Buffer) => bytes.length === file.bytes && hash(bytes) === file.sha256;+ try {+ const cached = await readFile(cachedPath);+ if (matches(cached)) return cached;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }const response = await this.request(url, { redirect: 'error', signal: AbortSignal.timeout(30_000) });if (!response.ok) throw new Error(`模板文件下载失败:${file.path}(HTTP ${response.status})`);const bytes = Buffer.from(await response.arrayBuffer());- if (bytes.length !== file.bytes || hash(bytes) !== file.sha256) throw new Error(`模板文件校验失败:${file.path}`);+ if (!matches(bytes)) throw new Error(`模板文件校验失败:${file.path}`);+ await atomicWrite(cachedPath, bytes);return bytes;}@@ -167,11 +176,19 @@ export class TemplateCatalog {if (!template.files?.some(file => file.path === 'index.html')) throw new Error('模板缺少 index.html');for (const file of template.files) {if (!file.path || path.isAbsolute(file.path) || file.path.includes('\\') || file.path.split('/').some(part => !part || part === '..' || part === '.')) throw new Error('模板文件路径无效');- const bytes = await this.downloadFile(file);- const target = path.join(directory, file.path);- await mkdir(path.dirname(target), { recursive: true });- await writeFile(target, bytes, { flag: 'wx' });}+ const files = template.files.values();+ const workers = await Promise.allSettled(Array.from({ length: Math.min(4, template.files.length) }, async () => {+ for (const file of files) {+ const bytes = await this.downloadFile(file);+ const target = path.join(directory, file.path);+ await mkdir(path.dirname(target), { recursive: true });+ await writeFile(target, bytes, { flag: 'wx' });+ }+ }));+ // Settle all writes before the caller removes a failed project directory.+ const failed = workers.find(result => result.status === 'rejected');+ if (failed) throw failed.reason;}}diff --git a/studio/src/motion/ConnectionDialog.tsx b/studio/src/motion/ConnectionDialog.tsxindex 6c12d6a6..8118f903 100644--- a/studio/src/motion/ConnectionDialog.tsx+++ b/studio/src/motion/ConnectionDialog.tsx@@ -45,7 +45,7 @@ export function ConnectionDialog(props: Props) {</div><button id="close-connections" className="ui-button ui-button--ghost ui-button--icon" aria-label={t("Close MCP connection")} disabled={props.busy} onClick={props.onClose}><MotionIcon name="close" /></button></div>- {(props.error || props.busy) && <p className="connect-error" role="status">{props.error ? t(props.error) : t('Preparing editable project…')}</p>}+ {props.error ? <p className="connect-error" role="alert">{t(props.error)}</p> : props.busy && <p className="connect-progress" role="status"><span className="connect-progress-spinner" aria-hidden="true" />{t('Preparing editable project…')}</p>}<div id="connection-root" ref={root} /></dialog>;}diff --git a/tests/prism-templates.test.ts b/tests/prism-templates.test.tsindex bd256fa0..18cdd907 100644--- a/tests/prism-templates.test.ts+++ b/tests/prism-templates.test.ts@@ -1,6 +1,6 @@import test from 'node:test';import assert from 'node:assert/strict';-import { mkdtemp, readFile, readdir, rm, stat } from 'node:fs/promises';+import { mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import path from 'node:path';import { execFileSync } from 'node:child_process';@@ -130,3 +130,20 @@ test('template files cannot escape the destination; known built-ins work withoutremote.offline();assert.equal((await catalog.get('product-promo')).kind, 'builtin');});++test('reopening a template reuses verified files without sharing mutable project files', async t => {+ const directory = await mkdtemp(path.join(tmpdir(), 'motion-prism-files-'));+ t.after(() => rm(directory, { recursive: true, force: true }));+ const remote = mockPrism();+ const catalog = new TemplateCatalog(directory, { fetch: remote.request });+ const template = await catalog.get('test-motion-1');+ await catalog.copy(template, path.join(directory, 'first'), pluginRoot);+ await writeFile(path.join(directory, 'first', 'index.html'), 'User edits');+ const requests = remote.requests.length;+ remote.offline();+ const reopened = new TemplateCatalog(directory, { fetch: remote.request });+ await reopened.copy(template, path.join(directory, 'second'), pluginRoot);+ assert.equal(remote.requests.length, requests);+ assert.equal(await readFile(path.join(directory, 'second', 'index.html'), 'utf8'), contents['index.html']);+ assert.equal((await reopened.detail('test-motion-1')).instructions, contents['TEMPLATE.md']);+});diff --git a/web/connect.css b/web/connect.cssindex b25352a8..e978c694 100644--- a/web/connect.css+++ b/web/connect.css@@ -1114,6 +1114,10 @@.connect-workspace dt { color: var(--motion-muted); }.connect-workspace dd { margin: 0; overflow-wrap: anywhere; }.connect-error { padding: var(--motion-space-12) var(--motion-space-16); margin-top: var(--motion-space-16); background: var(--motion-danger-soft); color: var(--motion-danger); border-radius: var(--motion-radius-sm); font-size: var(--motion-text-sm); line-height: var(--motion-leading-prose); text-align: left; }+.connect-progress { display: flex; align-items: center; gap: var(--motion-space-8); padding: var(--motion-space-12) var(--motion-space-16); margin: 0; background: var(--motion-panel); color: var(--motion-muted); font-size: var(--motion-text-sm); }+.connect-progress-spinner { width: var(--motion-space-16); height: var(--motion-space-16); flex-shrink: 0; border: 2px solid var(--motion-border); border-top-color: currentColor; border-radius: 50%; animation: connect-progress-spin var(--motion-duration-loading) linear infinite; }+@keyframes connect-progress-spin { to { transform: rotate(360deg); } }+@media (prefers-reduced-motion: reduce) { .connect-progress-spinner { animation: none; } }.connect-api { margin-top: var(--motion-space-24); padding-top: var(--motion-space-20); border-top: 1px solid var(--motion-border); }.connect-api h3 { font-size: var(--motion-text-heading); }.connect-template-media { position: relative; display: flex; align-items: center; justify-content: center; overflow: hidden; }