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
refactor: share image pixel primitives (#4654)
[._.]/ Adam Eivyfed6d7c1396a
diff --git a/server/lib/README.md b/server/lib/README.mdindex 563201ec8f..dccbb5951f 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -163,6 +163,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|+| `borderKey.js` | Sharp-free image primitives shared by sprites and image-to-3D: statistics median, subsampled border-band sampling, solid-border coverage detection, and meaningful-alpha checks. || `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `loadAllResult` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. `loadAll` silently drops corrupt records; `loadAllResult()` → `{ records, failedIds }` keeps the "which ids failed to load" signal so a caller can tell a partial set from a complete one. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. **Type-index `config` slot** holds cross-record state (see the `TypeIndexConfig` typedef + header convention): `{ runs?: [], featureFlags?: {}, lockPolicies?: {} }` — `runs` is the shipped slot (universeBuilder's capped history log), the other two are reserved names; consumers may add their own keys but should reuse a reserved name when it fits and document the shape next to the consumer. `saveTypeIndex({ config })` shallow-merges `config` one level deep (a patched `runs` replaces the whole array), so a read-modify-write of a slot must load → mutate a copy → write inside `queueTypeIndexWrite(fn)`. || `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. || `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |@@ -175,6 +176,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `fileWriteQueue.js` | Serialize read-modify-write cycles so they don't interleave. `createFileWriteQueue()` → single-tail `queue(fn)` for one shared file; `createRecordWriteQueue(assertId?)` → id-keyed `queueRecordWrite(id, fn)` where same-id cycles serialize and different-id cycles run in parallel (the queue the PG/file store facades use for `collectionStore.queueRecordWrite` parity); `createKeyedFileWriteQueue()` → `queueKeyedWrite(key, fn)` that collapses the pipeline stage stores' hand-rolled `Map` + per-key `createFileWriteQueue` factory (falsy keys → shared `'__unknown__'` tail; self-pruning via `createKeyCachedQueue`). || `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `compositeIgnoreZone(base, original, mask, { feather })` (preserve-region compositing: restore original pixels into a feathered mask over a diffused result) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer` and appends a CPU light diffusion pass (`applyLightRegen` from `services/imageGen/regen.js`) for the `diffusion=light` SynthID-disruption step. || `imageFrameStats.js` | Degenerate-frame classifier (#4173) — `describeFrameStats(bufferOrPath)` runs one `sharp` `.stats()` decode and returns `{ ok, reason, perChannel }`, rejecting `solid-fill` (every colour channel stdev under `SOLID_FILL_STDEV_EPSILON`), `fully-transparent` (alpha max 0) and `near-empty` (greyscale entropy under `NEAR_EMPTY_ENTROPY_FLOOR`). Deliberately NOT a quality judge: a legitimately dark or minimalist render keeps real per-channel variance and is accepted. `ok` is three-valued — `true`/`false`/`null`, where `null` means could-not-measure (undecodable buffer, or under `MIN_JUDGEABLE_PIXELS`) and must never read as degenerate; gate on `isDegenerateFrame(stats)` / `ok === false`, never `!ok`. Called by the Image Gen provider completion seams, sprite reference normalization, and `visionTest.js` (so a paid vision call is never spent on a blank frame). |+| `imageRgba.js` | Sharp-backed RGBA boundary: `decodeRgbaFrame` decodes an image to `{ data, width, height }`, and `encodePng` turns a raw frame into PNG bytes for the caller's destination/hash policy. || `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. || `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). || `localMemory.js` | Shared best-effort local-model unload + available-memory report (`prepareLocalMemory`) for GPU-heavy local work; only loopback Ollama / LM Studio backends are evicted. |diff --git a/server/lib/borderKey.js b/server/lib/borderKey.jsnew file mode 100644index 0000000000..44272156e5--- /dev/null+++ b/server/lib/borderKey.js@@ -0,0 +1,95 @@+/**+ * Sharp-free border and alpha primitives shared by image-processing lanes.+ *+ * Border sampling deliberately uses a narrow band and a subsampled perimeter:+ * one dirty edge row should not overturn an otherwise flat background, while a+ * large source should not allocate one sample for every border pixel.+ */++/** statistics.median: middle value, or mean of the two middles. */+export function median(values) {+ const sorted = [...values].sort((a, b) => a - b);+ const mid = sorted.length >> 1;+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;+}++const borderBandOffsets = ({ width, height }) => {+ const minDim = Math.min(width, height);+ const band = Math.max(4, Math.floor(minDim / 120));+ const step = Math.max(1, Math.floor(minDim / 320));+ const offsets = [];+ const push = (x, y) => offsets.push((y * width + x) * 4);++ for (let x = 0; x < width; x += step) {+ for (let o = 0; o < band && o < height; o += 1) {+ push(x, o);+ push(x, height - 1 - o);+ }+ }+ for (let y = 0; y < height; y += step) {+ for (let o = 0; o < band && o < width; o += 1) {+ push(o, y);+ push(width - 1 - o, y);+ }+ }+ return offsets;+};++const borderColor = (data, offsets) => (+ [0, 1, 2].map((channel) => median(offsets.map((offset) => data[offset + channel])))+);++const rgbDistanceSq = (data, offset, [r, g, b]) => (+ (data[offset] - r) ** 2+ + (data[offset + 1] - g) ** 2+ + (data[offset + 2] - b) ** 2+);++/**+ * Sample the median RGB value across the subsampled border band.+ *+ * The returned medians intentionally retain the statistics semantics for an+ * even sample count. Callers that need a codec/pipeline-specific integer+ * rounding policy should apply it at their domain boundary.+ *+ * @param {{data: Buffer|Uint8Array, width: number, height: number}} frame+ * @returns {[number, number, number]}+ */+export function sampleBorderKey({ data, width, height }) {+ const offsets = borderBandOffsets({ width, height });+ return borderColor(data, offsets);+}++/**+ * Detect a flat border background using the shared band sampler.+ *+ * @param {{data: Buffer|Uint8Array, width: number, height: number}} frame+ * @param {{tolerance?: number, minCoverage?: number}} options+ * @returns {[number, number, number]|null}+ */+export function detectSolidBorderColor(+ { data, width, height },+ { tolerance = 30, minCoverage = 0.9 } = {},+) {+ const offsets = borderBandOffsets({ width, height });+ if (!offsets.length) return null;+ const color = borderColor(data, offsets);+ const toleranceSq = tolerance ** 2;+ const matching = offsets.reduce(+ (count, offset) => count + (rgbDistanceSq(data, offset, color) <= toleranceSq ? 1 : 0),+ 0,+ );+ return matching / offsets.length >= minCoverage ? color : null;+}++/**+ * Whether an RGBA buffer contains alpha below the caller's meaningfulness+ * threshold. The default preserves image-to-3D's historical 250 cutoff; the+ * sprite lane passes 255 to preserve its previous "any alpha variation" test.+ */+export function hasMeaningfulAlpha(data, alphaThreshold = 250) {+ for (let i = 3; i < data.length; i += 4) {+ if (data[i] < alphaThreshold) return true;+ }+ return false;+}diff --git a/server/lib/borderKey.test.js b/server/lib/borderKey.test.jsnew file mode 100644index 0000000000..85978d7010--- /dev/null+++ b/server/lib/borderKey.test.js@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';+import {+ detectSolidBorderColor,+ hasMeaningfulAlpha,+ median,+ sampleBorderKey,+} from './borderKey.js';++const makeFrame = (width, height, paint) => {+ const data = new Uint8Array(width * height * 4);+ for (let y = 0; y < height; y += 1) {+ for (let x = 0; x < width; x += 1) {+ const [r, g, b, a = 255] = paint(x, y);+ const i = (y * width + x) * 4;+ data[i] = r;+ data[i + 1] = g;+ data[i + 2] = b;+ data[i + 3] = a;+ }+ }+ return { data, width, height };+};++const GREEN = [30, 200, 40];++describe('borderKey', () => {+ it('uses statistics median semantics for even samples', () => {+ expect(median([4, 1, 3, 2])).toBe(2.5);+ });++ it('keeps a solid border measurement through one dirty edge row', () => {+ const frame = makeFrame(20, 20, (x, y) => {+ if (y === 0) return [255, 0, 0];+ if (x >= 5 && x < 15 && y >= 5 && y < 15) return [140, 90, 50];+ return GREEN;+ });+ expect(sampleBorderKey(frame)).toEqual(GREEN);+ expect(detectSolidBorderColor(frame)).toEqual(GREEN);+ });++ it('shares the alpha meaningfulness threshold with an explicit override', () => {+ const almostOpaque = makeFrame(2, 1, (x) => [0, 0, 0, x ? 255 : 249]);+ expect(hasMeaningfulAlpha(almostOpaque.data)).toBe(true);+ expect(hasMeaningfulAlpha(almostOpaque.data, 255)).toBe(true);+ expect(hasMeaningfulAlpha(makeFrame(2, 1, () => [0, 0, 0, 255]).data)).toBe(false);+ });+});diff --git a/server/lib/imageRgba.js b/server/lib/imageRgba.jsnew file mode 100644index 0000000000..95464a214c--- /dev/null+++ b/server/lib/imageRgba.js@@ -0,0 +1,24 @@+/**+ * Small sharp-backed RGBA helpers shared by image-processing lanes.+ *+ * Pixel algorithms belong in sharp-free modules; this file is the deliberate+ * boundary for decoding encoded images and producing PNG bytes.+ */++import sharp from 'sharp';++/** Decode an image to a raw RGBA frame `{ data, width, height }`. */+export async function decodeRgbaFrame(src) {+ const { data, info } = await sharp(src)+ .ensureAlpha()+ .raw()+ .toBuffer({ resolveWithObject: true });+ return { data, width: info.width, height: info.height };+}++/** Encode a raw frame as PNG bytes without choosing a destination. */+export async function encodePng({ data, width, height }, channels = 4) {+ return sharp(data, { raw: { width, height, channels } })+ .png()+ .toBuffer();+}diff --git a/server/lib/imageRgba.test.js b/server/lib/imageRgba.test.jsnew file mode 100644index 0000000000..66eef9547a--- /dev/null+++ b/server/lib/imageRgba.test.js@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';+import { decodeRgbaFrame, encodePng } from './imageRgba.js';++describe('imageRgba', () => {+ it('round-trips a raw RGBA frame through PNG bytes', async () => {+ const frame = {+ data: Buffer.from([255, 0, 0, 255, 0, 0, 255, 128]),+ width: 2,+ height: 1,+ };+ const encoded = await encodePng(frame);+ const decoded = await decodeRgbaFrame(encoded);+ expect(decoded.width).toBe(2);+ expect(decoded.height).toBe(1);+ expect([...decoded.data]).toEqual([...frame.data]);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex eaf8c74734..e37f84fc48 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -165,6 +165,7 @@ export * from './tuiShellLaunch.js';export * from './tuiUsageScrape.js';// === File & I/O ===+export * from './borderKey.js';export * from './boundedStateMap.js';export * from './collectionStore.js';export * from './conflictJournal.js';@@ -178,6 +179,7 @@ export * from './spawnCwd.js';export * from './schemaVersions.js';export * from './imageClean.js';export * from './imageFrameStats.js';+export * from './imageRgba.js';export * from './imageWatermark.js';export * from './localImageFilename.js';export * from './localMemory.js';diff --git a/server/services/imageTo3d/sourceKeying.js b/server/services/imageTo3d/sourceKeying.jsindex 46eb432978..3678241bf4 100644--- a/server/services/imageTo3d/sourceKeying.js+++ b/server/services/imageTo3d/sourceKeying.js@@ -16,8 +16,9 @@* A deliberately simpler edge model than the sprites lane's chroma unmix* (`services/sprites/chromaKey.js`): that lane reverses source-over compositing* against a known pure-channel key; this one only needs "background gone, 1px- * anti-spill feather" for an arbitrary measured background color. Consolidating- * the shared border/median primitives with the sprites lane is tracked separately.+ * anti-spill feather" for an arbitrary measured background color. The shared+ * border/median primitives live in `server/lib/borderKey.js`; this module retains+ * only the image-to-3D flood fill and its conservative sanity gates.** Algorithm (deliberately conservative — "not sure" means "don't touch it"):* 1. Sample the border pixels; take the per-channel median as the candidate@@ -34,7 +35,15 @@* the detection was wrong → pass through untouched.*/+import { stat } from 'node:fs/promises';+import { Worker } from 'node:worker_threads';import sharp from 'sharp';+import {+ detectSolidBorderColor as detectSolidBorderColorShared,+ hasMeaningfulAlpha as hasMeaningfulAlphaShared,+} from '../../lib/borderKey.js';+import { atomicWrite, readJSONFile } from '../../lib/fileUtils.js';+import { decodeRgbaFrame, encodePng } from '../../lib/imageRgba.js';/** Euclidean RGB distance for the border/flood match (0–441 scale). */export const KEY_TOLERANCE = 30;@@ -55,6 +64,20 @@ export const KEY_MAX_KEYED_RATIO = 0.98;* matting handles oversized sources. */export const KEY_MAX_PIXELS = 16_000_000;+// Bump the leading version when the kernel changes. The numeric inputs are+// included so changing a tolerance invalidates fresh keyed output without+// relying on a developer to remember a second, separate cache edit.+export const KEYING_CACHE_VERSION = [+ 'source-keying-v1',+ KEY_TOLERANCE,+ KEY_TIGHT_TOLERANCE,+ KEY_MIN_BORDER_COVERAGE,+ KEY_SOFT_BAND,+ KEY_MIN_KEYED_RATIO,+ KEY_MAX_KEYED_RATIO,+ KEY_MAX_PIXELS,+].join(':');+// Squared-distance comparisons throughout the hot loops — Math.sqrt only where a// real distance is needed (the feather ramp, edge pixels only).const KEY_TOLERANCE_SQ = KEY_TOLERANCE ** 2;@@ -64,18 +87,8 @@ const distSq = (data, i, [r, g, b]) => ((data[i] - r) ** 2 + (data[i + 1] - g) ** 2 + (data[i + 2] - b) ** 2);-const median = (values) => {- const sorted = [...values].sort((a, b) => a - b);- return sorted[Math.floor(sorted.length / 2)];-};-/** Whether an RGBA buffer already carries a meaningful (non-opaque) alpha channel. */-export function hasMeaningfulAlpha(data) {- for (let i = 3; i < data.length; i += 4) {- if (data[i] < 250) return true;- }- return false;-}+export const hasMeaningfulAlpha = hasMeaningfulAlphaShared;/*** Detect a solid border color in a raw RGBA buffer. Returns `[r, g, b]` when at@@ -85,14 +98,10 @@ export function hasMeaningfulAlpha(data) {* @returns {[number, number, number]|null}*/export function detectSolidBorderColor({ data, width, height }) {- const offsets = [];- for (let x = 0; x < width; x += 1) { offsets.push(x * 4, ((height - 1) * width + x) * 4); }- for (let y = 1; y < height - 1; y += 1) { offsets.push(y * width * 4, (y * width + width - 1) * 4); }-- const color = [0, 1, 2].map((c) => median(offsets.map((i) => data[i + c])));- let matching = 0;- for (const i of offsets) { if (distSq(data, i, color) <= KEY_TOLERANCE_SQ) matching += 1; }- return matching / offsets.length >= KEY_MIN_BORDER_COVERAGE ? color : null;+ return detectSolidBorderColorShared(+ { data, width, height },+ { tolerance: KEY_TOLERANCE, minCoverage: KEY_MIN_BORDER_COVERAGE },+ );}/**@@ -167,6 +176,56 @@ export function keySolidBackground({ data, width, height }) {return { data: out, background, keyedRatio };}+const runKeySolidBackground = (frame) => {+ const source = frame.data instanceof Uint8Array ? frame.data : Uint8Array.from(frame.data);+ // Always copy the exact view into a fresh ArrayBuffer. Native image decoders+ // and test runners may expose pooled/shared backing stores that Node refuses+ // to transfer, while this copy keeps the worker contract deterministic.+ const transferable = new Uint8Array(source.byteLength);+ transferable.set(source);++ return new Promise((resolve, reject) => {+ const worker = new Worker(new URL('./sourceKeyingWorker.js', import.meta.url), {+ workerData: {+ data: transferable.buffer,+ width: frame.width,+ height: frame.height,+ },+ transferList: [transferable.buffer],+ });+ let settled = false;+ const settle = (handler, value) => {+ if (settled) return;+ settled = true;+ handler(value);+ };+ worker.on('message', (message) => {+ if (message?.type === 'complete') settle(resolve, message.result);+ if (message?.type === 'error') {+ settle(reject, new Error(message.error || 'Background keying worker failed'));+ }+ });+ worker.once('error', (error) => settle(reject, error));+ worker.once('exit', (code) => {+ if (code !== 0) settle(reject, new Error(`Background keying worker exited with code ${code}`));+ });+ });+};++const keyedCacheMetadataPath = (targetPath) => `${targetPath}.meta.json`;++const hasFreshKeyedSource = async (sourcePath, targetPath) => {+ const sourceStats = await stat(sourcePath);+ const targetStats = await stat(targetPath).catch(() => null);+ if (!targetStats?.isFile() || targetStats.mtimeMs <= sourceStats.mtimeMs) return false;++ // A missing metadata sidecar is accepted for compatibility with the first+ // cache implementation. New outputs write one, so future algorithm/tolerance+ // bumps invalidate all outputs produced by this version.+ const metadata = await readJSONFile(keyedCacheMetadataPath(targetPath), null, { logError: false });+ return !metadata?.version || metadata.version === KEYING_CACHE_VERSION;+};+/*** Resolve whether a render should consume a keyed copy of its source. Reads* `sourcePath`; when it has no meaningful alpha and sits on a solid background,@@ -183,21 +242,23 @@ export function keySolidBackground({ data, width, height }) {* @returns {Promise<string|null>} the keyed image path, or null to use the original*/export async function prepareSourceImage({ sourcePath, targetPath }) {+ if (await hasFreshKeyedSource(sourcePath, targetPath)) return targetPath;+// Header-only probe: bail before the full decode when the source is too// large to key affordably (KEY_MAX_PIXELS), and when it has no alpha channel// at all, skip the full-buffer meaningful-alpha scan below (ensureAlpha// fabricates the channel).const { hasAlpha, width, height } = await sharp(sourcePath).metadata();if (!width || !height || width * height > KEY_MAX_PIXELS) return null;- const { data, info } = await sharp(sourcePath)- .ensureAlpha()- .raw()- .toBuffer({ resolveWithObject: true });- if (hasAlpha && hasMeaningfulAlpha(data)) return null;- const result = keySolidBackground({ data, width: info.width, height: info.height });+ const frame = await decodeRgbaFrame(sourcePath);+ if (hasAlpha && hasMeaningfulAlpha(frame.data)) return null;+ const result = await runKeySolidBackground(frame);if (!result) return null;- await sharp(result.data, { raw: { width: info.width, height: info.height, channels: 4 } })- .png()- .toFile(targetPath);+ await atomicWrite(targetPath, await encodePng({+ data: result.data,+ width: frame.width,+ height: frame.height,+ }));+ await atomicWrite(keyedCacheMetadataPath(targetPath), { version: KEYING_CACHE_VERSION }).catch(() => {});return targetPath;}diff --git a/server/services/imageTo3d/sourceKeying.test.js b/server/services/imageTo3d/sourceKeying.test.jsindex bcf95cb003..9b394eaf42 100644--- a/server/services/imageTo3d/sourceKeying.test.js+++ b/server/services/imageTo3d/sourceKeying.test.js@@ -1,4 +1,4 @@-import { mkdtemp, rm } from 'node:fs/promises';+import { mkdtemp, readFile, rm, utimes, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';import { afterAll, describe, expect, it } from 'vitest';@@ -7,6 +7,7 @@ import {detectSolidBorderColor,hasMeaningfulAlpha,keySolidBackground,+ KEYING_CACHE_VERSION,prepareSourceImage,} from './sourceKeying.js';@@ -156,4 +157,31 @@ describe('prepareSourceImage', () => {const result = await prepareSourceImage({ sourcePath, targetPath: join(await tempDir(), 'never3.png') });expect(result).toBeNull();});++ it('reuses a keyed target newer than the gallery source', async () => {+ const sourcePath = await writePng('cache-source.png', subjectOnGreen());+ const cachedTarget = await writePng('cache-target.png', makeImage(20, 20, () => [255, 0, 0, 255]));+ const fresh = new Date(Date.now() + 60_000);+ await utimes(cachedTarget, fresh, fresh);++ const result = await prepareSourceImage({ sourcePath, targetPath: cachedTarget });+ expect(result).toBe(cachedTarget);+ const { data } = await sharp(cachedTarget).ensureAlpha().raw().toBuffer({ resolveWithObject: true });+ expect([...data.slice(0, 4)]).toEqual([255, 0, 0, 255]);+ });++ it('recomputes a fresh target when its keying-version metadata is stale', async () => {+ const sourcePath = await writePng('version-source.png', subjectOnGreen());+ const targetPath = await writePng('version-target.png', makeImage(20, 20, () => [255, 0, 0, 255]));+ await writeFile(`${targetPath}.meta.json`, JSON.stringify({ version: 'source-keying-old' }));+ const fresh = new Date(Date.now() + 60_000);+ await utimes(targetPath, fresh, fresh);++ const result = await prepareSourceImage({ sourcePath, targetPath });+ expect(result).toBe(targetPath);+ const { data } = await sharp(targetPath).ensureAlpha().raw().toBuffer({ resolveWithObject: true });+ expect(alphaAt({ data, width: 20, height: 20 }, 0, 0)).toBe(0);+ expect(JSON.parse(await readFile(`${targetPath}.meta.json`, 'utf8')))+ .toEqual({ version: KEYING_CACHE_VERSION });+ });});diff --git a/server/services/imageTo3d/sourceKeyingWorker.js b/server/services/imageTo3d/sourceKeyingWorker.jsnew file mode 100644index 0000000000..a9102b7baa--- /dev/null+++ b/server/services/imageTo3d/sourceKeyingWorker.js@@ -0,0 +1,19 @@+import { parentPort, workerData } from 'node:worker_threads';+import { keySolidBackground } from './sourceKeying.js';++const frame = {+ data: new Uint8Array(workerData.data),+ width: workerData.width,+ height: workerData.height,+};++Promise.resolve()+ .then(() => keySolidBackground(frame))+ .then((result) => {+ const transferList = result?.data?.buffer ? [result.data.buffer] : [];+ parentPort.postMessage({ type: 'complete', result }, transferList);+ })+ .catch((error) => parentPort.postMessage({+ type: 'error',+ error: error.message || String(error),+ }));diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.jsindex b6afde5510..0228785ff8 100644--- a/server/services/sprites/walkPostprocess.js+++ b/server/services/sprites/walkPostprocess.js@@ -23,8 +23,14 @@ import sharp from 'sharp';import { join } from 'path';import { readdir, writeFile } from 'fs/promises';import { createHash } from 'crypto';+import {+ hasMeaningfulAlpha,+ median,+ sampleBorderKey as sampleBorderKeyShared,+} from '../../lib/borderKey.js';import { ensureDir, atomicWrite, sha256File } from '../../lib/fileUtils.js';import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';+import { decodeRgbaFrame, encodePng } from '../../lib/imageRgba.js';import { keyChannelSplit, keyness, keyShareFn, hexToRgb } from './chromaKey.js';// Authoring bounds + pure label/clamp helpers live in a sharp-free leaf module@@ -46,6 +52,10 @@ export {walkPhaseLabels, clampFrameCount, clampFps,} from './walkBounds.js';+// Preserve the sprite lane's established deep-import surface while the+// implementations live in the shared leaves.+export { decodeRgbaFrame, median };+// Source pipeline constants (animation_postprocess.py) — values are part of// the cross-install artifact contract (imported manifests carry them).// WALK_FPS is the source-EXTRACTION sampling rate (how densely we pull frames@@ -106,21 +116,8 @@ export function pyRoundTo(x, dp) {const clampChannel = (v) => Math.max(0, Math.min(255, pyRound(v)));-/** statistics.median: middle value, or mean of the two middles. */-export function median(values) {- const sorted = [...values].sort((a, b) => a - b);- const mid = sorted.length >> 1;- return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;-}-export const sha256Buffer = (buf) => createHash('sha256').update(buf).digest('hex');-/** Decode a PNG to a raw RGBA frame `{ data, width, height }`. */-export async function decodeRgbaFrame(src) {- const { data, info } = await sharp(src).ensureAlpha().raw().toBuffer({ resolveWithObject: true });- return { data, width: info.width, height: info.height };-}-/*** Decode a validated sprite source into a straight-alpha transparent frame.* Already-transparent sources receive the same despill safety pass as packaged@@ -131,14 +128,7 @@ export async function decodeRgbaFrame(src) {export async function decodeTransparentSpriteSource(src, split, keyHex) {const frame = await decodeRgbaFrame(src);const { data } = frame;- let alphaMin = 255;- let alphaMax = 0;- for (let i = 3; i < data.length; i += 4) {- const alpha = data[i];- if (alpha < alphaMin) alphaMin = alpha;- if (alpha > alphaMax) alphaMax = alpha;- }- if (alphaMin < alphaMax) return despillKeyFrame(frame, split);+ if (hasMeaningfulAlpha(data, 255)) return despillKeyFrame(frame, split);const measured = sampleBorderKey(frame);validateMeasuredKey(measured, split, keyHex);return despillKeyFrame(recoverAlphaFrame(frame, measured, split), split);@@ -147,9 +137,7 @@ export async function decodeTransparentSpriteSource(src, split, keyHex) {// Encode + write + hash in one pass — hashing the in-memory PNG buffer saves// reading every just-written artifact back off disk purely to checksum it.async function encodePngWithHash(frame, dest, channels = 4) {- const buf = await sharp(frame.data, { raw: { width: frame.width, height: frame.height, channels } })- .png()- .toBuffer();+ const buf = await encodePng(frame, channels);await writeFile(dest, buf);return sha256Buffer(buf);}@@ -160,28 +148,7 @@ async function encodePngWithHash(frame, dest, channels = 4) {* exactly, the requested key — codecs shift it).*/export function sampleBorderKey(frame) {- const { data, width, height } = frame;- const minDim = Math.min(width, height);- const band = Math.max(4, Math.floor(minDim / 120));- const step = Math.max(1, Math.floor(minDim / 320));- const rs = []; const gs = []; const bs = [];- const push = (x, y) => {- const i = (y * width + x) * 4;- rs.push(data[i]); gs.push(data[i + 1]); bs.push(data[i + 2]);- };- for (let x = 0; x < width; x += step) {- for (let o = 0; o < band && o < height; o++) {- push(x, o);- push(x, height - 1 - o);- }- }- for (let y = 0; y < height; y += step) {- for (let o = 0; o < band && o < width; o++) {- push(o, y);- push(width - 1 - o, y);- }- }- return [pyRound(median(rs)), pyRound(median(gs)), pyRound(median(bs))];+ return sampleBorderKeyShared(frame).map((value) => pyRound(value));}/**diff --git a/server/services/sprites/walkTrims.js b/server/services/sprites/walkTrims.jsindex 5d2812468d..3018f4a72b 100644--- a/server/services/sprites/walkTrims.js+++ b/server/services/sprites/walkTrims.js@@ -17,12 +17,12 @@import { join } from 'path';import { mkdtemp, rm, writeFile } from 'fs/promises';import { tmpdir } from 'os';-import sharp from 'sharp';import {ensureDir, atomicWrite, pathExists, sha256File, readJSONFile,} from '../../lib/fileUtils.js';import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';import { ServerError } from '../../lib/errorHandler.js';+import { decodeRgbaFrame, encodePng } from '../../lib/imageRgba.js';import { resolveSpriteAssetPath, spriteDir, toRecordRelativeAssetPath } from './paths.js';import { requireCharacter } from './reference.js';import { withWalkWriteTail, getWalkState } from './walk.js';@@ -49,9 +49,10 @@ async function encodeTrimGif(frames, fps, destAbs) {if (!ffmpeg) throw new ServerError('ffmpeg not found — install ffmpeg to render trim GIFs', { status: 503, code: 'FFMPEG_MISSING' });const scratch = await mkdtemp(join(tmpdir(), 'portos-sprite-trim-'));for (let i = 0; i < frames.length; i++) {- await sharp(frames[i].data, { raw: { width: frames[i].width, height: frames[i].height, channels: 4 } })- .png()- .toFile(join(scratch, `frame-${String(i).padStart(3, '0')}.png`));+ await writeFile(+ join(scratch, `frame-${String(i).padStart(3, '0')}.png`),+ await encodePng(frames[i]),+ );}const result = await runFfmpegProcess({bin: ffmpeg,@@ -160,8 +161,8 @@ async function saveLoopTrimImpl(recordId, payload) {if (!await pathExists(atlasAbs)) {throw new ServerError(`Packed strip not found: ${stripPath}`, { status: 404, code: 'ATLAS_NOT_FOUND' });}- const { data, info } = await sharp(atlasAbs).ensureAlpha().raw().toBuffer({ resolveWithObject: true });- if ((Math.max(...allColumns) + 1) * cellSize > info.width || cellSize > info.height) {+ const { data, width, height } = await decodeRgbaFrame(atlasAbs);+ if ((Math.max(...allColumns) + 1) * cellSize > width || cellSize > height) {throw new ServerError('Packed strip does not match its manifest geometry', { status: 409, code: 'RUN_STRIP_INVALID' });}@@ -169,7 +170,7 @@ async function saveLoopTrimImpl(recordId, payload) {const frames = enabled.map((col) => {const out = Buffer.alloc(cellSize * cellSize * 4);for (let y = 0; y < cellSize; y++) {- const srcStart = (y * info.width + col * cellSize) * 4;+ const srcStart = (y * width + col * cellSize) * 4;data.copy(out, y * cellSize * 4, srcStart, srcStart + cellSize * 4);}return { data: out, width: cellSize, height: cellSize };@@ -191,9 +192,11 @@ async function saveLoopTrimImpl(recordId, payload) {}});const stripName = `${prefix}-strip.png`;- const stripBuf = await sharp(strip, { raw: { width: cellSize * frames.length, height: cellSize, channels: 4 } })- .png()- .toBuffer();+ const stripBuf = await encodePng({+ data: strip,+ width: cellSize * frames.length,+ height: cellSize,+ });await writeFile(join(trimsAbs, stripName), stripBuf);const gifName = `${prefix}.gif`;