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

address review (claude): serialize vision slice on the caption mutex, reject+SIGKILL on CLI timeout, cover grid-fallback slicing

Adam Eivy2c4243eeca2c
diff --git a/server/services/loraDatasetGenerate.js b/server/services/loraDatasetGenerate.js
index e24993f40f..9676cb5ae4 100644
--- a/server/services/loraDatasetGenerate.js
+++ b/server/services/loraDatasetGenerate.js
@@ -25,7 +25,7 @@ import { buildVariationMatrix } from '../lib/loraDataset.js';
import { extractJson } from '../lib/jsonExtract.js';
import { readSheetPointer, LEGACY_SHEET_VARIANT_ID } from '../lib/storyBible.js';
import { describeImageDataUrlDetailed } from './visionTest.js';
-import { resolveCaptionModel } from './loraDatasetCaption.js';
+import { resolveCaptionModel, withCaptionVisionLock } from './loraDatasetCaption.js';
import { getSettings } from './settings.js';
import { getUniverse } from './universeBuilder.js';
import { buildStyleClause } from './universeCanon.js';
@@ -501,7 +501,11 @@ export async function proposeCropRegions(sheetPath, dims, {
if (!bytes) return [];
const dataUrl = `data:image/png;base64,${bytes.toString('base64')}`;
- const result = await describeImage({
+ // Funnel the vision call through the SAME mutex the caption loop uses, so a
+ // slice-while-captioning can't fire two concurrent requests at a single-GPU
+ // local backend (doubled KV-cache VRAM, no throughput win — see the lock's
+ // header in loraDatasetCaption.js).
+ const result = await withCaptionVisionLock(() => describeImage({
dataUrl,
prompt: CROP_PROPOSAL_PROMPT,
providerId: resolved.providerId,
@@ -509,7 +513,7 @@ export async function proposeCropRegions(sheetPath, dims, {
// Boxes are short, but a thinking model needs headroom — match the
// captioner's reasoning budget rather than the 500-token short default.
maxTokens: 600,
- }).catch((err) => {
+ })).catch((err) => {
console.log(`⚠️ Vision crop slicing failed (${resolved.model}): ${err?.message || err}`);
return null;
});
diff --git a/server/services/loraDatasetGenerate.test.js b/server/services/loraDatasetGenerate.test.js
index 351fbd13e9..fa4711d571 100644
--- a/server/services/loraDatasetGenerate.test.js
+++ b/server/services/loraDatasetGenerate.test.js
@@ -7,17 +7,35 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('./loraDatasets.js', async (importOriginal) => ({
...(await importOriginal()),
getDataset: vi.fn(),
+ updateDataset: vi.fn(async () => ({})),
+ datasetImagesDir: vi.fn(() => '/tmp/ds-images'),
+ datasetImagePath: vi.fn((id, file) => `/tmp/ds-images/${file}`),
}));
vi.mock('./universeBuilder.js', async (importOriginal) => ({
...(await importOriginal()),
getUniverse: vi.fn(),
}));
+// sharp is only exercised by the slice path — stub the metadata() probe and the
+// extract().png().toFile() crop chain so the grid-fallback test never touches a
+// real image. The chainable mock records each extract rect for assertions, and
+// `sheetMeta` lets a test set the reported sheet dimensions.
+const extractCalls = [];
+const sheetMeta = { width: 900, height: 600 };
+vi.mock('sharp', () => ({
+ default: vi.fn(() => ({
+ metadata: vi.fn(async () => ({ ...sheetMeta })),
+ extract: vi.fn(function extract(rect) { extractCalls.push(rect); return this; }),
+ png: vi.fn(function png() { return this; }),
+ toFile: vi.fn(async () => ({})),
+ })),
+}));
+
import {
buildDatasetImagePrompt, deriveVariationAxes, getDatasetVariationAxes,
- normalizeCropProposals, proposeCropRegions,
+ normalizeCropProposals, proposeCropRegions, sliceReferenceSheet,
} from './loraDatasetGenerate.js';
-import { getDataset } from './loraDatasets.js';
+import { getDataset, updateDataset } from './loraDatasets.js';
import { getUniverse } from './universeBuilder.js';
// Pure-function coverage for the kind-aware prompt builder + variation axes.
@@ -255,3 +273,58 @@ describe('proposeCropRegions', () => {
expect(rects).toEqual([]);
});
});
+
+describe('sliceReferenceSheet — grid fallback path', () => {
+ beforeEach(() => {
+ extractCalls.length = 0;
+ sheetMeta.width = 900;
+ sheetMeta.height = 600;
+ getDataset.mockReset();
+ getUniverse.mockReset();
+ updateDataset.mockClear();
+ });
+
+ // The load-bearing path: most installs have no vision model, so `useVision:
+ // false` (or an empty vision result) falls through to the fixed cols×rows
+ // grid. Stubbed sharp reports 900×600; a 3×2 grid yields six 300×300 crops.
+ const wireSubject = () => {
+ getDataset.mockResolvedValue({
+ id: 'ds1',
+ character: { entryKind: 'characters', universeId: 'u1', entryId: 'c1' },
+ images: [],
+ });
+ getUniverse.mockResolvedValue({
+ characters: [{ id: 'c1', name: 'Kessa', referenceSheetImageRef: 'kessa-sheet.png' }],
+ });
+ };
+
+ it('emits cols×rows grid crops when useVision is false', async () => {
+ wireSubject();
+ const result = await sliceReferenceSheet('ds1', { cols: 3, rows: 2, useVision: false });
+ expect(result.method).toBe('grid');
+ expect(result.images).toHaveLength(6);
+ // Every crop is a 300×300 grid cell.
+ expect(extractCalls).toHaveLength(6);
+ expect(extractCalls.every((r) => r.width === 300 && r.height === 300)).toBe(true);
+ expect(result.images.every((img) => img.source === 'refsheet-slice' && img.status === 'ready')).toBe(true);
+ expect(updateDataset).toHaveBeenCalledOnce();
+ });
+
+ it('rejects a 400 when the grid cells would be smaller than 64px', async () => {
+ wireSubject();
+ // A small sheet: 300/6 = 50px cells, below the 64px MIN_CROP floor.
+ sheetMeta.width = 300;
+ sheetMeta.height = 300;
+ await expect(sliceReferenceSheet('ds1', { cols: 6, rows: 6, useVision: false }))
+ .rejects.toMatchObject({ status: 400 });
+ });
+
+ it('throws 409 when the subject has no reference sheet', async () => {
+ getDataset.mockResolvedValue({
+ id: 'ds1', character: { entryKind: 'characters', universeId: 'u1', entryId: 'c1' }, images: [],
+ });
+ getUniverse.mockResolvedValue({ characters: [{ id: 'c1', name: 'Kessa' }] }); // no referenceSheetImageRef
+ await expect(sliceReferenceSheet('ds1', { useVision: false }))
+ .rejects.toMatchObject({ status: 409, code: 'LORA_DATASET_NO_SHEET' });
+ });
+});
diff --git a/server/services/visionCli.js b/server/services/visionCli.js
index e51fb0d338..94c68603c0 100644
--- a/server/services/visionCli.js
+++ b/server/services/visionCli.js
@@ -116,16 +116,25 @@ export async function describeImageViaCli({
});
let out = '';
let err = '';
+ let killTimer = null;
+ // On timeout, SIGTERM the child AND reject now — don't wait on `close`. A
+ // wedged CLI that ignores SIGTERM would otherwise never emit `close`, so
+ // the promise would hang forever and the temp dir (cleaned in `finally`)
+ // would leak. Escalate to SIGKILL on a short grace timer.
const timer = timeout > 0 ? setTimeout(() => {
if (!child.killed) child.kill('SIGTERM');
+ killTimer = setTimeout(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); }, 5000);
+ killTimer?.unref?.();
+ reject(new Error(`${command} vision call timed out after ${timeout}ms`));
}, timeout) : null;
timer?.unref?.();
+ const clearTimers = () => { if (timer) clearTimeout(timer); if (killTimer) clearTimeout(killTimer); };
- child.on('error', (e) => { if (timer) clearTimeout(timer); reject(new Error(`Failed to spawn ${command}: ${e.message}`)); });
+ child.on('error', (e) => { clearTimers(); reject(new Error(`Failed to spawn ${command}: ${e.message}`)); });
child.stdout?.on('data', (d) => { out += d.toString(); });
child.stderr?.on('data', (d) => { err += d.toString(); });
child.on('close', (code) => {
- if (timer) clearTimeout(timer);
+ clearTimers();
if (code === 0) return resolve(out.trim());
const tail = err.trim().split('\n').slice(-4).join('\n');
reject(new Error(`${command} vision call exited ${code}${tail ? `: ${tail}` : ''}`));
diff --git a/server/services/visionCli.test.js b/server/services/visionCli.test.js
index fca1d583d4..a616723fc5 100644
--- a/server/services/visionCli.test.js
+++ b/server/services/visionCli.test.js
@@ -115,6 +115,22 @@ describe('describeImageViaCli', () => {
await expect(promise).rejects.toThrow(/Failed to spawn codex.*ENOENT/s);
});
+ it('rejects (and does not hang) when the child exceeds the timeout', async () => {
+ const child = makeFakeChild();
+ const spawnImpl = vi.fn(() => child);
+ const promise = describeImageViaCli({
+ provider: { id: 'codex', command: 'codex', args: [] },
+ dataUrl: PNG_DATA_URL,
+ prompt: 'p',
+ timeout: 20,
+ spawnImpl,
+ });
+ // The child never emits `close` (simulates a wedged process); the timeout
+ // must SIGTERM it and reject on its own rather than awaiting `close`.
+ await expect(promise).rejects.toThrow(/timed out after 20ms/);
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ });
+
it('throws on a malformed data URL before spawning', async () => {
const spawnImpl = vi.fn();
await expect(describeImageViaCli({