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

20.7 KB
Raw Blame
{
  "objective": "The launch-video run failed with the old instruction: \"If no music engine is ready, stop and report the blocker.\" Change this so I can choose between the configured music service and agent synthesis of original music on a machine with no music engine. Default to agent synthesis, keep the service readiness guard for an explicitly selected service, and include the synthesized soundtrack in the video.",
  "diff": "diff --git a/client/src/components/apps/LaunchVideoPanel.jsx b/client/src/components/apps/LaunchVideoPanel.jsx\nindex 4e41eaa791..1adac35351 100644\n--- a/client/src/components/apps/LaunchVideoPanel.jsx\n+++ b/client/src/components/apps/LaunchVideoPanel.jsx\n@@ -29,6 +29,7 @@ function LaunchVideoForm({ appId, onQueued }) {\n   const [motionGraphics, setMotionGraphics] = useState(false);\n   const [music, setMusic] = useState(false);\n   const [generateMusic, setGenerateMusic] = useState(false);\n+  const [musicMethod, setMusicMethod] = useState('agent');\n   const [musicTrack, setMusicTrack] = useState('');\n   const [tracks, setTracks] = useState(null);\n   const [error, setError] = useState('');\n@@ -48,7 +49,7 @@ function LaunchVideoForm({ appId, onQueued }) {\n     submitting.current = true;\n     await createAppLaunchVideo(appId, {\n       tone, direction, format, targetDurationSec: duration, motionGraphics,\n-      ...(music ? (generateMusic ? { generateMusic: true } : { musicTrack }) : {}),\n+      ...(music ? (generateMusic ? { generateMusic: true, musicMethod } : { musicTrack }) : {}),\n       ...picker.pin,\n     }, { silent: true }).then(onQueued).finally(() => { submitting.current = false; });\n   });\n@@ -65,7 +66,15 @@ function LaunchVideoForm({ appId, onQueued }) {\n     <div><label htmlFor=\"launch-duration\">Duration (15\u2013120 seconds)</label><input id=\"launch-duration\" type=\"number\" min={15} max={120} step={1} required className={inputClass} value={duration} onChange={event => setDuration(event.target.value === '' ? '' : Number(event.target.value))} /></div>\n     <div><label htmlFor=\"launch-motion-graphics\"><input id=\"launch-motion-graphics\" type=\"checkbox\" checked={motionGraphics} onChange={event => setMotionGraphics(event.target.checked)} /> Dynamic motion graphics</label><p className=\"text-sm text-port-text-muted\">Beat-cut showreel style: kinetic type, color-field swaps and generative shapes around the key flow.</p></div>\n     <div><label htmlFor=\"launch-music\"><input id=\"launch-music\" type=\"checkbox\" checked={music} onChange={event => setMusic(event.target.checked)} /> Include music</label></div>\n-    {music && <div><label htmlFor=\"launch-generate-music\"><input id=\"launch-generate-music\" type=\"checkbox\" checked={generateMusic} onChange={event => setGenerateMusic(event.target.checked)} /> Generate original music</label><p className=\"text-sm text-port-text-muted\">The agent uses your configured music engine; provider charges may apply.</p></div>}\n+    {music && <div><label htmlFor=\"launch-generate-music\"><input id=\"launch-generate-music\" type=\"checkbox\" checked={generateMusic} onChange={event => setGenerateMusic(event.target.checked)} /> Generate original music</label><p className=\"text-sm text-port-text-muted\">Choose how the original soundtrack is made.</p></div>}\n+    {music && generateMusic && <div>\n+      <label htmlFor=\"launch-music-method\">Music creation</label>\n+      <select id=\"launch-music-method\" className={inputClass} value={musicMethod} onChange={event => setMusicMethod(event.target.value)}>\n+        <option value=\"agent\">Agent composition (no music model required)</option>\n+        <option value=\"service\">Configured music service</option>\n+      </select>\n+      <p className=\"text-sm text-port-text-muted\">{musicMethod === 'agent' ? 'The agent writes an instrumental score using available synthesis tools, such as Web Audio or Tone.js.' : 'Uses a ready PortOS music engine. Setup and provider charges may apply.'}</p>\n+    </div>}\n     {music && !generateMusic && <fieldset className=\"space-y-2\">\n       <legend>Music-library track</legend>\n       {tracks === null && <p className=\"text-sm text-port-text-muted\">Loading tracks\u2026</p>}\ndiff --git a/server/routes/apps/launchVideos.js b/server/routes/apps/launchVideos.js\nindex 278968b393..7eaee442d6 100644\n--- a/server/routes/apps/launchVideos.js\n+++ b/server/routes/apps/launchVideos.js\n@@ -76,6 +76,7 @@ router.post('/:id/launch-videos', loadApp, asyncHandler(async (req, res) => {\n   const runId = `${Date.now()}-${randomUUID()}`;\n   const directory = `launch-videos/${app.id}/${runId}/composition`;\n   const payload = { directory, musicTrack: options.musicTrack,\n+    ...(options.generateMusic && options.musicMethod === 'agent' ? { synthesizeMusic: true } : {}),\n     launchVideo: { appId: app.id, runId, targetDurationSec: options.targetDurationSec } };\n   // addTask's state lock makes the stable description + app identity atomic\n   // across overlapping requests, including requests with different options.\ndiff --git a/server/services/htmlComposition/encode.js b/server/services/htmlComposition/encode.js\nindex 9aa5cd014d..36bb865a14 100644\n--- a/server/services/htmlComposition/encode.js\n+++ b/server/services/htmlComposition/encode.js\n@@ -1,3 +1,4 @@\n+import { pcmToWavBuffer } from '../../lib/chiptuneRender.js';\n import { spawn } from '../../lib/childProcess.js';\n import { safeChildProcessOptions } from '../../lib/processEnv.js';\n import { killWithEscalation } from '../../lib/killWithEscalation.js';\n@@ -61,3 +62,26 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,\n     if (!exited) await new Promise(resolve => proc.once('close', resolve));\n   }\n }\n+\n+// Source remains subject to the composition sandbox and launch privacy gate;\n+// only bounded PCM leaves the browser, never arbitrary paths or encoded files.\n+export async function synthesizeCompositionMusic(page, durationSec) {\n+  const sampleRate = 24000;\n+  const length = Math.round(sampleRate * durationSec);\n+  // browser.js evaluate -> send supplies a 30-second command deadline and\n+  // rejects all pending commands on the render signal abort; index.js closes\n+  // the disposable context in finally, including a never-settling score.\n+  const samples = await page.evaluate(`(async () => {\n+    const renderAudio = globalThis.portosComposition.renderAudio;\n+    if (typeof renderAudio !== 'function') throw new Error('portosComposition.renderAudio is required for synthesized music');\n+    const samples = await renderAudio({ sampleRate: ${sampleRate}, durationSec: ${durationSec} });\n+    if (!Array.isArray(samples) || samples.length !== ${length}) throw new Error('renderAudio must return exactly ${length} mono PCM samples');\n+    if (samples.some(value => !Number.isFinite(value) || value < -1 || value > 1)) throw new Error('renderAudio must return finite mono PCM samples in [-1, 1]');\n+    return samples;\n+  })()`);\n+  if (!Array.isArray(samples) || samples.length !== length || samples.some(value => !Number.isFinite(value) || value < -1 || value > 1)) {\n+    throw new Error('renderAudio must return finite mono PCM samples in [-1, 1]');\n+  }\n+  if (!samples.some(value => Math.abs(value) > 0.0001)) throw new Error('renderAudio returned a silent soundtrack');\n+  return pcmToWavBuffer(Float32Array.from(samples), { sampleRate });\n+}\ndiff --git a/server/services/htmlComposition/index.js b/server/services/htmlComposition/index.js\nindex b437759165..84a8a8463b 100644\n--- a/server/services/htmlComposition/index.js\n+++ b/server/services/htmlComposition/index.js\n@@ -1,5 +1,6 @@\n import { join, resolve } from 'node:path';\n-import { open, realpath } from 'node:fs/promises';\n+import { mkdtemp, open, realpath, rm, writeFile } from 'node:fs/promises';\n+import { tmpdir } from 'node:os';\n import { createReadStream } from 'node:fs';\n import { pipeline } from 'node:stream/promises';\n import { PATHS, ensureDir, unlinkGuarded } from '../../lib/fileUtils.js';\n@@ -9,7 +10,7 @@ import { videoGenEvents } from '../videoGen/events.js';\n import { mutateVideoHistory } from '../videoGen/history.js';\n import { resolveMusicTrackPath } from '../pipeline/audioMux.js';\n import { openComposition } from './browser.js';\n-import { encodeComposition } from './encode.js';\n+import { encodeComposition, synthesizeCompositionMusic } from './encode.js';\n import { validateLaunchVideoAssets } from '../../lib/launchVideoValidation.js';\n \n const active = new Map();\n@@ -28,6 +29,7 @@ export async function renderComposition({ jobId, ...input }) {\n   const filename = `composition-${jobId}.mp4`;\n   const outputPath = join(PATHS.videos, filename);\n   let page;\n+  let audioDirectory;\n   let success = false;\n   let result;\n   let failure;\n@@ -39,8 +41,8 @@ export async function renderComposition({ jobId, ...input }) {\n     try { await write(handle); } finally { await handle.close(); }\n   };\n   try {\n-    const { directory, musicTrack, launchVideo } = validateRequest(htmlCompositionRenderSchema, input);\n-    const musicPath = musicTrack ? await resolveMusicTrackPath(musicTrack) : null;\n+    const { directory, musicTrack, launchVideo, synthesizeMusic } = validateRequest(htmlCompositionRenderSchema, input);\n+    let musicPath = musicTrack ? await resolveMusicTrackPath(musicTrack) : null;\n     if (musicTrack && !musicPath) throw new Error('musicTrack is missing from the Music library');\n     signal.throwIfAborted();\n     let launchPlan;\n@@ -68,6 +70,13 @@ export async function renderComposition({ jobId, ...input }) {\n     if (launchPlan && Math.abs(contract.durationSec - launchPlan.durationSec) > 1e-8) {\n       throw new Error('Composition durationSec must match storyboard.json');\n     }\n+    if (synthesizeMusic) {\n+      const wav = await synthesizeCompositionMusic(page, contract.durationSec);\n+      page.check();\n+      audioDirectory = await mkdtemp(join(tmpdir(), 'portos-composition-audio-'));\n+      musicPath = join(audioDirectory, 'score.wav');\n+      await writeFile(musicPath, wav, { flag: 'wx' });\n+    }\n     await ensureDir(PATHS.videos);\n     await encodeComposition(page, contract, outputPath, { musicPath, signal, onProgress: progress => {\n       videoGenEvents.emit('progress', { generationId: jobId, progress: progress * 0.95 });\n@@ -111,6 +120,9 @@ export async function renderComposition({ jobId, ...input }) {\n     failure = error;\n   } finally {\n     await page?.close();\n+    if (audioDirectory) await rm(audioDirectory, { recursive: true, force: true }).catch(() => {\n+      console.warn('\u26a0\ufe0f Could not remove temporary composition audio');\n+    });\n     if (!success) {\n       for (const path of deliveredPaths) await unlinkGuarded(path).catch(() => {});\n       await unlinkGuarded(outputPath).catch(() => {});\ndiff --git a/server/services/htmlComposition/index.test.js b/server/services/htmlComposition/index.test.js\nindex 74451258f2..f70ef793ba 100644\n--- a/server/services/htmlComposition/index.test.js\n+++ b/server/services/htmlComposition/index.test.js\n@@ -135,6 +135,17 @@ describe.skipIf(!chrome || !ffmpeg)('HTML composition with real Chrome and ffmpe\n     expect(await loadHistory()).not.toContainEqual(expect.objectContaining({ id: input.jobId }));\n   });\n \n+  it('muxes agent-composed PCM without a music engine and refuses missing or invalid scores', async () => {\n+    const input = await composition(fixture('', `renderAudio: async ({ sampleRate, durationSec }) =>\n+      Array.from({ length: Math.round(sampleRate * durationSec) }, (_, n) => 0.2 * Math.sin(2 * Math.PI * 440 * n / sampleRate)),`));\n+    const result = await renderComposition({ ...input, synthesizeMusic: true });\n+    const pcm = execFileSync(ffmpeg, ['-v', 'error', '-i', join(PATHS.videos, result.filename), '-vn', '-f', 'f32le', '-ac', '1', '-ar', '24000', '-']);\n+    expect(pcm.length).toBeGreaterThanOrEqual(24000 * 4);\n+    expect(Array.from({ length: 1000 }, (_, n) => Math.abs(pcm.readFloatLE(n * 4))).some(value => value > 0.05)).toBe(true);\n+    await expect(renderComposition({ ...await composition(), synthesizeMusic: true })).rejects.toThrow('renderAudio is required');\n+    await expect(renderComposition({ ...await composition(fixture('', 'renderAudio: async () => Array(24000).fill(2),')), synthesizeMusic: true })).rejects.toThrow('finite mono PCM');\n+  }, 30000);\n+\n   it('loops and trims library music to the video with a half-second tail fade', async () => {\n     await mkdir(PATHS.music, { recursive: true });\n     execFileSync(ffmpeg, ['-v', 'error', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=0.3', '-y', join(PATHS.music, 'example.wav')]);\ndiff --git a/server/services/taskPromptDefaults/appLaunchVideo.js b/server/services/taskPromptDefaults/appLaunchVideo.js\nindex 256b114f78..308df20d4b 100644\n--- a/server/services/taskPromptDefaults/appLaunchVideo.js\n+++ b/server/services/taskPromptDefaults/appLaunchVideo.js\n@@ -9,6 +9,8 @@ Write only to the supplied output directory (plus the runner's completion sentin\n Every scene has durationSec; every visible text element has text, its exact whitespace-separated wordCount, and holdSec. Total 15\u2013120 seconds and within two seconds of the chosen target. Each hold is at least max(0.8, 0.3 * wordCount) and fits its scene. Implement those holds faithfully, including transitions. Choose posterSec at the strongest settled beat.\n - index.html and local assets: globalThis.portosComposition = {durationSec, fps:24, width, height, async seek(t){...}}. Use dimensions 1920x1080 (landscape), 1080x1920 (vertical), or 1080x1080 (square). Seek deterministically from t; await fonts and any asynchronous work. No wall-clock animations, external URLs, popups, workers or browser storage. Keep HTML/CSS/JS/SVG/JSON/Markdown/text UTF-8. No raster screenshots or footage.\n When motionGraphics is true, make a dynamic motion-graphics piece: a designer's showreel built around this product, not a slideshow of recreated screens. Cut on a steady beat (a new beat every one to two seconds, landing on bar boundaries when music is present) and give each beat a distinct technique: bold color-field swaps drawn from the app's palette, oversized kinetic typography (scale, mask and slide reveals; repeated-word patterns), easing-curve showcases (expo, back, elastic, bounce), generative geometry computed from t (tiling patterns, radial bursts, particle fields, wireframe forms), shape morphs, and a logo/name lockup endcard. A thin HUD overlay (corner crop marks, timecode, beat counter) may frame the piece. Keep the recreated key flow as one or two punchy beats so the evidence-backed claim still lands. All motion stays a pure function of t: seeded pseudo-randomness only, never Math.random or timers. Every word shown, including repeated kinetic words and HUD labels, is a storyboard line whose hold meets the reading-time gate; keep HUD text to digits and symbols. When motionGraphics is false, favor a clear, paced product walkthrough.\n-When generateMusic is true, the user explicitly requests original instrumental music. Compose a music prompt matching the storyboard and tone, using only fictional/public product context. First GET /api/music/engines from the supplied PortOS service API base. Select a ready, platformSupported engine (prefer defaultEngine when ready), using its ready default model or a model marked ready in modelReadyById. If none is ready, report the setup requirement and stop. POST {\"prompt\":\"<your musical direction>\",\"instrumentalOnly\":true,\"engine\":\"<selected engine id>\",\"modelId\":\"<selected model id>\",\"durationSec\":<duration within the engine limits>} to the supplied PortOS service API base + /api/music/generate with the same Authorization header as rendering. Aim for targetDurationSec within the engine duration limits; a shorter music bed is looped and faded by the renderer to fill the video. Do not install models or change provider settings. Subscribe to /api/html-composition/<jobId>/events (the shared media queue stream) until complete; take result.filename from that completed job as musicTrack in the render JSON. Cancel that job via /api/html-composition/<jobId>/cancel if canceled. If generation fails, report the failure rather than silently rendering without music. This API may write its generated track to the Music library; do not write arbitrary files there yourself. When generateMusic is false, never generate music; preserve the supplied library musicTrack, if any.\n-Render using the supplied POST URL and JSON payload (adding only the completed generated musicTrack when requested) with the agent's Authorization: Bearer credential from PORTOS_API_TOKEN; never print or persist the credential. Privacy and readability checks fail closed and name the file/pattern or scene/line. Replace offending content, never bypass the gates. A queued job is not success: subscribe to its /events SSE endpoint until complete, error or canceled. Do not poll. On cancellation, cancel the media job with its /cancel endpoint. Keep the CoS run active through rendering. Only report success after complete. The server copies the validated plan, storyboard and caption plus MP4 and poster into the run directory and registers the video in Media History.\n+When generateMusic is true, the user explicitly requests original instrumental music. musicMethod chooses how: \"agent\" (the default) means compose and synthesize it yourself; \"service\" means use a configured PortOS music engine. Never require a music engine for the agent method.\n+For the agent method, implement async globalThis.portosComposition.renderAudio({sampleRate, durationSec}) returning a plain array of exactly Math.round(sampleRate * durationSec) finite mono PCM samples in [-1, 1]. The renderer supplies sampleRate=24000 and the video duration, writes a temporary soundtrack and muxes it into the MP4. Compose a deliberate instrumental arrangement matching the storyboard, with melody, harmony, rhythm, dynamics and an ending; document tempo and musical direction in plan.md. Use native OfflineAudioContext, deterministic sample synthesis, or locally available Tone.js/Strudel code that can export this PCM contract. Use only procedural synthesis, no recordings or fetched samples. Keep all source in composition/ as inspectable UTF-8 JavaScript. No installs, CDN imports, network calls, live playback or binary audio assets. Do not assume Tone.js or Strudel is installed; native Web Audio or plain JavaScript synthesis requires no additional music runtime. Add synthesizeMusic:true to the render JSON; do not set musicTrack or call /api/music/engines or /api/music/generate. Audio played by the page is NOT captured: renderAudio is required. A failed audio render is a failed task, never silently omit requested music.\n+For the service method only: Compose a music prompt matching the storyboard and tone, using only fictional/public product context. First GET /api/music/engines from the supplied PortOS service API base. Select a ready, platformSupported engine (prefer defaultEngine when ready), using its ready default model or a model marked ready in modelReadyById. If none is ready, report the setup requirement and stop. POST {\"prompt\":\"<your musical direction>\",\"instrumentalOnly\":true,\"engine\":\"<selected engine id>\",\"modelId\":\"<selected model id>\",\"durationSec\":<duration within the engine limits>} to the supplied PortOS service API base + /api/music/generate with the same Authorization header as rendering. Aim for targetDurationSec within the engine duration limits; a shorter music bed is looped and faded by the renderer to fill the video. Do not install models or change provider settings. Subscribe to /api/html-composition/<jobId>/events (the shared media queue stream) until complete; take result.filename from that completed job as musicTrack in the render JSON. Cancel that job via /api/html-composition/<jobId>/cancel if canceled. If generation fails, report the failure rather than silently rendering without music. This API may write its generated track to the Music library; do not write arbitrary files there yourself. When generateMusic is false, never generate music; preserve the supplied library musicTrack, if any.\n+Render using the supplied POST URL and JSON payload (adding synthesizeMusic:true for agent composition or the completed generated musicTrack for the service method) with the agent's Authorization: Bearer credential from PORTOS_API_TOKEN; never print or persist the credential. Privacy and readability checks fail closed and name the file/pattern or scene/line. Replace offending content, never bypass the gates. A queued job is not success: subscribe to its /events SSE endpoint until complete, error or canceled. Do not poll. On cancellation, cancel the media job with its /cancel endpoint. Keep the CoS run active through rendering. Only report success after complete. The server copies the validated plan, storyboard and caption plus MP4 and poster into the run directory and registers the video in Media History.\n `;\n"
}