Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Load composition preview media on demand instead of all at once

Claude6c76bbb8805c
diff --git a/.claude/skills/portos-music-video-code/SKILL.md b/.claude/skills/portos-music-video-code/SKILL.md
index 1baf85d2ad..71096ea1e6 100644
--- a/.claude/skills/portos-music-video-code/SKILL.md
+++ b/.claude/skills/portos-music-video-code/SKILL.md
@@ -42,6 +42,6 @@ Choose **Design and composition media** independently of **Authoring renderer**.
In **Compose → Document**, choose **Three.js authored worlds → Generate authored 3D composition** for complete geometry scenes. Each section's `render(ctx, env)` receives `ctx.THREE`, a fresh `ctx.scene`, a perspective `ctx.camera`, and the transparent Canvas2D `ctx.text`. Author environments, articulated characters, props, lights, camera movement and dramatic actions from absolute song time. Every seek creates a fresh world; do not integrate physics or depend on earlier frames. This generated renderer currently composes geometry and typography only. Use the Canvas layered renderer or an imported document for selected images/video. Native **Code** remains a separate 720p Canvas capability, not the definition of code-only.
-PortOS packages installed Three.js, license, local fonts, validated author functions and a dependency hash manifest in the immutable document version. It does not install packages, load CDNs or grant network access. Preview supports acyclic local static ES-module graphs (including inline module entrypoints); remote/bare/dynamic imports are unsupported. The same `portosComposition.seek(t)` drives preview, excerpt and final capture, normally 1080p24. Finish every `await` (image decode; video `seeked` plus a presented frame, as the layered template's `seekVideo` waits for) before clearing, drawing or showing a layer: the render waits for the whole seek, but the live preview paints at each await, so clear-then-await flashes in the preview only. Imported documents may declare supported motion blur; export honors that contract. A valid contract proves execution, not art quality: inspect authored characters/action and changing frames, then the existing treatment/proof workflow decides readiness.
+PortOS packages installed Three.js, license, local fonts, validated author functions and a dependency hash manifest in the immutable document version. It does not install packages, load CDNs or grant network access. Preview supports acyclic local static ES-module graphs (including inline module entrypoints); remote/bare/dynamic imports are unsupported. The same `portosComposition.seek(t)` drives preview, excerpt and final capture, normally 1080p24. Finish every `await` (image decode; video `seeked` plus a presented frame, as the layered template's `seekVideo` waits for) before clearing, drawing or showing a layer: the render waits for the whole seek, but the live preview paints at each await, so clear-then-await flashes in the preview only. Preview media loads on demand when a media `src` first names it, so a far scrub waits for that file inside `seek`; keep decoded-image caches to a few seconds around the playhead (a 2048×1152 frame decodes to about 9 MB), or iPhone Safari reloads the tab. Imported documents may declare supported motion blur; export honors that contract. A valid contract proves execution, not art quality: inspect authored characters/action and changing frames, then the existing treatment/proof workflow decides readiness.
Code-only autopilot preserves text direction and defaults to this document authoring path, retaining explicitly saved legacy Code choices. It never requests image guides or an image/video provider. Code-rendered prototypes and visual planning remain required by the production review workflow; skipping raster moodboard assets is not approval to skip art direction.
diff --git a/client/src/components/musicVideo/CompositionPreviewPlayer.jsx b/client/src/components/musicVideo/CompositionPreviewPlayer.jsx
index 7744682bee..c9ea8b9e2d 100644
--- a/client/src/components/musicVideo/CompositionPreviewPlayer.jsx
+++ b/client/src/components/musicVideo/CompositionPreviewPlayer.jsx
@@ -16,12 +16,29 @@ const lyricAt = (cues, t) => {
const DESKTOP_QUERY = '(min-width: 1024px)';
const startsDeferred = (collapsed) => collapsed && window.matchMedia?.(DESKTOP_QUERY).matches === false;
+// Fetched preview media kept for the iframe to ask for again (a scrub back, a
+// rebuilt document). Least recently used blobs go first; the newest one stays
+// even when it alone exceeds the budget. A phone tab's memory is the limit.
+export const PREVIEW_BLOB_BUDGET_BYTES = 64 * 1024 * 1024;
+const remember = (cache, url, blob) => {
+ cache.set(url, blob);
+ let total = 0;
+ for (const kept of cache.values()) total += kept.size;
+ for (const [key, kept] of cache) {
+ if (total <= PREVIEW_BLOB_BUDGET_BYTES || cache.size === 1) break;
+ cache.delete(key);
+ total -= kept.size;
+ }
+};
+
/**
* Live preview of the project's composition document: the sandboxed iframe,
* the song, play/scrub and the lyric line being sung. The iframe runs in an
- * opaque-origin sandbox that cannot fetch, so this component fetches the scene
- * takes and document media and posts them in as Blobs over the
- * `portos-mv:*` message bridge, then drives the document with seek messages.
+ * opaque-origin sandbox that cannot fetch, so this component posts it the
+ * manifest of bridged media, fetches each scene take or document file only
+ * when the document first asks for it (`portos-mv:request`), posts it in as a
+ * Blob over the `portos-mv:*` message bridge, and drives the document with
+ * seek messages. Only listed keys are ever fetched.
*
* `seekRequest` (`{ t, n }`) moves the player from outside — the board seeks it
* to a scene's start; `n` changes on every request so seeking twice to the same
@@ -61,6 +78,7 @@ export default function CompositionPreviewPlayer({ project, audioUrl, seekReques
let active = true;
setPreview(null);
setPreviewError('');
+ setStatus('');
seekState.current = { inFlight: false, pending: null, ready: false };
if (!refresh || !wanted) return () => { active = false; };
getMusicVideoCompositionPreview(project.id, { silent: true, draft })
@@ -81,31 +99,53 @@ export default function CompositionPreviewPlayer({ project, audioUrl, seekReques
useEffect(() => {
if (!preview) return undefined;
let active = true;
+ let missing = false;
+ let firstFrame = true;
+ const inFlight = new Map();
+ const byKey = new Map((preview.assets || []).map((asset) => [String(asset.key).replace(/^\.\//, ''), asset]));
+ // Only the first frame announces loading: a status line appearing on every later fetch would shift the layout mid-playback.
+ const showStatus = () => {
+ if (active) setStatus(missing ? 'Some preview media could not be loaded' : firstFrame ? 'Loading preview media…' : '');
+ };
+ const mediaFor = async (url) => {
+ const cache = blobCache.current;
+ if (cache.has(url)) {
+ const blob = cache.get(url);
+ cache.delete(url);
+ cache.set(url, blob);
+ return blob;
+ }
+ if (!inFlight.has(url)) {
+ inFlight.set(url, fetchMusicVideoPreviewAsset(url)
+ .then((blob) => { remember(cache, url, blob); return blob; }, () => null)
+ .finally(() => inFlight.delete(url)));
+ }
+ return inFlight.get(url);
+ };
const onMessage = async (event) => {
if (event.source !== iframeRef.current?.contentWindow) return;
const message = event.data || {};
const state = seekState.current;
if (message.type === 'portos-mv:loaded') {
- const files = {};
- let loaded = 0;
- let missingMedia = false;
- for (const asset of preview.assets || []) {
- if (!active) return;
- setStatus(`Loading preview media ${loaded + 1}/${preview.assets.length}…`);
- const blob = blobCache.current.get(asset.url) || await fetchMusicVideoPreviewAsset(asset.url).catch(() => null);
- if (blob) { blobCache.current.set(asset.url, blob); files[asset.key] = blob; }
- else missingMedia = true;
- loaded += 1;
- }
- if (!active) return;
- setStatus(missingMedia ? 'Some preview media could not be loaded' : '');
- iframeRef.current?.contentWindow?.postMessage({ type: 'portos-mv:assets', files }, '*');
+ // The manifest only: each file is fetched when the document first asks for it, so the first
+ // frame waits on the media near the playhead rather than on every take in the project.
+ event.source.postMessage({ type: 'portos-mv:manifest', keys: [...byKey.keys()] }, '*');
+ showStatus();
state.ready = true;
postSeek(t);
+ } else if (message.type === 'portos-mv:request') {
+ const key = String(message.key);
+ const asset = byKey.get(key);
+ const blob = asset ? await mediaFor(asset.url) : null;
+ if (!blob) { missing = true; showStatus(); }
+ if (active) event.source.postMessage({ type: 'portos-mv:asset', key, blob }, '*');
} else if (message.type === 'portos-mv:seeked') {
+ if (firstFrame) { firstFrame = false; showStatus(); }
state.inFlight = false;
if (state.pending != null) { const next = state.pending; state.pending = null; postSeek(next); }
} else if (message.type === 'portos-mv:error') {
+ firstFrame = false;
+ showStatus();
state.inFlight = false;
setPreviewError(String(message.message || 'The composition document failed in the preview'));
}
diff --git a/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx b/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx
index 0e0ba57322..577d3604b7 100644
--- a/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx
+++ b/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx
@@ -7,7 +7,7 @@ const api = vi.hoisted(() => ({
}));
vi.mock('../../services/apiMusicVideo.js', () => api);
-import CompositionPreviewPlayer from './CompositionPreviewPlayer.jsx';
+import CompositionPreviewPlayer, { PREVIEW_BLOB_BUDGET_BYTES } from './CompositionPreviewPlayer.jsx';
const DOCUMENT = { directory: 'music-video/mv-1/composition/doc-a', entry: 'index.html' };
const project = {
@@ -21,28 +21,69 @@ beforeEach(() => {
});
describe('CompositionPreviewPlayer', () => {
- it.each([false, true])('loads available preview media and reports missing assets when a fetch fails (%s)', async (missing) => {
- const assets = [{ key: 'scene-a', url: '/preview/scene-a' }, { key: 'scene-b', url: '/preview/scene-b' }];
- const blob = new Blob(['example media'], { type: 'image/png' });
- let finishPreview;
- api.getMusicVideoCompositionPreview.mockImplementation(() => new Promise((resolve) => { finishPreview = resolve; }));
- api.fetchMusicVideoPreviewAsset.mockImplementation((url) => missing && url === assets[1].url
- ? Promise.reject(new Error('Example unavailable asset')) : Promise.resolve(blob));
+ // The iframe is played by the test: it reports `loaded`, then asks for keys the way the bootstrap does.
+ const loadPreview = async (assets) => {
+ api.getMusicVideoCompositionPreview.mockResolvedValue({ html: '<!doctype html><p>preview</p>', assets, fps: 24, durationSec: 10 });
render(<CompositionPreviewPlayer project={project} audioUrl={null} />);
- await act(async () => {
- finishPreview({ html: '<!doctype html><p>preview</p>', assets, fps: 24, durationSec: 10 });
- });
- const frame = screen.getByTitle('Composition document preview');
+ const frame = await screen.findByTitle('Composition document preview');
const post = vi.spyOn(frame.contentWindow, 'postMessage');
- await act(async () => {
- window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, data: { type: 'portos-mv:loaded' } }));
+ const send = (data) => act(async () => {
+ window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, data }));
});
- await waitFor(() => expect(post).toHaveBeenCalledWith({
- type: 'portos-mv:assets', files: missing ? { 'scene-a': blob } : { 'scene-a': blob, 'scene-b': blob },
- }, '*'));
- if (missing) expect(screen.getByText('Some preview media could not be loaded')).toBeInTheDocument();
- else expect(screen.queryByText('Some preview media could not be loaded')).not.toBeInTheDocument();
- expect(screen.queryByText(/Loading preview media/)).not.toBeInTheDocument();
+ await send({ type: 'portos-mv:loaded' });
+ const ask = async (key) => {
+ await send({ type: 'portos-mv:request', key });
+ await waitFor(() => expect(post).toHaveBeenCalledWith(expect.objectContaining({ type: 'portos-mv:asset', key }), '*'));
+ const answer = post.mock.calls.filter(([data]) => data.type === 'portos-mv:asset' && data.key === key).at(-1)[0];
+ post.mockClear();
+ return answer.blob;
+ };
+ return { post, send, ask };
+ };
+
+ it('posts the media manifest first and fetches only the files the document asks for', async () => {
+ const assets = [{ key: 'media/scene-a.mp4', url: '/preview/scene-a' }, { key: 'media/scene-b.png', url: '/preview/scene-b' }, { key: 'media/scene-c.png', url: '/preview/scene-c' }];
+ const blob = new Blob(['example media'], { type: 'image/png' });
+ api.fetchMusicVideoPreviewAsset.mockResolvedValue(blob);
+ const { post, ask } = await loadPreview(assets);
+ expect(post).toHaveBeenCalledWith({ type: 'portos-mv:manifest', keys: assets.map((asset) => asset.key) }, '*');
+ expect(post).toHaveBeenCalledWith({ type: 'portos-mv:seek', t: 0 }, '*');
+ expect(api.fetchMusicVideoPreviewAsset).not.toHaveBeenCalled();
+
+ expect(await ask('media/scene-b.png')).toBe(blob);
+ expect(api.fetchMusicVideoPreviewAsset.mock.calls).toEqual([['/preview/scene-b']]);
+ // A key outside the manifest is refused without a request: document code names nothing else.
+ expect(await ask('../secrets.png')).toBeNull();
+ expect(api.fetchMusicVideoPreviewAsset).toHaveBeenCalledTimes(1);
+ expect(screen.queryByText('Some preview media could not be loaded')).toBeInTheDocument();
+ });
+
+ it('answers a failed fetch with no blob and reports the missing media once the first frame is drawn', async () => {
+ api.fetchMusicVideoPreviewAsset.mockRejectedValue(new Error('Example unavailable asset'));
+ const { send, ask } = await loadPreview([{ key: 'media/scene-a.png', url: '/preview/scene-a' }]);
+ expect(screen.getByText('Loading preview media…')).toBeInTheDocument();
+ expect(await ask('media/scene-a.png')).toBeNull();
+ await send({ type: 'portos-mv:seeked', t: 0 });
+ expect(screen.getByText('Some preview media could not be loaded')).toBeInTheDocument();
+ expect(screen.queryByText('Loading preview media…')).not.toBeInTheDocument();
+ });
+
+ it('keeps fetched media within the blob budget, dropping the least recently used file first', async () => {
+ const assets = ['a', 'b', 'c', 'd'].map((name) => ({ key: `media/${name}.jpg`, url: `/preview/${name}` }));
+ // Each file is half the budget, so two fit; sizes stand in for real blobs without allocating them.
+ api.fetchMusicVideoPreviewAsset.mockImplementation(async (url) => ({ url, size: PREVIEW_BLOB_BUDGET_BYTES / 2 }));
+ const { ask } = await loadPreview(assets);
+ const fetched = () => api.fetchMusicVideoPreviewAsset.mock.calls.map(([url]) => url);
+ await ask('media/a.jpg');
+ await ask('media/b.jpg');
+ await ask('media/a.jpg'); // cached, and now the most recently used
+ expect(fetched()).toEqual(['/preview/a', '/preview/b']);
+ await ask('media/c.jpg'); // over budget: b goes, a stays
+ await ask('media/a.jpg');
+ expect(fetched()).toEqual(['/preview/a', '/preview/b', '/preview/c']);
+ await ask('media/b.jpg'); // evicted, so fetched again (and c, now oldest, goes)
+ await ask('media/c.jpg');
+ expect(fetched()).toEqual(['/preview/a', '/preview/b', '/preview/c', '/preview/b', '/preview/c']);
});
it('keeps the loaded preview through an unrelated project save and rebuilds when the document version changes', async () => {
diff --git a/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.md
index 1c3c954dd8..c4729a5ac9 100644
--- a/docs/HTML_COMPOSITIONS.md
+++ b/docs/HTML_COMPOSITIONS.md
@@ -392,9 +392,23 @@ front of the template's engine tag.
The in-app preview is a self-contained `srcdoc` in an opaque-origin sandbox
with no network: the server inlines the document's scripts, stylesheets and
-small assets, the PortOS page fetches the larger media on the user's behalf
-and posts it in as Blobs (`window.PORTOS_MV_ASSETS` resolves to
-`{ src: blobUrl }`), and the scrubber posts `portos-mv:seek` messages.
+small assets, and the scrubber posts `portos-mv:seek` messages. Larger media
+is bridged on demand: the PortOS page posts only the list of files
+(`window.PORTOS_MV_ASSETS` resolves to `{ src: src }`), and the first time a
+script sets a media element's `src` to one of them, the page fetches that file
+on the user's behalf and posts it in as a Blob (`window.PORTOS_MV_ASSET(src)`
+returns a promise of its blob: URL for other uses). The page keeps a bounded
+cache of fetched files, and object URLs idle for a few seconds are revoked
+once the preview holds more than 64 MB, unless a media element still plays
+them. So assign `src` when a frame needs the file, not every file at startup.
+
+Bound your own decoded-image cache the same way. A decoded 2048×1152 frame
+costs about 9 MB however small its JPEG is, so a cache of 90 atlases can hold
+most of a gigabyte, and iPhone Safari reloads the tab ("A problem repeatedly
+occurred") or purges and re-decodes images mid-playback. Keep a few seconds
+around the playhead (for example the current frame plus the next one or two
+seconds), release the rest by dropping their `Image` objects, and decode the
+next frame inside `seek` before drawing it.
## Launch-video admission (API foundation)
diff --git a/server/services/musicVideo/documentPreview.js b/server/services/musicVideo/documentPreview.js
index a3f9826be5..644776c72c 100644
--- a/server/services/musicVideo/documentPreview.js
+++ b/server/services/musicVideo/documentPreview.js
@@ -11,14 +11,18 @@ import { musicVideoMediaMode } from '../../lib/musicVideoMediaPolicy.js';
* - the document's own scripts and stylesheets inlined, and every file its
* CSS or `<img>` tags name inlined as a data: URL;
* - `window.PORTOS_MV` built exactly as a render builds it (portos-mv.js);
- * - a bootstrap that receives the large media (scene takes, shipped video
- * and images) as Blobs the PortOS page fetched on the user's behalf and
- * posted in (`portos-mv:assets`), exposes them as `window.PORTOS_MV_ASSETS`
- * (a promise of `{ 'media/…': 'blob:…' }`), maps any relative media `src`
- * a script sets onto them, and answers `portos-mv:seek` messages.
+ * - a bootstrap that bridges the large media (scene takes, shipped video and
+ * images) on demand: the PortOS page posts the manifest of keys
+ * (`portos-mv:manifest`, resolving `window.PORTOS_MV_ASSETS` to
+ * `{ 'media/…': 'media/…' }`); the first relative media `src` naming a key
+ * asks the page for that one file (`portos-mv:request` →
+ * `portos-mv:asset` with a Blob the page fetched on the user's behalf) and
+ * then points at its blob: URL. Past PREVIEW_MEDIA_BUDGET_BYTES, URLs idle
+ * for a few seconds and no longer playing in a media element are revoked.
+ * It also answers `portos-mv:seek` messages.
*
- * `assets` lists what the client should fetch and post: `{ key, url }` with
- * `url` a same-origin PortOS path.
+ * `assets` lists what the client may fetch when asked: `{ key, url }` with
+ * `url` a same-origin PortOS path. The page never fetches an unlisted key.
*/
import { readFile } from 'fs/promises';
@@ -35,6 +39,9 @@ import {
const INLINE_FILE_MAX = 4 * 1024 * 1024;
const INLINE_TOTAL_MAX = 24 * 1024 * 1024;
const BRIDGED = new Set(['.mp4', '.mov', '.webm', '.mp3', '.wav', '.png', '.jpg', '.jpeg', '.webp', '.gif']);
+// Blob bytes the preview keeps object URLs for before revoking idle ones (a phone tab's memory is the limit).
+export const PREVIEW_MEDIA_BUDGET_BYTES = 64 * 1024 * 1024;
+const PREVIEW_MEDIA_IDLE_MS = 5000;
export const PREVIEW_CSP = [
"default-src 'none'", "script-src 'unsafe-inline' data:", "style-src 'unsafe-inline'",
@@ -59,8 +66,12 @@ const BOOTSTRAP = `(() => {
Object.defineProperty(globalThis, key, { configurable: false, writable: false,
value: function() { throw new Error(key + ' is disabled in compositions'); } });
}
- const map = new Map();
- let resolved = false;
+ // Media arrives on demand: the parent posts a manifest of bridged keys, and the first relative src
+ // naming one asks the parent for that file alone, so a phone never holds every take and atlas at once.
+ const map = new Map(); // key → { url, size, used, media: Set<WeakRef> } for files received
+ const waiting = new Map(); // key → callbacks awaiting the parent's answer
+ const assigned = new WeakMap(); // element → token of its latest src assignment (a stale answer must not win)
+ let keys = null; // the manifest; null until the parent posts it
let resolveAssets;
window.PORTOS_MV_PREVIEW = true;
window.PORTOS_MV_ASSETS = new Promise((resolve) => { resolveAssets = resolve; });
@@ -72,6 +83,55 @@ const BOOTSTRAP = `(() => {
// anything else is a relative src whose query and hash are not.
const keyOf = (value) => { const path = local(value); return path !== value ? String(path) : String(value).replace(/^\\.\\//, '').split(/[?#]/)[0]; };
const relative = (value) => { value = local(value); return typeof value === 'string' && value && !/^[a-z][a-z0-9+.-]*:/i.test(value) && !value.startsWith('/'); };
+ const post = (message) => parent.postMessage(message, '*');
+ // Received files past this many bytes are revoked once idle and no media element still plays them;
+ // a later src asks the parent again (its own bounded cache usually answers without a refetch).
+ const BUDGET_BYTES = ${PREVIEW_MEDIA_BUDGET_BYTES};
+ const IDLE_MS = ${PREVIEW_MEDIA_IDLE_MS};
+ const inUse = (entry) => {
+ for (const ref of entry.media) {
+ const el = ref.deref();
+ if (el && (el.getAttribute('src') === entry.url || el.currentSrc === entry.url)) return true;
+ entry.media.delete(ref);
+ }
+ return false;
+ };
+ const sweep = () => {
+ let total = 0;
+ for (const entry of map.values()) total += entry.size;
+ const now = performance.now();
+ for (const [key, entry] of [...map].sort((a, b) => a[1].used - b[1].used)) {
+ if (total <= BUDGET_BYTES) return;
+ if (now - entry.used < IDLE_MS || inUse(entry)) continue;
+ URL.revokeObjectURL(entry.url);
+ map.delete(key);
+ total -= entry.size;
+ }
+ };
+ // Calls back with the file's entry (null when the parent has none), asking the parent at most once at a time.
+ const request = (key, callback) => {
+ const entry = map.get(key);
+ if (entry) { entry.used = performance.now(); return callback(entry); }
+ if (!waiting.has(key)) { waiting.set(key, []); post({ type: 'portos-mv:request', key }); }
+ waiting.get(key).push(callback);
+ };
+ const apply = (el, desc, value, token) => {
+ const key = keyOf(value);
+ if (!keys.has(key)) return desc.set.call(el, value);
+ request(key, (entry) => {
+ if (assigned.get(el) !== token) return;
+ if (!entry) return desc.set.call(el, value);
+ if (el instanceof HTMLMediaElement || el instanceof HTMLSourceElement) entry.media.add(new WeakRef(el));
+ desc.set.call(el, entry.url);
+ });
+ };
+ // A promise of a bridged file's blob: URL (null when unavailable), for uses other than a media src.
+ // An idle URL can be revoked later, so ask again for each new use.
+ window.PORTOS_MV_ASSET = (value) => window.PORTOS_MV_ASSETS.then(() => new Promise((resolve) => {
+ const key = keyOf(value);
+ if (!keys.has(key)) return resolve(null);
+ request(key, (entry) => resolve(entry ? entry.url : null));
+ }));
const pending = [];
for (const Ctor of [HTMLMediaElement, HTMLImageElement, HTMLSourceElement]) {
const desc = Object.getOwnPropertyDescriptor(Ctor.prototype, 'src');
@@ -79,15 +139,13 @@ const BOOTSTRAP = `(() => {
Object.defineProperty(Ctor.prototype, 'src', { configurable: true, enumerable: desc.enumerable,
get() { return desc.get.call(this); },
set(value) {
- if (relative(value)) {
- const url = map.get(keyOf(value));
- if (url) return desc.set.call(this, url);
- if (!resolved) { pending.push([this, desc, value]); return; }
- }
- desc.set.call(this, value);
+ const token = {};
+ assigned.set(this, token);
+ if (!relative(value)) return desc.set.call(this, value);
+ if (!keys) { pending.push([this, desc, value, token]); return; }
+ apply(this, desc, value, token);
} });
}
- const post = (message) => parent.postMessage(message, '*');
const contract = () => {
const c = globalThis.portosComposition;
return c ? { durationSec: c.durationSec, fps: c.fps, width: c.width, height: c.height, formats: c.formats || null, layout: typeof c.layout === 'function' } : null;
@@ -96,13 +154,18 @@ const BOOTSTRAP = `(() => {
addEventListener('message', (event) => {
const message = event.data;
if (!message || typeof message !== 'object') return;
- if (message.type === 'portos-mv:assets' && !resolved) {
- for (const [key, blob] of Object.entries(message.files || {})) {
- if (blob instanceof Blob) map.set(String(key).replace(/^\\.\\//, ''), URL.createObjectURL(blob));
- }
- resolved = true;
- for (const [el, desc, value] of pending.splice(0)) desc.set.call(el, map.get(keyOf(value)) || value);
- resolveAssets(Object.fromEntries(map));
+ if (message.type === 'portos-mv:manifest' && !keys) {
+ keys = new Set((Array.isArray(message.keys) ? message.keys : []).map((key) => String(key).replace(/^\\.\\//, '')));
+ for (const [el, desc, value, token] of pending.splice(0)) if (assigned.get(el) === token) apply(el, desc, value, token);
+ resolveAssets(Object.freeze(Object.fromEntries([...keys].map((key) => [key, key]))));
+ } else if (message.type === 'portos-mv:asset' && waiting.has(String(message.key))) {
+ const key = String(message.key);
+ const callbacks = waiting.get(key);
+ waiting.delete(key);
+ if (message.blob instanceof Blob) map.set(key, { url: URL.createObjectURL(message.blob), size: message.blob.size, used: performance.now(), media: new Set() });
+ const entry = map.get(key) || null;
+ for (const callback of callbacks) callback(entry);
+ sweep();
} else if (message.type === 'portos-mv:seek') {
const t = Number(message.t) || 0;
seeking = seeking.then(() => globalThis.portosComposition?.seek(t)).then(
diff --git a/server/services/musicVideo/documentRender.browser.test.js b/server/services/musicVideo/documentRender.browser.test.js
index 7bf5d83fd1..27d2b31f64 100644
--- a/server/services/musicVideo/documentRender.browser.test.js
+++ b/server/services/musicVideo/documentRender.browser.test.js
@@ -80,7 +80,7 @@ describe.skipIf(!canRun)('layered template with real Chrome and ffmpeg', () => {
let proc;
let browser;
let PATHS, encodeDocumentComposition, prepareDocumentRender, documentRenderClock, importDocumentTemplate;
- let generateMixedMediaDocument, regenerateMixedMediaSection, acceptMixedMediaDocument, buildDocumentPreview, projects;
+ let generateMixedMediaDocument, regenerateMixedMediaSection, acceptMixedMediaDocument, buildDocumentPreview, PREVIEW_MEDIA_BUDGET_BYTES, projects;
beforeAll(async () => {
// Keep collection read-only when Chrome/ffmpeg prerequisites skip the suite.
({ PATHS } = await import('../../lib/paths.js'));
@@ -93,7 +93,7 @@ describe.skipIf(!canRun)('layered template with real Chrome and ffmpeg', () => {
});
({ importDocumentTemplate } = await import('./compositionDocument.js'));
({ generateMixedMediaDocument, regenerateMixedMediaSection, acceptMixedMediaDocument } = await import('./documentGeneration.js'));
- ({ buildDocumentPreview } = await import('./documentPreview.js'));
+ ({ buildDocumentPreview, PREVIEW_MEDIA_BUDGET_BYTES } = await import('./documentPreview.js'));
projects = await import('./projects.js');
const profile = join(PATHS.data, 'chrome-test-profile');
proc = spawn(chrome, _testChromeCaptureArgs(profile), { stdio: ['ignore', 'ignore', 'pipe'] });
@@ -307,6 +307,51 @@ describe.skipIf(!canRun)('layered template with real Chrome and ffmpeg', () => {
expect(rendered.reduce((sum, v, i) => sum + Math.abs(v-pixels[i]), 0) / pixels.length).toBeLessThan(15);
}, 120000);
+ it('revokes idle preview media past the budget, keeps what a media element still plays, and asks again on reuse', async () => {
+ const created = await projects.createProject({ name: 'Synthetic bridge budget' });
+ await projects.mutateProjectRecord(created.id, (current) => ({ project: { ...current,
+ audioAnalysis: { durationSec: 1, beats: [0], downbeats: [0], sections: [{ id: 'song', label: 'Verse', startSec: 0, endSec: 1 }] },
+ composition: { mode: 'document' },
+ scenes: [{ sceneId: 'card', startSec: 0, endSec: 1, visualLayer: 'card', cardText: '' }],
+ } }));
+ await importDocumentTemplate(created.id);
+ const page = await browser.newPage();
+ await page.setContent((await buildDocumentPreview(await projects.getProject(created.id))).html);
+ const result = await page.evaluate(async (size) => {
+ const requested = [];
+ const revoked = [];
+ const revoke = URL.revokeObjectURL;
+ URL.revokeObjectURL = (url) => { revoked.push(url); revoke(url); };
+ // Idle time is read from performance.now, so the test moves the clock instead of sleeping.
+ const now = performance.now.bind(performance);
+ let offset = 0;
+ performance.now = () => now() + offset;
+ addEventListener('message', ({ data }) => {
+ if (data?.type !== 'portos-mv:request') return;
+ requested.push(data.key);
+ postMessage({ type: 'portos-mv:asset', key: data.key, blob: new Blob([new Uint8Array(size)]) }, '*');
+ });
+ postMessage({ type: 'portos-mv:manifest', keys: ['media/clip.webm', 'media/a.jpg', 'media/b.jpg'] }, '*');
+ const video = document.createElement('video');
+ video.src = 'media/clip.webm';
+ while (!video.getAttribute('src')?.startsWith('blob:')) await new Promise((resolve) => setTimeout(resolve, 10));
+ const first = await window.PORTOS_MV_ASSET('media/a.jpg');
+ const again = await window.PORTOS_MV_ASSET('media/a.jpg');
+ offset += 60000;
+ await window.PORTOS_MV_ASSET('media/b.jpg'); // three files now exceed the budget
+ const reused = await window.PORTOS_MV_ASSET('media/a.jpg');
+ return { requested, revoked, first, again, reused, video: video.getAttribute('src') };
+ }, Math.ceil(PREVIEW_MEDIA_BUDGET_BYTES * 0.6));
+ await page.close();
+ expect(result.again).toBe(result.first);
+ // The idle file goes; the clip a <video> still points at stays though it is older.
+ expect(result.revoked).toEqual([result.first]);
+ expect(result.revoked).not.toContain(result.video);
+ expect(result.requested).toEqual(['media/clip.webm', 'media/a.jpg', 'media/b.jpg', 'media/a.jpg']);
+ expect(result.reused).toMatch(/^blob:/);
+ expect(result.reused).not.toBe(result.first);
+ }, 30000);
+
it('keeps event frames identical across shuffled seeks, an excerpt and a full render, and freezes silence', async () => {
const created = await projects.createProject({ name: 'Synthetic event proof' });
const base = { durationSec: 0.2, narrativeFunction: 'Mark the story turn', mediumRationale: 'Exact code graphics' };
@@ -329,7 +374,7 @@ describe.skipIf(!canRun)('layered template with real Chrome and ffmpeg', () => {
const preview = await buildDocumentPreview(project);
const page = await browser.newPage();
await page.setContent(preview.html);
- await page.evaluate(() => window.postMessage({ type: 'portos-mv:assets', files: {} }, '*'));
+ await page.evaluate(() => window.postMessage({ type: 'portos-mv:manifest', keys: [] }, '*'));
const at = (frame) => page.evaluate(async (frame) => {
await window.portosComposition.seek(frame / 24);
return { pixels: document.getElementById('stage').toDataURL(), state: window.PORTOS_MV_EVENT_STATE(window.PORTOS_MV.song, frame / 24, 24) };
@@ -671,28 +716,47 @@ describe.skipIf(!canRun)('layered template with real Chrome and ffmpeg', () => {
const preview = await buildDocumentPreview(project);
expect(preview.html).toContain('PORTOS_MV_GENERATED');
expect(preview.html).toContain('"inSec":1');
- const previewFrames = async (current, times) => {
+ // Plays the PortOS page's side of the lazy bridge: the manifest first, then each file only when asked.
+ const previewFrames = async (current, times, requested = []) => {
const page = await browser.newPage();
const prepared = await buildDocumentPreview(current);
await page.setContent(prepared.html);
const files = Object.fromEntries(await Promise.all(prepared.assets.map(async (asset) => [asset.key,
(await readFile(asset.key.endsWith('.webm') ? clip : join(PATHS.images, 'generated-still.png'))).toString('base64')])));
await page.evaluate(async (encoded) => {
- const blobs = Object.fromEntries(Object.entries(encoded).map(([key, value]) => [key,
- new Blob([Uint8Array.from(atob(value), (c) => c.charCodeAt(0))], { type: key.endsWith('.webm') ? 'video/webm' : 'image/png' })]));
- window.postMessage({ type: 'portos-mv:assets', files: blobs }, '*');
+ window.requested = [];
+ addEventListener('message', ({ data }) => {
+ if (data?.type !== 'portos-mv:request') return;
+ window.requested.push(data.key);
+ const value = encoded[data.key];
+ const blob = value && new Blob([Uint8Array.from(atob(value), (c) => c.charCodeAt(0))], { type: data.key.endsWith('.webm') ? 'video/webm' : 'image/png' });
+ window.postMessage({ type: 'portos-mv:asset', key: data.key, blob: blob || null }, '*');
+ });
+ window.postMessage({ type: 'portos-mv:manifest', keys: Object.keys(encoded) }, '*');
await window.PORTOS_MV_ASSETS;
}, files);
const pixels = [];
- for (const time of times) pixels.push(await page.evaluate(async (t) => {
- await window.portosComposition.seek(t);
- const canvas = document.getElementById('stage');
- return [...canvas.getContext('2d').getImageData(Math.floor(canvas.width / 2), Math.floor(canvas.height / 2), 1, 1).data].slice(0, 3);
- }, time));
+ for (const time of times) {
+ pixels.push(await page.evaluate(async (t) => {
+ await window.portosComposition.seek(t);
+ const canvas = document.getElementById('stage');
+ return [...canvas.getContext('2d').getImageData(Math.floor(canvas.width / 2), Math.floor(canvas.height / 2), 1, 1).data].slice(0, 3);
+ }, time));
+ requested.push(await page.evaluate(() => window.requested.splice(0)));
+ }
await page.close();
return pixels;
};
- const beforeProof = await previewFrames(project, [0, 1, 2]);
+ const requested = [];
+ const beforeProof = await previewFrames(project, [0, 1, 2], requested);
+ const [stillKey, clipKey] = [preview.assets.find((asset) => asset.key.endsWith('.png')).key, preview.assets.find((asset) => asset.key.endsWith('.webm')).key];
+ // Nothing is fetched up front: the card frame needs no media, and each file is fetched once, when first named.
+ expect(requested[0]).toEqual([]);
+ expect(requested.flat().sort()).toEqual([clipKey, stillKey].sort());
+ // A far scrub on a fresh preview fetches only that time's clip and still paints the complete frame.
+ const farRequested = [];
+ expect(await previewFrames(project, [2], farRequested)).toEqual([beforeProof[2]]);
+ expect(farRequested).toEqual([[clipKey]]);
// The full-duration proof samples static section boundaries. A 3s song at
// the supported 12fps minimum keeps one section per second at 36 frames of
// real Chrome capture (a 30s song was 360 frames, ~100s, and timed out on a