@lalalic/markcut 3.2.37 → 3.2.38
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.
- package/docs/developer-reference.md +4 -0
- package/package.json +1 -1
- package/skills/markcut/references/mcp-preview-lifecycle.md +9 -7
- package/src/mcp/bridge.mjs +13 -4
- package/src/mcp/compile-operation.mjs +5 -3
- package/src/mcp/compile-worker.mjs +3 -2
- package/src/mcp/preview.mjs +12 -33
- package/src/mcp/server.mjs +7 -3
- package/src/mcp/source-fingerprint.mjs +24 -0
- package/tests/mcp-preview-bridge.test.ts +39 -23
- package/tests/mcp-preview.test.ts +7 -8
- package/tests/mcp-review-sessions.test.ts +17 -0
|
@@ -302,6 +302,10 @@ For comment-editor or timeline-dot changes, verify the built MCP player in a rea
|
|
|
302
302
|
|
|
303
303
|
Whenever Markcut MCP server, preview UI, bridge, or bundled player code changes, rebuild the MCP bundle and reload **only the Markcut MCP provider** through Neo's provider control interface before testing or declaring the change live. Verify the running provider serves the new resource URI, then open a fresh ChatGPT iframe and check its displayed version and affected behavior. A Git push or ChatGPT tool-list refresh alone is not a provider reload. Never restart the whole Neo MCP app as a workaround; if scoped reload fails, report the live version and blocker explicitly.
|
|
304
304
|
|
|
305
|
+
## Stateless MCP review
|
|
306
|
+
|
|
307
|
+
`markcut.preview` compiles and publishes an immutable revision for the calling ChatGPT conversation. The hosted app verifies the current path-keyed revision record before enabling review and sends decisions to that same conversation with `ui/message`. Neo Mobile owns its locally notified requests and delivery. Markcut does not store shared review history or poll for decisions. `markcut.preview.media({contentHash})` reads a compiled revision when a client needs its scene tree; operation status, immutable content fingerprints, media cache and safe pruning remain server-owned.
|
|
308
|
+
|
|
305
309
|
## MCP background-audio regression guard
|
|
306
310
|
|
|
307
311
|
When extracting HTTPS BGM from a preview tree, traverse the tree **before** returning the captured audio variable. JavaScript evaluates object properties left-to-right: returning `{audio, playbackRoot: strip(root)}` silently loses the BGM handle while removing the native audio node. Keep the pure extraction in `src/mcp/audio-preview-tree.ts` and run `tests/mcp-web-audio-preview.test.ts`. For user-style playback verification, check network HTTP 200, decoded duration, a running AudioContext, advancing Remotion frames, and nonzero Web Audio analyser RMS; a decoded source alone does not establish audible playback. Browser TTS must retain BGM and environmental audio, and only generated narration can be removed; listen for speech start/end to duck and restore Web Audio music gain.
|
package/package.json
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
# ChatGPT MCP
|
|
1
|
+
# ChatGPT MCP preview lifecycle
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`markcut.preview({path})` compiles and publishes an immutable video revision for the calling ChatGPT conversation. The result includes `contentHash` and `revisionId`; the hosted player loads the compiled revision and checks the current path-keyed record at `revisions/<sha256(requestedPath)>.json` before enabling review actions.
|
|
4
4
|
|
|
5
|
-
The
|
|
5
|
+
Review is client-owned. The hosted ChatGPT app sends one `ui/message` containing the decision, revision identity, path, and comments directly to the conversation that opened it. Neo Mobile owns its locally notified review requests and handles its own delivery. Markcut does not keep a global review inbox, persist review decisions, or poll for decisions. A successful `ui/message` response means the conversation received the message; only then does the player show that review was sent. Failures are retried and reported without showing acceptance.
|
|
6
|
+
|
|
7
|
+
`markcut.preview.media({contentHash})` retrieves the immutable compiled scene tree for clients that need it. No review-session tools are provided. `markcut.preview` compilation operations and content fingerprinting remain available, and completed output is published at the same immutable resource locations.
|
|
6
8
|
|
|
7
9
|
Human review behavior:
|
|
8
10
|
|
|
9
|
-
- Draft comments may belong to a scene or
|
|
10
|
-
- An explicit `decision: approved`
|
|
11
|
+
- Draft comments may belong to a scene or playback timestamp. Submitting feedback sends `decision: changes_requested` with revision context. The agent edits the original Markcut Markdown and calls `markcut.preview` again for a new revision.
|
|
12
|
+
- An explicit `decision: approved` applies only to the reviewed content hash and revision. Unsaved comments are not an approval.
|
|
11
13
|
- Earlier preview revisions are read-only after supersession. Failed compilation does not invalidate previously successful revisions, but does not authorize approval of an unrendered new one.
|
|
12
|
-
- Browser TTS is a
|
|
14
|
+
- Browser TTS is a preview playback option, not an authoritative representation of the voice used in rendered MP4. Confirm the final file's audio independently.
|
|
13
15
|
|
|
14
|
-
For implementation-specific caching, publishing and iframe internals,
|
|
16
|
+
For implementation-specific caching, publishing, and iframe internals, consult `docs/mcp-static-preview.md`.
|
package/src/mcp/bridge.mjs
CHANGED
|
@@ -104,7 +104,7 @@ async function loadRemoteScenes(path){
|
|
|
104
104
|
}catch(e){status.textContent='Scene lookup failed: '+String(e);}
|
|
105
105
|
}
|
|
106
106
|
function send(msg){window.parent.postMessage(msg,'*');}
|
|
107
|
-
function request(method,params){const id=++nextId;
|
|
107
|
+
function request(method,params){const id=++nextId;return new Promise((resolve,reject)=>{const timer=setTimeout(()=>{pending.delete(id);reject(new Error('MCP request timed out'));},15000);pending.set(id,{resolve,reject,timer});send({jsonrpc:'2.0',id,method,params});});}
|
|
108
108
|
function showVideoName(path,title){const el=document.getElementById('video-md-version');if(!el)return;const file=typeof path==='string'?decodeURIComponent(path.split('/').pop()||'video.md'):'video.md';el.textContent=typeof title==='string'&&title.trim()?title.trim():file.replace(/\.md$/i,'').replace(/[-_]+/g,' ');}
|
|
109
109
|
function applyToolInput(params){
|
|
110
110
|
const input=params?.arguments||params?.input||params?.toolInput||params||{};
|
|
@@ -123,6 +123,11 @@ function applyToolInput(params){
|
|
|
123
123
|
}
|
|
124
124
|
}
|
|
125
125
|
let operationGeneration=0;
|
|
126
|
+
async function sendDecisionMessage(result){
|
|
127
|
+
for(let attempt=0;attempt<3;attempt++){
|
|
128
|
+
try{await request('ui/message',{role:'user',content:[{type:'text',text:JSON.stringify(result)}]});return true;}catch(e){if(attempt===2){status.textContent='Could not send review to this conversation: '+String(e.message||e);return false;}await new Promise(resolve=>setTimeout(resolve,250*(attempt+1)));}
|
|
129
|
+
}return false;
|
|
130
|
+
}
|
|
126
131
|
async function trackOperation(data){
|
|
127
132
|
const generation=++operationGeneration;
|
|
128
133
|
++fallbackGeneration; // Prevent an old published revision from replacing in-progress UI.
|
|
@@ -211,7 +216,7 @@ window.addEventListener('message',event=>{
|
|
|
211
216
|
const message=event.data;
|
|
212
217
|
if(!message||message.jsonrpc!=='2.0')return;
|
|
213
218
|
if(Object.prototype.hasOwnProperty.call(message,'id')&&pending.has(message.id)){
|
|
214
|
-
const item=pending.get(message.id);pending.delete(message.id);
|
|
219
|
+
const item=pending.get(message.id);pending.delete(message.id);clearTimeout(item.timer);
|
|
215
220
|
if(message.error)item.reject(new Error(message.error.message||'MCP request failed'));
|
|
216
221
|
else item.resolve(message.result);
|
|
217
222
|
}else if(message.method==='ui/notifications/tool-input')applyToolInput(message.params);
|
|
@@ -240,9 +245,13 @@ async function submit(decision){
|
|
|
240
245
|
result.feedback=preparedComments.length===1?preparedComments[0].text:preparedComments.map((item,index)=>String(index+1)+'. ['+sceneKey(item.playbackContext)+' @ '+(item.playbackContext.timeSeconds??0)+'s] '+item.text).join('\\n');
|
|
241
246
|
if(window.__markcutPlaybackContext)result.playbackContext=window.__markcutPlaybackContext;
|
|
242
247
|
}
|
|
243
|
-
busy=true;status.textContent='
|
|
248
|
+
busy=true;status.textContent='Sending review to this conversation…';
|
|
244
249
|
const submittedId=result.revisionId;
|
|
245
|
-
try{
|
|
250
|
+
try{
|
|
251
|
+
const delivered=await sendDecisionMessage(result);
|
|
252
|
+
if(!delivered){busy=false;return;}
|
|
253
|
+
if(identity?.revisionId===submittedId){submittedRevision=submittedId;status.textContent=decision==='approved'?'Review sent.':'Feedback sent. Waiting for the updated preview.';}
|
|
254
|
+
}
|
|
246
255
|
catch(e){busy=false;status.textContent=e.message||'Unable to submit review';}
|
|
247
256
|
}
|
|
248
257
|
document.getElementById('approve').onclick=()=>submit('approved');
|
|
@@ -5,6 +5,7 @@ import {join} from "node:path";
|
|
|
5
5
|
import {fileURLToPath} from "node:url";
|
|
6
6
|
import {EXPORT_ROOT,publicOrigin,resolvePreviewPath} from "./remote-assets.mjs";
|
|
7
7
|
import {validateMarkdownPath} from "./preview.mjs";
|
|
8
|
+
import {fingerprintInputs} from "./source-fingerprint.mjs";
|
|
8
9
|
const folder=join(EXPORT_ROOT,"operations");
|
|
9
10
|
const RETAIN_MS=24*60*60*1000;
|
|
10
11
|
function cleanupOldOperations(){
|
|
@@ -29,12 +30,13 @@ export function writeOperation(id,data){
|
|
|
29
30
|
export function startCompileOperation(path,relay){
|
|
30
31
|
const valid=validateMarkdownPath(resolvePreviewPath(path));
|
|
31
32
|
if(!statSync(valid).isFile())throw new Error("Preview source must be a Markdown file");
|
|
32
|
-
const
|
|
33
|
+
const input=fingerprintInputs(valid);
|
|
34
|
+
const sourceHash=createHash("sha256").update(input.source).update("\0").update(JSON.stringify(input.assets)).digest("hex");
|
|
33
35
|
cleanupOldOperations();
|
|
34
36
|
const id=randomUUID(),startedAt=Date.now();
|
|
35
|
-
|
|
37
|
+
writeOperation(id,{id,state:"compiling",stage:"queued",startedAt,requestedPath:path});
|
|
36
38
|
const worker=fileURLToPath(new URL("./compile-worker.mjs",import.meta.url));
|
|
37
|
-
|
|
39
|
+
const child=spawn(process.execPath,[worker,id,valid,path,JSON.stringify(relay||null),sourceHash],{detached:true,stdio:"ignore"});
|
|
38
40
|
child.on("error",e=>{
|
|
39
41
|
writeOperation(id,{id,state:"failed",stage:"failed",startedAt,requestedPath:path,error:e.message});
|
|
40
42
|
});
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import {createHash} from "node:crypto";
|
|
2
|
-
import {readFileSync} from "node:fs";
|
|
3
2
|
import {ensureVideoPreview} from "./preview.mjs";
|
|
4
3
|
import {publishPreviewRevision} from "./remote-assets.mjs";
|
|
5
4
|
import {writeOperation} from "./compile-operation.mjs";
|
|
5
|
+
import {fingerprintInputs} from "./source-fingerprint.mjs";
|
|
6
6
|
const [id,path,requestedPath,relayText,sourceHash]=process.argv.slice(2);
|
|
7
7
|
const startedAt=Date.now();
|
|
8
8
|
function update(stage){writeOperation(id,{id,state:"compiling",stage,startedAt,updatedAt:Date.now(),requestedPath});}
|
|
9
9
|
try{
|
|
10
10
|
update("resolving-and-compiling");
|
|
11
|
-
const
|
|
11
|
+
const input=fingerprintInputs(path);
|
|
12
|
+
const actualHash=createHash("sha256").update(input.source).update("\0").update(JSON.stringify(input.assets)).digest("hex");
|
|
12
13
|
if(actualHash!==sourceHash)throw new Error("Source changed while queued; retry preview");
|
|
13
14
|
const result=await ensureVideoPreview(path,{onProgress:update});
|
|
14
15
|
update("publishing");
|
package/src/mcp/preview.mjs
CHANGED
|
@@ -6,9 +6,10 @@ import { isAbsolute, extname, dirname, resolve, basename } from "node:path";
|
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
import { buildPreviewBridgeScript } from "./bridge.mjs";
|
|
8
8
|
import { externalizePreviewMedia, publicOrigin, resolveMountedFile, resolvePreviewPath, publishPlayerBundle, publishCompiledCache, prunePublishedCache, EXPORT_ROOT } from "./remote-assets.mjs";
|
|
9
|
+
import {fingerprintInputs} from "./source-fingerprint.mjs";
|
|
9
10
|
|
|
10
11
|
export const TOOL_NAME = "markcut.preview";
|
|
11
|
-
export const RESOURCE_URI = "ui://markcut/video-preview-
|
|
12
|
+
export const RESOURCE_URI = "ui://markcut/video-preview-v40.html";
|
|
12
13
|
const PREVIEW_VERSION = RESOURCE_URI.match(/video-preview-(v\d+)/)?.[1] ?? "unknown";
|
|
13
14
|
// Legacy entrypoints remain registered, but serve the current implementation.
|
|
14
15
|
export const LEGACY_RESOURCE_URIS = [
|
|
@@ -47,6 +48,8 @@ export const LEGACY_RESOURCE_URIS = [
|
|
|
47
48
|
"ui://markcut/video-preview-v35.html",
|
|
48
49
|
"ui://markcut/video-preview-v36.html",
|
|
49
50
|
"ui://markcut/video-preview-v37.html",
|
|
51
|
+
"ui://markcut/video-preview-v39.html",
|
|
52
|
+
"ui://markcut/video-preview-v38.html",
|
|
50
53
|
];
|
|
51
54
|
export const RESOURCE_MIME_TYPE = "text/html;profile=mcp-app";
|
|
52
55
|
// Google Maps JS loads libraries, tiles and Routes RPCs from these HTTPS origins.
|
|
@@ -170,8 +173,9 @@ async function pruneCache(dir, indexFile, entries, currentHash) {
|
|
|
170
173
|
export async function ensureVideoPreview(path, options = {}) {
|
|
171
174
|
const validatedPath = validateMarkdownPath(resolvePreviewPath(path));
|
|
172
175
|
await access(validatedPath, fsConstants.R_OK);
|
|
173
|
-
const
|
|
174
|
-
const
|
|
176
|
+
const input=fingerprintInputs(validatedPath);
|
|
177
|
+
const source=input.source.toString("utf8");
|
|
178
|
+
const sourceHash=createHash("sha256").update(input.source).update("\0").update(JSON.stringify(input.assets)).digest("hex");
|
|
175
179
|
const key=validatedPath+"\0"+sourceHash;
|
|
176
180
|
if(pendingCompiles.has(key))return pendingCompiles.get(key);
|
|
177
181
|
const prior=activeCompilesByPath.get(validatedPath)||Promise.resolve();
|
|
@@ -186,21 +190,13 @@ export async function ensureVideoPreview(path, options = {}) {
|
|
|
186
190
|
const cacheDir=resolve(outputRoot,"cache");
|
|
187
191
|
const indexFile=resolve(dir,"cache-index.json");
|
|
188
192
|
const audio=await readPreviewAudio(validatedPath);
|
|
189
|
-
const referencedAssets=
|
|
190
|
-
for(const match of source.matchAll(/\b(?:src|audio)\s*:\s*["']?([^"'\s;]+\.(?:png|jpe?g|webp|svg|gif|mp4|mov|webm|wav|mp3|m4a|ogg|vtt|srt))/gi)){
|
|
191
|
-
const candidate=match[1];
|
|
192
|
-
if(candidate.includes("://")||candidate.startsWith("/"))continue;
|
|
193
|
-
try {
|
|
194
|
-
const info=await stat(resolve(baseDir,candidate));
|
|
195
|
-
if(info.isFile())referencedAssets.push([candidate,info.size,info.mtimeMs]);
|
|
196
|
-
}catch{}
|
|
197
|
-
}
|
|
193
|
+
const referencedAssets=input.assets;
|
|
198
194
|
referencedAssets.sort((a,b)=>String(a[0]).localeCompare(String(b[0])));
|
|
199
195
|
// Compilation generates random scene ids. Identity must be based on inputs,
|
|
200
196
|
// not on non-semantic runtime ids, so unchanged files reuse identical cache.
|
|
201
197
|
if(audio.audioSrc && audio.audioSrc.startsWith("/")){
|
|
202
198
|
const info=await stat(audio.audioSrc);
|
|
203
|
-
referencedAssets.push([audio.audioSrc,
|
|
199
|
+
referencedAssets.push([audio.audioSrc,createHash("sha256").update(await readFile(audio.audioSrc)).digest("hex")]);
|
|
204
200
|
}
|
|
205
201
|
const hash=createHash("sha256").update(validatedPath).update("\0")
|
|
206
202
|
.update(source).update("\0").update(JSON.stringify(referencedAssets)).update("\0").update(audio.audioSrc||"")
|
|
@@ -241,7 +237,9 @@ export async function ensureVideoPreview(path, options = {}) {
|
|
|
241
237
|
catch(error){if(error.code!=="EEXIST")throw error;}
|
|
242
238
|
}
|
|
243
239
|
const currentSource=await readFile(validatedPath,"utf8");
|
|
244
|
-
|
|
240
|
+
const current=fingerprintInputs(validatedPath,Buffer.from(currentSource));
|
|
241
|
+
const currentHash=createHash("sha256").update(current.source).update("\0").update(JSON.stringify(current.assets)).digest("hex");
|
|
242
|
+
if(currentHash!==sourceHash)
|
|
245
243
|
throw new Error("Source changed during compilation; retry preview");
|
|
246
244
|
await mkdir(dir,{recursive:true});
|
|
247
245
|
report("publishing-static-preview");
|
|
@@ -268,25 +266,6 @@ export async function ensureVideoPreview(path, options = {}) {
|
|
|
268
266
|
// Compatibility export: there is no longer a managed player to stop.
|
|
269
267
|
export function stopManagedVideoPreview() {}
|
|
270
268
|
|
|
271
|
-
export function reviewResult(decision, feedback = "") {
|
|
272
|
-
if (decision === "approved") return { decision };
|
|
273
|
-
if (decision === "changes_requested") {
|
|
274
|
-
const normalized = typeof feedback === "string" ? feedback.trim() : "";
|
|
275
|
-
if (!normalized) throw new Error("feedback is required when requesting changes");
|
|
276
|
-
return { decision, feedback: normalized };
|
|
277
|
-
}
|
|
278
|
-
throw new Error(`unsupported review decision: ${String(decision)}`);
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
export function reviewMessage(result) {
|
|
282
|
-
const normalized = reviewResult(result?.decision, result?.feedback);
|
|
283
|
-
return {
|
|
284
|
-
jsonrpc: "2.0",
|
|
285
|
-
method: "ui/message",
|
|
286
|
-
params: { role: "user", content: [{ type: "text", text: JSON.stringify(normalized) }] },
|
|
287
|
-
};
|
|
288
|
-
}
|
|
289
|
-
|
|
290
269
|
export function buildPreviewHtml() {
|
|
291
270
|
const playerScriptUrl = publishPlayerBundle(bundlePath);
|
|
292
271
|
// Base64 keeps HTML parser-sensitive sequences inside the large JS bundle
|
package/src/mcp/server.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { z } from "zod";
|
|
|
6
6
|
import {publishPreviewRevision} from "./remote-assets.mjs";
|
|
7
7
|
import {startCompileOperation} from "./compile-operation.mjs";
|
|
8
8
|
import {
|
|
9
|
-
TOOL_NAME, RESOURCE_URI, LEGACY_RESOURCE_URIS, buildPreviewResourceResult, previewCsp, getPreviewMedia,
|
|
9
|
+
TOOL_NAME, RESOURCE_URI, LEGACY_RESOURCE_URIS, buildPreviewResourceResult, previewCsp, getPreviewMedia, stopManagedVideoPreview,
|
|
10
10
|
} from "./preview.mjs";
|
|
11
11
|
|
|
12
12
|
const server = new McpServer({ name: "markcut", version: "3.2.0" });
|
|
@@ -30,7 +30,11 @@ server.registerTool(
|
|
|
30
30
|
},
|
|
31
31
|
async ({contentHash}) => {
|
|
32
32
|
try {
|
|
33
|
-
|
|
33
|
+
// Mobile clients need the current published player without a server-owned
|
|
34
|
+
// review session. Both resources are immutable and keyed by contentHash.
|
|
35
|
+
const media=getPreviewMedia(contentHash);
|
|
36
|
+
media.playerUrl=publishPlayerBundle(fileURLToPath(new URL("./remotion-app.bundle.js",import.meta.url)),publicOrigin());
|
|
37
|
+
return {content:[{type:"text",text:"Preview media ready"}], structuredContent:media};
|
|
34
38
|
} catch (error) {
|
|
35
39
|
return {isError:true,content:[{type:"text",text:error.message||String(error)}]};
|
|
36
40
|
}
|
|
@@ -41,7 +45,7 @@ registerAppTool(
|
|
|
41
45
|
server,
|
|
42
46
|
TOOL_NAME,
|
|
43
47
|
{
|
|
44
|
-
description: "
|
|
48
|
+
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.",
|
|
45
49
|
inputSchema: z.object({
|
|
46
50
|
path: z.string().describe("Absolute .md path or NeoY HTTPS mounted file URL"),
|
|
47
51
|
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."),
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import {createHash} from "node:crypto";
|
|
2
|
+
import {closeSync,openSync,readFileSync,readSync,statSync} from "node:fs";
|
|
3
|
+
import {basename,dirname,isAbsolute,resolve} from "node:path";
|
|
4
|
+
|
|
5
|
+
const assetPattern=/\b(?:src|audio)\s*:\s*["']?([^"'\s;]+\.(?:png|jpe?g|webp|svg|gif|mp4|mov|webm|wav|mp3|m4a|ogg|vtt|srt))/gi;
|
|
6
|
+
function hashFile(path){
|
|
7
|
+
const fd=openSync(path,"r"),buffer=Buffer.allocUnsafe(1024*1024),hash=createHash("sha256");
|
|
8
|
+
try{let count;while((count=readSync(fd,buffer,0,buffer.length,null))>0)hash.update(buffer.subarray(0,count));return hash.digest("hex");}
|
|
9
|
+
finally{closeSync(fd);}
|
|
10
|
+
}
|
|
11
|
+
export function fingerprintInputs(path, sourceBytes=readFileSync(path)) {
|
|
12
|
+
const source=Buffer.isBuffer(sourceBytes)?sourceBytes:Buffer.from(sourceBytes);
|
|
13
|
+
const base=dirname(path), assets=[];
|
|
14
|
+
for(const match of source.toString("utf8").matchAll(assetPattern)){
|
|
15
|
+
const candidate=match[1]; if(candidate.includes("://")||isAbsolute(candidate))continue;
|
|
16
|
+
try {const file=resolve(base,candidate),info=statSync(file);if(info.isFile())assets.push([candidate,hashFile(file)]);}catch{}
|
|
17
|
+
}
|
|
18
|
+
if(![...source.toString("utf8").matchAll(assetPattern)].some(match=>/\baudio\s*:/i.test(match[0]))){
|
|
19
|
+
const file=resolve(base,basename(path,".md")+".wav");
|
|
20
|
+
try {const info=statSync(file);if(info.isFile())assets.push([file,hashFile(file)]);}catch{}
|
|
21
|
+
}
|
|
22
|
+
assets.sort((a,b)=>String(a[0]).localeCompare(String(b[0])));
|
|
23
|
+
return {source,assets};
|
|
24
|
+
}
|
|
@@ -3,7 +3,7 @@ import vm from 'node:vm';
|
|
|
3
3
|
import {webcrypto} from 'node:crypto';
|
|
4
4
|
import {buildPreviewBridgeScript} from '../src/mcp/bridge.mjs';
|
|
5
5
|
|
|
6
|
-
function harness(remoteData?:any, fetchOverride?:(url:string)=>Promise<any
|
|
6
|
+
function harness(remoteData?:any, fetchOverride?:(url:string)=>Promise<any>, toolCall?:(message:any)=>any) {
|
|
7
7
|
const messages:any[]=[];
|
|
8
8
|
const listeners:Record<string,Array<(evt:any)=>void>>={};
|
|
9
9
|
const element=()=>({value:'',textContent:'',onclick:null as null|(()=>void),oninput:null as null|(()=>void),
|
|
@@ -15,7 +15,8 @@ function harness(remoteData?:any, fetchOverride?:(url:string)=>Promise<any>) {
|
|
|
15
15
|
feedback:element(),status:element(),'path-label':element(),'video-md-version':element(),'interactive-ui':element(),approve:element(),changes:element(),'save-spot':element(),'remove-spot':element(),'comment-target':element(),'comment-count':element(),'comment-mode':element(),'overall-mode':element()
|
|
16
16
|
};
|
|
17
17
|
nodes['comment-mode'].value='spot';
|
|
18
|
-
|
|
18
|
+
let dispatch:(message:any,source?:any)=>void;
|
|
19
|
+
const parent={postMessage:(m:any)=>{messages.push(m);if(m.method==='tools/call'||m.method==='ui/message')setTimeout(()=>{const response=toolCall?.(m);dispatch?.(response?.rpcError?{id:m.id,error:response.rpcError}:{id:m.id,result:response||{content:[]}})},0)}};
|
|
19
20
|
const events:any[]=[];
|
|
20
21
|
const window={
|
|
21
22
|
parent,
|
|
@@ -23,9 +24,9 @@ function harness(remoteData?:any, fetchOverride?:(url:string)=>Promise<any>) {
|
|
|
23
24
|
dispatchEvent:(evt:any)=>{events.push(evt);return true},
|
|
24
25
|
};
|
|
25
26
|
const fetch=fetchOverride|| (async()=>({ok:true,json:async()=>remoteData}));
|
|
26
|
-
const context=vm.createContext({crypto:webcrypto,TextEncoder,URL,fetch,setTimeout,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}}});
|
|
27
|
-
|
|
28
|
-
const result=(data:any)=>dispatch({method:'ui/notifications/tool-result',params:{result:{structuredContent:data}}});
|
|
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
|
+
dispatch=(message:any,source=parent)=>(listeners.message??[]).forEach(listener=>listener({source,data:{jsonrpc:'2.0',...message}}));
|
|
29
|
+
const result=(data:any)=>dispatch({method:'ui/notifications/tool-result',params:{result:{structuredContent:{...data}}}});
|
|
29
30
|
const respond=(id:number,result:any={})=>dispatch({id,result});
|
|
30
31
|
vm.runInContext(buildPreviewBridgeScript().replaceAll("__MARKCUT_ORIGIN__",JSON.stringify("https://neoy.qili2.com")),context);
|
|
31
32
|
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}}))};
|
|
@@ -42,25 +43,34 @@ describe('MCP Remotion bridge',()=>{
|
|
|
42
43
|
expect(h.events.at(-1)?.detail?.revisionId).toBe('remote-r1');
|
|
43
44
|
expect(h.nodes.status.textContent).toBe('');
|
|
44
45
|
});
|
|
45
|
-
it('initializes, delivers compiled scenes and
|
|
46
|
+
it('initializes, delivers compiled scenes and sends review directly to the caller',async()=>{
|
|
46
47
|
const h=harness();
|
|
47
48
|
expect(h.messages[0]).toMatchObject({id:1,method:'ui/initialize'});
|
|
48
49
|
h.respond(1);
|
|
49
50
|
await nextTick();
|
|
50
51
|
expect(h.messages[1]).toMatchObject({method:'ui/notifications/initialized'});
|
|
51
52
|
const compiled={width:640,height:480,fps:30,children:[{name:'Scene-A',durationInSeconds:2}]};
|
|
52
|
-
h.result({id:'one',revisionId:'rev1',contentHash:'
|
|
53
|
+
h.result({id:'one',revisionId:'rev1',contentHash:'a'.repeat(64),path:'/tmp/a.md',compiled});
|
|
53
54
|
expect(h.events.map(e=>e.type)).toEqual(['markcut:revision']);
|
|
54
55
|
expect(h.events[0].detail.compiled).toEqual(compiled);
|
|
55
56
|
expect(h.nodes['path-label'].textContent).toBe('/tmp/a.md');
|
|
56
57
|
expect(h.nodes['video-md-version'].textContent).toBe('a');
|
|
57
|
-
expect(h.messages.filter(m=>m.method==='tools/call')).toHaveLength(0);
|
|
58
58
|
h.nodes.approve.onclick?.();
|
|
59
|
-
expect(h.messages
|
|
60
|
-
|
|
61
|
-
h.
|
|
59
|
+
expect(h.messages.filter(m=>m.method==='tools/call')).toHaveLength(0);
|
|
60
|
+
await nextTick();
|
|
61
|
+
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'});
|
|
63
|
+
h.respond(notification.id);
|
|
62
64
|
await nextTick();
|
|
63
|
-
expect(h.nodes.status.textContent).toBe('
|
|
65
|
+
expect(h.nodes.status.textContent).toBe('Review sent.');
|
|
66
|
+
});
|
|
67
|
+
it('retries ui/message delivery errors and never reports success before delivery',async()=>{
|
|
68
|
+
let failed=0;const h=harness(undefined,undefined,(m)=>{if(m.method==='ui/message'&&failed++<2)return {rpcError:{message:'temporary delivery failure'}};return {content:[]};});
|
|
69
|
+
h.result({id:'retry',revisionId:'retry-r1',contentHash:'c'.repeat(64),path:'/retry.md',compiled:{children:[]}});
|
|
70
|
+
h.nodes.approve.onclick?.();
|
|
71
|
+
for(let i=0;i<80&&h.messages.filter(m=>m.method==='ui/message').length<3;i++)await new Promise(resolve=>setTimeout(resolve,10));
|
|
72
|
+
expect(h.messages.filter(m=>m.method==='tools/call')).toHaveLength(0);
|
|
73
|
+
expect(h.messages.filter(m=>m.method==='ui/message')).toHaveLength(3);
|
|
64
74
|
});
|
|
65
75
|
it('keeps previews isolated per iframe and enforces feedback',async()=>{
|
|
66
76
|
const a=harness(),b=harness();
|
|
@@ -76,7 +86,7 @@ describe('MCP Remotion bridge',()=>{
|
|
|
76
86
|
a.nodes.feedback.value='Shorten the opening';
|
|
77
87
|
a.nodes['save-spot'].onclick?.();
|
|
78
88
|
a.nodes.changes.onclick?.();
|
|
79
|
-
expect(JSON.parse(a.messages
|
|
89
|
+
expect(JSON.parse(a.messages.find(m=>m.method==='ui/message').params.content[0].text)).toMatchObject({decision:'changes_requested',comments:[{scope:'overall',text:'Shorten the opening'}]});
|
|
80
90
|
expect(b.messages.filter(m=>m.method==='ui/message')).toHaveLength(0);
|
|
81
91
|
});
|
|
82
92
|
it('does not show the latest B result inside an A-bound iframe',()=>{
|
|
@@ -106,14 +116,15 @@ describe('MCP Remotion bridge',()=>{
|
|
|
106
116
|
second.dispatch({method:'ui/notifications/tool-input',params:{arguments:{path:url}}});
|
|
107
117
|
expect(second.events.at(-1).detail.revisionId).toBe('url-rev');
|
|
108
118
|
second.nodes.approve.onclick?.();
|
|
109
|
-
expect(
|
|
119
|
+
expect(second.messages.filter(m=>m.method==='tools/call')).toHaveLength(0);
|
|
110
120
|
});
|
|
111
|
-
it('preserves optional Relay job/task context across review decisions',()=>{
|
|
121
|
+
it('preserves optional Relay job/task context across review decisions',async()=>{
|
|
112
122
|
const h=harness();
|
|
113
123
|
const relay={jobId:'job-7',taskId:19,executionId:'exec-1'};
|
|
114
124
|
h.result({id:'r',revisionId:'r',contentHash:'hash',path:'/video.md',relay,compiled:{children:[]}});
|
|
115
125
|
h.selectSpot(0);h.nodes.feedback.value='shorter title';h.nodes['save-spot'].onclick?.();h.nodes.changes.onclick?.();
|
|
116
|
-
|
|
126
|
+
await nextTick();
|
|
127
|
+
expect(JSON.parse(h.messages.find(m=>m.method==='ui/message').params.content[0].text).relay).toEqual(relay);
|
|
117
128
|
});
|
|
118
129
|
it('handles request changes followed by a new revision and approval in the same app',async()=>{
|
|
119
130
|
const h=harness();h.respond(1);await nextTick();
|
|
@@ -121,8 +132,9 @@ describe('MCP Remotion bridge',()=>{
|
|
|
121
132
|
const next={id:'second',revisionId:'r2',contentHash:'sha2',path:'/video.md',compiled:{children:[{name:'Next'}]}};
|
|
122
133
|
h.result(first);
|
|
123
134
|
h.selectSpot(0);h.nodes.feedback.value='lowercase title';h.nodes['save-spot'].onclick?.();h.nodes.changes.onclick?.();
|
|
124
|
-
expect(JSON.parse(h.messages
|
|
125
|
-
|
|
135
|
+
expect(JSON.parse(h.messages.find(m=>m.method==='ui/message').params.content[0].text)).toMatchObject({decision:'changes_requested'});
|
|
136
|
+
await nextTick();
|
|
137
|
+
h.respond(3);await nextTick();
|
|
126
138
|
expect(h.nodes.status.textContent).toContain('Waiting for the updated preview');
|
|
127
139
|
h.nodes.approve.onclick?.();
|
|
128
140
|
expect(h.messages.filter(m=>m.method==='ui/message')).toHaveLength(1);
|
|
@@ -130,7 +142,7 @@ describe('MCP Remotion bridge',()=>{
|
|
|
130
142
|
h.nodes.approve.onclick?.();
|
|
131
143
|
const decisions=h.messages.filter(m=>m.method==='ui/message').map(m=>JSON.parse(m.params.content[0].text));
|
|
132
144
|
expect(decisions).toHaveLength(2);
|
|
133
|
-
expect(decisions[1]).toMatchObject({
|
|
145
|
+
expect(decisions[1]).toMatchObject({contentHash:'sha2',decision:'approved'});
|
|
134
146
|
});
|
|
135
147
|
|
|
136
148
|
});
|
|
@@ -186,7 +198,7 @@ describe('MCP Remotion bridge',()=>{
|
|
|
186
198
|
dots=h.events.filter(e=>e.type==='markcut:spots-change').at(-1).detail.spots;
|
|
187
199
|
expect(dots.filter((x:any)=>x.scope==='overall')).toEqual([expect.objectContaining({text:'Overall draft'})]);
|
|
188
200
|
});
|
|
189
|
-
it('saves overall, scene and spot scopes at their canonical timeline positions',()=>{
|
|
201
|
+
it('saves overall, scene and spot scopes at their canonical timeline positions',async()=>{
|
|
190
202
|
const h=harness();h.result({id:'multi',revisionId:'r1',contentHash:'hash',compiled:{children:[]}});
|
|
191
203
|
h.selectSpot(0);
|
|
192
204
|
h.nodes.feedback.value='Improve pacing';h.nodes['save-spot'].onclick?.();
|
|
@@ -200,10 +212,11 @@ describe('MCP Remotion bridge',()=>{
|
|
|
200
212
|
expect(h.events.filter(e=>e.type==='markcut:comments-change').at(-1).detail.sceneNames).toEqual(['Scene-A']);
|
|
201
213
|
h.nodes.approve.onclick?.();expect(h.nodes.status.textContent).toContain('Submit or remove');
|
|
202
214
|
h.nodes.changes.onclick?.();
|
|
215
|
+
await nextTick();
|
|
203
216
|
const payload=JSON.parse(h.messages.filter(m=>m.method==='ui/message').at(-1).params.content[0].text);
|
|
204
217
|
expect(payload.comments.map((x:any)=>x.scope)).toEqual(['overall','scene','spot']);
|
|
205
218
|
});
|
|
206
|
-
it('supports multiple timed notes on one scene and restores a saved note',()=>{
|
|
219
|
+
it('supports multiple timed notes on one scene and restores a saved note',async()=>{
|
|
207
220
|
const h=harness();
|
|
208
221
|
h.result({id:'spots',revisionId:'r1',contentHash:'hash',compiled:{children:[]}});
|
|
209
222
|
h.scene({sceneId:'s1',sceneName:'Scene-A',timeSeconds:1});
|
|
@@ -222,13 +235,14 @@ describe('MCP Remotion bridge',()=>{
|
|
|
222
235
|
h.nodes.feedback.value='Trim first second';
|
|
223
236
|
h.nodes['save-spot'].onclick?.();
|
|
224
237
|
h.nodes.changes.onclick?.();
|
|
238
|
+
await nextTick();
|
|
225
239
|
const payload=JSON.parse(h.messages.at(-1).params.content[0].text);
|
|
226
240
|
expect(payload.comments).toHaveLength(2);
|
|
227
241
|
expect(h.nodes['comment-count'].textContent).toBe('2 comments');
|
|
228
242
|
expect(payload.comments.map((x:any)=>x.text)).toContain('Trim first second');
|
|
229
243
|
expect(payload.comments.map((x:any)=>x.text)).toContain('Keep reaction');
|
|
230
244
|
});
|
|
231
|
-
it('keeps typed text across scope switches and blocks unsaved submission',()=>{
|
|
245
|
+
it('keeps typed text across scope switches and blocks unsaved submission',async()=>{
|
|
232
246
|
const h=harness();h.result({id:'draft',revisionId:'r',contentHash:'hash',compiled:{children:[]}});
|
|
233
247
|
h.scene({sceneId:'s1',sceneName:'Scene-A',sceneStart:2,timeSeconds:3});
|
|
234
248
|
h.nodes.feedback.value='Keep this text';
|
|
@@ -240,9 +254,10 @@ describe('MCP Remotion bridge',()=>{
|
|
|
240
254
|
const note=h.events.filter(e=>e.type==='markcut:spots-change').at(-1).detail.spots.find((x:any)=>!x.placeholder);
|
|
241
255
|
h.selectSpot(note.id);
|
|
242
256
|
h.nodes.changes.onclick?.();
|
|
257
|
+
await nextTick();
|
|
243
258
|
expect(h.messages.filter(m=>m.method==='ui/message')).toHaveLength(1);
|
|
244
259
|
});
|
|
245
|
-
it('deletes only the selected timeline marker',()=>{
|
|
260
|
+
it('deletes only the selected timeline marker',async()=>{
|
|
246
261
|
const h=harness();h.result({id:'dots',revisionId:'r1',contentHash:'hash',compiled:{children:[]}});
|
|
247
262
|
h.scene({sceneId:'s1',sceneName:'Scene-A',timeSeconds:1});
|
|
248
263
|
h.nodes.feedback.value='First';h.nodes['save-spot'].onclick?.();
|
|
@@ -255,6 +270,7 @@ describe('MCP Remotion bridge',()=>{
|
|
|
255
270
|
expect(h.nodes['remove-spot'].disabled).toBe(true);
|
|
256
271
|
expect(h.events.filter(e=>e.type==='markcut:spots-change').at(-1).detail.spots).toHaveLength(2);
|
|
257
272
|
h.nodes.changes.onclick?.();
|
|
273
|
+
await nextTick();
|
|
258
274
|
expect(JSON.parse(h.messages.at(-1).params.content[0].text).comments.map((x:any)=>x.text)).toEqual(['Second']);
|
|
259
275
|
});
|
|
260
276
|
describe('static compiled-JSON bridge',()=>{
|
|
@@ -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,
|
|
3
|
+
import {buildPreviewHtml,buildPreviewResourceResult,RESOURCE_URI,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';
|
|
@@ -20,7 +20,7 @@ describe('Markcut Remotion MCP App',()=>{
|
|
|
20
20
|
expect(html).toContain('#comment-tools>*{width:30px;height:28px;padding:0;border:0');
|
|
21
21
|
expect(html).toContain('https://neoy.example.test/files/_neoy/markcut/player/');
|
|
22
22
|
expect(html).not.toContain('id="remotion-bundle"');
|
|
23
|
-
expect(html.length).toBeLessThan(
|
|
23
|
+
expect(html.length).toBeLessThan(24000);
|
|
24
24
|
expect(html).not.toContain('<video id="video-player"');
|
|
25
25
|
expect(html).not.toContain('data:video/mp4');
|
|
26
26
|
expect(html).not.toContain('127.0.0.1');
|
|
@@ -44,7 +44,10 @@ describe('Markcut Remotion MCP App',()=>{
|
|
|
44
44
|
expect(script).toContain('ui/notifications/tool-result');
|
|
45
45
|
expect(script).toContain("CustomEvent('markcut:revision'");
|
|
46
46
|
expect(script).toContain('data.compiled');
|
|
47
|
-
expect(script).not.toContain(
|
|
47
|
+
expect(script).not.toContain('markcut.review.decide');
|
|
48
|
+
expect(script).not.toContain('markcut.review.get');
|
|
49
|
+
expect(script).toContain("request('ui/message'");
|
|
50
|
+
expect(script).not.toContain('pollDecision');
|
|
48
51
|
expect(script).not.toContain('videoBase64');
|
|
49
52
|
expect(script).toContain('fetch(');
|
|
50
53
|
expect(script).toContain('/files/_neoy/markcut/revisions/');
|
|
@@ -74,8 +77,4 @@ describe('Markcut Remotion MCP App',()=>{
|
|
|
74
77
|
expect(compiled.root.children).toHaveLength(1);
|
|
75
78
|
expect(mixed.root.durationInSeconds).toBe(6);
|
|
76
79
|
});
|
|
77
|
-
|
|
78
|
-
expect(reviewResult('approved')).toEqual({decision:'approved'});
|
|
79
|
-
expect(()=>reviewResult('changes_requested','')).toThrow(/feedback/);
|
|
80
|
-
});
|
|
81
|
-
});
|
|
80
|
+
});
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import {describe,it,expect} from 'vitest';
|
|
2
|
+
import {readFile} from 'node:fs/promises';
|
|
3
|
+
|
|
4
|
+
describe('stateless Markcut review',()=>{
|
|
5
|
+
it('does not register review session tools or reference a session store',async()=>{
|
|
6
|
+
const server=await readFile(new URL('../src/mcp/server.mjs',import.meta.url),'utf8');
|
|
7
|
+
const operation=await readFile(new URL('../src/mcp/compile-operation.mjs',import.meta.url),'utf8');
|
|
8
|
+
const worker=await readFile(new URL('../src/mcp/compile-worker.mjs',import.meta.url),'utf8');
|
|
9
|
+
const source=server+operation+worker;
|
|
10
|
+
for(const tool of ['markcut.review.list','markcut.review.get','markcut.review.media','markcut.review.decide'])expect(source).not.toContain(tool);
|
|
11
|
+
expect(source).toContain('markcut.preview.media');
|
|
12
|
+
expect(server).toContain('media.playerUrl=publishPlayerBundle');
|
|
13
|
+
expect(source).not.toContain('review-sessions.json');
|
|
14
|
+
expect(source).not.toContain('createOrReuseReviewSession');
|
|
15
|
+
expect(source).not.toContain('publishReviewRevision');
|
|
16
|
+
});
|
|
17
|
+
});
|