@lalalic/markcut 3.2.40 → 3.2.42

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.
@@ -0,0 +1,47 @@
1
+ // Provider-side validation: the UI cannot invent an event destination or a Relay terminal event.
2
+ const ID = /^[A-Za-z0-9_-]{1,128}$/;
3
+ const SOURCE = /^job\/[A-Za-z0-9_-]+\/task\/[A-Za-z0-9_-]+\/execution\/[A-Za-z0-9_-]+$/;
4
+ const RECORD = value => value && typeof value === "object" && !Array.isArray(value);
5
+ function copyData(value) {
6
+ if (!RECORD(value)) throw new Error("eventTemplate.data must be an object");
7
+ // No executable values or reserved overrides can be shipped in a template.
8
+ const encoded=JSON.stringify(value);
9
+ if (!encoded || encoded.length > 12000) throw new Error("Invalid eventTemplate.data");
10
+ const clean=JSON.parse(encoded);
11
+ const walk=(node)=>{
12
+ if (!node || typeof node !== "object") return;
13
+ for (const [key, val] of Object.entries(node)) {
14
+ if (["__proto__", "constructor", "prototype"].includes(key)) throw new Error("Unsafe eventTemplate data");
15
+ walk(val);
16
+ }
17
+ };
18
+ walk(clean);
19
+ if (Object.hasOwn(clean,"review")) throw new Error("data.review is reserved for the human result");
20
+ return clean;
21
+ }
22
+ export function normalizeReviewConfig(value) {
23
+ if (value === undefined) return {delivery:"text"};
24
+ if (!RECORD(value) || !["text","event"].includes(value.delivery ?? "text")) throw new Error("Unsupported review delivery");
25
+ if (value.delivery !== "event") {
26
+ if (value.eventTemplate !== undefined) throw new Error("eventTemplate requires event delivery");
27
+ return {delivery:"text"};
28
+ }
29
+ const template=value.eventTemplate;
30
+ if (!RECORD(template) || template.type!=="markcut.review.submitted"
31
+ || typeof template.source!=="string" || !SOURCE.test(template.source)
32
+ || !RECORD(template.data)) throw new Error("Invalid review event template");
33
+ if (Object.keys(template).some(key=>!["type","source","data"].includes(key))) throw new Error("Unexpected eventTemplate fields");
34
+ return {delivery:"event",eventTemplate:{
35
+ type:template.type,source:template.source,data:copyData(template.data),
36
+ }};
37
+ }
38
+ export function eventForReview(config,review) {
39
+ const {eventTemplate:template}=normalizeReviewConfig(config);
40
+ if (!template) throw new Error("Event mode required");
41
+ if (!RECORD(review) || !ID.test(review.requestId || "") || !ID.test(review.revisionId || "")
42
+ || !/^[a-f0-9]{64}$/.test(review.contentHash || "")
43
+ || !["approved","changes_requested"].includes(review.decision)
44
+ || !ID.test(review.idempotencyKey || "") || !Array.isArray(review.comments))
45
+ throw new Error("Invalid review result");
46
+ return {type:template.type,source:template.source,data:{...template.data,review:structuredClone(review)}};
47
+ }
@@ -3,6 +3,7 @@ import { McpServer } from "@modelcontextprotocol/server";
3
3
  import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
4
4
  import { registerAppResource, registerAppTool } from "@modelcontextprotocol/ext-apps/server";
5
5
  import { z } from "zod";
6
+ import {normalizeReviewConfig} from "./review-delivery.mjs";
6
7
  import {publishPreviewRevision,publishPlayerBundle,publicOrigin} from "./remote-assets.mjs";
7
8
  import {fileURLToPath} from "node:url";
8
9
  import {startCompileOperation} from "./compile-operation.mjs";
@@ -46,18 +47,19 @@ registerAppTool(
46
47
  server,
47
48
  TOOL_NAME,
48
49
  {
49
- description: "Compile and publish an immutable Markcut preview revision for this ChatGPT conversation. The hosted player sends human review feedback directly to this conversation with ui/message; feedback is not stored or routed by the server. Approval applies only to the exact contentHash shown.",
50
+ description: "Compile and publish an immutable Markcut preview revision for this ChatGPT conversation. Review delivery defaults to ui/message, or submits an authorized caller-bound event when explicitly configured. Approval applies only to the exact contentHash shown.",
50
51
  inputSchema: z.object({
51
52
  path: z.string().describe("Absolute .md path or NeoY HTTPS mounted file URL"),
53
+ review: z.object({delivery:z.enum(["text","event"]).optional(),eventTemplate:z.object({type:z.string(),source:z.string(),data:z.record(z.string(),z.unknown())}).optional()}).optional(),
52
54
  relay: z.object({jobId:z.string(),taskId:z.union([z.string(),z.number()]),executionId:z.string().optional()}).optional().describe("Optional Agents Relay task correlation. No Relay dependency for standalone ChatGPT/Work reviews."),
53
55
  }),
54
56
  _meta: {
55
57
  ui: { resourceUri: RESOURCE_URI },
56
58
  },
57
59
  },
58
- async ({ path, relay }) => {
60
+ async ({ path, relay, review }) => {
59
61
  try {
60
- const operation=startCompileOperation(path,relay);
62
+ const operation=startCompileOperation(path,relay,normalizeReviewConfig(review));
61
63
  const payload={...operation,...(relay ? {relay} : {})};
62
64
  return {
63
65
  content: [{ type: "text", text: `Compilation started: ${operation.path}` }],
@@ -10,6 +10,10 @@ export function SharedPlayer({root, playerRef, ...props}: {root:any;playerRef?:R
10
10
  return <Player ref={playerRef as any} component={MarkCut} inputProps={inputProps}
11
11
  durationInFrames={durationInFrames} fps={fps}
12
12
  compositionWidth={root?.width||1080} compositionHeight={root?.height||1920}
13
+ errorFallback={({error}) => <div data-testid="markcut-player-error" role="alert" style={{
14
+ color:"#fff",background:"#471818",fontSize:16,padding:24,whiteSpace:"pre-wrap",overflowWrap:"anywhere",
15
+ width:"100%",height:"100%",boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",
16
+ }}>{"Playback error: "+String(error?.message||error).slice(0,800)}</div>}
13
17
  controls={true} showPlaybackRateControl={true} allowFullscreen={true}
14
18
  clickToPlay={false} doubleClickToFullscreen={true} autoPlay={false} {...props}/>;
15
19
  }
@@ -13,6 +13,7 @@ import { ComposeContext, AudioContext, useFrameEvents } from "../context/index";
13
13
  import { cssJS, toClassName } from "../utils/index";
14
14
  import type { Scene as SceneStream } from "../schema/index";
15
15
  import { FolderLeaf } from "./Folder";
16
+ import { remotionFolderName } from "./remotion-folder-name";
16
17
 
17
18
  export function SceneLeaf({ stream }: { stream: SceneStream }) {
18
19
  const { Container } = React.useContext(ComposeContext);
@@ -33,7 +34,7 @@ export function SceneLeaf({ stream }: { stream: SceneStream }) {
33
34
  style={cssJS(stream.style) as React.CSSProperties}
34
35
  className={`scene ${toClassName(stream.name ?? "")}`}
35
36
  >
36
- <Folder name={stream.name ?? ""}>
37
+ <Folder name={remotionFolderName(stream.name, stream.id)}>
37
38
  <FolderLeaf stream={stream as any} />
38
39
  </Folder>
39
40
  </Container>
@@ -0,0 +1,19 @@
1
+ // Remotion's <Folder> accepts only ASCII letters, digits, '-', and basic CJK.
2
+ // This is an internal timeline label, not the authored scene name or review ID.
3
+ const VALID_NAME = /^[a-zA-Z0-9\u4E00-\u9FFF-]+$/;
4
+ function safePart(value: string, limit: number): string {
5
+ return value.normalize("NFKC")
6
+ .replace(/[^a-zA-Z0-9\u4E00-\u9FFF-]+/g, "-")
7
+ .replace(/-+/g, "-")
8
+ .replace(/^-+|-+$/g, "")
9
+ .slice(0, limit)
10
+ .replace(/-+$/g, "");
11
+ }
12
+
13
+ export function remotionFolderName(name?: string, id?: string): string {
14
+ const authored = (name ?? "").trim();
15
+ if (VALID_NAME.test(authored)) return authored;
16
+ const base = safePart(authored, 80) || "Scene";
17
+ const suffix = safePart(id ?? "", 24);
18
+ return suffix ? `${base}-${suffix}` : base;
19
+ }
@@ -43,6 +43,20 @@ describe('MCP Remotion bridge',()=>{
43
43
  expect(h.events.at(-1)?.detail?.revisionId).toBe('remote-r1');
44
44
  expect(h.nodes.status.textContent).toBe('');
45
45
  });
46
+ it("never reconstructs event destinations from another caller's path cache",async()=>{
47
+ const path='/shared-video.md';
48
+ const remote={id:'shared',revisionId:'rev1',contentHash:'a'.repeat(64),requestedPath:path,
49
+ compiled:{children:[{name:'Shared'}]}};
50
+ const h=harness(remote);
51
+ h.dispatch({method:'ui/notifications/tool-input',params:{arguments:{path,
52
+ review:{delivery:'event',eventTemplate:{type:'markcut.review.submitted',
53
+ source:'job/a/task/b/execution/c',data:{correlation:{secret:'other'}}}}}}});
54
+ for(let i=0;i<20&&!h.events.some(e=>e.detail?.revisionId==='rev1');i++)await nextTick();
55
+ expect(h.events.some(e=>e.detail?.revisionId==='rev1')).toBe(true);
56
+ expect(h.nodes.approve.disabled).toBe(true);
57
+ h.nodes.approve.onclick?.();
58
+ expect(h.messages.filter(m=>m.method==='tools/call'||m.method==='ui/message')).toHaveLength(0);
59
+ });
46
60
  it('initializes, delivers compiled scenes and sends review directly to the caller',async()=>{
47
61
  const h=harness();
48
62
  expect(h.messages[0]).toMatchObject({id:1,method:'ui/initialize'});
@@ -59,7 +73,8 @@ describe('MCP Remotion bridge',()=>{
59
73
  expect(h.messages.filter(m=>m.method==='tools/call')).toHaveLength(0);
60
74
  await nextTick();
61
75
  const notification=h.messages.find(m=>m.method==='ui/message');
62
- expect(JSON.parse(notification.params.content[0].text)).toEqual({previewId:'one',revisionId:'rev1',contentHash:'a'.repeat(64),path:'/tmp/a.md',decision:'approved'});
76
+ expect(JSON.parse(notification.params.content[0].text)).toMatchObject({requestId:'rev1',previewId:'one',revisionId:'rev1',contentHash:'a'.repeat(64),path:'/tmp/a.md',decision:'approved',comments:[]});
77
+ expect(JSON.parse(notification.params.content[0].text).idempotencyKey).toMatch(/^[a-f0-9-]{36}$/);
63
78
  h.respond(notification.id);
64
79
  await nextTick();
65
80
  expect(h.nodes.status.textContent).toBe('Review sent.');
@@ -344,3 +359,45 @@ describe('async compilation UI transition',()=>{
344
359
  expect(h.nodes.status.textContent).toContain('TTS unavailable');
345
360
  });
346
361
  });
362
+
363
+ describe('Review event delivery',()=>{
364
+ const template={type:'markcut.review.submitted',
365
+ source:'job/551/task/producer/execution/e1',data:{correlation:{jobId:'551'},purpose:'video'}};
366
+ const media={id:'video1',requestId:'d9b2006a-0618-45aa-a3d8-31363fa629ca',revisionId:'rv1',
367
+ contentHash:'a'.repeat(64),path:'/tmp/video.md',compiled:{children:[]},review:{delivery:'event',eventTemplate:template}};
368
+ it('does not publish until explicit Submit, preserves fixed envelope and scoped comments',async()=>{
369
+ const h=harness(undefined,undefined, m=> m.method==='tools/call'?{published:true,event:{event_id:'ack'}}:undefined);
370
+ h.result(media);h.scene({sceneId:'intro',timeSeconds:2.25,sceneStart:0});
371
+ h.nodes.feedback.value='Trim opening';h.nodes['save-spot'].onclick?.();
372
+ expect(h.messages.filter(m=>m.method==='tools/call')).toHaveLength(0);
373
+ h.nodes.changes.onclick?.();await nextTick();
374
+ const calls=h.messages.filter(m=>m.method==='tools/call');
375
+ expect(calls).toHaveLength(1);
376
+ expect(calls[0]).toMatchObject({params:{name:'events',arguments:{command:'publish',
377
+ args:{type:template.type,source:template.source,data:{correlation:template.data.correlation,purpose:'video',
378
+ review:{requestId:media.requestId,revisionId:media.revisionId,contentHash:media.contentHash,
379
+ decision:'changes_requested',comments:[{sceneId:'intro',timeSeconds:2.25,text:'Trim opening'}]}}}}}});
380
+ expect(h.messages.filter(m=>m.method==='ui/message')).toHaveLength(0);
381
+ expect(h.nodes.status.textContent).toContain('submitted');
382
+ });
383
+ it('fails visibly without host Events access and reuses the idempotency key on retry',async()=>{
384
+ const h=harness(undefined,undefined,m=>m.method==='tools/call'?{rpcError:{message:'Host denies cross-server tool'}}:undefined);
385
+ h.result(media);h.nodes.approve.onclick?.();await nextTick();await nextTick();
386
+ expect(h.nodes.status.textContent).toContain('Review not submitted');
387
+ h.nodes.approve.onclick?.();await nextTick();await nextTick();
388
+ const calls=h.messages.filter(m=>m.method==='tools/call');
389
+ expect(calls).toHaveLength(2);
390
+ expect(calls[0].params.arguments.args.data.review.idempotencyKey)
391
+ .toBe(calls[1].params.arguments.args.data.review.idempotencyKey);
392
+ expect(h.messages.filter(m=>m.method==='ui/message')).toHaveLength(0);
393
+ });
394
+ it('rejects non-acknowledging host and prevents a second submit after acceptance',async()=>{
395
+ let accepted=false;
396
+ const h=harness(undefined,undefined,m=>m.method==='tools/call'?{published:accepted}:undefined);
397
+ h.result(media);h.nodes.approve.onclick?.();await nextTick();await nextTick();
398
+ expect(h.nodes.status.textContent).toContain('not submitted');
399
+ accepted=true;h.nodes.approve.onclick?.();await nextTick();await nextTick();
400
+ h.nodes.approve.onclick?.();
401
+ expect(h.messages.filter(m=>m.method==='tools/call')).toHaveLength(2);
402
+ });
403
+ });
@@ -0,0 +1,33 @@
1
+ import {describe,it,expect} from 'vitest';
2
+ import {normalizeReviewConfig,eventForReview} from '../src/mcp/review-delivery.mjs';
3
+
4
+ const template={type:'markcut.review.submitted',source:'job/j1/task/t1/execution/e1',data:{job:'j1',meta:{source:'ok'}}};
5
+ const review={requestId:'r1',previewId:'p1',revisionId:'rev1',contentHash:'a'.repeat(64),
6
+ decision:'changes_requested',comments:[{sceneId:'intro',timeSeconds:3.2,text:'Shorter intro'}],idempotencyKey:'key1'};
7
+
8
+ describe('Provider-bound preview delivery',()=>{
9
+ it('defaults to text and disallows a third delivery mode',()=>{
10
+ expect(normalizeReviewConfig(undefined)).toEqual({delivery:'text'});
11
+ expect(normalizeReviewConfig({delivery:'text'})).toEqual({delivery:'text'});
12
+ expect(()=>normalizeReviewConfig({delivery:'callback'})).toThrow();
13
+ expect(()=>normalizeReviewConfig({delivery:'event'})).toThrow();
14
+ });
15
+ it('rejects terminal event spoofing, arbitrary source and reserved data overrides',()=>{
16
+ expect(()=>normalizeReviewConfig({delivery:'event',eventTemplate:{...template,type:'task.completed'}})).toThrow();
17
+ expect(()=>normalizeReviewConfig({delivery:'event',eventTemplate:{...template,source:'job/a/task/b/execution/e/forged'}})).toThrow();
18
+ expect(()=>normalizeReviewConfig({delivery:'event',eventTemplate:{...template,data:{review:{decision:'approved'}}}})).toThrow();
19
+ });
20
+ it('retains caller-owned envelope and only fills data.review',()=>{
21
+ const config=normalizeReviewConfig({delivery:'event',eventTemplate:template});
22
+ template.data.meta.source='changed after validation';
23
+ const event=eventForReview(config,review);
24
+ expect(event).toMatchObject({type:'markcut.review.submitted',source:template.source,
25
+ data:{job:'j1',meta:{source:'ok'},review}});
26
+ expect(event.data.review.idempotencyKey).toBe('key1');
27
+ });
28
+ it('refuses malformed review identity or decision',()=>{
29
+ const config=normalizeReviewConfig({delivery:'event',eventTemplate:template});
30
+ expect(()=>eventForReview(config,{...review,contentHash:'bogus'})).toThrow();
31
+ expect(()=>eventForReview(config,{...review,decision:'task.completed'})).toThrow();
32
+ });
33
+ });
@@ -0,0 +1,25 @@
1
+ import {describe,expect,it} from "vitest";
2
+ import {remotionFolderName} from "../src/types/remotion-folder-name";
3
+
4
+ const accepted=/^[a-zA-Z0-9\u4E00-\u9FFF-]+$/;
5
+ describe("Remotion scene folder name",()=>{
6
+ it("preserves valid authored names",()=>{
7
+ expect(remotionFolderName("Opening-Long","a1")).toBe("Opening-Long");
8
+ expect(remotionFolderName("湖边","a2")).toBe("湖边");
9
+ });
10
+ it("sanitizes names rejected by Remotion without altering source metadata",()=>{
11
+ for(const [name,id] of [
12
+ ["Opening_Long","xxvsny5a"],["Scene with spaces","id-1"],["emoji 🎬 !","scene-3"],
13
+ ["シーン 一","scene-4"],["/","scene-5"],["","scene-6"],
14
+ ]){
15
+ const safe=remotionFolderName(name,id);
16
+ expect(safe).toMatch(accepted);
17
+ expect(safe).not.toContain("_");
18
+ expect(remotionFolderName(name,id)).toBe(safe);
19
+ }
20
+ expect(remotionFolderName("Opening_Long","xxvsny5a")).toBe("Opening-Long-xxvsny5a");
21
+ });
22
+ it("keeps distinct invalid names distinct when IDs differ",()=>{
23
+ expect(remotionFolderName("A_B","id1")).not.toBe(remotionFolderName("A B","id2"));
24
+ });
25
+ });