@lalalic/markcut 3.2.59 → 3.2.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +20 -4
  2. package/bin/markcut +10 -0
  3. package/docs/developer-reference.md +41 -1
  4. package/package.json +8 -2
  5. package/recipes/markcut/map-cinematic-follow.json +17 -0
  6. package/recipes/markcut/map-location-reveal.json +17 -0
  7. package/recipes/markcut/map-route-journey.json +18 -0
  8. package/recipes/markcut/map-streetview-explore.json +17 -0
  9. package/skills/markcut/SKILL.md +5 -1
  10. package/skills/markcut/docs/markdown-descriptive.md +68 -1
  11. package/skills/markcut/docs/recipes.md +45 -0
  12. package/skills/markcut/references/mobile-event-preview-cli.md +9 -5
  13. package/src/descriptive/compiler.ts +38 -2
  14. package/src/descriptive/markdown.ts +30 -0
  15. package/src/descriptive/model3d.test.ts +38 -0
  16. package/src/editor-decision/cli.mjs +21 -0
  17. package/src/editor-decision/editor-decision.schema.json +41 -0
  18. package/src/editor-decision/index.mjs +115 -0
  19. package/src/editor-decision/index.test.mjs +63 -0
  20. package/src/mcp/bridge.mjs +46 -9
  21. package/src/mcp/compile-worker.mjs +2 -2
  22. package/src/mcp/mobile-review-cli.mjs +40 -33
  23. package/src/mcp/preview-mobile.css +23 -10
  24. package/src/mcp/preview.mjs +95 -56
  25. package/src/mcp/remote-assets.mjs +85 -7
  26. package/src/mcp/remotion-app.bundle.js +5013 -1117
  27. package/src/mcp/remotion-app.tsx +117 -10
  28. package/src/mcp/server.mjs +4 -2
  29. package/src/player/browser.tsx +1 -3
  30. package/src/player/bundle/player.js +73054 -17357
  31. package/src/player/components/HeaderBar.tsx +3 -1
  32. package/src/player/components/VariantBar.tsx +20 -21
  33. package/src/player/pipeline.mjs +133 -77
  34. package/src/player/server.mjs +43 -23
  35. package/src/recipes/catalog.mjs +115 -0
  36. package/src/recipes/cli.mjs +87 -0
  37. package/src/render/cli.mjs +38 -1
  38. package/src/schema/index.ts +21 -0
  39. package/src/types/Folder.tsx +2 -0
  40. package/src/types/Model3D.tsx +91 -0
  41. package/src/vision/cli.mjs +63 -50
  42. package/tests/mcp-editor-decisions-mobile.test.ts +35 -0
  43. package/tests/mcp-preview-bridge.test.ts +44 -3
  44. package/tests/mcp-preview-proxy-version.test.mjs +80 -0
  45. package/tests/mcp-preview.test.ts +43 -10
  46. package/tests/mcp-remote-assets.test.ts +17 -0
  47. package/tests/mcp-static-preview.test.ts +1 -1
  48. package/tests/mcp-video-selector.test.ts +55 -0
  49. package/tests/mobile-preview-cli.test.ts +10 -15
  50. package/tests/recipes-catalog.test.ts +141 -0
  51. package/tests/vision-generic-vtt-hooks.test.ts +7 -7
  52. package/tests/vision-normalized-metadata.test.ts +23 -0
@@ -95,6 +95,23 @@ function loadMetadata(folder) {
95
95
  const path = join(folder, "metadata.json");
96
96
  try {
97
97
  const raw = JSON.parse(readFileSync(path, "utf-8"));
98
+ // Metadata keys are exact source filenames, including their extensions.
99
+ // Re-key any existing basename-only data when there is one unambiguous match.
100
+ const media = [...scanMedia(folder).images, ...scanMedia(folder).videos];
101
+ const byStem = new Map();
102
+ for (const source of media) {
103
+ const stem = basename(source, extname(source));
104
+ byStem.set(stem, [...(byStem.get(stem) || []), basename(source)]);
105
+ }
106
+ for (const [stem, names] of byStem) {
107
+ if (Object.hasOwn(raw, stem)) {
108
+ if (names.length === 1 && !Object.hasOwn(raw, names[0])) raw[names[0]] = raw[stem];
109
+ // A stem-only entry is ambiguous when both photo.jpg and photo.mp4 exist.
110
+ delete raw[stem];
111
+ }
112
+ }
113
+ const files = new Set(media.map(source => basename(source)));
114
+ for (const name of Object.keys(raw)) if (!files.has(name)) delete raw[name];
98
115
  const cacheMap = {};
99
116
  for (const [key, entry] of Object.entries(raw)) {
100
117
  if (entry._cache && entry.perception?.desc) {
@@ -281,7 +298,7 @@ function tryParseGPS(val, ref) {
281
298
 
282
299
  function normalizeImage(srcPath, normDir, maxDim = MAX_IMAGE_DIMENSION) {
283
300
  const srcExt = extname(srcPath);
284
- const outName = `${basename(srcPath, srcExt)}_${maxDim}.jpg`;
301
+ const outName = `${basename(srcPath)}_${maxDim}.jpg`;
285
302
  const outPath = join(normDir, outName);
286
303
  if (existsSync(outPath)) return outPath;
287
304
  const filter = `scale='min(${maxDim},iw)':'min(${maxDim},ih)':force_original_aspect_ratio=decrease`;
@@ -293,35 +310,30 @@ function normalizeImage(srcPath, normDir, maxDim = MAX_IMAGE_DIMENSION) {
293
310
  function normalizeVideo(srcPath, normDir, duration, maxDim = MAX_VIDEO_DIMENSION, maxDur = MAX_VIDEO_DURATION, maxSamples = 60) {
294
311
  const srcExt = extname(srcPath); // Keep original case for basename stripping
295
312
  const ext = srcExt.toLowerCase() || ".mp4";
296
- const base = basename(srcPath, srcExt);
313
+ const base = basename(srcPath);
297
314
  const totalDur = duration || getVideoDuration(srcPath);
298
315
 
299
- if (totalDur <= maxDur) {
300
- const timeHint = `0to${Math.floor(totalDur)}`;
301
- const outName = `${base}_${timeHint}.mp4`;
302
- const outPath = join(normDir, outName);
303
- if (existsSync(outPath)) return { path: outPath, trimmedDuration: totalDur, timeHint };
304
- const filter = `scale='min(${maxDim},iw)':'min(${maxDim},ih)':force_original_aspect_ratio=decrease,pad='ceil(iw/2)*2':'ceil(ih/2)*2':-1:-1`;
305
- const cmd = `ffmpeg -y -i ${shQuote(srcPath)} -t ${totalDur} -map_metadata -1 -map_chapters -1 -vf ${shQuote(filter)} -c:v libx264 -preset fast -crf 28 -c:a aac -b:a 64k ${shQuote(outPath)}`;
306
- try { run(cmd, { timeout: 600_000 }); return { path: outPath, trimmedDuration: totalDur, timeHint }; }
307
- catch (e) { emitWarn(`Failed to normalize video ${basename(srcPath)}: ${e.message}`); return { path: srcPath, trimmedDuration: totalDur, timeHint }; }
316
+ // Preserve the complete original time axis for preview and segment lookup.
317
+ // Vision frame sampling belongs in the model adapter, not in the proxy.
318
+ const timeHint = "full";
319
+ const outPath = join(normDir, `${base}_full.mp4`);
320
+ if (existsSync(outPath)) {
321
+ // Earlier releases used the same _full.mp4 name for a 1 fps sample reel.
322
+ // Reject that cache when its duration differs from the original timeline.
323
+ const cachedDuration = getVideoDuration(outPath);
324
+ if (cachedDuration > 0 && Math.abs(cachedDuration - totalDur) < 0.5)
325
+ return { path: outPath, trimmedDuration: totalDur, timeHint };
326
+ rmSync(outPath, { force: true });
308
327
  }
309
-
310
- const timeHint = `full`;
311
- const outName = `${base}_${timeHint}.mp4`;
312
- const outPath = join(normDir, outName);
313
- if (existsSync(outPath)) return { path: outPath, trimmedDuration: totalDur, timeHint };
314
-
315
- const frameCount = getVideoFrameCount(srcPath);
316
- const step = Math.max(1, Math.floor(frameCount / maxSamples));
317
- const actualSamples = Math.min(maxSamples, Math.ceil(frameCount / step));
318
- const filter = `select='not(mod(n,${step}))',setpts=N/TB,scale='min(${maxDim},iw)':'min(${maxDim},ih)':force_original_aspect_ratio=decrease,pad='ceil(iw/2)*2':'ceil(ih/2)*2':-1:-1`;
319
- const cmd = `ffmpeg -y -i ${shQuote(srcPath)} -map_metadata -1 -map_chapters -1 -vf ${shQuote(filter)} -c:v libx264 -preset fast -crf 28 -an -t ${actualSamples} -r 1 ${shQuote(outPath)}`;
328
+ const filter = `scale='min(${maxDim},iw)':'min(${maxDim},ih)':force_original_aspect_ratio=decrease,pad='ceil(iw/2)*2':'ceil(ih/2)*2':-1:-1`;
329
+ const cmd = `ffmpeg -y -i ${shQuote(srcPath)} -map_metadata -1 -map_chapters -1 -vf ${shQuote(filter)} -c:v libx264 -preset fast -crf 28 -c:a aac -b:a 64k -movflags +faststart ${shQuote(outPath)}`;
320
330
  try {
321
- emitInfo(` Sampling ${actualSamples} frames across ${totalDur.toFixed(1)}s video`);
322
331
  run(cmd, { timeout: 600_000 });
323
332
  return { path: outPath, trimmedDuration: totalDur, timeHint };
324
- } catch (e) { emitWarn(`Failed to normalize video ${basename(srcPath)}: ${e.message}`); return { path: srcPath, trimmedDuration: totalDur, timeHint }; }
333
+ } catch (e) {
334
+ emitWarn(`Failed to normalize video ${basename(srcPath)}: ${e.message}`);
335
+ return { path: srcPath, trimmedDuration: totalDur, timeHint };
336
+ }
325
337
  }
326
338
 
327
339
  function getVideoDuration(filePath) {
@@ -616,7 +628,7 @@ async function runMetadataMode(folder, pickSet, dryRun) {
616
628
 
617
629
  for (const filePath of [...images, ...videos]) {
618
630
  if (pickSet.size > 0 && !pickSet.has(basename(filePath))) continue;
619
- const base = basename(filePath, extname(filePath));
631
+ const base = basename(filePath);
620
632
  const isVideo = VIDEO_EXTS.has(extname(filePath).toLowerCase());
621
633
  emitInfo(`\n${isVideo ? "🎬" : "📷"} ${base}`);
622
634
 
@@ -650,7 +662,7 @@ function buildPreviewTree(folder, metadata) {
650
662
  for (const f of allFiles) {
651
663
  const st = statSync(join(folder, f));
652
664
  if (!st.isFile()) continue;
653
- const key = basename(f, extname(f)).toLowerCase();
665
+ const key = f.toLowerCase();
654
666
  if (!fileMap.has(key)) fileMap.set(key, f);
655
667
  }
656
668
 
@@ -997,7 +1009,7 @@ async function runFullPipeline(folder, prompts, context, pickSet, vttSampleInter
997
1009
  return;
998
1010
  }
999
1011
 
1000
- const metadata = JSON.parse(readFileSync(metadataPath, "utf-8"));
1012
+ const { results: metadata } = loadMetadata(folder);
1001
1013
  if (Object.keys(metadata).length === 0) {
1002
1014
  emitError("metadata.json is empty — no media found.");
1003
1015
  return;
@@ -1074,7 +1086,7 @@ async function runNormalizeAndPercept(folder, metadataPath, prompts, context, pi
1074
1086
  // Process images
1075
1087
  for (const fileName of imageFiles) {
1076
1088
  if (pickSet.size > 0 && !pickSet.has(fileName)) continue;
1077
- const base = basename(fileName, extname(fileName));
1089
+ const base = fileName;
1078
1090
  const meta = results[base];
1079
1091
  if (!meta) { emitWarn(` No metadata for ${fileName}, skipping.`); continue; }
1080
1092
  const userHint = meta.userHints?.overall || meta.userHint || "";
@@ -1101,7 +1113,7 @@ async function runNormalizeAndPercept(folder, metadataPath, prompts, context, pi
1101
1113
  if (perception.desc) cache[cacheKey] = perception;
1102
1114
  emitInfo(` ${perception.desc?.slice(0, 80)}...`);
1103
1115
  }
1104
- results[base] = { ...meta, perception, _cache: cacheKey };
1116
+ results[base] = { ...meta, normalized: normPath !== imgPath ? ".normalized/" + basename(normPath) : null, perception, _cache: cacheKey };
1105
1117
  writeFileSync(metadataPath, JSON.stringify(results, null, 2), "utf-8");
1106
1118
 
1107
1119
  // Enrich location for images too
@@ -1116,7 +1128,7 @@ async function runNormalizeAndPercept(folder, metadataPath, prompts, context, pi
1116
1128
  // Process videos
1117
1129
  for (const fileName of videoFiles) {
1118
1130
  if (pickSet.size > 0 && !pickSet.has(fileName)) continue;
1119
- const base = basename(fileName, extname(fileName));
1131
+ const base = fileName;
1120
1132
  const meta = results[base];
1121
1133
  if (!meta) { emitWarn(` No metadata for ${fileName}, skipping.`); continue; }
1122
1134
  const userHint = meta.userHints?.overall || meta.userHint || "";
@@ -1160,7 +1172,7 @@ async function runNormalizeAndPercept(folder, metadataPath, prompts, context, pi
1160
1172
  let location = meta.location;
1161
1173
  if (location) location = await enrichLocation(location);
1162
1174
 
1163
- results[base] = { ...meta, location, perception, _cache: cacheKey };
1175
+ results[base] = { ...meta, location, normalized: normInfo.path !== vidPath ? ".normalized/" + basename(normInfo.path) : null, perception, _cache: cacheKey };
1164
1176
  writeFileSync(metadataPath, JSON.stringify(results, null, 2), "utf-8");
1165
1177
  }
1166
1178
 
@@ -1182,7 +1194,7 @@ Usage:
1182
1194
 
1183
1195
  Options:
1184
1196
  --label Open interactive labeling preview before running AI pipeline
1185
- --normalize-only 360px video / 384px image inputs, full input-time mapping; long videos sampled; no AI
1197
+ --normalize-only Full-timeline 360px video / 384px image proxies; writes metadata.json; no AI
1186
1198
  --instruct "text" Background context about people/places (injected into prompts)
1187
1199
  --prompts-file <path> Path to prompts markdown file (default: vision_prompts.md)
1188
1200
  --vtt-sample-interval <n> Sample one video frame every N seconds (default: 5)
@@ -1282,30 +1294,31 @@ export async function main(args) {
1282
1294
  if (doLabel || candidateMode || dryRun || pickSet.size > 0) {
1283
1295
  throw new Error('--normalize-only cannot be combined with label, candidate, pick or dry-run');
1284
1296
  }
1285
- // Reuse exactly the normalization used by the VTT/ITT pipeline. No AI
1286
- // inference or full-resolution media is sent to an understanding model.
1287
1297
  const media = scanMedia(folder);
1288
1298
  if (media.images.length + media.videos.length === 0) throw new Error('No Vision Understanding source media');
1299
+ // Keep existing perception: normalization only edits proxy and source metadata.
1300
+ await runMetadataMode(folder, new Set(), false);
1301
+ const { results } = loadMetadata(folder);
1289
1302
  const normDir = join(folder, '.normalized');
1290
1303
  mkdirSync(normDir, { recursive: true });
1291
1304
  const files = [];
1292
- for (const original of media.images) {
1293
- const normalized = normalizeImage(original, normDir);
1294
- if (normalized === original || !existsSync(normalized)) throw new Error(`Failed to normalize Vision image: ${original}`);
1295
- files.push({ source: basename(original), path: normalized, kind: 'image', sampled: false,
1296
- maxDimension: MAX_IMAGE_DIMENSION });
1297
- }
1298
- for (const original of media.videos) {
1299
- const duration = getVideoDuration(original);
1300
- if (!Number.isFinite(duration) || duration <= 0) throw new Error(`Video has no usable duration: ${original}`);
1301
- const info = normalizeVideo(original, normDir, duration);
1302
- if (info.path === original || !existsSync(info.path)) throw new Error(`Failed to normalize Vision video: ${original}`);
1303
- files.push({ source: basename(original), path: info.path, kind: 'video',
1304
- sampled: duration > MAX_VIDEO_DURATION, sourceDurationSeconds: duration,
1305
- maxDimension: MAX_VIDEO_DIMENSION });
1305
+ for (const original of [...media.images, ...media.videos]) {
1306
+ const filename = basename(original);
1307
+ const image = IMAGE_EXTS.has(extname(original).toLowerCase());
1308
+ const duration = image ? null : getVideoDuration(original);
1309
+ const normalized = image ? normalizeImage(original, normDir)
1310
+ : duration > 0 ? normalizeVideo(original, normDir, duration).path : original;
1311
+ const usable = normalized !== original && existsSync(normalized);
1312
+ results[filename] = { ...results[filename],
1313
+ normalized: usable ? '.normalized/' + basename(normalized) : null,
1314
+ ...(image ? {} : {duration}) };
1315
+ files.push({ source: filename, path: usable ? normalized : original,
1316
+ kind: image ? 'image' : 'video', normalized: usable, sampled: false,
1317
+ ...(duration !== null ? {sourceDurationSeconds:duration} : {}),
1318
+ maxDimension: image ? MAX_IMAGE_DIMENSION : MAX_VIDEO_DIMENSION });
1306
1319
  }
1307
- console.log(JSON.stringify({ status: 'PASS', usage: 'vision-understanding-only',
1308
- profile: 'markcut-vision-normalized-v1', files }));
1320
+ writeFileSync(join(folder, 'metadata.json'), JSON.stringify(results, null, 2) + '\n');
1321
+ console.log(JSON.stringify({ status: 'PASS', profile: 'markcut-vision-normalized-v1', usage: 'vision-understanding-only', files }));
1309
1322
  return;
1310
1323
  }
1311
1324
  if (doLabel) {
@@ -0,0 +1,35 @@
1
+ import {describe,it,expect} from 'vitest';
2
+ import {mkdtemp,writeFile,mkdir,rm,readFile} from 'node:fs/promises';
3
+ import {tmpdir} from 'node:os';
4
+ import {join} from 'node:path';
5
+
6
+ describe('mobile compiled video + editorial decision preview',()=>{
7
+ it('serves a distinct compiled EDL tree through existing markcut.preview.media data contract',async()=>{
8
+ const root=await mkdtemp(join(tmpdir(),'markcut-mobile-edl-'));
9
+ const prevExport=process.env.MARKCUT_EXPORT_ROOT,prevOrigin=process.env.NEOY_PUBLIC_ORIGIN;
10
+ process.env.MARKCUT_EXPORT_ROOT=join(root,'exports');
11
+ process.env.NEOY_PUBLIC_ORIGIN='https://neoy.example.test';
12
+ try{
13
+ const {ensureVideoPreview,getPreviewMedia}=await import('../src/mcp/preview.mjs');
14
+ const file=join(root,'video.md');
15
+ await mkdir(join(root,'input','media'),{recursive:true});
16
+ await writeFile(join(root,'input','media','001.png'),Buffer.from('small-image-payload'));
17
+ await writeFile(file,'---\nedl: ./video.edl.json\n---\n# video\nwidth:320 height:568 fps:24 layout:series\n## Main\n- image src:input/media/001.png duration:1\n');
18
+ await writeFile(join(root,'video.edl.json'),JSON.stringify({schema_version:1,editorial_intent:'Show the quiet moment',edits:[
19
+ {shot_id:'detail',source_src:'input/media/001.png',in_seconds:0,out_seconds:1,editor_reason:'Hold for quiet'}
20
+ ]}));
21
+ const preview=await ensureVideoPreview(file);
22
+ const mobile=getPreviewMedia(preview.contentHash);
23
+ expect(preview.edlCompiledUrl).toContain('/files/_neoy/markcut/cache/');
24
+ expect(mobile.compiled.children.map((s:any)=>s.name)).toEqual(['Main']);
25
+ expect(mobile.editorDecisions.children.map((s:any)=>s.name)).toEqual(['EditorialIntent','Shot1']);
26
+ expect(JSON.stringify(mobile.editorDecisions)).toContain('Hold for quiet');
27
+ expect(JSON.stringify(mobile.editorDecisions)).toContain('/preview-files/_neoy/markcut/generated/');
28
+ expect((await readFile(join(root,'video.md'),'utf8'))).toContain('edl: ./video.edl.json');
29
+ }finally{
30
+ if(prevExport===undefined)delete process.env.MARKCUT_EXPORT_ROOT; else process.env.MARKCUT_EXPORT_ROOT=prevExport;
31
+ if(prevOrigin===undefined)delete process.env.NEOY_PUBLIC_ORIGIN; else process.env.NEOY_PUBLIC_ORIGIN=prevOrigin;
32
+ await rm(root,{recursive:true,force:true});
33
+ }
34
+ },20000);
35
+ });
@@ -11,8 +11,9 @@ function harness(remoteData?:any, fetchOverride?:(url:string)=>Promise<any>, too
11
11
  addEventListener(type:string,listener:Function){this.listeners[type]=listener},
12
12
  replaceChildren(){this.children=[]},append(...items:any[]){this.children.push(...items)}
13
13
  });
14
+ const actions=element();
14
15
  const nodes:Record<string,ReturnType<typeof element>>={
15
- feedback:element(),status:element(),'path-label':element(),'video-md-version':element(),'interactive-ui':element(),'comment-entry':element(),approve:element(),changes:element(),'save-spot':element(),'remove-spot':element(),'comment-target':element(),'comment-mode':element(),'overall-mode':element(),'review-delivery-mode':element()
16
+ feedback:element(),status:element(),'path-label':element(),'video-md-version':element(),'interactive-ui':element(),'comment-entry':element(),approve:element(),changes:element(),'questions-submit':element(),'save-spot':element(),'remove-spot':element(),'comment-target':element(),'comment-mode':element(),'overall-mode':element(),'review-delivery-mode':element()
16
17
  };
17
18
  nodes['comment-mode'].value='spot';
18
19
  let dispatch:(message:any,source?:any)=>void;
@@ -24,16 +25,56 @@ function harness(remoteData?:any, fetchOverride?:(url:string)=>Promise<any>, too
24
25
  dispatchEvent:(evt:any)=>{events.push(evt);return true},
25
26
  };
26
27
  const fetch=fetchOverride|| (async()=>({ok:true,json:async()=>remoteData}));
27
- const context=vm.createContext({crypto:webcrypto,TextEncoder,URL,fetch,setTimeout,clearTimeout,window,document:{getElementById:(id:string)=>nodes[id],createElement:()=>element()},CustomEvent:class {type:string;detail:any;constructor(t:string,opts:any){this.type=t;this.detail=opts.detail}}});
28
+ const context=vm.createContext({crypto:webcrypto,TextEncoder,URL,fetch,setTimeout,clearTimeout,window,document:{getElementById:(id:string)=>nodes[id],querySelector:()=>actions,createElement:()=>element()},CustomEvent:class {type:string;detail:any;constructor(t:string,opts:any){this.type=t;this.detail=opts.detail}}});
28
29
  dispatch=(message:any,source=parent)=>(listeners.message??[]).forEach(listener=>listener({source,data:{jsonrpc:'2.0',...message}}));
29
30
  const result=(data:any)=>dispatch({method:'ui/notifications/tool-result',params:{result:{structuredContent:{...data}}}});
30
31
  const respond=(id:number,result:any={})=>dispatch({id,result});
31
32
  vm.runInContext(buildPreviewBridgeScript().replaceAll("__MARKCUT_ORIGIN__",JSON.stringify("https://neoy.qili2.com")),context);
32
33
  events.length=0; // Ignore the initial Overall marker/selection render in tests about later events.
33
- return {messages,nodes,events,dispatch,result,respond,scene:(detail:any)=>(listeners['markcut:scene-change']||[]).forEach(listener=>listener({detail})),selectSpot:(id:number)=>(listeners['markcut:spot-select']||[]).forEach(listener=>listener({detail:{id}}))};
34
+ return {messages,nodes,events,dispatch,result,respond,scene:(detail:any)=>(listeners['markcut:scene-change']||[]).forEach(listener=>listener({detail})),selectSpot:(id:number)=>(listeners['markcut:spot-select']||[]).forEach(listener=>listener({detail:{id}})),questionAnswers:(answers:Record<string,string>)=>(listeners['markcut:questions-change']||[]).forEach(listener=>listener({detail:{answers}}))};
34
35
  }
35
36
  const nextTick=()=>new Promise(resolve=>setTimeout(resolve,0));
36
37
 
38
+ describe('Markdown questions mode',()=>{
39
+ it('renders question UI state, stores per-Scene answers and has only one Submit action',async()=>{
40
+ const h=harness();
41
+ h.result({path:'/tmp/.ghost.askquestions.md',title:'Vlog 选择',id:'questions',
42
+ revisionId:'qrev',contentHash:'a'.repeat(64),review:{delivery:'text',mode:'questions'},
43
+ compiled:{children:[{id:'scene-a',type:'scene',name:'Q1',title:'md64:YWJj'},
44
+ {id:'scene-b',type:'scene',name:'Q2',title:'md64:ZGVm'}]}});
45
+ expect(h.nodes['video-md-version'].textContent).toBe('Vlog 选择');
46
+ expect(h.nodes.approve.style.display).toBe('none');
47
+ expect(h.nodes.changes.style.display).toBe('none');
48
+ expect(h.nodes['comment-entry'].style.display).toBe('none');
49
+ expect(h.nodes['questions-submit'].hidden).toBe(false);
50
+ h.questionAnswers({Q1:'加拿大生活 **很有趣**'});
51
+ h.nodes['questions-submit'].onclick?.();
52
+ await nextTick();
53
+ const result=JSON.parse(h.messages.find(m=>m.method==='ui/message').params.content[0].text);
54
+ expect(result).toMatchObject({status:'submitted',decision:'approved',answers:[
55
+ {questionId:'Q1',answer:'加拿大生活 **很有趣**'},{questionId:'Q2',answer:''}]});
56
+ expect(result.comments).toMatchObject([
57
+ {sceneId:'scene-a',scope:'scene',text:'加拿大生活 **很有趣**',playbackContext:{sceneName:'Q1'}},
58
+ {sceneId:'scene-b',scope:'scene',text:'',playbackContext:{sceneName:'Q2'}}]);
59
+ });
60
+ it('publishes the existing bound event with scene answers on Submit',async()=>{
61
+ const h=harness();
62
+ const eventTemplate={type:'task.interactive_decision',source:'job/1/task/2/execution/3',
63
+ responseKey:'interactive',data:{interactive:{jobId:'1',taskId:'2',executionId:'3'}}};
64
+ h.result({path:'/tmp/questions.md',id:'qa',revisionId:'qa-rev',contentHash:'b'.repeat(64),
65
+ review:{delivery:'event',mode:'questions',eventTemplate},
66
+ compiled:{children:[{id:'s1',type:'scene',name:'Q1',title:'md64:Zm9v'}]}});
67
+ h.questionAnswers({Q1:'答案'});
68
+ h.nodes['questions-submit'].onclick?.();
69
+ await nextTick();
70
+ const published=h.messages.find(m=>m.method==='tools/call'&&m.params.name==='events');
71
+ expect(published.params.arguments.args).toMatchObject({
72
+ type:'task.interactive_decision',data:{interactive:{decision:'approved',comments:[
73
+ {sceneId:'s1',text:'答案',scope:'scene',playbackContext:{sceneName:'Q1'}}
74
+ ]}}});
75
+ });
76
+ });
77
+
37
78
  describe('MCP Remotion bridge',()=>{
38
79
  it('readonly input displays playback without review controls or messages',async()=>{
39
80
  const h=harness();
@@ -0,0 +1,80 @@
1
+ import {test} from 'vitest';
2
+ import assert from 'node:assert/strict';
3
+ import {mkdtempSync, mkdirSync, writeFileSync, rmSync, utimesSync} from 'node:fs';
4
+ import {tmpdir} from 'node:os';
5
+ import {join} from 'node:path';
6
+ import {execFileSync} from 'node:child_process';
7
+ import {versionPreviewMedia} from '../src/mcp/remote-assets.mjs';
8
+
9
+ test('immutable cache key tracks mounted preview source and works for past compiled revisions',()=>{
10
+ const dir=mkdtempSync(join(tmpdir(),'markcut-proxy-version-'));
11
+ try {
12
+ mkdirSync(join(dir,'run'),{recursive:true});
13
+ const file=join(dir,'run','film.mp4');
14
+ writeFileSync(file,Buffer.from('first film'));
15
+ const origin='https://preview.example.test';
16
+ const url=origin+'/preview-files/vlog/run/film.mp4';
17
+ const exported=join(dir,'exports','_neoy','markcut');
18
+ const generated=join(exported,'generated','1234567890abcdef');
19
+ mkdirSync(generated,{recursive:true});
20
+ const generatedVideo=join(generated,'clip.mp4');
21
+ writeFileSync(generatedVideo,Buffer.from('generated film'));
22
+ const generatedURL=origin+'/files/_neoy/markcut/generated/1234567890abcdef/clip.mp4';
23
+ const source={root:{children:[{type:'video',src:url}, {src:origin+'/files/vlog/run/film.mp4'},
24
+ {src:'https://elsewhere.example.test/preview-files/vlog/run/film.mp4'},
25
+ {type:'video',src:generatedURL}, {type:'audio',src:origin+'/files/_neoy/markcut/generated/sound.m4a'},
26
+ {markup:`<video src='${origin}/files/vlog/run/film.mp4' autoPlay />`},
27
+ {src:origin+'/files/_neoy/markcut/cache/preserved.mp4'}]}};
28
+ const mounts={vlog:dir};
29
+ const first=versionPreviewMedia(source,origin,mounts,exported);
30
+ const found=first.root.children[0].src;
31
+ assert.match(found,/\?pv=[a-f0-9]{16}$/);
32
+ assert.equal(versionPreviewMedia(source,origin,mounts,exported).root.children[0].src,found);
33
+ assert.equal(first.root.children[1].src,found,'older /files/ videos use the preview route');
34
+ assert.equal(first.root.children[2].src,source.root.children[2].src);
35
+ const exportedPreview=first.root.children[3].src;
36
+ assert.match(exportedPreview,/\/preview-files\/_neoy\/markcut\/generated\/.+\?pv=[a-f0-9]{16}$/);
37
+ assert.equal(first.root.children[4].src,source.root.children[4].src,'audio remains untouched');
38
+ assert.match(first.root.children[5].markup,/\/preview-files\/vlog\/run\/film\.mp4\?pv=/,
39
+ 'legacy inline HTML video attributes use the same proxy');
40
+ assert.equal(first.root.children[6].src,source.root.children[6].src,
41
+ 'other private export URLs do not get converted');
42
+ assert.equal(source.root.children[0].src,url,'compiled source is not mutated');
43
+ assert.equal(versionPreviewMedia(first,origin,mounts,exported).root.children[0].src,found,'idempotent');
44
+ writeFileSync(file,Buffer.from('updated video longer than before'));
45
+ const second=versionPreviewMedia(source,origin,mounts,exported).root.children[0].src;
46
+ assert.notEqual(second,found,'a replaced video cannot reuse a stale CDN key');
47
+ writeFileSync(generatedVideo,Buffer.from('new snapshot of generated video'));
48
+ const newExported=versionPreviewMedia(source,origin,mounts,exported).root.children[3].src;
49
+ assert.notEqual(newExported,exportedPreview,'generated snapshot changes must version URL too');
50
+ } finally {rmSync(dir,{recursive:true,force:true});}
51
+ });
52
+
53
+
54
+ test('immutable compiled revisions publish a new transport variant instead of overwriting an old player cache',()=>{
55
+ const dir=mkdtempSync(join(tmpdir(),'markcut-transport-variant-'));
56
+ try{
57
+ const moduleURL=new URL('../src/mcp/remote-assets.mjs',import.meta.url).href;
58
+ const script=`
59
+ import {publishCompiledCache, prunePublishedCache} from ${JSON.stringify(moduleURL)};
60
+ import {readFileSync,existsSync} from 'node:fs';
61
+ import {join} from 'node:path';
62
+ const hash='a'.repeat(64);
63
+ const old={root:{children:[{src:'https://preview.example.test/files/demo/video.mp4'}]}};
64
+ const next={root:{children:[{src:'https://preview.example.test/preview-files/demo/video.mp4?pv=1234567890abcdef'}]}};
65
+ const original=publishCompiledCache(hash,old,'https://preview.example.test');
66
+ const updated=publishCompiledCache(hash,next,'https://preview.example.test');
67
+ if(original===updated || !updated.includes('-'))throw new Error('no distinct immutable variant');
68
+ if(!updated.match(/-[a-f0-9]{16}\.json$/))throw new Error('variant URL missing suffix');
69
+ if(publishCompiledCache(hash,next,'https://preview.example.test')!==updated)throw new Error('not idempotent');
70
+ if(!readFileSync(join(process.env.MARKCUT_EXPORT_ROOT,'cache',hash+'.json'),'utf8').includes('/files/demo/'))throw new Error('original overwritten');
71
+ await prunePublishedCache(hash);
72
+ if(existsSync(join(process.env.MARKCUT_EXPORT_ROOT,'cache',hash+'.json')))throw new Error('canonical not pruned');
73
+ if(existsSync(join(process.env.MARKCUT_EXPORT_ROOT,'cache',updated.split('/').pop())))throw new Error('variant not pruned');
74
+ console.log('TRANSPORT_VARIANTS_PASS');
75
+ `;
76
+ const result=execFileSync(process.execPath,['--input-type=module','-e',script],
77
+ {encoding:'utf8',env:{...process.env,MARKCUT_EXPORT_ROOT:dir}});
78
+ assert.match(result,/TRANSPORT_VARIANTS_PASS/);
79
+ }finally{rmSync(dir,{recursive:true,force:true});}
80
+ });
@@ -1,6 +1,6 @@
1
1
  import {describe,it,expect} from 'vitest';
2
2
  process.env.NEOY_PUBLIC_ORIGIN = 'https://neoy.example.test';
3
- import {buildPreviewHtml,buildPreviewResourceResult,RESOURCE_URI,LEGACY_RESOURCE_URIS,validateMarkdownPath,getPreviewMedia,readPreviewAudio,withPreviewAudio} from '../src/mcp/preview.mjs';
3
+ import {buildPreviewHtml,buildPreviewResourceResult,RESOURCE_URI,STABLE_RESOURCE_URI,PREVIEW_VERSION_NUMBER,LEGACY_RESOURCE_URIS,validateMarkdownPath,getPreviewMedia,readPreviewAudio,withPreviewAudio} from '../src/mcp/preview.mjs';
4
4
  import {buildPreviewBridgeScript} from '../src/mcp/bridge.mjs';
5
5
  import {mkdtemp,writeFile,rm} from 'node:fs/promises';
6
6
  import {tmpdir} from 'node:os';
@@ -17,7 +17,8 @@ describe('Markcut Remotion MCP App',()=>{
17
17
  expect(html).toContain('<textarea id="feedback" rows="3"');
18
18
  expect(html).toContain('id="comment-tools"');
19
19
  expect(html).toContain('id="overall-mode" hidden>Overall');
20
- expect(html).toContain('id="review-delivery-mode"');
20
+ expect(html).toContain('id="markcut-video-selector-slot"');
21
+ expect(html).not.toContain('id="review-delivery-mode"');
21
22
  expect(html).toContain('Text mode');
22
23
  expect(html).toContain('Submit feedback');
23
24
  expect(html).not.toContain('Submit all feedback');
@@ -26,23 +27,40 @@ describe('Markcut Remotion MCP App',()=>{
26
27
  expect(html).not.toContain('<option value="overall"');
27
28
  expect(html).toContain('#comment-tools>*{width:30px;height:28px;padding:0;border:0');
28
29
  expect(html).toContain('https://neoy.example.test/files/_neoy/markcut/player/');
30
+ // On iOS an MCP UI resource URI may remain cached across server upgrades.
31
+ // Bumping the URI forces the WebGL-capable schema/player to be reloaded.
32
+ const bundle=readFileSync(new URL('../src/mcp/remotion-app.bundle.js',import.meta.url),'utf8');
33
+ expect(bundle).toContain('model3d');
34
+ expect(bundle).toContain('model3d requires a .glb');
35
+
29
36
  expect(html).not.toContain('id="remotion-bundle"');
30
37
  // The generic event contract requires client-side identity and reserved-field validation.
31
- expect(html.length).toBeLessThan(30000);
38
+ expect(html.length).toBeLessThan(33000);
32
39
  expect(html).not.toContain('<video id="video-player"');
33
40
  expect(html).not.toContain('data:video/mp4');
34
41
  expect(html).not.toContain('127.0.0.1');
35
42
  expect(html).not.toContain('src="/player.js"');
36
43
  });
37
- it('fits the phone player by BOTH width and height, with scenes above canvas and actions in normal flow',()=>{
44
+ it('keeps askquestions Markdown and answers readable in both color schemes',()=>{
38
45
  const html=buildPreviewHtml();
39
- expect(html).toContain('@media (max-width: 640px), (max-height: 520px)');
40
- expect(html).toContain('var(--markcut-player-ratio, 0.5625)');
41
- expect(html).toContain('#scene-thumbnails { order: -1;');
46
+ expect(html).toContain('#markcut-questions{');
47
+ expect(html).toContain('background:#fff;color:#17202a');
48
+ expect(html).toContain('background:#161b22;color:#f2f5fb');
49
+ expect(html).toContain('#markcut-questions textarea');
50
+ });
51
+ it('fits the phone player by BOTH width and height, with scenes below canvas and actions in normal flow',()=>{
52
+ const html=buildPreviewHtml();
53
+ expect(html).toContain('@media (max-width: 640px), (max-width: 900px) and (max-height: 520px)');
54
+ expect(html).toContain('width: min(100%, calc(760px * var(--markcut-player-ratio, 0.5625)))');
55
+ expect(html).toContain('width: min(100%, calc(min(76dvh, 520px) * var(--markcut-player-ratio, 0.5625)))');
56
+ expect(html).not.toContain('58dvh');
57
+ expect(html).toContain('#scene-thumbnails { order: 0;');
42
58
  expect(html).toContain("grid-template-areas: 'changes approve' 'status status'");
43
59
  expect(html).not.toMatch(/#remotion-canvas\s*\{[^}]*position\s*:\s*absolute/);
44
60
  const app=readFileSync(new URL('../src/mcp/remotion-app.tsx',import.meta.url),'utf8');
45
61
  expect(app).toContain('showPlaybackRateControl={!compact}');
62
+ expect(app).not.toContain("maxHeight:'65vh'");
63
+ expect(app).not.toContain("width:'100%',aspectRatio");
46
64
  expect(app).toContain('Boolean(data?.subtitle?.src)&&document.getElementById');
47
65
  });
48
66
  it('omits the developer BGM decode-status row while preserving Web Audio playback',()=>{
@@ -52,9 +70,24 @@ describe('Markcut Remotion MCP App',()=>{
52
70
  expect(audio).toContain('ctx.decodeAudioData(bytes)');
53
71
  expect(audio).toContain("p.addEventListener('play',play)");
54
72
  });
55
- it('publishes v47 while retaining v46 as a compatible alias',()=>{
56
- expect(RESOURCE_URI).toBe('ui://markcut/video-preview-v47.html');
57
- expect(LEGACY_RESOURCE_URIS).toContain('ui://markcut/video-preview-v46.html');
73
+ it('maps every historical preview version and the stable URI to the latest',()=>{
74
+ expect(PREVIEW_VERSION_NUMBER).toBe(55);
75
+ expect(RESOURCE_URI).toBe('ui://markcut/video-preview-v55.html');
76
+ expect(STABLE_RESOURCE_URI).toBe('ui://markcut/video-preview.html');
77
+ expect(LEGACY_RESOURCE_URIS).toHaveLength(PREVIEW_VERSION_NUMBER);
78
+ expect(new Set([RESOURCE_URI,...LEGACY_RESOURCE_URIS]).size).toBe(PREVIEW_VERSION_NUMBER+1);
79
+ expect(LEGACY_RESOURCE_URIS).toContain(STABLE_RESOURCE_URI);
80
+ const latestHtml=buildPreviewResourceResult(RESOURCE_URI).contents[0].text;
81
+ expect(buildPreviewResourceResult(STABLE_RESOURCE_URI).contents[0].text).toBe(latestHtml);
82
+ for (let version=1;version<PREVIEW_VERSION_NUMBER;version++) {
83
+ const uri=`ui://markcut/video-preview-v${version}.html`;
84
+ expect(LEGACY_RESOURCE_URIS).toContain(uri);
85
+ const resource=buildPreviewResourceResult(uri);
86
+ expect(resource.contents[0].uri).toBe(uri);
87
+ expect(resource.contents[0].text).toBe(latestHtml);
88
+ expect(resource.contents[0].text).toContain(`>${'v'+PREVIEW_VERSION_NUMBER}</span>`);
89
+ expect(resource.contents[0].text).toContain('https://neoy.example.test/files/_neoy/markcut/player/');
90
+ }
58
91
  });
59
92
  it('registers latest resource at startup and aliases previous URIs',()=>{
60
93
  for(const uri of [RESOURCE_URI,...LEGACY_RESOURCE_URIS]){
@@ -20,6 +20,23 @@ describe("NeoY backed preview files",()=>{
20
20
  expect(input.root.children[0].src).toContain("data:audio/");
21
21
  }finally{rmSync(join(EXPORT_ROOT,"generated",id),{recursive:true,force:true});}
22
22
  });
23
+ it("snapshots a local GLB for hosted model3d preview without changing the source",()=>{
24
+ const dir=mkdtempSync(join(tmpdir(),"markcut-model3d-"));
25
+ const source=join(dir,"toy.glb");
26
+ const data=Buffer.from("glTF\x02\x00\x00\x00","binary");
27
+ writeFileSync(source,data);
28
+ try {
29
+ const tree={root:{type:"root",children:[{type:"model3d",src:"toy.glb",durationInSeconds:2}]}};
30
+ const {compiled,assets}=externalizePreviewMedia(tree,id,"https://example.org",dir);
31
+ expect(assets).toEqual(["file-0.glb"]);
32
+ expect(compiled.root.children[0].src).toBe("https://example.org/files/_neoy/markcut/generated/"+id+"/file-0.glb");
33
+ expect(readFileSync(join(EXPORT_ROOT,"generated",id,"file-0.glb"))).toEqual(data);
34
+ expect(readFileSync(source)).toEqual(data);
35
+ } finally {
36
+ rmSync(dir,{recursive:true,force:true});
37
+ rmSync(join(EXPORT_ROOT,"generated",id),{recursive:true,force:true});
38
+ }
39
+ });
23
40
  it("rejects a local HTTP media reference",()=>{
24
41
  expect(()=>externalizePreviewMedia({src:"http://127.0.0.1:4571/asset"},id,"https://example.org")).toThrow(/HTTPS|local media URL/);
25
42
  });
@@ -54,7 +54,7 @@ describe('stateless Markcut MCP cache',()=>{
54
54
  await writeFile(media,'# video\nwidth:640 height:480 fps:30 layout:series\n## Photo\n- image src:photo2.png duration:1\n');
55
55
  const mediaPreview=await ensureVideoPreview(media);
56
56
  const mediaJson=await readFile(join(run,'exports','cache',mediaPreview.contentHash+'.json'),'utf8');
57
- expect(mediaJson).toContain('/files/_neoy/markcut/generated/'+mediaPreview.contentHash+'/file-0.png');
57
+ expect(mediaJson).toContain('/preview-files/_neoy/markcut/generated/'+mediaPreview.contentHash+'/file-0.png');
58
58
  expect(await readFile(join(run,'exports','generated',mediaPreview.contentHash,'file-0.png'))).toEqual(await readFile(photo));
59
59
  await writeFile(photo,Buffer.from('different-image-payload'));
60
60
  const modified=await ensureVideoPreview(media);
@@ -0,0 +1,55 @@
1
+ import {describe,it,expect} from 'vitest';
2
+ import {mkdtemp,writeFile,mkdir,rm,readFile} from 'node:fs/promises';
3
+ import {tmpdir} from 'node:os';
4
+ import {join} from 'node:path';
5
+
6
+ describe('one video selector for original, named variants, and editor decisions',()=>{
7
+ it('compiles and publishes every named variant and the EDL without modifying the authored film',async()=>{
8
+ const root=await mkdtemp(join(tmpdir(),'markcut-video-selector-'));
9
+ const beforeExport=process.env.MARKCUT_EXPORT_ROOT,beforeOrigin=process.env.NEOY_PUBLIC_ORIGIN;
10
+ process.env.MARKCUT_EXPORT_ROOT=join(root,'exports');
11
+ process.env.NEOY_PUBLIC_ORIGIN='https://neoy.example.test';
12
+ try {
13
+ const {ensureVideoPreview,getPreviewMedia}=await import('../src/mcp/preview.mjs');
14
+ await mkdir(join(root,'input','media'),{recursive:true});
15
+ await writeFile(join(root,'input','media','frame.png'),Buffer.from('media'));
16
+ const film=join(root,'video.md');
17
+ const markdown=['---','edl: ./video.edl.json','---','# video',
18
+ 'width:320 height:568 fps:24 layout:series','','## Main',
19
+ '- image src:input/media/frame.png duration:1','','# landscape',
20
+ 'width:640 height:360 fps:24','','# square',
21
+ 'width:480 height:480 fps:24',''].join('\n');
22
+ await writeFile(film,markdown);
23
+ await writeFile(join(root,'video.edl.json'),JSON.stringify({schema_version:1,
24
+ edits:[{shot_id:'intro',source_src:'input/media/frame.png',in_seconds:0,out_seconds:1,editor_reason:'Hold the opening'}]}));
25
+ const preview=await ensureVideoPreview(film);
26
+ const media=getPreviewMedia(preview.contentHash);
27
+ expect([media.compiled.width,media.compiled.height]).toEqual([320,568]);
28
+ expect(Object.keys(media.variants)).toEqual(['landscape','square']);
29
+ expect([media.variants.landscape.width,media.variants.landscape.height]).toEqual([640,360]);
30
+ expect([media.variants.square.width,media.variants.square.height]).toEqual([480,480]);
31
+ expect(media.editorDecisions.children.map((scene:any)=>scene.name)).toEqual(['Shot1']);
32
+ expect(JSON.parse(await readFile(join(root,'exports','cache',preview.contentHash+'.variants.json'),'utf8')))
33
+ .toHaveProperty('landscape');
34
+ expect(await readFile(film,'utf8')).toBe(markdown);
35
+ // Validate published resource while the test's Neo origin and export directory
36
+ // are set; CI has no actual NeoY deployment.json.
37
+ const {buildPreviewHtml}=await import('../src/mcp/preview.mjs');
38
+ const html=buildPreviewHtml();
39
+ expect(html).toContain('id="markcut-video-selector-slot"');
40
+ expect(html).not.toContain('id="review-delivery-mode"');
41
+ } finally {
42
+ if(beforeExport===undefined)delete process.env.MARKCUT_EXPORT_ROOT;else process.env.MARKCUT_EXPORT_ROOT=beforeExport;
43
+ if(beforeOrigin===undefined)delete process.env.NEOY_PUBLIC_ORIGIN;else process.env.NEOY_PUBLIC_ORIGIN=beforeOrigin;
44
+ await rm(root,{recursive:true,force:true});
45
+ }
46
+ },25000);
47
+ it('ships a right-hand selector without a separate mode label or EDL tab bar',async()=>{
48
+ const {readFileSync}=await import('node:fs');
49
+ const app=readFileSync(new URL('../src/mcp/remotion-app.tsx',import.meta.url),'utf8');
50
+ expect(app).toContain('id="markcut-video-selector"');
51
+ expect(app).toContain('editor-decisions');
52
+ expect(app).not.toContain('role="tablist"');
53
+ expect(app).not.toContain('Editorial view · Switch to Video');
54
+ });
55
+ });