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: annotation sketch sidecar endpoint for media images (#2036)

Adam Eivya22d313b4fca
diff --git a/server/index.js b/server/index.js
index c1f55b52bf..d3b74a68ed 100644
--- a/server/index.js
+++ b/server/index.js
@@ -86,6 +86,7 @@ import paletteRoutes from './routes/palette.js';
import dashboardLayoutsRoutes from './routes/dashboardLayouts.js';
import mediaCollectionsRoutes from './routes/mediaCollections.js';
import mediaAnnotationsRoutes from './routes/mediaAnnotations.js';
+import mediaSketchesRoutes from './routes/mediaSketches.js';
import dataSyncRoutes from './routes/dataSync.js';
import identityRoutes from './routes/identity.js';
import instancesRoutes from './routes/instances.js';
@@ -443,6 +444,7 @@ app.use('/api/palette', paletteRoutes);
app.use('/api/dashboard/layouts', dashboardLayoutsRoutes);
app.use('/api/media/collections', mediaCollectionsRoutes);
app.use('/api/media/annotations', mediaAnnotationsRoutes);
+app.use('/api/media/sketches', mediaSketchesRoutes);
app.use('/api/attachments', attachmentsRoutes);
app.use('/api/client-errors', clientErrorsRoutes);
app.use('/api/backup', backupRoutes);
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 4742fb6624..ebd9d4690a 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -269,6 +269,36 @@ export const searchQuerySchema = z.object({
q: z.string().min(2).max(200).trim()
});
+// =============================================================================
+// MEDIA SKETCH / ANNOTATION SCHEMAS (issue #2036, phase 1)
+// =============================================================================
+
+// Vector strokes drawn over a generated image. Points are stored in the
+// image's natural-pixel space so they restore exactly regardless of the
+// display size (see AnnotationCanvas.jsx). The service (mediaSketches.js)
+// re-sanitizes + clamps beyond this schema; the Zod layer rejects the
+// obviously-malformed shapes early with a 400.
+const sketchPointSchema = z.object({
+ x: z.number().finite(),
+ y: z.number().finite()
+});
+
+const sketchStrokeSchema = z.object({
+ mode: z.enum(['draw', 'erase']).optional(),
+ color: z.string().max(32).optional(),
+ size: z.number().positive().max(512).optional(),
+ points: z.array(sketchPointSchema).min(1).max(20000)
+});
+
+export const mediaSketchSaveSchema = z.object({
+ width: z.number().positive(),
+ height: z.number().positive(),
+ strokes: z.array(sketchStrokeSchema).max(5000),
+ // Flattened raster (image + strokes) as a PNG data URL. Optional so a caller
+ // can persist just the vector layer; the service decodes + stores the bytes.
+ png: z.string().startsWith('data:image/png;base64,').optional()
+});
+
// =============================================================================
// BACKUP SCHEMAS
// =============================================================================
diff --git a/server/routes/mediaSketches.js b/server/routes/mediaSketches.js
new file mode 100644
index 0000000000..2cbd9b09d6
--- /dev/null
+++ b/server/routes/mediaSketches.js
@@ -0,0 +1,48 @@
+/**
+ * GET /api/media/sketches/:key
+ * → { key, sketch: { width, height, strokes, updatedAt, hasPng } | null }
+ * PUT /api/media/sketches/:key
+ * body: { width, height, strokes: [...], png?: dataURL }
+ * → { key, sketch } (sketch.strokes empty ⇒ sidecar removed)
+ * 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.
+ */
+
+import { Router } from 'express';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest, mediaSketchSaveSchema } from '../lib/validation.js';
+import * as svc from '../services/mediaSketches.js';
+
+const router = Router();
+
+const mapServiceError = (err) => {
+ if (err?.code === svc.ERR_VALIDATION) {
+ return new ServerError(err.message, { status: 400, code: err.code });
+ }
+ return err;
+};
+
+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 });
+}));
+
+router.get('/:key/png', asyncHandler(async (req, res) => {
+ const png = await svc.getSketchPng(req.params.key).catch((err) => { throw mapServiceError(err); });
+ if (!png) throw new ServerError('No sketch export for this media', { status: 404, code: 'NOT_FOUND' });
+ res.type('image/png').send(png);
+}));
+
+router.put('/:key', asyncHandler(async (req, res) => {
+ const body = validateRequest(mediaSketchSaveSchema, req.body ?? {});
+ const sketch = await svc.saveSketch(req.params.key, body).catch((err) => { throw mapServiceError(err); });
+ // Broadcast so other open views (History, Collections, other tabs) can drop a
+ // stale "has annotation" badge or refresh without a manual reload.
+ req.app.get('io')?.emit('media:sketch:updated', { key: req.params.key, sketch });
+ res.json({ key: req.params.key, sketch });
+}));
+
+export default router;
diff --git a/server/routes/mediaSketches.test.js b/server/routes/mediaSketches.test.js
new file mode 100644
index 0000000000..6c2a0f1968
--- /dev/null
+++ b/server/routes/mediaSketches.test.js
@@ -0,0 +1,87 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+// Stub the service so we assert the route's request → svc-call → response
+// wiring (incl. 400/404 mapping) without touching the real file-backed store.
+const stubs = {
+ getSketch: vi.fn(),
+ getSketchPng: vi.fn(),
+ saveSketch: vi.fn(),
+};
+
+vi.mock('../services/mediaSketches.js', async () => {
+ const actual = await vi.importActual('../services/mediaSketches.js');
+ return {
+ ...actual,
+ getSketch: (...a) => stubs.getSketch(...a),
+ getSketchPng: (...a) => stubs.getSketchPng(...a),
+ saveSketch: (...a) => stubs.saveSketch(...a),
+ };
+});
+
+const router = (await import('./mediaSketches.js')).default;
+
+function makeApp() {
+ const app = express();
+ app.use(express.json({ limit: '55mb' }));
+ app.use('/api/media/sketches', router);
+ app.use(errorMiddleware);
+ return app;
+}
+
+const KEY = encodeURIComponent('image:foo.png');
+const sampleStrokes = [{ mode: 'draw', color: '#ef4444', size: 6, points: [{ x: 1, y: 2 }, { x: 3, y: 4 }] }];
+
+describe('mediaSketches routes', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('GET /:key returns the sketch projection', async () => {
+ stubs.getSketch.mockResolvedValue({ key: 'image:foo.png', width: 10, height: 10, strokes: sampleStrokes, updatedAt: 'now', hasPng: true });
+ const r = await request(makeApp()).get(`/api/media/sketches/${KEY}`);
+ expect(r.status).toBe(200);
+ expect(r.body.sketch.strokes).toHaveLength(1);
+ expect(stubs.getSketch).toHaveBeenCalledWith('image:foo.png');
+ });
+
+ it('GET /:key returns sketch:null when none saved', async () => {
+ stubs.getSketch.mockResolvedValue(null);
+ const r = await request(makeApp()).get(`/api/media/sketches/${KEY}`);
+ expect(r.status).toBe(200);
+ expect(r.body.sketch).toBeNull();
+ });
+
+ it('PUT /:key round-trips a save and echoes the stored sketch', async () => {
+ const stored = { key: 'image:foo.png', width: 100, height: 80, strokes: sampleStrokes, updatedAt: 'now', hasPng: false };
+ stubs.saveSketch.mockResolvedValue(stored);
+ const r = await request(makeApp())
+ .put(`/api/media/sketches/${KEY}`)
+ .send({ width: 100, height: 80, strokes: sampleStrokes });
+ expect(r.status).toBe(200);
+ expect(r.body.key).toBe('image:foo.png');
+ expect(r.body.sketch).toEqual(stored);
+ expect(stubs.saveSketch).toHaveBeenCalledWith('image:foo.png', expect.objectContaining({ width: 100, height: 80 }));
+ });
+
+ it('PUT /:key 400s on a malformed payload before hitting the service', async () => {
+ const r = await request(makeApp())
+ .put(`/api/media/sketches/${KEY}`)
+ .send({ width: 100 }); // missing height + strokes
+ expect(r.status).toBe(400);
+ expect(stubs.saveSketch).not.toHaveBeenCalled();
+ });
+
+ it('GET /:key/png streams the flattened bytes', async () => {
+ stubs.getSketchPng.mockResolvedValue(Buffer.from('png-bytes'));
+ const r = await request(makeApp()).get(`/api/media/sketches/${KEY}/png`);
+ expect(r.status).toBe(200);
+ expect(r.headers['content-type']).toContain('image/png');
+ });
+
+ it('GET /:key/png 404s when no export exists', async () => {
+ stubs.getSketchPng.mockResolvedValue(null);
+ const r = await request(makeApp()).get(`/api/media/sketches/${KEY}/png`);
+ expect(r.status).toBe(404);
+ });
+});
diff --git a/server/services/mediaSketches.js b/server/services/mediaSketches.js
new file mode 100644
index 0000000000..67ecc536a9
--- /dev/null
+++ b/server/services/mediaSketches.js
@@ -0,0 +1,148 @@
+/**
+ * Sketch & annotation overlays for generated media, keyed by `<kind>:<ref>`.
+ *
+ * Phase 1 of the Sketch & Annotation Canvas (issue #2036): a user draws over an
+ * existing generated image and the strokes are persisted as a per-key sidecar so
+ * they survive reload and job pruning. Each key stores two files:
+ *
+ * data/media-sketches/<id>.json — stroke vectors + canvas dimensions
+ * data/media-sketches/<id>.png — flattened raster (image + strokes)
+ *
+ * where `<id>` is a filesystem-safe base64url encoding of the `<kind>:<ref>` key
+ * (a ref is an arbitrary filename, so it can't be used as a path segment
+ * 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.
+ */
+
+import { join } from 'path';
+import { unlink } from 'fs/promises';
+import { PATHS, atomicWrite, readJSONFile, ensureDir, tryReadFile } from '../lib/fileUtils.js';
+import { isValidKey, parseKey } from '../lib/mediaItemKey.js';
+
+const SKETCH_DIR = join(PATHS.data, 'media-sketches');
+
+export const ERR_VALIDATION = 'VALIDATION_ERROR';
+const makeErr = (message, code) => Object.assign(new Error(message), { code });
+
+// Guardrails so a hand-rolled or malicious payload can't balloon a sidecar.
+export const MAX_STROKES = 5000;
+export const MAX_POINTS_PER_STROKE = 20000;
+export const STROKE_MODES = new Set(['draw', 'erase']);
+
+export { isValidKey };
+
+// 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
+// path segment). base64url keeps every valid key to a single safe token.
+const keyToId = (key) => Buffer.from(key, 'utf8').toString('base64url');
+const jsonPathFor = (key) => join(SKETCH_DIR, `${keyToId(key)}.json`);
+const pngPathFor = (key) => join(SKETCH_DIR, `${keyToId(key)}.png`);
+
+const DATA_URL_PNG = /^data:image\/png;base64,([A-Za-z0-9+/=]+)$/;
+
+const isFinitePositive = (n) => typeof n === 'number' && Number.isFinite(n) && n > 0;
+
+// Sanitize a single stroke into the persisted shape or return null to drop it.
+function sanitizeStroke(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ if (!Array.isArray(raw.points) || raw.points.length === 0) return null;
+ const points = [];
+ for (const p of raw.points) {
+ if (!p || typeof p !== 'object') continue;
+ if (typeof p.x !== 'number' || typeof p.y !== 'number') continue;
+ if (!Number.isFinite(p.x) || !Number.isFinite(p.y)) continue;
+ points.push({ x: p.x, y: p.y });
+ if (points.length >= MAX_POINTS_PER_STROKE) break;
+ }
+ if (points.length === 0) return null;
+ const mode = STROKE_MODES.has(raw.mode) ? raw.mode : 'draw';
+ const color = typeof raw.color === 'string' ? raw.color.slice(0, 32) : '#ef4444';
+ const size = isFinitePositive(raw.size) ? Math.min(raw.size, 512) : 4;
+ return { mode, color, size, points };
+}
+
+export function sanitizeSketchInput(input) {
+ if (!input || typeof input !== 'object') throw makeErr('sketch payload required', ERR_VALIDATION);
+ if (!Array.isArray(input.strokes)) throw makeErr('strokes must be an array', ERR_VALIDATION);
+ if (!isFinitePositive(input.width) || !isFinitePositive(input.height)) {
+ throw makeErr('width and height must be positive numbers', ERR_VALIDATION);
+ }
+ const strokes = [];
+ for (const raw of input.strokes) {
+ const s = sanitizeStroke(raw);
+ if (s) strokes.push(s);
+ if (strokes.length >= MAX_STROKES) break;
+ }
+ let png = null;
+ if (typeof input.png === 'string' && input.png) {
+ const m = DATA_URL_PNG.exec(input.png);
+ if (!m) throw makeErr('png must be a data:image/png;base64 URL', ERR_VALIDATION);
+ png = Buffer.from(m[1], 'base64');
+ }
+ return {
+ width: input.width,
+ height: input.height,
+ strokes,
+ png, // Buffer | null
+ };
+}
+
+/** Read the persisted sketch for a key, or null when none exists. */
+export async function getSketch(key) {
+ if (!isValidKey(key)) throw makeErr(`Invalid key: ${key}`, ERR_VALIDATION);
+ const data = await readJSONFile(jsonPathFor(key), null, { logError: false });
+ if (!data || typeof data !== 'object' || !Array.isArray(data.strokes)) return null;
+ return {
+ key,
+ width: data.width,
+ height: data.height,
+ strokes: data.strokes,
+ updatedAt: data.updatedAt || null,
+ hasPng: !!data.hasPng,
+ };
+}
+
+/** Raw flattened PNG bytes for a key, or null. */
+export async function getSketchPng(key) {
+ if (!isValidKey(key)) throw makeErr(`Invalid key: ${key}`, ERR_VALIDATION);
+ return tryReadFile(pngPathFor(key), null); // Buffer | 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.
+ * Returns the stored projection `{ key, width, height, strokes, updatedAt, hasPng }`.
+ */
+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);
+ const clean = sanitizeSketchInput(input);
+ await ensureDir(SKETCH_DIR);
+
+ if (clean.strokes.length === 0) {
+ await removeSketch(key);
+ return { key, width: clean.width, height: clean.height, strokes: [], updatedAt: null, hasPng: false };
+ }
+
+ const hasPng = !!clean.png;
+ if (hasPng) await atomicWrite(pngPathFor(key), clean.png);
+ const record = {
+ key,
+ width: clean.width,
+ height: clean.height,
+ strokes: clean.strokes,
+ updatedAt: new Date().toISOString(),
+ hasPng,
+ };
+ await atomicWrite(jsonPathFor(key), record);
+ return record;
+}
+
+/** Remove a key's sidecar (json + png). Idempotent. */
+export async function removeSketch(key) {
+ if (!isValidKey(key)) throw makeErr(`Invalid key: ${key}`, ERR_VALIDATION);
+ await unlink(jsonPathFor(key)).catch(() => {});
+ await unlink(pngPathFor(key)).catch(() => {});
+}
diff --git a/server/services/mediaSketches.test.js b/server/services/mediaSketches.test.js
new file mode 100644
index 0000000000..df8254e347
--- /dev/null
+++ b/server/services/mediaSketches.test.js
@@ -0,0 +1,93 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const fileStore = new Map();
+
+vi.mock('../lib/fileUtils.js', () => ({
+ PATHS: { data: '/mock/data' },
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),
+ tryReadFile: vi.fn(async (path) => (fileStore.has(path) ? fileStore.get(path) : null)),
+}));
+
+vi.mock('fs/promises', () => ({
+ unlink: vi.fn(async (path) => { fileStore.delete(path); }),
+}));
+
+const svc = await import('./mediaSketches.js');
+
+const KEY = 'image:foo.png';
+const PNG_DATA_URL = `data:image/png;base64,${Buffer.from('fake-png-bytes').toString('base64')}`;
+
+const sampleStrokes = [
+ { mode: 'draw', color: '#ef4444', size: 6, points: [{ x: 1, y: 2 }, { x: 3, y: 4 }] },
+ { mode: 'erase', color: '#000000', size: 12, points: [{ x: 5, y: 6 }] },
+];
+
+describe('mediaSketches service', () => {
+ beforeEach(() => { fileStore.clear(); });
+
+ it('getSketch returns null for a fresh key', async () => {
+ expect(await svc.getSketch(KEY)).toBeNull();
+ });
+
+ it('saveSketch → getSketch round-trips strokes + dimensions', async () => {
+ const saved = await svc.saveSketch(KEY, { width: 100, height: 80, strokes: sampleStrokes, png: PNG_DATA_URL });
+ expect(saved.strokes).toHaveLength(2);
+ expect(saved.width).toBe(100);
+ expect(saved.hasPng).toBe(true);
+ expect(saved.updatedAt).toBeTruthy();
+
+ const loaded = await svc.getSketch(KEY);
+ expect(loaded.strokes).toEqual(saved.strokes);
+ expect(loaded.width).toBe(100);
+ expect(loaded.height).toBe(80);
+ expect(loaded.hasPng).toBe(true);
+ });
+
+ it('saveSketch persists the flattened PNG as decoded bytes', async () => {
+ await svc.saveSketch(KEY, { width: 10, height: 10, strokes: sampleStrokes, png: PNG_DATA_URL });
+ const png = await svc.getSketchPng(KEY);
+ expect(Buffer.isBuffer(png)).toBe(true);
+ expect(png.toString()).toBe('fake-png-bytes');
+ });
+
+ it('saveSketch with empty strokes removes the sidecar', async () => {
+ await svc.saveSketch(KEY, { width: 10, height: 10, strokes: sampleStrokes, png: PNG_DATA_URL });
+ expect(await svc.getSketch(KEY)).not.toBeNull();
+ const cleared = await svc.saveSketch(KEY, { width: 10, height: 10, strokes: [] });
+ expect(cleared.strokes).toEqual([]);
+ expect(await svc.getSketch(KEY)).toBeNull();
+ });
+
+ it('sanitizeSketchInput drops malformed strokes/points and clamps size', () => {
+ const clean = svc.sanitizeSketchInput({
+ width: 50,
+ height: 50,
+ strokes: [
+ { points: [] }, // dropped: no points
+ { points: [{ x: 'bad', y: 1 }] }, // dropped: non-numeric → no valid points
+ { mode: 'weird', points: [{ x: 1, y: 1 }] }, // mode coerced to draw
+ { size: 9999, points: [{ x: 2, y: 2 }] }, // size clamped to 512
+ ],
+ });
+ expect(clean.strokes).toHaveLength(2);
+ expect(clean.strokes[0].mode).toBe('draw');
+ expect(clean.strokes[1].size).toBe(512);
+ expect(clean.png).toBeNull();
+ });
+
+ it('rejects a non-image key', async () => {
+ await expect(svc.saveSketch('video:abc', { width: 1, height: 1, strokes: sampleStrokes }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('rejects an invalid key', async () => {
+ await expect(svc.getSketch('not-a-key')).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('rejects a non-PNG data URL', () => {
+ expect(() => svc.sanitizeSketchInput({ width: 1, height: 1, strokes: [], png: 'data:image/jpeg;base64,AAAA' }))
+ .toThrowError();
+ });
+});