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

feat: blank-canvas storyboard sketches attachable to pipeline scenes (#2036)

[._.]/ Adam Eivyb882a3be9ae8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5819c565d8..0b82dc420a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -70,6 +70,7 @@
- **Installing a video LoRA from HuggingFace now shows live download progress.** The LoRA Manager's "Install video LoRA from HuggingFace" form (and the curated video quick-install buttons) used to freeze on a static "Downloading…" label with no indication of how far along a multi-GB LoRA was — unlike image-model downloads, which show a percentage. The install now streams byte-level progress over SSE: the button shows `Downloading 42%` and a progress bar with `received / total` bytes fills as it downloads (an indeterminate pulse when the server can't read a Content-Length). Errors — including the "couldn't detect the model family" case that offers the inline "Install as LTX-Video" retry — still surface exactly as before.
- **The LoRA Manager's Installed list is now grouped by Video / Image.** The curated "Video LoRAs" suggestion cards sat directly above a single flat "Installed" grid, so installed *image* LoRAs looked like they belonged to the video section. The Installed section is now visually divided from the suggestions and, in the "All" view, splits into labeled **Video LoRAs** / **Image LoRAs** subsections (mirroring the suggestion panel) so it's obvious which renders each LoRA applies to. The Image/Video filter still collapses it to a single scoped list.
- **[issue-2036] Sketch & Annotation Canvas (phase 2): re-render an image guided by your annotations.** The annotate page (`/media/annotate/:mediaKey`) gained a "Re-render" action: draw over a generated image, then feed your markup back through local img2img so the marks reshape the render. A confirmation dialog names the exact local model it will run (no surprise AI calls) and lets you add an optional prompt and tune how much to change before it starts; the new render is queued and appears in Media History. Requires a local FLUX img2img runner — the action explains when one isn't available. Phase 3 (blank-canvas storyboard) remains open on #2036.
+- **[issue-2036] Sketch & Annotation Canvas (phase 3): blank-canvas storyboard sketches on pipeline scenes.** Each scene in the Storyboards stage now has a **Sketch** button that opens a blank drawing surface — the same draw/erase/undo/color/size toolbar as the image annotator, but starting from an empty white canvas instead of over a generated image. Rough out a composition or shot idea for the scene, save it, and a thumbnail appears inline on the scene; the button becomes **Edit sketch** to reopen the same canvas. The sketch is deep-linked and reload-safe (`/media/annotate/sketch:<id>`) and returns you to the storyboards stage when you're done. Blank sketches are stored under a `sketch:` key kept local to the media-sketch service — deliberately outside the shared media vocabulary so they never leak into collections, cross-machine sync, or the media catalog. Closes #2036. (`server/services/mediaSketches.js`, `server/routes/mediaSketches.js`, `client/src/components/media/AnnotationCanvas.jsx`, `client/src/pages/MediaAnnotate.jsx`, `client/src/components/pipeline/stages/StoryboardsStage.jsx`)
- **[issue-2199] LoRA downloads are now verified for corruption before install.** A truncated or corrupt `.safetensors` download from Civitai or HuggingFace used to install silently and then render garbage ("mosaic") output at generate time. PortOS now checks every freshly downloaded LoRA's structure (safetensors header + size) and, when Civitai provides a SHA-256 for the file, compares it against the bytes on disk. On any mismatch the partial file is deleted and the install fails with a clear error so you re-download instead of training or rendering against corrupt weights.
- **[issue-2196] Video Gen now takes an exact custom Width×Height.** The `/media/video` page only offered a 9-item resolution preset dropdown, so a size the presets didn't cover was only reachable via URL params, remix/continue, or aspect-snap on upload. Two numeric Width and Height inputs now sit beside the preset select — type any dimensions and the render uses them (the server still rounds each down to a multiple of 64 and enforces the per-tier pixel budget). Uploading a source image still auto-snaps the size to the image's aspect ratio by default, until you take the dimensions into your own hands.
- **[issue-2197] First-run model downloads now show GB progress instead of raw text.** The video and image generation handlers now parse byte sizes from `DOWNLOAD:` markers and tqdm progress bars, displaying a formatted "Downloading model · first run · X.X GB / Y.Y GB" message instead of the raw protocol output. Progress frames include `downloadedBytes`/`totalBytes` numeric fields so the UI can build download progress bars. Phase tracking (`isDownloading`, `currentPhase`) ensures the formatting only applies during actual download phases.
diff --git a/client/src/components/media/AnnotationCanvas.jsx b/client/src/components/media/AnnotationCanvas.jsx
index cf1232b1a1..25f1bdf44d 100644
--- a/client/src/components/media/AnnotationCanvas.jsx
+++ b/client/src/components/media/AnnotationCanvas.jsx
@@ -1,18 +1,36 @@
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { drawStrokes, createStroke, appendPoint } from '../../lib/sketchCanvas';
-// Drawing surface for the Sketch & Annotation Canvas (issue #2036, phase 1).
-// Renders the target image with a transparent <canvas> stroke layer on top.
+// Drawing surface for the Sketch & Annotation Canvas (issue #2036).
+// Two modes:
+// - Overlay (phases 1–2): pass `imageSrc` — the target image renders with a
+// transparent <canvas> stroke layer on top; export flattens image + strokes.
+// - Blank canvas (phase 3): omit `imageSrc` and pass `blankWidth`/`blankHeight`
+// (+ optional `backgroundColor`) — a solid-fill canvas the user draws on from
+// scratch; export paints the background then the strokes.
// Controlled: the parent owns `strokes` + the active `tool` and receives
// committed strokes via `onStrokesChange`. Pointer events cover mouse, pen, AND
// touch (the canvas sets `touch-action: none` so a drag doesn't scroll the page).
//
-// The imperative handle exposes `exportPng()` (flattened image + strokes) and
+// The imperative handle exposes `exportPng()` (flattened output) and
// `dimensions` so the parent can persist / download without reaching into refs.
+const DEFAULT_BLANK_BG = '#ffffff';
+
const AnnotationCanvas = forwardRef(function AnnotationCanvas(
- { imageSrc, strokes, tool, onStrokesChange, onImageLoad, onImageError },
+ {
+ imageSrc,
+ strokes,
+ tool,
+ onStrokesChange,
+ onImageLoad,
+ onImageError,
+ blankWidth = 1024,
+ blankHeight = 1024,
+ backgroundColor = DEFAULT_BLANK_BG,
+ },
ref,
) {
+ const isBlank = !imageSrc;
const canvasRef = useRef(null);
const imgRef = useRef(null);
const drawingRef = useRef(null); // in-progress (uncommitted) stroke
@@ -29,17 +47,36 @@ const AnnotationCanvas = forwardRef(function AnnotationCanvas(
onImageLoad?.({ w, h });
}, [onImageLoad]);
+ // Blank mode has no <img> to fire onLoad — derive dims straight from the
+ // requested canvas size (clamped to a sane positive integer) and report them.
+ useEffect(() => {
+ if (!isBlank) return;
+ const w = Math.max(1, Math.round(blankWidth) || 1);
+ const h = Math.max(1, Math.round(blankHeight) || 1);
+ setDims({ w, h });
+ onImageLoad?.({ w, h });
+ }, [isBlank, blankWidth, blankHeight, onImageLoad]);
+
// Redraw the whole layer from the committed strokes plus any in-progress
// stroke. Full redraw (rather than incremental) keeps undo/erase trivially
- // correct — the layer is a pure function of the stroke list.
+ // correct — the layer is a pure function of the stroke list. In blank mode the
+ // background fills first so erase (destination-out) reveals the paper, not the
+ // page behind the canvas.
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas || !dims) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ if (isBlank) {
+ ctx.save();
+ ctx.fillStyle = backgroundColor;
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ ctx.restore();
+ }
const all = inProgress ? [...strokes, inProgress] : strokes;
drawStrokes(ctx, all, canvas.width, canvas.height);
- }, [strokes, inProgress, dims]);
+ }, [strokes, inProgress, dims, isBlank, backgroundColor]);
// Map a pointer event to natural-pixel canvas coordinates, accounting for the
// CSS scale between the displayed size and the canvas's internal resolution.
@@ -90,35 +127,49 @@ const AnnotationCanvas = forwardRef(function AnnotationCanvas(
useImperativeHandle(ref, () => ({
dimensions: dims,
- // Flatten the image + stroke layer into a single PNG data URL at natural
- // resolution. Same-origin image (/data/images/...) so the canvas isn't
- // tainted and toDataURL succeeds.
+ // Flatten to a single opaque PNG data URL at natural resolution. Overlay
+ // mode composites the same-origin image (/data/images/...) under the strokes
+ // (so the canvas isn't tainted and toDataURL succeeds); blank mode fills the
+ // background color instead so the export is never transparent.
exportPng: () => {
const canvas = canvasRef.current;
- const img = imgRef.current;
- if (!canvas || !img || !dims) return null;
+ if (!canvas || !dims) return null;
const out = document.createElement('canvas');
out.width = dims.w;
out.height = dims.h;
const ctx = out.getContext('2d');
if (!ctx) return null;
- ctx.drawImage(img, 0, 0, dims.w, dims.h);
+ if (isBlank) {
+ ctx.fillStyle = backgroundColor;
+ ctx.fillRect(0, 0, dims.w, dims.h);
+ } else {
+ const img = imgRef.current;
+ if (!img) return null;
+ ctx.drawImage(img, 0, 0, dims.w, dims.h);
+ }
ctx.drawImage(canvas, 0, 0, dims.w, dims.h);
return out.toDataURL('image/png');
},
- }), [dims]);
+ }), [dims, isBlank, backgroundColor]);
return (
<div className="relative inline-block max-w-full bg-port-bg rounded-lg overflow-hidden">
- <img
- ref={imgRef}
- src={imageSrc}
- onLoad={handleImgLoad}
- onError={onImageError}
- alt="Media being annotated"
- className="block max-w-full h-auto select-none"
- draggable={false}
- />
+ {isBlank ? (
+ // A sized spacer establishes the natural aspect ratio so the absolutely
+ // positioned canvas below scales to it (matches the <img> layout in
+ // overlay mode). No <img> element exists in blank mode.
+ <div style={{ aspectRatio: `${dims?.w || blankWidth} / ${dims?.h || blankHeight}` }} className="w-full max-w-full" />
+ ) : (
+ <img
+ ref={imgRef}
+ src={imageSrc}
+ onLoad={handleImgLoad}
+ onError={onImageError}
+ alt="Media being annotated"
+ className="block max-w-full h-auto select-none"
+ draggable={false}
+ />
+ )}
{dims && (
<canvas
ref={canvasRef}
diff --git a/client/src/components/pipeline/stages/StoryboardsStage.jsx b/client/src/components/pipeline/stages/StoryboardsStage.jsx
index 373b423c95..57326715fd 100644
--- a/client/src/components/pipeline/stages/StoryboardsStage.jsx
+++ b/client/src/components/pipeline/stages/StoryboardsStage.jsx
@@ -17,7 +17,8 @@
*/
import { useMemo, useRef, useState } from 'react';
-import { Plus, Trash2, Sparkles, Loader2, Wand2, Film, WandSparkles, Shirt, Layers } from 'lucide-react';
+import { useNavigate } from 'react-router-dom';
+import { Plus, Trash2, Sparkles, Loader2, Wand2, Film, WandSparkles, Shirt, Layers, Pencil } from 'lucide-react';
import toast from '../../ui/Toast';
import InlineConfirmRow from '../../ui/InlineConfirmRow';
import { SHOT_TYPES, SCREEN_DIRECTIONS, SHOT_TYPE_LABELS, SCREEN_DIRECTION_LABELS } from '../../../lib/shotGrammar';
@@ -30,6 +31,7 @@ import {
generatePipelineSceneImagePrompts,
updatePipelineIssue,
extractPipelineStoryboardScenes,
+ createBlankSketch,
} from '../../../services/api';
import useUniverse from '../../../hooks/useUniverse';
import { matchCharactersInText } from '../../../lib/scenePrompt';
@@ -38,8 +40,12 @@ import ImagePromptCandidates, { PromptCountInput } from '../ImagePromptCandidate
import { genConfigToImageOptions, genConfigToRefineOptions, IMAGE_PROMPT_COUNT_DEFAULT } from './VisualGenSettings';
export default function StoryboardsStage({ issue, series, onStageUpdate, actionsGated = false }) {
+ const navigate = useNavigate();
const stage = issue.stages?.storyboards || { status: 'empty', scenes: [] };
const [scenes, setScenes] = useState(stage.scenes || []);
+ // Scene index currently minting a blank sketch (so its button shows a spinner
+ // and can't be double-clicked while the POST is in flight).
+ const [sketchingIdx, setSketchingIdx] = useState(null);
// Per-stage gen config — edited from the page-level settings modal.
const genConfig = stage.genConfig || null;
const [savingIdx, setSavingIdx] = useState(null);
@@ -385,6 +391,32 @@ export default function StoryboardsStage({ issue, series, onStageUpdate, actions
toast.success(`Queued scene video (${result.jobId.slice(0, 8)})`);
};
+ // Attach a blank-canvas storyboard sketch to this scene (issue #2036 phase 3).
+ // The scene stores a `sketchKey` ("sketch:<uuid>") — a namespace the media
+ // sketch service owns, minted server-side (crypto.randomUUID is unavailable on
+ // PortOS's plain-HTTP origin). An existing key just reopens the same canvas.
+ // The sketch page returns here (?returnTo=) at the same stage.
+ const openSceneSketch = async (i) => {
+ const scene = scenes[i];
+ let key = scene.sketchKey;
+ if (!key) {
+ setSketchingIdx(i);
+ const res = await createBlankSketch({ silent: true }).catch((err) => {
+ toast.error(err.message || 'Failed to create sketch');
+ return null;
+ });
+ setSketchingIdx(null);
+ if (!res?.key) return;
+ key = res.key;
+ // Persist the key on the scene BEFORE navigating so a reload/return lands
+ // on the same canvas. persist() resolves once the PATCH settles.
+ const ok = await persist(scenes.map((s, j) => j === i ? { ...s, sketchKey: key } : s));
+ if (!ok) return;
+ }
+ const returnTo = `/pipeline/issues/${issue.id}/storyboards`;
+ navigate(`/media/annotate/${encodeURIComponent(key)}?returnTo=${encodeURIComponent(returnTo)}`);
+ };
+
return (
<div className="space-y-4">
<div className="flex items-center justify-between gap-3 flex-wrap">
@@ -515,6 +547,16 @@ export default function StoryboardsStage({ issue, series, onStageUpdate, actions
{renderingVideoIdx === i ? <Loader2 size={12} className="animate-spin" /> : <Film size={12} />}
Scene video
</button>
+ <button
+ type="button"
+ onClick={() => openSceneSketch(i)}
+ disabled={sketchingIdx !== null}
+ title={scene.sketchKey ? 'Open this scene’s storyboard sketch' : 'Draw a blank-canvas storyboard sketch for this scene'}
+ className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-card border border-port-border text-white text-xs hover:border-port-accent/50 disabled:opacity-50"
+ >
+ {sketchingIdx === i ? <Loader2 size={12} className="animate-spin" /> : <Pencil size={12} />}
+ {scene.sketchKey ? 'Edit sketch' : 'Sketch'}
+ </button>
{scene.imageJobId ? (
<>
<MediaJobThumb jobId={scene.imageJobId} label={`Scene ${i + 1}`} size="md" />
@@ -527,6 +569,23 @@ export default function StoryboardsStage({ issue, series, onStageUpdate, actions
<span className="text-[10px] text-gray-500 font-mono break-all">vid {scene.sceneVideoJobId.slice(0, 8)}</span>
</>
) : null}
+ {scene.sketchKey ? (
+ <button
+ type="button"
+ onClick={() => openSceneSketch(i)}
+ title="Open this scene’s storyboard sketch"
+ className="block rounded border border-port-border overflow-hidden hover:border-port-accent/50"
+ >
+ {/* The flattened PNG sidecar is served at /png; the query
+ key busts the cache after each save (updatedAt broadcast). */}
+ <img
+ src={`/api/media/sketches/${encodeURIComponent(scene.sketchKey)}/png`}
+ alt={`Scene ${i + 1} sketch`}
+ className="w-full h-auto"
+ onError={(e) => { e.currentTarget.style.display = 'none'; }}
+ />
+ </button>
+ ) : null}
</div>
</div>
{sceneCandidates[i] ? (
diff --git a/client/src/pages/MediaAnnotate.jsx b/client/src/pages/MediaAnnotate.jsx
index 70cf44da25..1bf4b210e9 100644
--- a/client/src/pages/MediaAnnotate.jsx
+++ b/client/src/pages/MediaAnnotate.jsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { useParams, Link, useNavigate } from 'react-router-dom';
+import { useParams, useSearchParams, Link, useNavigate } from 'react-router-dom';
import { Pencil, Eraser, Undo2, Trash2, Save, Download, ArrowLeft, ImageOff, Wand2, Loader2 } from 'lucide-react';
import toast from '../components/ui/Toast';
import Modal from '../components/ui/Modal';
@@ -14,9 +14,21 @@ import { getMediaSketch, saveMediaSketch, getRegenAvailability, rerenderWithAnno
const DEFAULT_ANNOTATED_STRENGTH = 0.5;
const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));
-// Parse a media key `<kind>:<ref>` on the client (mirrors server/lib/mediaItemKey.js
-// rules loosely — the server re-validates authoritatively). Phase 1 only supports
-// annotating images.
+// Blank-canvas defaults (phase 3). A storyboard sketch opens at a square 1:1
+// unless the caller passes ?w=&h= (e.g. matching the scene's aspect ratio).
+const DEFAULT_BLANK_DIM = 1024;
+const MIN_BLANK_DIM = 64;
+const MAX_BLANK_DIM = 4096;
+const clampDim = (v, fallback) => {
+ const n = Math.round(Number(v));
+ if (!Number.isFinite(n)) return fallback;
+ return Math.min(MAX_BLANK_DIM, Math.max(MIN_BLANK_DIM, n));
+};
+
+// Parse a sketch key on the client (mirrors server/services/mediaSketches.js
+// loosely — the server re-validates authoritatively). Supported kinds:
+// image:<filename> — annotate over a generated image (phases 1–2)
+// sketch:<uuid> — free-standing blank canvas (phase 3)
function parseMediaKey(key) {
if (typeof key !== 'string') return null;
const idx = key.indexOf(':');
@@ -31,12 +43,23 @@ const COLOR_SWATCHES = ['#ef4444', '#f59e0b', '#22c55e', '#3b82f6', '#a855f7', '
export default function MediaAnnotate() {
const { mediaKey } = useParams();
+ const [searchParams] = useSearchParams();
const navigate = useNavigate();
const parsed = useMemo(() => parseMediaKey(mediaKey), [mediaKey]);
const isImage = parsed?.kind === 'image';
+ const isBlank = parsed?.kind === 'sketch';
+ const isSupported = isImage || isBlank;
// Images are served from /data/images/<filename>; the ref IS the filename.
+ // A blank sketch has no backing image (the canvas fills a solid background).
const imageSrc = isImage ? `/data/images/${parsed.ref}` : null;
+ // Blank-canvas size + a return link, both driven by the URL so the page is
+ // reload-safe and shareable (the storyboard scene passes them when it opens
+ // a sketch). Falls back to a square default when absent/invalid.
+ const blankWidth = useMemo(() => clampDim(searchParams.get('w'), DEFAULT_BLANK_DIM), [searchParams]);
+ const blankHeight = useMemo(() => clampDim(searchParams.get('h'), DEFAULT_BLANK_DIM), [searchParams]);
+ const returnTo = searchParams.get('returnTo');
+
const canvasApiRef = useRef(null);
const [strokes, setStrokes] = useState([]);
const [dims, setDims] = useState(null);
@@ -76,7 +99,7 @@ export default function MediaAnnotate() {
// transient view state synchronously before fetching — otherwise the previous
// key's strokes / imageError / dims leak onto the new image.
useEffect(() => {
- if (!isImage) { setLoading(false); return; }
+ if (!isSupported) { setLoading(false); return; }
let active = true;
setStrokes([]);
setDims(null);
@@ -92,7 +115,7 @@ export default function MediaAnnotate() {
.catch(() => { if (active) toast.error('Failed to load saved annotation'); })
.finally(() => { if (active) setLoading(false); });
return () => { active = false; };
- }, [mediaKey, isImage]);
+ }, [mediaKey, isSupported]);
const tool = useMemo(() => ({ color, size, mode }), [color, size, mode]);
@@ -111,21 +134,25 @@ export default function MediaAnnotate() {
return res;
}, { errorMessage: 'Failed to save annotation' });
+ const noun = isBlank ? 'Sketch' : 'Annotation';
+ const backPath = returnTo || '/media/history';
+ const backLabel = returnTo ? 'Back' : 'Media History';
+
const handleSave = useCallback(async () => {
const res = await save();
- if (res) toast.success(strokes.length ? 'Annotation saved' : 'Annotation cleared');
- }, [save, strokes.length]);
+ if (res) toast.success(strokes.length ? `${noun} saved` : `${noun} cleared`);
+ }, [save, strokes.length, noun]);
const handleExport = useCallback(() => {
const dataUrl = canvasApiRef.current?.exportPng?.();
if (!dataUrl) { toast.error('Nothing to export yet'); return; }
const a = document.createElement('a');
a.href = dataUrl;
- a.download = `annotated-${parsed?.ref || 'image'}.png`;
+ a.download = isBlank ? `sketch-${parsed?.ref || 'canvas'}.png` : `annotated-${parsed?.ref || 'image'}.png`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
- }, [parsed]);
+ }, [parsed, isBlank]);
const strengthMin = regenInfo?.strengthMin ?? 0.02;
const strengthMax = regenInfo?.strengthMax ?? 0.6;
@@ -160,7 +187,7 @@ export default function MediaAnnotate() {
navigate('/media/history');
}, [rerender, navigate]);
- if (!isImage) {
+ if (!isSupported) {
return (
<div className="p-4 md:p-6 max-w-3xl mx-auto text-sm text-gray-400">
<Link to="/media/history" className="text-port-accent hover:underline inline-flex items-center gap-1">
@@ -169,7 +196,7 @@ export default function MediaAnnotate() {
<div className="mt-6 bg-port-card border border-port-border rounded-xl p-8 text-center">
<ImageOff className="w-8 h-8 mx-auto mb-2 text-gray-600" />
{mediaKey
- ? 'Only generated images can be annotated. This link points at an unsupported or missing item.'
+ ? 'Only generated images or blank-canvas sketches can be annotated. This link points at an unsupported or missing item.'
: 'Open a generated image from Media History or a Collection and choose “Annotate” to draw over it.'}
</div>
</div>
@@ -179,8 +206,8 @@ export default function MediaAnnotate() {
return (
<div className="flex flex-col h-full overflow-y-auto">
<div className="p-3 md:p-4 border-b border-port-border flex flex-wrap items-center gap-2 sticky top-0 bg-port-bg/95 backdrop-blur z-10">
- <Link to="/media/history" className="text-gray-400 hover:text-white inline-flex items-center gap-1 text-sm mr-1" title="Back to Media History">
- <ArrowLeft className="w-4 h-4" /> <span className="hidden sm:inline">History</span>
+ <Link to={backPath} className="text-gray-400 hover:text-white inline-flex items-center gap-1 text-sm mr-1" title={`Back to ${backLabel}`}>
+ <ArrowLeft className="w-4 h-4" /> <span className="hidden sm:inline">{backLabel}</span>
</Link>
{/* Draw / erase */}
@@ -275,19 +302,23 @@ export default function MediaAnnotate() {
onClick={handleSave}
disabled={saving || !dims}
className="px-3 py-1.5 text-xs bg-port-card border border-port-border text-gray-200 rounded hover:bg-port-border disabled:opacity-40 inline-flex items-center gap-1"
- title="Save annotation"
+ title={`Save ${noun.toLowerCase()}`}
>
<Save className="w-3.5 h-3.5" /> {saving ? 'Saving…' : 'Save'}
</button>
- <button
- type="button"
- onClick={openRerender}
- disabled={!dims || strokes.length === 0}
- className="px-3 py-1.5 text-xs bg-port-accent text-white rounded hover:bg-port-accent/80 disabled:opacity-40 inline-flex items-center gap-1"
- title={strokes.length === 0 ? 'Draw over the image first' : 'Re-render this image guided by your annotations'}
- >
- <Wand2 className="w-3.5 h-3.5" /> <span className="hidden sm:inline">Re-render</span>
- </button>
+ {/* Re-render is img2img over an existing generated image — only for the
+ overlay (image) mode. A blank sketch has no source render to feed. */}
+ {isImage ? (
+ <button
+ type="button"
+ onClick={openRerender}
+ disabled={!dims || strokes.length === 0}
+ className="px-3 py-1.5 text-xs bg-port-accent text-white rounded hover:bg-port-accent/80 disabled:opacity-40 inline-flex items-center gap-1"
+ title={strokes.length === 0 ? 'Draw over the image first' : 'Re-render this image guided by your annotations'}
+ >
+ <Wand2 className="w-3.5 h-3.5" /> <span className="hidden sm:inline">Re-render</span>
+ </button>
+ ) : null}
</div>
</div>
@@ -302,10 +333,12 @@ export default function MediaAnnotate() {
</div>
) : (
<div className="w-full max-w-4xl">
- {loading && <div className="text-gray-500 text-sm mb-2">Loading saved annotation…</div>}
+ {loading && <div className="text-gray-500 text-sm mb-2">Loading saved {noun.toLowerCase()}…</div>}
<AnnotationCanvas
ref={canvasApiRef}
imageSrc={imageSrc}
+ blankWidth={blankWidth}
+ blankHeight={blankHeight}
strokes={strokes}
tool={tool}
onStrokesChange={setStrokes}
diff --git a/client/src/pages/MediaAnnotate.test.jsx b/client/src/pages/MediaAnnotate.test.jsx
index 054dc7f819..1354336e3b 100644
--- a/client/src/pages/MediaAnnotate.test.jsx
+++ b/client/src/pages/MediaAnnotate.test.jsx
@@ -106,3 +106,41 @@ describe('MediaAnnotate re-render with annotations', () => {
expect(rerenderWithAnnotations).not.toHaveBeenCalled();
});
});
+
+describe('MediaAnnotate blank-canvas sketch (phase 3)', () => {
+ const renderBlank = (search = '') => render(
+ <MemoryRouter initialEntries={[`/media/annotate/sketch:11111111-1111-1111-1111-111111111111${search}`]}>
+ <Routes>
+ <Route path="/media/annotate/:mediaKey" element={<MediaAnnotate />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getMediaSketch.mockResolvedValue({ sketch: null });
+ saveMediaSketch.mockResolvedValue({ sketch: {} });
+ });
+
+ it('renders a canvas with no Re-render button and saves under the sketch key', async () => {
+ renderBlank();
+ // The canvas mounts (stub reports dims) but Re-render (img2img) is absent —
+ // a blank sketch has no source render to feed back.
+ await screen.findByTestId('stub-canvas');
+ expect(screen.queryByTitle('Re-render this image guided by your annotations')).toBeNull();
+ // No img2img availability probe for a blank canvas.
+ expect(getRegenAvailability).not.toHaveBeenCalled();
+
+ const saveBtn = await screen.findByTitle('Save sketch');
+ await waitFor(() => expect(saveBtn).not.toBeDisabled());
+ fireEvent.click(saveBtn);
+ await waitFor(() => expect(saveMediaSketch).toHaveBeenCalledTimes(1));
+ expect(saveMediaSketch.mock.calls[0][0]).toBe('sketch:11111111-1111-1111-1111-111111111111');
+ });
+
+ it('routes the back link to ?returnTo when provided', async () => {
+ renderBlank('?returnTo=%2Fpipeline%2Fissues%2Fabc%2Fstoryboards');
+ const back = await screen.findByRole('link', { name: 'Back' });
+ expect(back).toHaveAttribute('href', '/pipeline/issues/abc/storyboards');
+ });
+});
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 8d4e172015..932a6e7791 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -238,8 +238,9 @@ export const setMediaAnnotation = (key, patch) => request(`/media/annotations/${
body: JSON.stringify(patch),
});
-// Media sketches — freehand annotation strokes drawn over a generated image,
-// keyed by "<kind>:<ref>" (only image:* is supported in phase 1 of #2036).
+// Media sketches — freehand strokes over a generated image ("image:<ref>",
+// phases 1–2 of #2036) OR a free-standing blank canvas ("sketch:<uuid>",
+// phase 3, attachable to a pipeline storyboard scene).
// GET returns `{ key, sketch: { width, height, strokes, updatedAt, hasPng } | null }`.
// PUT persists strokes + an optional flattened PNG data URL. The persisted PNG
// is retrievable at GET /media/sketches/:key/png (consumed by phase 2's
@@ -252,6 +253,11 @@ export const saveMediaSketch = (key, payload, { silent = false } = {}) =>
body: JSON.stringify(payload),
silent,
});
+// Mint a fresh blank-canvas sketch key ("sketch:<uuid>"). Server-generated
+// because PortOS is served over plain HTTP (crypto.randomUUID is unavailable on
+// an insecure origin). Returns `{ key }`.
+export const createBlankSketch = ({ silent = false } = {}) =>
+ request('/media/sketches', { method: 'POST', silent });
// Models management (HF cache + LoRAs)
export const listCachedModels = () => request('/image-video/models');
diff --git a/server/routes/mediaSketches.js b/server/routes/mediaSketches.js
index 2cbd9b09d6..89dc985315 100644
--- a/server/routes/mediaSketches.js
+++ b/server/routes/mediaSketches.js
@@ -1,4 +1,6 @@
/**
+ * POST /api/media/sketches
+ * → { key: 'sketch:<uuid>' } (mint a fresh blank-canvas sketch key)
* GET /api/media/sketches/:key
* → { key, sketch: { width, height, strokes, updatedAt, hasPng } | null }
* PUT /api/media/sketches/:key
@@ -7,8 +9,9 @@
* GET /api/media/sketches/:key/png
* → flattened PNG bytes (image + strokes), 404 when none saved
*
- * Key shape: `<kind>:<ref>` (only `image:*` may be annotated in phase 1).
- * Phase 1 of the Sketch & Annotation Canvas — issue #2036.
+ * Key shape: `image:<ref>` (annotate over a generated image, phases 1–2) or
+ * `sketch:<uuid>` (a free-standing blank canvas, phase 3 — attachable to a
+ * pipeline storyboard scene). Both are issue #2036.
*/
import { Router } from 'express';
@@ -25,6 +28,13 @@ const mapServiceError = (err) => {
return err;
};
+// Mint a blank-canvas sketch key. The client can't rely on crypto.randomUUID
+// (PortOS is served over plain HTTP on Tailscale, an insecure origin), so the
+// server owns id generation.
+router.post('/', asyncHandler(async (_req, res) => {
+ res.status(201).json({ key: svc.createBlankSketchKey() });
+}));
+
router.get('/:key', asyncHandler(async (req, res) => {
const sketch = await svc.getSketch(req.params.key).catch((err) => { throw mapServiceError(err); });
res.json({ key: req.params.key, sketch });
diff --git a/server/routes/mediaSketches.test.js b/server/routes/mediaSketches.test.js
index 6c2a0f1968..cdb19c769d 100644
--- a/server/routes/mediaSketches.test.js
+++ b/server/routes/mediaSketches.test.js
@@ -84,4 +84,10 @@ describe('mediaSketches routes', () => {
const r = await request(makeApp()).get(`/api/media/sketches/${KEY}/png`);
expect(r.status).toBe(404);
});
+
+ it('POST / mints a fresh blank-canvas sketch key (phase 3)', async () => {
+ const r = await request(makeApp()).post('/api/media/sketches');
+ expect(r.status).toBe(201);
+ expect(r.body.key).toMatch(/^sketch:[a-f0-9-]{36}$/);
+ });
});
diff --git a/server/services/mediaSketches.js b/server/services/mediaSketches.js
index ca8e795cef..ec4b0ac60b 100644
--- a/server/services/mediaSketches.js
+++ b/server/services/mediaSketches.js
@@ -13,12 +13,23 @@
* directly). This is file-backed sidecar data (media-adjacent binary + vector
* blobs, no relational shape) per the docs/STORAGE.md classification — the same
* class as media-annotations.json / thumbnails, NOT a db-primary record.
+ *
+ * Phase 3 adds free-standing **blank-canvas sketches** (no backing image) keyed
+ * by `sketch:<id>`, attachable to pipeline storyboard scenes. That `sketch`
+ * kind is DELIBERATELY local to this service and is NOT part of the shared
+ * `mediaItemKey` vocabulary (ITEM_KINDS stays image|video) — so it can never
+ * leak into media collections, peer-sync asset manifests, or the media_assets
+ * table, all of which enumerate the shared kinds. Storage layout is identical:
+ * the same base64url-of-key → `<id>.json` + `<id>.png` sidecar pair. A blank
+ * sketch's flattened PNG is a self-contained raster (no source image to
+ * composite), so the Phase 2 img2img feedback path works on it unchanged.
*/
import { join } from 'path';
+import { randomUUID } from 'crypto';
import { unlink, access } from 'fs/promises';
import { PATHS, atomicWrite, readJSONFile, ensureDir, tryReadFile } from '../lib/fileUtils.js';
-import { isValidKey, parseKey } from '../lib/mediaItemKey.js';
+import { isValidKey as isValidMediaKey, parseKey } from '../lib/mediaItemKey.js';
const SKETCH_DIR = join(PATHS.data, 'media-sketches');
@@ -30,7 +41,21 @@ export const MAX_STROKES = 5000;
export const MAX_POINTS_PER_STROKE = 20000;
export const STROKE_MODES = new Set(['draw', 'erase']);
-export { isValidKey };
+// Blank-canvas sketch keys (Phase 3). `sketch:<uuid>` — a namespace local to
+// this service (see the module header). The id half is a UUID we mint, so it's
+// always a safe single path token.
+const BLANK_SKETCH_PREFIX = 'sketch:';
+const BLANK_SKETCH_ID = /^sketch:[a-f0-9-]{36}$/;
+
+/** A `sketch:<uuid>` blank-canvas key this service owns (not a shared media key). */
+export const isBlankSketchKey = (key) => typeof key === 'string' && BLANK_SKETCH_ID.test(key);
+
+/** Mint a fresh blank-canvas sketch key. */
+export const createBlankSketchKey = () => `${BLANK_SKETCH_PREFIX}${randomUUID()}`;
+
+// A key this service can persist: either a shared `image:<ref>` media key OR a
+// locally-owned `sketch:<uuid>` blank canvas. Video keys stay unsupported.
+export const isValidKey = (key) => isBlankSketchKey(key) || isValidMediaKey(key);
// A ref is an arbitrary filename (e.g. `image:my file:v2.png` is rejected by
// parseKey, but `image:my-file.png` is fine and still needs escaping for a
@@ -127,8 +152,12 @@ export async function getSketchPngPath(key) {
*/
export async function saveSketch(key, input) {
if (!isValidKey(key)) throw makeErr(`Invalid key: ${key}`, ERR_VALIDATION);
- const parsed = parseKey(key);
- if (parsed.kind !== 'image') throw makeErr('Only image media can be annotated', ERR_VALIDATION);
+ // A blank-canvas sketch (`sketch:<uuid>`) has no backing media; any other key
+ // must be an `image:<ref>` — video and the rest of the shared vocabulary stay
+ // unsupported (a video can't carry a stroke overlay in this UI).
+ if (!isBlankSketchKey(key) && parseKey(key)?.kind !== 'image') {
+ throw makeErr('Only image media or blank-canvas sketches can be annotated', ERR_VALIDATION);
+ }
const clean = sanitizeSketchInput(input);
await ensureDir(SKETCH_DIR);
diff --git a/server/services/mediaSketches.test.js b/server/services/mediaSketches.test.js
index f804eef1e6..9296c4e634 100644
--- a/server/services/mediaSketches.test.js
+++ b/server/services/mediaSketches.test.js
@@ -116,4 +116,38 @@ describe('mediaSketches service', () => {
expect(() => svc.sanitizeSketchInput({ width: 1, height: 1, strokes: [], png: 'data:image/jpeg;base64,AAAA' }))
.toThrowError();
});
+
+ describe('blank-canvas sketches (phase 3)', () => {
+ it('createBlankSketchKey mints a recognizable sketch:<uuid> key', () => {
+ const key = svc.createBlankSketchKey();
+ expect(key).toMatch(/^sketch:[a-f0-9-]{36}$/);
+ expect(svc.isBlankSketchKey(key)).toBe(true);
+ expect(svc.isValidKey(key)).toBe(true);
+ });
+
+ it('isBlankSketchKey rejects image/video/garbage keys', () => {
+ expect(svc.isBlankSketchKey('image:foo.png')).toBe(false);
+ expect(svc.isBlankSketchKey('video:abc')).toBe(false);
+ expect(svc.isBlankSketchKey('sketch:not-a-uuid')).toBe(false);
+ expect(svc.isBlankSketchKey('sketch:')).toBe(false);
+ expect(svc.isBlankSketchKey(null)).toBe(false);
+ });
+
+ it('saveSketch → getSketch round-trips a blank-canvas key', async () => {
+ const key = svc.createBlankSketchKey();
+ const saved = await svc.saveSketch(key, { width: 512, height: 512, strokes: sampleStrokes, png: PNG_DATA_URL });
+ expect(saved.strokes).toHaveLength(2);
+ expect(saved.hasPng).toBe(true);
+ const loaded = await svc.getSketch(key);
+ expect(loaded.strokes).toEqual(saved.strokes);
+ expect(loaded.width).toBe(512);
+ // The flattened PNG path resolves for the img2img feedback path too.
+ expect(await svc.getSketchPngPath(key)).not.toBeNull();
+ });
+
+ it('still rejects a video key (only image + blank sketch are supported)', async () => {
+ await expect(svc.saveSketch('video:abc', { width: 1, height: 1, strokes: sampleStrokes }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+ });
});