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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-2036]): re-render generated images from annotations (phase 2)
Adam Eivy994e419c9d8c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdnew file mode 100644index 0000000000..8cb6befd95--- /dev/null+++ b/.changelog/NEXT.md@@ -0,0 +1,5 @@+# Unreleased Changes++## Media++- **[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.diff --git a/client/src/pages/MediaAnnotate.jsx b/client/src/pages/MediaAnnotate.jsxindex 91df711586..39b55fd21d 100644--- a/client/src/pages/MediaAnnotate.jsx+++ b/client/src/pages/MediaAnnotate.jsx@@ -1,11 +1,18 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { useParams, Link } from 'react-router-dom';-import { Pencil, Eraser, Undo2, Trash2, Save, Download, ArrowLeft, ImageOff } from 'lucide-react';+import { useParams, 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';import AnnotationCanvas from '../components/media/AnnotationCanvas';import { useAsyncAction } from '../hooks/useAsyncAction';import { undoStrokes, clampSize, DEFAULT_COLOR, DEFAULT_SIZE, MIN_SIZE, MAX_SIZE } from '../lib/sketchCanvas';-import { getMediaSketch, saveMediaSketch } from '../services/api';+import { getMediaSketch, saveMediaSketch, getRegenAvailability, rerenderWithAnnotations } from '../services/api';++// Default denoise for an annotation re-render — high enough that the drawn marks+// actually reshape the image (mirrors the server's REGEN_ANNOTATED_STRENGTH_DEFAULT).+// Clamped into the backend's advertised [min, max] bounds at render time.+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@@ -24,6 +31,7 @@ const COLOR_SWATCHES = ['#ef4444', '#f59e0b', '#22c55e', '#3b82f6', '#a855f7', 'export default function MediaAnnotate() {const { mediaKey } = useParams();+ const navigate = useNavigate();const parsed = useMemo(() => parseMediaKey(mediaKey), [mediaKey]);const isImage = parsed?.kind === 'image';// Images are served from /data/images/<filename>; the ref IS the filename.@@ -38,6 +46,24 @@ export default function MediaAnnotate() {const [loading, setLoading] = useState(true);const [imageError, setImageError] = useState(false);+ // Re-render (issue #2036 phase 2). `regenInfo` is the same local-FLUX+ // img2img availability the lightbox uses — it names the exact model a+ // re-render would run, so the user sees the provider/model before any AI+ // call (no cold-bootstrap). null until fetched; `available:false` gates it.+ const [regenInfo, setRegenInfo] = useState(null);+ const [rerenderOpen, setRerenderOpen] = useState(false);+ const [rerenderPrompt, setRerenderPrompt] = useState('');+ const [rerenderStrength, setRerenderStrength] = useState(DEFAULT_ANNOTATED_STRENGTH);++ useEffect(() => {+ if (!isImage) return;+ let active = true;+ getRegenAvailability()+ .then((r) => { if (active) setRegenInfo(r || null); })+ .catch(() => { if (active) setRegenInfo(null); });+ return () => { active = false; };+ }, [isImage]);+// Load any previously-saved strokes for this media key. React Router reuses// this component instance across :mediaKey changes (no remount), so reset all// transient view state synchronously before fetching — otherwise the previous@@ -94,6 +120,39 @@ export default function MediaAnnotate() {document.body.removeChild(a);}, [parsed]);+ const strengthMin = regenInfo?.strengthMin ?? 0.02;+ const strengthMax = regenInfo?.strengthMax ?? 0.6;+ const regenAvailable = !!regenInfo?.available;+ const regenModelLabel = regenInfo?.modelId || 'local FLUX img2img';++ const openRerender = useCallback(() => {+ setRerenderStrength(clamp(DEFAULT_ANNOTATED_STRENGTH, strengthMin, strengthMax));+ setRerenderPrompt('');+ setRerenderOpen(true);+ }, [strengthMin, strengthMax]);++ // Persist the annotation (writes the flattened PNG sidecar the server uses as+ // the img2img init image), then enqueue the re-render. Both API calls are+ // silent so useAsyncAction owns the single error toast.+ const [rerender, rerendering] = useAsyncAction(async () => {+ if (!dims) throw new Error('Canvas not ready');+ if (strokes.length === 0) throw new Error('Draw over the image before re-rendering');+ const png = canvasApiRef.current?.exportPng?.() || undefined;+ await saveMediaSketch(mediaKey, { width: dims.w, height: dims.h, strokes, png }, { silent: true });+ return rerenderWithAnnotations(parsed.ref, {+ strength: rerenderStrength,+ prompt: rerenderPrompt.trim() || undefined,+ });+ }, { errorMessage: 'Failed to start re-render' });++ const handleRerender = useCallback(async () => {+ const res = await rerender();+ if (!res) return;+ setRerenderOpen(false);+ toast.success('Re-rendering with your annotations — it’ll appear in Media History');+ navigate('/media/history');+ }, [rerender, navigate]);+if (!isImage) {return (<div className="p-4 md:p-6 max-w-3xl mx-auto text-sm text-gray-400">@@ -208,11 +267,20 @@ export default function MediaAnnotate() {type="button"onClick={handleSave}disabled={saving || !dims}- 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"+ 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"><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></div></div>@@ -240,6 +308,88 @@ export default function MediaAnnotate() {</div>)}</div>++ <Modal+ open={rerenderOpen}+ onClose={() => !rerendering && setRerenderOpen(false)}+ size="sm"+ closeOnBackdrop={!rerendering}+ closeOnEsc={!rerendering}+ ariaLabel="Re-render with annotations"+ panelClassName="bg-port-card border border-port-border rounded-xl p-5 text-sm"+ >+ <h2 className="text-base font-semibold text-white flex items-center gap-2">+ <Wand2 className="w-4 h-4 text-port-accent" /> Re-render with annotations+ </h2>+ <p className="text-gray-400 mt-1 text-xs">+ Your drawing is flattened onto the image and fed back through img2img so the marks reshape the render.+ </p>++ {/* Provider/model visible before any AI call runs (no cold-bootstrap). */}+ <div className="mt-3 rounded-lg bg-port-bg border border-port-border px-3 py-2 text-xs">+ <span className="text-gray-500">Renders locally via </span>+ <span className="text-gray-200 font-mono">{regenModelLabel}</span>+ </div>++ {!regenAvailable ? (+ <div className="mt-3 text-xs text-port-warning">+ {regenInfo?.reason || 'Local img2img isn’t available on this install. A local FLUX runner is required to re-render.'}+ </div>+ ) : (+ <>+ <div className="mt-4">+ <label htmlFor="rerender-prompt" className="block text-xs text-gray-400 mb-1">+ Prompt <span className="text-gray-600">(optional — steer the redraw)</span>+ </label>+ <textarea+ id="rerender-prompt"+ value={rerenderPrompt}+ onChange={(e) => setRerenderPrompt(e.target.value)}+ rows={2}+ placeholder="Leave blank to let the annotations alone guide the redraw"+ className="w-full rounded-lg bg-port-bg border border-port-border px-3 py-2 text-sm text-gray-200 resize-none focus:outline-none focus:border-port-accent"+ />+ </div>++ <div className="mt-3">+ <label htmlFor="rerender-strength" className="flex items-center justify-between text-xs text-gray-400 mb-1">+ <span>Strength <span className="text-gray-600">(how much to change)</span></span>+ <span className="text-gray-300 tabular-nums">{rerenderStrength.toFixed(2)}</span>+ </label>+ <input+ id="rerender-strength"+ type="range"+ min={strengthMin}+ max={strengthMax}+ step={0.01}+ value={rerenderStrength}+ onChange={(e) => setRerenderStrength(clamp(parseFloat(e.target.value), strengthMin, strengthMax))}+ className="w-full accent-port-accent"+ />+ </div>+ </>+ )}++ <div className="mt-5 flex items-center justify-end gap-2">+ <button+ type="button"+ onClick={() => setRerenderOpen(false)}+ disabled={rerendering}+ className="px-3 py-1.5 text-xs bg-port-card border border-port-border rounded hover:bg-port-border disabled:opacity-40"+ >+ Cancel+ </button>+ <button+ type="button"+ onClick={handleRerender}+ disabled={rerendering || !regenAvailable}+ 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"+ >+ {rerendering ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Wand2 className="w-3.5 h-3.5" />}+ {rerendering ? 'Starting…' : 'Re-render'}+ </button>+ </div>+ </Modal></div>);}diff --git a/client/src/pages/MediaAnnotate.test.jsx b/client/src/pages/MediaAnnotate.test.jsxnew file mode 100644index 0000000000..054dc7f819--- /dev/null+++ b/client/src/pages/MediaAnnotate.test.jsx@@ -0,0 +1,108 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor, within } from '@testing-library/react';+import { MemoryRouter, Routes, Route } from 'react-router-dom';+import MediaAnnotate from './MediaAnnotate';++// Re-render (issue #2036 phase 2) is the focus: annotate an image, then feed the+// flattened markup back through img2img. The canvas itself is exercised by+// sketchCanvas.test.js — here it's stubbed to synchronously report dimensions+// and expose a flattened-PNG export so the page's re-render wiring can run.+vi.mock('../components/media/AnnotationCanvas', async () => {+ const React = await import('react');+ return {+ default: React.forwardRef(function StubCanvas({ onImageLoad }, ref) {+ React.useImperativeHandle(ref, () => ({ exportPng: () => 'data:image/png;base64,QQ==' }), []);+ // Defer to a macrotask: the real <img> onLoad fires asynchronously, AFTER+ // the page's own mount effect resets dims to null. Reporting synchronously+ // here would be clobbered by that reset (child effects run before parent).+ React.useEffect(() => {+ const t = setTimeout(() => onImageLoad?.({ w: 100, h: 80 }), 0);+ return () => clearTimeout(t);+ }, [onImageLoad]);+ return <div data-testid="stub-canvas" />;+ }),+ };+});++const getMediaSketch = vi.fn();+const saveMediaSketch = vi.fn();+const getRegenAvailability = vi.fn();+const rerenderWithAnnotations = vi.fn();++vi.mock('../services/api', () => ({+ getMediaSketch: (...a) => getMediaSketch(...a),+ saveMediaSketch: (...a) => saveMediaSketch(...a),+ getRegenAvailability: (...a) => getRegenAvailability(...a),+ rerenderWithAnnotations: (...a) => rerenderWithAnnotations(...a),+}));++const toastSuccess = vi.fn();+const toastError = vi.fn();+vi.mock('../components/ui/Toast', () => ({+ default: { success: (...a) => toastSuccess(...a), error: (...a) => toastError(...a) },+}));++const navigate = vi.fn();+vi.mock('react-router-dom', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, useNavigate: () => navigate };+});++const renderPage = () => render(+ <MemoryRouter initialEntries={['/media/annotate/image:foo.png']}>+ <Routes>+ <Route path="/media/annotate/:mediaKey" element={<MediaAnnotate />} />+ </Routes>+ </MemoryRouter>,+);++describe('MediaAnnotate re-render with annotations', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getMediaSketch.mockResolvedValue({ sketch: { strokes: [{ mode: 'draw', color: '#ef4444', size: 4, points: [{ x: 1, y: 2 }] }] } });+ getRegenAvailability.mockResolvedValue({ available: true, modelId: 'flux-dev', strengthMin: 0.02, strengthMax: 0.6, strengthDefault: 0.25 });+ saveMediaSketch.mockResolvedValue({ sketch: {} });+ rerenderWithAnnotations.mockResolvedValue({ jobId: 'job-1', position: 1, status: 'queued' });+ });++ it('saves the annotation and enqueues an img2img re-render, naming the local model', async () => {+ renderPage();++ // The button enables once the canvas reports dims AND saved strokes load.+ const btn = await screen.findByTitle('Re-render this image guided by your annotations');+ await waitFor(() => expect(btn).not.toBeDisabled());+ fireEvent.click(btn);++ // Provider/model is visible before any AI call (no cold-bootstrap).+ expect(await screen.findByText('flux-dev')).toBeInTheDocument();++ // Confirm → persist annotation (flattened PNG) then enqueue the re-render.+ const dialog = screen.getByRole('dialog');+ fireEvent.click(within(dialog).getByRole('button', { name: 'Re-render' }));++ await waitFor(() => expect(rerenderWithAnnotations).toHaveBeenCalledTimes(1));+ expect(saveMediaSketch).toHaveBeenCalledWith(+ 'image:foo.png',+ expect.objectContaining({ width: 100, height: 80, png: 'data:image/png;base64,QQ==' }),+ { silent: true },+ );+ expect(rerenderWithAnnotations).toHaveBeenCalledWith('foo.png', { strength: 0.5, prompt: undefined });+ expect(toastSuccess).toHaveBeenCalled();+ expect(navigate).toHaveBeenCalledWith('/media/history');+ });++ it('disables re-render and surfaces the reason when local img2img is unavailable', async () => {+ getRegenAvailability.mockResolvedValue({ available: false, reason: 'No local FLUX runner installed.' });+ renderPage();++ const btn = await screen.findByTitle('Re-render this image guided by your annotations');+ await waitFor(() => expect(btn).not.toBeDisabled());+ fireEvent.click(btn);++ expect(await screen.findByText('No local FLUX runner installed.')).toBeInTheDocument();+ // The confirm button in the modal is disabled when unavailable.+ const confirm = within(screen.getByRole('dialog')).getByRole('button', { name: 'Re-render' });+ expect(confirm).toBeDisabled();+ expect(rerenderWithAnnotations).not.toHaveBeenCalled();+ });+});diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex fa3fc8488e..38839c8fc4 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -75,6 +75,22 @@ export const regenerateGalleryImage = (filename, { strength, steps, prompt, meth// Whether the local FLUX regen backend is installed (hardware gate). Also carries// the strength slider bounds: `{ available, modelId, reason, strengthMin, strengthMax, strengthDefault }`.export const getRegenAvailability = () => request('/image-gen/regen/availability', { silent: true });+// Annotation re-render (issue #2036 phase 2). Feeds the saved flattened sketch+// (source image + drawn strokes) back through the local-FLUX img2img regen as the+// init image; returns the queue ack ({ jobId, position, ... }). The annotation+// must already be saved (the flattened PNG sidecar is the init image). `silent`+// so the annotate page owns its own error toast (single-layer rule).+export const rerenderWithAnnotations = (filename, { strength, steps, prompt } = {}) =>+ request(`/image-gen/${encodeURIComponent(filename)}/regenerate`, {+ method: 'POST',+ body: JSON.stringify({+ annotated: true,+ ...(strength != null ? { strength } : {}),+ ...(steps != null ? { steps } : {}),+ ...(prompt != null ? { prompt } : {}),+ }),+ silent: true,+ });// HuggingFace token (gated local Flux models). Stored in settings.imageGen.hfToken;// reads fall back to HF_TOKEN env var and then ~/.cache/huggingface/token.diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex ec0e5fd914..9fa292ea36 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -40,8 +40,10 @@ import { STYLE_PRESETS } from '../lib/writersRoomStylePresets.js';import {resolveRegenBackend, getRegenAvailability, readImageDimensions, buildRegenParams,REGEN_STRENGTH_MIN, REGEN_STRENGTH_MAX,- resolveRegenStrengthDefault,+ resolveRegenStrengthDefault, REGEN_ANNOTATED_STRENGTH_DEFAULT,} from '../services/imageGen/regen.js';+import { getSketchPngPath, isValidKey as isValidSketchKey } from '../services/mediaSketches.js';+import { itemKey } from '../lib/mediaItemKey.js';import { purgeImageRefFromAllUniverses } from '../services/universeCanon.js';import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';import * as characterService from '../services/character.js';@@ -261,6 +263,11 @@ const regenerateSchema = z.object({// 'flux' (default) = GPU img2img round-trip; 'light' = CPU-only spatial pass// for installs without a FLUX runner (strength/steps/prompt ignored).method: z.enum(['flux', 'light']).optional(),+ // Annotation re-render (issue #2036 phase 2): seed the img2img init image from+ // the saved flattened sketch (source + drawn strokes) instead of the raw+ // gallery file, so the marks reshape the render. GPU-only (light ignores the+ // init image); defaults to a higher denoise so the strokes take effect.+ annotated: z.boolean().optional(),});// Visible-watermark removal — erases the Gemini / Nano-Banana bottom-right ✦.@@ -694,6 +701,25 @@ router.post('/:filename/regenerate', asyncHandler(async (req, res) => {if (!sourceAbsPath) {throw new ServerError('Image not found', { status: 404, code: 'NOT_FOUND' });}++ // Annotation re-render (issue #2036 phase 2): use the saved flattened sketch+ // (source + strokes) as the img2img init image. It's a whole-image denoise, so+ // the light spatial pass can't honor the marks — GPU only.+ let initImageAbsPath = null;+ if (body.annotated) {+ if (body.method === 'light') {+ throw new ServerError('Annotation re-render needs the GPU img2img pass, not the light method.', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const key = itemKey({ kind: 'image', ref: filename });+ if (!isValidSketchKey(key)) {+ throw new ServerError('Image cannot be annotated', { status: 400, code: 'VALIDATION_ERROR' });+ }+ initImageAbsPath = await getSketchPngPath(key);+ if (!initImageAbsPath) {+ throw new ServerError('No saved annotation to re-render — draw over the image and save first.', { status: 400, code: 'NO_ANNOTATION' });+ }+ }+// Sidecar (for prompt/model) and the on-disk dimension probe have no data// dependency — overlap the two reads.const [{ metadata: sourceMeta }, sourceDims] = await Promise.all([@@ -714,9 +740,11 @@ router.post('/:filename/regenerate', asyncHandler(async (req, res) => {}// Provider-aware default (issue #912): SynthID-bearing sources keep the- // known-good 0.25; local FLUX sources use a lighter pass. The explicit- // `strength` override always wins.- const strength = body.strength ?? resolveRegenStrengthDefault(sourceMeta);+ // known-good 0.25; local FLUX sources use a lighter pass. An annotation+ // re-render instead defaults higher so the drawn marks reshape the render+ // (issue #2036). The explicit `strength` override always wins.+ const strength = body.strength+ ?? (body.annotated ? REGEN_ANNOTATED_STRENGTH_DEFAULT : resolveRegenStrengthDefault(sourceMeta));const params = buildRegenParams({filename,sourceAbsPath,@@ -727,9 +755,12 @@ router.post('/:filename/regenerate', asyncHandler(async (req, res) => {strength,steps: body.steps,promptOverride: body.prompt,+ initImageAbsPath,+ annotated: !!body.annotated,});const queued = enqueueJob({ kind: 'image', params });- console.log(`♻️ Regenerating ${filename} via ${backend.model.id} (strength=${strength}) → job ${queued.jobId.slice(0, 8)}`);+ const via = body.annotated ? 'annotation re-render' : 'Regenerating';+ console.log(`♻️ ${via} ${filename} via ${backend.model.id} (strength=${strength}) → job ${queued.jobId.slice(0, 8)}`);return res.json(queuedImageResponse({ ...queued, mode: IMAGE_GEN_MODE.LOCAL, model: backend.model.id }));}));diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex 8e94fd4ffd..d53b10e25a 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -5,6 +5,7 @@ import { errorMiddleware } from '../lib/errorHandler.js';import imageGenRoutes from './imageGen.js';import * as fileUtils from '../lib/fileUtils.js';import * as regen from '../services/imageGen/regen.js';+import * as mediaSketches from '../services/mediaSketches.js';vi.mock('../services/imageGen/index.js', () => ({checkConnection: vi.fn(),@@ -1161,5 +1162,74 @@ describe('Image Gen Routes', () => {resolveBackendSpy.mockRestore();buildParamsSpy.mockRestore();});++ // Annotation re-render (issue #2036 phase 2)+ it('400s an annotated re-render when no annotation has been saved', async () => {+ const resolveGallerySpy = vi.spyOn(fileUtils, 'resolveGalleryImage')+ .mockReturnValueOnce('/fake/gallery/source.png');+ const sketchPathSpy = vi.spyOn(mediaSketches, 'getSketchPngPath')+ .mockResolvedValueOnce(null);++ const response = await request(app)+ .post('/api/image-gen/source.png/regenerate')+ .send({ annotated: true });++ expect(response.status).toBe(400);+ expect(response.body.code).toBe('NO_ANNOTATION');+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();++ resolveGallerySpy.mockRestore();+ sketchPathSpy.mockRestore();+ });++ it('400s an annotated re-render on the light method (init image needs the GPU pass)', async () => {+ const resolveGallerySpy = vi.spyOn(fileUtils, 'resolveGalleryImage')+ .mockReturnValueOnce('/fake/gallery/source.png');++ const response = await request(app)+ .post('/api/image-gen/source.png/regenerate')+ .send({ annotated: true, method: 'light' });++ expect(response.status).toBe(400);+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();++ resolveGallerySpy.mockRestore();+ });++ it('seeds the annotated re-render init image from the sketch PNG at the higher default strength', async () => {+ const resolveGallerySpy = vi.spyOn(fileUtils, 'resolveGalleryImage')+ .mockReturnValueOnce('/fake/gallery/source.png');+ const sketchPathSpy = vi.spyOn(mediaSketches, 'getSketchPngPath')+ .mockResolvedValueOnce('/fake/data/media-sketches/abc.png');+ imageGen.local.readImageSidecar.mockResolvedValueOnce({+ path: '/fake/gallery/source.png.json',+ metadata: { modelId: 'flux-dev', prompt: 'a robot' },+ });+ const readDimsSpy = vi.spyOn(regen, 'readImageDimensions')+ .mockResolvedValueOnce({ width: 1024, height: 1024 });+ const resolveBackendSpy = vi.spyOn(regen, 'resolveRegenBackend')+ .mockResolvedValueOnce({ available: true, model: { id: 'flux-dev' }, pythonPath: '/fake/venv/python' });+ const buildParamsSpy = vi.spyOn(regen, 'buildRegenParams')+ .mockReturnValueOnce({ kind: 'image', regenJob: true, filename: 'source.png' });+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'annot-job-001', position: 1, status: 'queued' });++ const response = await request(app)+ .post('/api/image-gen/source.png/regenerate')+ .send({ annotated: true }); // no explicit strength → annotated default++ expect(response.status).toBe(200);+ expect(response.body.jobId).toBe('annot-job-001');+ expect(buildParamsSpy).toHaveBeenCalledWith(expect.objectContaining({+ initImageAbsPath: '/fake/data/media-sketches/abc.png',+ annotated: true,+ strength: regen.REGEN_ANNOTATED_STRENGTH_DEFAULT,+ }));++ resolveGallerySpy.mockRestore();+ sketchPathSpy.mockRestore();+ readDimsSpy.mockRestore();+ resolveBackendSpy.mockRestore();+ buildParamsSpy.mockRestore();+ });});});diff --git a/server/services/imageGen/regen.js b/server/services/imageGen/regen.jsindex bb8229e1da..e343a12003 100644--- a/server/services/imageGen/regen.js+++ b/server/services/imageGen/regen.js@@ -63,6 +63,14 @@ export const REGEN_STRENGTH_MAX = 0.6;// fidelity when regenerated for other reasons.export const REGEN_LIGHT_STRENGTH_DEFAULT = 0.15;+// Annotation re-render default (issue #2036 phase 2). Unlike a SynthID pass —+// which wants the LOWEST denoise that still overwrites the watermark — an+// annotation re-render exists to let the drawn marks actually reshape the image,+// so it needs a much higher denoise. 0.5 (just under REGEN_STRENGTH_MAX) lets the+// strokes meaningfully redraw while still anchoring on the source composition.+// The API `strength` override and the [MIN, MAX] bounds are unaffected.+export const REGEN_ANNOTATED_STRENGTH_DEFAULT = 0.5;+// Provider-aware denoise default for a regen of `sourceMeta`. SynthID rides on// gpt-image (codex) / Imagen / Gemini / Nano-Banana output; those keep the// conservative 0.25. Local FLUX sources (a `modelId` with no external `mode`,@@ -261,7 +269,12 @@ export async function readImageDimensions(absPath) {// clamping changes the dims, `upscaleTo` carries the source's exact dimensions// so `generateImage` resizes the result back up, delivering a watermark-free// copy at the original resolution.-export function buildRegenParams({ filename, sourceAbsPath, sourceMeta = {}, sourceDims = null, model, pythonPath, strength, steps, promptOverride }) {+export function buildRegenParams({ filename, sourceAbsPath, sourceMeta = {}, sourceDims = null, model, pythonPath, strength, steps, promptOverride, initImageAbsPath, annotated = false }) {+ // The img2img base pixels normally come from the clicked source, but an+ // annotation re-render (issue #2036 phase 2) points the init image at the+ // flattened source+strokes PNG while STILL reading dimensions/metadata/lineage+ // from the original source below.+ const initPath = initImageAbsPath || sourceAbsPath;const src = sourceDims|| (sourceMeta.width && sourceMeta.height ? { width: Math.round(sourceMeta.width), height: Math.round(sourceMeta.height) } : null);const trimmedPrompt = typeof promptOverride === 'string' ? promptOverride.trim() : '';@@ -280,9 +293,10 @@ export function buildRegenParams({ filename, sourceAbsPath, sourceMeta = {}, soumodelId: model.id,prompt: trimmedPrompt,negativePrompt: trimmedPrompt && typeof sourceMeta.negativePrompt === 'string' ? sourceMeta.negativePrompt : '',- initImagePath: sourceAbsPath,+ initImagePath: initPath,initImageStrength: strength,regenOf: groupRoot,+ ...(annotated ? { annotatedRegen: true } : {}),};if (src) {const render = clampRegenDimensions(src.width, src.height);diff --git a/server/services/imageGen/regen.test.js b/server/services/imageGen/regen.test.jsindex cc9c5f3f05..f5f40d1b54 100644--- a/server/services/imageGen/regen.test.js+++ b/server/services/imageGen/regen.test.js@@ -246,6 +246,26 @@ describe('buildRegenParams', () => {expect(params.height % 16).toBe(0);expect(params.upscaleTo).toEqual({ width: 1024, height: 1000 });});++ it('annotation re-render seeds initImagePath from the sketch PNG while keeping source lineage', () => {+ // Issue #2036 phase 2: the img2img base is the flattened source+strokes PNG,+ // but dimensions/lineage still come from the original source (regenOf).+ const params = buildRegenParams({+ ...base,+ sourceMeta: { prompt: 'x', width: 1024, height: 768 },+ initImageAbsPath: '/data/media-sketches/abc.png',+ annotated: true,+ });+ expect(params.initImagePath).toBe('/data/media-sketches/abc.png');+ expect(params.regenOf).toBe('source.png');+ expect(params.annotatedRegen).toBe(true);+ });++ it('leaves initImagePath at the source and omits annotatedRegen for a normal regen', () => {+ const params = buildRegenParams({ ...base, sourceMeta: { prompt: 'x' } });+ expect(params.initImagePath).toBe('/data/images/source.png');+ expect(params.annotatedRegen).toBeUndefined();+ });});describe('clampRegenDimensions', () => {diff --git a/server/services/mediaSketches.js b/server/services/mediaSketches.jsindex 7a3abce419..ca8e795cef 100644--- a/server/services/mediaSketches.js+++ b/server/services/mediaSketches.js@@ -16,7 +16,7 @@*/import { join } from 'path';-import { unlink } from 'fs/promises';+import { unlink, access } from 'fs/promises';import { PATHS, atomicWrite, readJSONFile, ensureDir, tryReadFile } from '../lib/fileUtils.js';import { isValidKey, parseKey } from '../lib/mediaItemKey.js';@@ -109,6 +109,17 @@ export async function getSketchPng(key) {return tryReadFile(pngPathFor(key), null); // Buffer | null}+/**+ * Absolute path to a key's flattened PNG sidecar when it exists on disk, else+ * null. Phase 2 (issue #2036) feeds this file to the img2img regen pipeline as+ * the init image, so it needs the path (not the bytes) to hand off to the runner.+ */+export async function getSketchPngPath(key) {+ if (!isValidKey(key)) throw makeErr(`Invalid key: ${key}`, ERR_VALIDATION);+ const path = pngPathFor(key);+ return access(path).then(() => path).catch(() => null);+}+/*** Persist (or replace) the sketch for a key. An empty stroke list removes the* sidecar entirely so a fully-erased canvas doesn't leave a stale record.diff --git a/server/services/mediaSketches.test.js b/server/services/mediaSketches.test.jsindex 390f182a5c..f804eef1e6 100644--- a/server/services/mediaSketches.test.js+++ b/server/services/mediaSketches.test.js@@ -12,6 +12,7 @@ vi.mock('../lib/fileUtils.js', () => ({vi.mock('fs/promises', () => ({unlink: vi.fn(async (path) => { fileStore.delete(path); }),+ access: vi.fn(async (path) => { if (!fileStore.has(path)) throw new Error('ENOENT'); }),}));const svc = await import('./mediaSketches.js');@@ -52,6 +53,21 @@ describe('mediaSketches service', () => {expect(png.toString()).toBe('fake-png-bytes');});+ it('getSketchPngPath returns the flattened PNG path when it exists, null otherwise', async () => {+ // Issue #2036 phase 2: the img2img re-render needs the sidecar path, not bytes.+ expect(await svc.getSketchPngPath(KEY)).toBeNull();+ await svc.saveSketch(KEY, { width: 10, height: 10, strokes: sampleStrokes, png: PNG_DATA_URL });+ const path = await svc.getSketchPngPath(KEY);+ expect(path).toBe('/mock/data/media-sketches/aW1hZ2U6Zm9vLnBuZw.png');+ // A vectors-only re-save drops the PNG, so the path resolver goes null again.+ await svc.saveSketch(KEY, { width: 10, height: 10, strokes: sampleStrokes });+ expect(await svc.getSketchPngPath(KEY)).toBeNull();+ });++ it('getSketchPngPath rejects an invalid key', async () => {+ await expect(svc.getSketchPngPath('not a key')).rejects.toThrow();+ });+it('re-saving with strokes but no PNG drops the stale flattened export', async () => {await svc.saveSketch(KEY, { width: 10, height: 10, strokes: sampleStrokes, png: PNG_DATA_URL });expect(await svc.getSketchPng(KEY)).not.toBeNull();