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

fix(creative-director): unstuck planning state + inline scene playback + audio defaults off

Adam Eivy94cbfea036bd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6d55c55f77..d715607db6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -28,6 +28,8 @@
## Changed
+- **Creative Director audio defaults to OFF.** The current macOS LTX/MLX video pipeline produces inconsistent audio across renders (gaps, garbled passes, off-mood beds), so new CD projects now create with `disableAudio: true`. The new-project form has a "Generate audio for each scene" checkbox (off by default; opt-in if you want the audio pipeline to run anyway), and the project Overview tab gained an Audio toggle (using the existing `ToggleSwitch` component to match the Apps/CoS settings-toggle pattern) that PATCHes `disableAudio` post-creation — applies to future scene renders only, since already-rendered scenes keep their original audio. `creativeDirectorProjectUpdateSchema` accepts the new field. Existing projects retain their original setting. (Standalone Video Gen still defaults audio ON — only CD changed.)
+
- **Writers Room — per-scene generated images persist across navigation + auto-collect.** Scene images used to vanish from the UI the moment you navigated away, even though the rendered PNG was sitting on disk. Now: when `image-gen:completed` fires for a scene, the client POSTs `/api/writers-room/works/:id/analysis/:analysisId/scene-image` which (a) writes the scene→image link to the analysis snapshot under `sceneImages[sceneId]`, and (b) appends the image to a per-work auto-created MediaGen Collection (`Writers Room: <title>`, lazily created on first render and cached on the work manifest under `mediaCollectionId`). Re-opening the Adapt result re-seeds each `SceneCard` with its persisted image, so it shows the final render immediately instead of an empty button. Stale collection ids (e.g. user deleted the collection out-of-band) fall through to a fresh create.
- **Writers Room — per-work reading theme switcher.** The WorkEditor header now has a Sun/Moon toggle (next to Save/Snapshot) that flips the prose textarea + AI sidebar's Adapt scene cards between dark mode (default — matches the rest of PortOS) and a sepia/light reading mode (`#f5f1e8` background, dark text) for users who don't want to read white-on-black for hours. Persists per-user via `localStorage` (`wr.readingTheme`); page chrome and library stay app-themed so the contrast cue stays consistent. Scene-card body text, character chips, dialogue, and the "X words / unsaved" status pill all flip with the toggle.
- **Writers Room — per-scene image gen has its own model + resolution settings.** The Adapt result now exposes a small inline settings row (gear button under the logline) where you can pick the model (`flux2-klein-4b` is the default — fastest FLUX.2 variant on Apple Silicon — with `flux2-klein-9b`, `flux2-klein-4b-int8`, and the existing `dev`/`schnell` mflux models also selectable) and a resolution preset (default 768×512 / 3:2; presets cover 1:1, 2:3, 16:9, and 1:1 1024). Choices persist to `settings.json` under `writersRoom.imageGen` so they survive reloads and apply across all works in the Writers Room. The per-scene preview area now uses the configured aspect ratio instead of always being square, so 3:2 / 16:9 renders aren't letterboxed inside an `aspect-square` slot.
@@ -42,6 +44,11 @@
## Fixed
+- **Creative Director projects no longer get stuck in `planning` with zero runs.** Clicking Start on a fresh `draft` project flipped status to `planning` in the route, then fired `startCreativeDirectorProject` → `advanceAfterSceneSettled`, which re-read the project, saw `status === 'planning'`, and bailed via a too-aggressive dedup early-return that was meant to catch "treatment task already in flight." The treatment task was never enqueued, no run was recorded, and the same flaw silently bricked `failed`/`paused` projects without a treatment plus the boot-time recovery path. Replaced the brittle status check with a runs-array probe (`runs.some(r => r.kind === 'treatment' && r.status === 'running')`) that actually reflects "a treatment task is mid-flight." Boot recovery now correctly resumes stuck projects on server restart. Two new regression tests in `orchestrator.test.js` cover the fresh-Start path and the genuine in-flight dedup path.
+
+- **Creative Director scene segments play inline.** The Segments tab used to render each scene's mp4 as an `<a target="_blank">`-wrapped thumbnail — clicking opened the file in a new tab, which is awkward for previewing 6–20 short clips in sequence. Each tile is now an inline `<video controls preload="none" playsInline poster=…>` element using the existing per-job thumbnail JPEG as the poster frame, so the grid still renders instantly without paying for 20 metadata round-trips on tab open. Fetching only happens on play. `onError` hides any tile whose mp4 is missing, matching the prior `<img>` fallback behavior.
+
+- **Browser downloads are now retrievable from the UI.** PortOS is accessed remotely over Tailscale, so any file Chrome saved into `data/browser-downloads/` was visible in the listing but unreachable — the row only rendered name/size/mtime, with no link to fetch the bytes. Added `GET /api/browser/downloads/:name` (path-traversal guarded via `basename` + `resolve` + `startsWith` on the configured download dir, MIME-typed for previewable files, `Content-Disposition: attachment` forced for risky types like `.html`/`.svg`/`.js`/`.xml` to keep same-origin XSS off the table) and a sibling `DELETE` route. The Downloads pane on `/browser` now renders each row as a clickable link (opens in a new tab for inline preview), plus an inline Download icon (`?attachment=1` + HTML5 `download` attr to force save-to-device) and a Trash icon that DELETEs and removes the row from local state.
- **Brain → memory bridge no longer fans out across every record on a single write.** Adding one inbox item used to trigger ~12 memory updates and 12+ embedding rebuilds for unrelated projects (visible as a block of `🧠🔗 Updated brain→memory` lines after a single classification). Root cause: `saveJsonStore` emits `${type}:changed` with the whole `{ records }` blob on every write, and `brainMemoryBridge.handleEntityChanged` iterated every record on each event. The journals path was already migrated to per-entry events for exactly this reason; the sibling entity types (people, projects, ideas, admin, memories) were never updated. `server/services/brainStorage.js` now also emits per-record `${type}:upserted` (with `{ id, record }`) on `create`/`update` and `${type}:deleted` on `remove`; `server/services/brainMemoryBridge.js` listens to those instead of `:changed`, so a single classify-and-file now produces a single memory write + embedding. The store-wide `:changed` event still fires for any UI listeners that genuinely want the full set.
- **Writers Room — "Add folder" form no longer clips its Cancel button.** The new-folder inline form previously laid out as `[input flex-1] [Add] [Cancel]` inside the 260px library aside, which left no room for the Cancel button — it overflowed off the right edge and was clipped by the panel's overflow boundary. Restructured to stack: the input takes the full width, then `[Add (flex-1)] [Cancel]` sits on a second row inside a `bg-port-card` boxed group matching the new-work form's existing layout.
- **FLUX.2 stepwise previews now actually render.** The callback's `vae.decode(latents)` was silently failing every step with `IndexError: tuple index out of range` because `Flux2KleinPipeline` hands the callback latents in transformer-packed shape `(B, num_patches, C·P²)` (e.g. `(1, 2304, 128)` for 1024×576) but the VAE expects unpacked `(B, C, H, W)`. New `_unpack_flux2_latents()` does the patch unpack (2×2 patches × 8× VAE downsample) before the decode call. `make_stepwise_callback()` now takes `height`/`width` and short-circuits the unpack if a future pipeline version hands us an already-4-D tensor.
diff --git a/client/src/components/creative-director/OverviewTab.jsx b/client/src/components/creative-director/OverviewTab.jsx
index 6721efaa52..46bf4069ad 100644
--- a/client/src/components/creative-director/OverviewTab.jsx
+++ b/client/src/components/creative-director/OverviewTab.jsx
@@ -1,11 +1,22 @@
import { Link } from 'react-router-dom';
+import toast from '../ui/Toast';
+import ToggleSwitch from '../ToggleSwitch.jsx';
+import { updateCreativeDirectorProject } from '../../services/apiCreativeDirector.js';
-export default function OverviewTab({ project }) {
+export default function OverviewTab({ project, onProjectUpdate }) {
const collectionLink = `/media/collections/${project.collectionId}`;
const final = project.finalVideoId
? <Link to={`/media/history?selected=${project.finalVideoId}`} className="text-port-accent">{project.finalVideoId}</Link>
: <span className="text-port-text-muted">not yet rendered</span>;
+ const setDisableAudio = async (next) => {
+ const updated = await updateCreativeDirectorProject(project.id, { disableAudio: next })
+ .catch((err) => { toast.error(err.message || 'Failed to update audio setting'); return null; });
+ if (!updated) return;
+ onProjectUpdate?.(updated);
+ toast.success(next ? 'Audio disabled for future scenes' : 'Audio enabled for future scenes');
+ };
+
return (
<div className="space-y-4 max-w-3xl">
<section className="bg-port-card border border-port-border rounded p-4 space-y-2">
@@ -20,6 +31,20 @@ export default function OverviewTab({ project }) {
{project.timelineProjectId && (
<Field label="Timeline" value={<Link to={`/media/timeline/${project.timelineProjectId}`} className="text-port-accent">{project.timelineProjectId}</Link>} />
)}
+ <Field
+ label="Audio"
+ value={
+ <div className="inline-flex items-center gap-2 text-port-text">
+ <ToggleSwitch
+ size="sm"
+ enabled={!project.disableAudio}
+ onChange={() => setDisableAudio(!project.disableAudio)}
+ ariaLabel="Toggle audio for future scene renders"
+ />
+ <span>{project.disableAudio ? 'Disabled' : 'Enabled'} <span className="text-port-text-muted">(applies to future scene renders)</span></span>
+ </div>
+ }
+ />
</section>
{project.styleSpec && (
diff --git a/client/src/components/creative-director/SegmentsTab.jsx b/client/src/components/creative-director/SegmentsTab.jsx
index 6a9b8084a8..6449509999 100644
--- a/client/src/components/creative-director/SegmentsTab.jsx
+++ b/client/src/components/creative-director/SegmentsTab.jsx
@@ -55,14 +55,15 @@ export default function SegmentsTab({ project, activeAgents = [] }) {
return (
<div key={s.sceneId} className={`bg-port-card border rounded overflow-hidden ${isInflight ? 'border-port-accent/60' : 'border-port-border'}`}>
{s.renderedJobId ? (
- <a href={`/data/videos/${s.renderedJobId}.mp4`} target="_blank" rel="noopener noreferrer" className="block bg-port-bg aspect-video">
- <img
- src={`/data/video-thumbnails/${s.renderedJobId}.jpg`}
- alt={`Scene ${s.order + 1}`}
- className="w-full h-full object-cover"
- onError={(e) => { e.currentTarget.style.display = 'none'; }}
- />
- </a>
+ <video
+ src={`/data/videos/${s.renderedJobId}.mp4`}
+ poster={`/data/video-thumbnails/${s.renderedJobId}.jpg`}
+ controls
+ preload="none"
+ playsInline
+ onError={(e) => { e.currentTarget.style.display = 'none'; }}
+ className="block w-full bg-port-bg aspect-video object-cover"
+ />
) : (
<div className="bg-port-bg aspect-video flex items-center justify-center text-port-text-muted text-xs">
{isInflight ? (
diff --git a/client/src/pages/CreativeDirector.jsx b/client/src/pages/CreativeDirector.jsx
index baebb924a3..0db191fbbb 100644
--- a/client/src/pages/CreativeDirector.jsx
+++ b/client/src/pages/CreativeDirector.jsx
@@ -39,6 +39,7 @@ export default function CreativeDirector() {
styleSpec: '',
userStory: '',
startingImageFile: '',
+ disableAudio: true,
});
const fetchProjects = useCallback(() => {
@@ -71,6 +72,7 @@ export default function CreativeDirector() {
styleSpec: form.styleSpec,
userStory: form.userStory || null,
startingImageFile: form.startingImageFile || null,
+ disableAudio: form.disableAudio,
};
try {
const created = await createCreativeDirectorProject(payload);
@@ -225,6 +227,17 @@ export default function CreativeDirector() {
maxLength={256}
/>
</label>
+ <label className="flex items-center gap-2 text-sm md:col-span-2">
+ <input
+ type="checkbox"
+ checked={!form.disableAudio}
+ onChange={(e) => setForm({ ...form, disableAudio: !e.target.checked })}
+ />
+ <span className="text-port-text-muted">
+ Generate audio for each scene
+ <span className="text-port-text-muted/70"> (off by default — current models produce inconsistent audio)</span>
+ </span>
+ </label>
</div>
<label className="block text-sm">
<span className="text-port-text-muted">Style spec</span>
diff --git a/client/src/pages/CreativeDirectorDetail.jsx b/client/src/pages/CreativeDirectorDetail.jsx
index 7b6ed545a6..7d633aaf3d 100644
--- a/client/src/pages/CreativeDirectorDetail.jsx
+++ b/client/src/pages/CreativeDirectorDetail.jsx
@@ -148,7 +148,7 @@ export default function CreativeDirectorDetail() {
<div className="flex-1 overflow-auto p-6">
<ActiveAgentsBanner agents={activeAgents} />
- {activeTab === 'overview' && <OverviewTab project={project} />}
+ {activeTab === 'overview' && <OverviewTab project={project} onProjectUpdate={setProject} />}
{activeTab === 'treatment' && <TreatmentTab project={project} />}
{activeTab === 'segments' && <SegmentsTab project={project} activeAgents={activeAgents} />}
{activeTab === 'runs' && <RunsTab project={project} />}
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 8f780a0cc2..4bf2097d1f 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -694,8 +694,10 @@ export const creativeDirectorProjectCreateSchema = z.object({
styleSpec: z.string().max(5000).default(''),
startingImageFile: safeBasename.nullable().optional(),
userStory: z.string().max(10000).nullable().optional(),
- // Test/dev knobs. Both default false. Smoke-test fixtures set these.
- disableAudio: z.boolean().optional().default(false),
+ // Audio defaults OFF for CD projects — current model audio output is
+ // inconsistent across renders and the user can re-enable per-project.
+ // (videoGen one-offs still default to enabled.)
+ disableAudio: z.boolean().optional().default(true),
autoAcceptScenes: z.boolean().optional().default(false),
});
@@ -710,6 +712,8 @@ export const creativeDirectorProjectUpdateSchema = z.object({
finalVideoId: z.string().max(64).nullable().optional(),
timelineProjectId: z.string().max(64).nullable().optional(),
failureReason: z.string().max(500).nullable().optional(),
+ // Toggleable post-creation — only affects future scene renders.
+ disableAudio: z.boolean().optional(),
}).strict();
// One scene in the treatment, written by the agent on the treatment task.
diff --git a/server/services/creativeDirector/completionHook.js b/server/services/creativeDirector/completionHook.js
index a6ca822d5a..b494c4b233 100644
--- a/server/services/creativeDirector/completionHook.js
+++ b/server/services/creativeDirector/completionHook.js
@@ -106,11 +106,19 @@ export async function advanceAfterSceneSettled(projectId) {
// No treatment yet → enqueue treatment task.
if (!project.treatment) {
- // Skip if status is already `planning` (a treatment task is in flight)
- // OR our in-memory dedup set has this project (covers the
- // updateProject→enqueueTreatmentTask window between two concurrent
- // advance calls).
- if (project.status === 'planning' || inflightTreatment.has(projectId)) return;
+ // Skip if a treatment run is already mid-flight (its run row stays
+ // 'running' until the agent's completion hook fires) OR our in-memory
+ // dedup set has this project (covers the updateProject→enqueueTreatmentTask
+ // window between two concurrent advance calls in this process).
+ //
+ // Note: we deliberately do NOT bail just because status === 'planning'.
+ // The route pre-flips `draft`/`paused`/`failed` projects to 'planning'
+ // before calling start, so a status check would short-circuit the very
+ // first Start click and leave the project stuck with no runs and no task.
+ const runningTreatment = (project.runs || []).some(
+ (r) => r.kind === 'treatment' && r.status === 'running',
+ );
+ if (runningTreatment || inflightTreatment.has(projectId)) return;
inflightTreatment.add(projectId);
await updateProject(project.id, { status: 'planning' })
.catch((e) => { inflightTreatment.delete(projectId); throw e; });
diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.js
index 407f7cdc31..b8daf34b71 100644
--- a/server/services/creativeDirector/local.js
+++ b/server/services/creativeDirector/local.js
@@ -42,7 +42,7 @@ export async function getProject(id) {
return all.find((p) => p.id === id) || null;
}
-export async function createProject({ name, aspectRatio, quality, modelId, targetDurationSeconds, styleSpec = '', startingImageFile = null, userStory = null, disableAudio = false, autoAcceptScenes = false }) {
+export async function createProject({ name, aspectRatio, quality, modelId, targetDurationSeconds, styleSpec = '', startingImageFile = null, userStory = null, disableAudio = true, autoAcceptScenes = false }) {
const id = `cd-${randomUUID()}`;
const now = new Date().toISOString();
diff --git a/server/services/creativeDirector/orchestrator.test.js b/server/services/creativeDirector/orchestrator.test.js
index 71ffddeeda..e5ad3cc9d3 100644
--- a/server/services/creativeDirector/orchestrator.test.js
+++ b/server/services/creativeDirector/orchestrator.test.js
@@ -24,6 +24,7 @@ vi.mock('./agentBridge.js', () => ({
}));
import * as localMod from './local.js';
+import * as agentBridge from './agentBridge.js';
import { advanceAfterSceneSettled } from './completionHook.js';
const baseProject = {
@@ -237,4 +238,41 @@ describe('advanceAfterSceneSettled', () => {
const [, sceneArg] = mockRunSceneRender.mock.calls[0];
expect(sceneArg.sceneId).toBe('scene-2');
});
+
+ it('enqueues treatment when project has no treatment, even if route already pre-flipped status to planning', async () => {
+ // Regression: the route's `draft → planning` pre-flip used to short-
+ // circuit advance via a `status === 'planning'` early-return, leaving
+ // brand-new projects stuck in planning with no runs and no agent task.
+ const project = {
+ id: 'cd-stuck',
+ status: 'planning',
+ finalVideoId: null,
+ treatment: null,
+ runs: [],
+ };
+ localMod.getProject
+ .mockResolvedValueOnce(project)
+ .mockResolvedValueOnce({ ...project });
+ agentBridge.enqueueTreatmentTask.mockClear();
+
+ await advanceAfterSceneSettled(project.id);
+
+ expect(agentBridge.enqueueTreatmentTask).toHaveBeenCalledTimes(1);
+ });
+
+ it('does NOT enqueue a duplicate treatment when one is already running', async () => {
+ const project = {
+ id: 'cd-dup',
+ status: 'planning',
+ finalVideoId: null,
+ treatment: null,
+ runs: [{ runId: 'r1', kind: 'treatment', status: 'running' }],
+ };
+ localMod.getProject.mockResolvedValueOnce(project);
+ agentBridge.enqueueTreatmentTask.mockClear();
+
+ await advanceAfterSceneSettled(project.id);
+
+ expect(agentBridge.enqueueTreatmentTask).not.toHaveBeenCalled();
+ });
});