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([issue-1408]): vision-assisted sheet slicing, CLI-provider captioning, training queue UX

Adam Eivyc9e1da3efc17
diff --git a/client/src/components/loraTraining/LiveSampleGallery.jsx b/client/src/components/loraTraining/LiveSampleGallery.jsx
index 1ed9b18dae..e06ee02472 100644
--- a/client/src/components/loraTraining/LiveSampleGallery.jsx
+++ b/client/src/components/loraTraining/LiveSampleGallery.jsx
@@ -18,24 +18,15 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { ImageOff, Radio } from 'lucide-react';
import { formatDurationMs } from '../../utils/formatters';
import { useTimeTick } from '../../hooks/useTimeTick';
+import { lossSparklineGeometry } from '../../lib/lossSparkline';
import { listLoraTrainingSamples } from '../../services/api';
const SPARK_W = 240;
const SPARK_H = 36;
function LossSparkline({ series }) {
- if (series.length < 2) return null;
- const losses = series.map((p) => p.loss);
- const min = Math.min(...losses);
- const max = Math.max(...losses);
- const points = series
- .map((p, i) => {
- const x = (i / (series.length - 1)) * SPARK_W;
- const y = max === min ? SPARK_H / 2 : SPARK_H - ((p.loss - min) / (max - min)) * SPARK_H;
- return `${x.toFixed(1)},${y.toFixed(1)}`;
- })
- .join(' ');
- const last = series[series.length - 1].loss;
+ const { points, last } = lossSparklineGeometry(series, { width: SPARK_W, height: SPARK_H });
+ if (!points) return null;
return (
<div>
<div className="flex items-center justify-between text-[11px] text-gray-500 mb-0.5">
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsx
index 4657426540..170cc72b9d 100644
--- a/client/src/components/media/MediaJobsQueue.jsx
+++ b/client/src/components/media/MediaJobsQueue.jsx
@@ -1,9 +1,11 @@
-import { useMemo, useState, useCallback } from 'react';
-import { ListOrdered, Image as ImageIcon, Film, X, RefreshCw, ChevronDown, ChevronRight, Trash2, RotateCw, Zap, Pencil } from 'lucide-react';
+import { useMemo, useState, useCallback, useEffect, useRef } from 'react';
+import { ListOrdered, Image as ImageIcon, Film, Cpu, X, RefreshCw, ChevronDown, ChevronRight, Trash2, RotateCw, Zap, Pencil } from 'lucide-react';
import toast from '../ui/Toast';
import ConfirmButtonPair from '../ui/ConfirmButtonPair';
import { listMediaJobs, cancelMediaJob, cancelQueuedMediaJobs, deleteMediaJob, retryMediaJob, runMediaJobNow } from '../../services/apiMediaJobs.js';
+import { listLoraTrainingCheckpoints } from '../../services/apiLoraTraining.js';
import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';
+import { lossSparklineGeometry } from '../../lib/lossSparkline';
import { useAutoRefetch } from '../../hooks/useAutoRefetch';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
@@ -15,13 +17,19 @@ const STATUS_BADGE = {
canceled: 'bg-port-warning/30 text-port-warning',
};
-const KIND_ICON = { video: Film, image: ImageIcon };
+const KIND_ICON = { video: Film, image: ImageIcon, training: Cpu };
// Compact "engine / model" badge so a failed row tells the user *what* failed,
// not just that it failed. Codex jobs carry `params.model`; local image/video
-// jobs carry `params.modelId`. Trims long HF repo paths to the tail segment.
+// jobs carry `params.modelId`; training jobs carry a runtime + character.
+// Trims long HF repo paths to the tail segment.
function modelLabel(params) {
if (!params) return null;
+ if (params.runtime || params.runId) {
+ // Training job — surface the engine + who's being trained, not a prompt.
+ const who = (params.characterName || '').trim();
+ return `${params.runtime || 'training'}${who ? ` / ${who}` : ''}`;
+ }
if (params.mode === IMAGE_GEN_MODE.CODEX) {
const m = (params.model || '').trim();
return m ? `codex / ${m}` : 'codex';
@@ -107,7 +115,8 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''
setJobs((prev) => prev.filter((j) => j.id !== id));
})
.catch((err) => toast.error(err?.message || 'Delete failed'));
- const headerLabel = kind ? `${kind === 'image' ? 'Image' : 'Video'} Render Queue` : 'Render Queue';
+ const KIND_LABEL = { image: 'Image', video: 'Video', training: 'Training' };
+ const headerLabel = kind ? `${KIND_LABEL[kind] || ''} ${kind === 'training' ? 'Queue' : 'Render Queue'}`.trim() : 'Render Queue';
const handleClearQueued = () => {
if (!queuedCount) return;
@@ -153,7 +162,9 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''
{loading ? (
<div className="text-port-text-muted text-xs">Loading…</div>
) : live.length === 0 && recent.length === 0 ? (
- <div className="text-port-text-muted text-xs">No {kind || 'media'} renders queued.</div>
+ <div className="text-port-text-muted text-xs">
+ No {kind || 'media'} {kind === 'training' ? 'runs' : 'renders'} queued.
+ </div>
) : (
<div className="space-y-2">
{live.map((j) => <JobRow key={j.id} job={j} onCancel={handleCancel} onRetry={handleRetry} onRunNow={handleRunNow} />)}
@@ -183,6 +194,103 @@ function formatCounts(live, recent, failedCount) {
return parts.join(' • ');
}
+// One-line training summary in place of the (absent) prompt: who's training,
+// the LoRA rank, and the step budget.
+function trainingSummary(params) {
+ if (!params) return 'training';
+ const who = (params.characterName || '').trim();
+ const bits = [
+ who ? `Training "${who}"` : 'Training',
+ Number.isFinite(params.rank) ? `rank ${params.rank}` : null,
+ Number.isFinite(params.steps) ? `${params.steps} steps` : null,
+ ].filter(Boolean);
+ return bits.join(' · ');
+}
+
+// Training-specific row treatment: a loss sparkline over the run's checkpoints
+// plus the latest sample thumbnails. The media-job record carries no loss /
+// sample data, so fetch the run's checkpoint list (step + loss + previewUrl).
+// Re-fetches while the run is live so the curve grows as checkpoints land.
+function TrainingJobDetail({ runId, status }) {
+ const [checkpoints, setCheckpoints] = useState(null); // null = loading; [] = none yet
+ const mountedRef = useRef(true);
+
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => { mountedRef.current = false; };
+ }, []);
+
+ const load = useCallback(() => {
+ listLoraTrainingCheckpoints(runId)
+ .then((res) => {
+ if (mountedRef.current) setCheckpoints(Array.isArray(res?.checkpoints) ? res.checkpoints : []);
+ })
+ .catch(() => { if (mountedRef.current) setCheckpoints([]); });
+ }, [runId]);
+
+ useEffect(() => { load(); }, [load]);
+ // Poll only while the run is live — a terminal run's checkpoints are fixed.
+ useEffect(() => {
+ if (status !== 'running' && status !== 'queued') return undefined;
+ const t = setInterval(load, 5000);
+ return () => clearInterval(t);
+ }, [status, load]);
+
+ if (checkpoints === null) {
+ return <div className="mt-2 text-[11px] text-port-text-muted">Loading checkpoints…</div>;
+ }
+ if (!checkpoints.length) {
+ return (
+ <div className="mt-2 text-[11px] text-port-text-muted">
+ No checkpoints yet — samples + loss appear once the first one is saved.
+ </div>
+ );
+ }
+
+ const series = checkpoints
+ .filter((c) => Number.isFinite(c.loss))
+ .map((c) => ({ step: c.step, loss: c.loss }));
+ const geo = lossSparklineGeometry(series, { width: 240, height: 36 });
+ const withPreview = checkpoints.filter((c) => c.previewUrl);
+
+ return (
+ <div className="mt-2 space-y-2">
+ {geo.points && (
+ <div>
+ <div className="flex items-center justify-between text-[11px] text-port-text-muted mb-0.5">
+ <span>Loss · {series.length} checkpoints</span>
+ {geo.last != null && <span className="text-gray-400 font-mono">{geo.last.toFixed(4)}</span>}
+ </div>
+ <svg
+ viewBox="0 0 240 36"
+ preserveAspectRatio="none"
+ className="w-full h-9 bg-port-bg rounded border border-port-border"
+ role="img"
+ aria-label={`Training loss curve over ${series.length} checkpoints${geo.last != null ? `, latest ${geo.last.toFixed(4)}` : ''}`}
+ >
+ <polyline points={geo.points} fill="none" stroke="#3b82f6" strokeWidth="1.5" vectorEffect="non-scaling-stroke" />
+ </svg>
+ </div>
+ )}
+ {withPreview.length > 0 && (
+ <div className="flex gap-1.5 overflow-x-auto pb-1">
+ {withPreview.map((c) => (
+ <div key={c.step} className="shrink-0 text-center">
+ <img
+ src={c.previewUrl}
+ alt={`sample @ step ${c.step}`}
+ loading="lazy"
+ className={`w-14 h-14 object-cover rounded border ${c.deployed ? 'border-port-accent' : 'border-port-border'}`}
+ />
+ <div className="text-[10px] text-port-text-muted mt-0.5">{c.step}</div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
function JobRow({ job, onCancel, onRetry, onRunNow, onDelete }) {
const Icon = KIND_ICON[job.kind] || Film;
const canCancel = job.status === 'queued' || job.status === 'running';
@@ -221,7 +329,9 @@ function JobRow({ job, onCancel, onRetry, onRunNow, onDelete }) {
)}
</div>
<div className="text-xs text-port-text-muted truncate" title={job.params?.prompt || undefined}>
- {job.params?.prompt ? `"${job.params.prompt.slice(0, 80)}${job.params.prompt.length > 80 ? '…' : ''}"` : 'no prompt'}
+ {job.kind === 'training'
+ ? trainingSummary(job.params)
+ : (job.params?.prompt ? `"${job.params.prompt.slice(0, 80)}${job.params.prompt.length > 80 ? '…' : ''}"` : 'no prompt')}
{job.owner && <span> · {job.owner}</span>}
</div>
</div>
@@ -306,6 +416,9 @@ function JobRow({ job, onCancel, onRetry, onRunNow, onDelete }) {
</div>
</div>
)}
+ {job.kind === 'training' && job.params?.runId && (
+ <TrainingJobDetail runId={job.params.runId} status={job.status} />
+ )}
<div className="text-xs text-port-text-muted mt-1">
{job.queuedAt && `queued ${new Date(job.queuedAt).toLocaleTimeString()}`}
{job.startedAt && ` · started ${new Date(job.startedAt).toLocaleTimeString()}`}
diff --git a/client/src/components/media/MediaJobsQueue.test.jsx b/client/src/components/media/MediaJobsQueue.test.jsx
new file mode 100644
index 0000000000..c1b030d17d
--- /dev/null
+++ b/client/src/components/media/MediaJobsQueue.test.jsx
@@ -0,0 +1,97 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+
+// Mock the media-jobs API so the queue renders a controlled job list without
+// the network. useAutoRefetch calls the fetcher on mount.
+const listMediaJobs = vi.fn();
+vi.mock('../../services/apiMediaJobs.js', () => ({
+ listMediaJobs: (...a) => listMediaJobs(...a),
+ cancelMediaJob: vi.fn(),
+ cancelQueuedMediaJobs: vi.fn(),
+ deleteMediaJob: vi.fn(),
+ retryMediaJob: vi.fn(),
+ runMediaJobNow: vi.fn(),
+}));
+
+const listLoraTrainingCheckpoints = vi.fn();
+vi.mock('../../services/apiLoraTraining.js', () => ({
+ listLoraTrainingCheckpoints: (...a) => listLoraTrainingCheckpoints(...a),
+}));
+
+import MediaJobsQueue from './MediaJobsQueue';
+
+const trainingJob = {
+ id: 'train1234deadbeef',
+ kind: 'training',
+ status: 'running',
+ progress: 0.5,
+ statusMsg: 'Training step 250/500',
+ queuedAt: '2026-06-19T10:00:00Z',
+ startedAt: '2026-06-19T10:01:00Z',
+ params: {
+ runId: 'run-abc',
+ runtime: 'mflux',
+ characterName: 'Kessa',
+ rank: 64,
+ steps: 500,
+ },
+};
+
+beforeEach(() => {
+ listMediaJobs.mockReset();
+ listLoraTrainingCheckpoints.mockReset();
+});
+
+describe('MediaJobsQueue — training rows', () => {
+ it('renders a training summary + engine/character label instead of a prompt', async () => {
+ listMediaJobs.mockResolvedValue([trainingJob]);
+ listLoraTrainingCheckpoints.mockResolvedValue({ checkpoints: [] });
+
+ render(<MediaJobsQueue kind="training" />);
+
+ await waitFor(() => expect(screen.getByText(/Training "Kessa"/)).toBeInTheDocument());
+ expect(screen.getByText(/mflux \/ Kessa/)).toBeInTheDocument();
+ // Header reads "Training Queue", not "… Render Queue".
+ expect(screen.getByText(/Training Queue/i)).toBeInTheDocument();
+ });
+
+ it('draws a loss sparkline and sample thumbnails from the run checkpoints', async () => {
+ listMediaJobs.mockResolvedValue([trainingJob]);
+ listLoraTrainingCheckpoints.mockResolvedValue({
+ checkpoints: [
+ { step: 100, loss: 0.8, previewUrl: '/api/lora-training/runs/run-abc/samples/a.png', deployed: false },
+ { step: 200, loss: 0.4, previewUrl: '/api/lora-training/runs/run-abc/samples/b.png', deployed: true },
+ ],
+ });
+
+ render(<MediaJobsQueue kind="training" />);
+
+ await waitFor(() => expect(screen.getByRole('img', { name: /Training loss curve/i })).toBeInTheDocument());
+ // Latest loss is surfaced.
+ expect(screen.getByText('0.4000')).toBeInTheDocument();
+ // Both checkpoint sample thumbnails render.
+ expect(screen.getByAltText('sample @ step 100')).toBeInTheDocument();
+ expect(screen.getByAltText('sample @ step 200')).toBeInTheDocument();
+ });
+
+ it('shows a friendly placeholder when no checkpoints exist yet', async () => {
+ listMediaJobs.mockResolvedValue([trainingJob]);
+ listLoraTrainingCheckpoints.mockResolvedValue({ checkpoints: [] });
+
+ render(<MediaJobsQueue kind="training" />);
+
+ await waitFor(() => expect(screen.getByText(/No checkpoints yet/i)).toBeInTheDocument());
+ });
+
+ it('does not fetch checkpoints for non-training jobs', async () => {
+ listMediaJobs.mockResolvedValue([{
+ id: 'img1', kind: 'image', status: 'running', progress: 0.2,
+ params: { prompt: 'a castle', modelId: 'z-image-turbo' },
+ }]);
+
+ render(<MediaJobsQueue kind="image" />);
+
+ await waitFor(() => expect(screen.getByText(/"a castle"/)).toBeInTheDocument());
+ expect(listLoraTrainingCheckpoints).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index df4978f23d..3bb64b6df6 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -100,6 +100,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |
| `editorialChecks.js` | Pure helpers for the Editorial Checks page (`/pipeline/editorial-checks`, #1285): `groupChecksByScope(checks)` buckets catalog rows into ordered Noun/Scene/Issue/Series sections; `groupFindingsByCheck(comments, rowsById)` groups check-sourced review comments per check with open/total + severity counts; `openFindingsTotal(groups)` sums open findings; `findingManuscriptLink(seriesId, comment)` builds the `?comment=` deep-link into the manuscript editor; plus `scopeLabel` and the `CHECK_SCOPE_ORDER`/`CHECK_SCOPE_LABELS` tables. No React/window — the page and its tests share them. |
| `editorialHealth.js` | Pure presentation helpers for the editorial health panel (`/pipeline/editorial-checks`, #1316): `scoreBand(score)` bands a 0–100 health score into a label + Tailwind tone; `deltaDisplay(delta)` formats the revision-to-revision score change (arrow + tone); `sparklineGeometry(points, box)` projects the trend's score points into SVG polyline coords; `orderedCategories(openByCategory)` sorts the per-category open-finding breakdown; plus the `SEVERITY_ORDER`/`SEVERITY_LABELS` and `READINESS_GATE_LABELS`/`READINESS_GATE_ORDER` tables. No React/window — the panel and its tests share them. |
+| `lossSparkline.js` | `lossSparklineGeometry(series, box)` — projects an unbounded training-loss series (`{step,loss}[]`) into SVG polyline coords, normalized to its own min/max (unlike `editorialHealth.sparklineGeometry`'s fixed 0–100 axis). Returns `{ points, coords, last, min, max }`. Drives the Render Queue's training-row loss curve (#1408). No React. |
| `metronome.js` | Sample-accurate Web Audio metronome — the shared timing grid for the song system and first consumer of the song `tempo` field. `createMetronome({ bpm, beatsPerBar, countInBars, onBeat, onCountInComplete })` lookahead-schedules accented click tones on the shared `AudioContext` clock (same pattern as `songPlayback.js`), emits `{ beat, bar, accent, countIn, whenAudioTime }` per beat (the beat-clock callback color-match/sing-to-score subscribe to), and tears down all timers on `stop()`. Plus `clampBpm` (20–320), `secondsPerBeat`, `timeSignatureFromScore`, `beatDescriptor`. |
| `pianoKeyboard.js` | Piano-keyboard geometry for the song system's Synthesia-style piano-roll visualizer (`<PianoRoll>`). Pure math, no canvas/React. `keyboardRange(midis, { minSemitones })` → `{ lowMidi, highMidi }` padded out to whole C–B octaves (min 2) so the keyboard always starts on a C / ends on a B and never collapses for a one-note part; `buildKeyboardLayout({ lowMidi, highMidi, width })` → `{ keys:[{midi,isBlack,x,w}], whiteWidth, blackWidth }` (white keys tiled edge-to-edge, black keys overlaid centered on the boundary, narrower); plus `isBlackKey(midi)`, `midiNoteName(midi)` (sharps spelling), and the `BLACK_KEY_RATIO`/`BLACK_KEY_HEIGHT_RATIO` constants. Pairs with `scorePlayback`'s per-note `midi` field. |
| `scoreNotation.js` | Parser for the PortOS lead-sheet notation — a dependency-free text format for melody + chords + lyrics that the `<ScoreSheet>` SVG renderer draws (no abcjs / VexFlow / OSMD). `parseScore(text)` → `{ clef, key, keySig, time, tempo, measures, errors }`; plus `parsePitch`, `diatonicStep`, `durationBeats`, `keySignature`, `DURATIONS`, and `scoreHasMusic(text)`. Forgiving: bad tokens collect into `errors` and are skipped, never thrown. Pure — the renderer only does geometry. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 446c94a3bf..4f6fb36d99 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -66,6 +66,7 @@ export * from './cityPlaybackFrame.js';
export * from './colorMatch.js';
export * from './editorialChecks.js';
export * from './editorialHealth.js';
+export * from './lossSparkline.js';
export * from './metronome.js';
export * from './pianoKeyboard.js';
export * from './pitchDetect.js';
diff --git a/client/src/lib/lossSparkline.js b/client/src/lib/lossSparkline.js
new file mode 100644
index 0000000000..7863cc698c
--- /dev/null
+++ b/client/src/lib/lossSparkline.js
@@ -0,0 +1,52 @@
+/**
+ * Pure geometry for an unbounded-value (training-loss) sparkline.
+ *
+ * Unlike `sparklineGeometry` in `editorialHealth.js` — which maps a fixed
+ * 0–100 `score` axis — a training loss curve has no known bound, so this
+ * normalizes each series to its own min/max. Used by the Render Queue's
+ * training-row treatment to draw a `<polyline>` over a run's per-checkpoint
+ * loss. Kept pure (no React) so the projection is unit-testable.
+ *
+ * @param {Array<{step?:number, loss:number}>} series — points with finite `loss`
+ * @param {object} [opts]
+ * @param {number} [opts.width=240]
+ * @param {number} [opts.height=36]
+ * @returns {{ points: string, coords: Array<{x:number,y:number,loss:number}>, last: number|null, min: number|null, max: number|null }}
+ * `points` is the SVG `points=""` string ('' when fewer than 2 valid points);
+ * `last` is the most recent loss (or null).
+ */
+export function lossSparklineGeometry(series = [], { width = 240, height = 36 } = {}) {
+ const list = Array.isArray(series)
+ ? series.filter((p) => p && Number.isFinite(p.loss))
+ : [];
+ if (list.length < 2) {
+ return {
+ points: '',
+ coords: [],
+ last: list.length ? list[list.length - 1].loss : null,
+ min: null,
+ max: null,
+ };
+ }
+ const losses = list.map((p) => p.loss);
+ const min = Math.min(...losses);
+ const max = Math.max(...losses);
+ const span = max - min;
+ const coords = list.map((p, i) => {
+ const x = (i / (list.length - 1)) * width;
+ // Higher loss → higher on screen (smaller y); a flat series sits mid-height.
+ const y = span === 0 ? height / 2 : height - ((p.loss - min) / span) * height;
+ return {
+ x: Math.round(x * 10) / 10,
+ y: Math.round(y * 10) / 10,
+ loss: p.loss,
+ };
+ });
+ return {
+ points: coords.map((c) => `${c.x},${c.y}`).join(' '),
+ coords,
+ last: losses[losses.length - 1],
+ min,
+ max,
+ };
+}
diff --git a/client/src/lib/lossSparkline.test.js b/client/src/lib/lossSparkline.test.js
new file mode 100644
index 0000000000..f4efc20c6d
--- /dev/null
+++ b/client/src/lib/lossSparkline.test.js
@@ -0,0 +1,52 @@
+import { describe, it, expect } from 'vitest';
+import { lossSparklineGeometry } from './lossSparkline.js';
+
+describe('lossSparklineGeometry', () => {
+ it('returns empty points but the last value for a single point', () => {
+ const geo = lossSparklineGeometry([{ step: 100, loss: 0.5 }]);
+ expect(geo.points).toBe('');
+ expect(geo.coords).toEqual([]);
+ expect(geo.last).toBe(0.5);
+ });
+
+ it('normalizes a descending loss series to its own min/max', () => {
+ // loss falls 1.0 → 0.0; higher loss sits higher (smaller y), so the first
+ // point is at the top (y=0) and the last at the bottom (y=height).
+ const geo = lossSparklineGeometry(
+ [{ step: 0, loss: 1.0 }, { step: 50, loss: 0.5 }, { step: 100, loss: 0.0 }],
+ { width: 200, height: 40 },
+ );
+ expect(geo.min).toBe(0);
+ expect(geo.max).toBe(1);
+ expect(geo.last).toBe(0);
+ expect(geo.coords[0]).toMatchObject({ x: 0, y: 0 });
+ expect(geo.coords[1]).toMatchObject({ x: 100, y: 20 });
+ expect(geo.coords[2]).toMatchObject({ x: 200, y: 40 });
+ expect(geo.points).toBe('0,0 100,20 200,40');
+ });
+
+ it('draws a flat line at mid-height when all losses are equal', () => {
+ const geo = lossSparklineGeometry(
+ [{ step: 0, loss: 0.3 }, { step: 10, loss: 0.3 }],
+ { width: 100, height: 30 },
+ );
+ expect(geo.coords.every((c) => c.y === 15)).toBe(true);
+ });
+
+ it('ignores non-finite loss points', () => {
+ const geo = lossSparklineGeometry([
+ { step: 0, loss: 1 },
+ { step: 1, loss: NaN },
+ { step: 2, loss: null },
+ { step: 3, loss: 0 },
+ ], { width: 100, height: 20 });
+ expect(geo.coords).toHaveLength(2);
+ expect(geo.last).toBe(0);
+ });
+
+ it('returns a safe empty shape for empty / non-array input', () => {
+ expect(lossSparklineGeometry([])).toMatchObject({ points: '', coords: [], last: null });
+ expect(lossSparklineGeometry(null)).toMatchObject({ points: '', coords: [], last: null });
+ expect(lossSparklineGeometry(undefined)).toMatchObject({ points: '', last: null });
+ });
+});
diff --git a/client/src/pages/LoraDatasetDetail.jsx b/client/src/pages/LoraDatasetDetail.jsx
index 1c9ce318e1..fdbaf7af6c 100644
--- a/client/src/pages/LoraDatasetDetail.jsx
+++ b/client/src/pages/LoraDatasetDetail.jsx
@@ -124,13 +124,17 @@ const deriveReadiness = (images, triggerWord) => {
function SliceDialog({ dataset, onClose, onSliced }) {
const [cols, setCols] = useState(3);
const [rows, setRows] = useState(2);
+ // Vision-auto detection is the default; the grid inputs are the fallback the
+ // user reaches for when no vision model is installed or auto-detect mis-cuts.
+ const [useVision, setUseVision] = useState(true);
const [submitting, setSubmitting] = useState(false);
const submit = async () => {
setSubmitting(true);
try {
- const result = await sliceLoraDatasetRefSheet(dataset.id, { cols, rows });
- toast.success(`Added ${result.images.length} crops from the reference sheet — prune any bad ones`);
+ const result = await sliceLoraDatasetRefSheet(dataset.id, { cols, rows, useVision });
+ const via = result.method === 'vision' ? 'auto-detected' : 'grid';
+ toast.success(`Added ${result.images.length} ${via} crops from the reference sheet — prune any bad ones`);
onSliced(result);
} finally {
setSubmitting(false);
@@ -163,10 +167,26 @@ function SliceDialog({ dataset, onClose, onSliced }) {
<div className="space-y-4">
<h2 id="lt-slice-title" className="text-base font-semibold text-white">Slice reference sheet</h2>
<p className="text-sm text-gray-400">
- Cuts the character&apos;s reference-sheet turnaround into a fixed grid of training crops.
+ Cuts the character&apos;s reference-sheet turnaround into individual training crops.
Sheet layouts vary, so expect to delete cells that caught labels or palette swatches.
</p>
- <div className="grid grid-cols-2 gap-3">
+ <label htmlFor="lt-slice-vision" className="flex items-start gap-2 text-sm text-gray-300">
+ <input
+ id="lt-slice-vision"
+ type="checkbox"
+ checked={useVision}
+ onChange={(e) => setUseVision(e.target.checked)}
+ className="mt-0.5"
+ />
+ <span>
+ Auto-detect figures with a vision model
+ <span className="block text-xs text-gray-500">
+ Proposes a crop per figure instead of a rigid grid. Falls back to the grid below if no
+ vision model is installed or detection finds nothing.
+ </span>
+ </span>
+ </label>
+ <div className={`grid grid-cols-2 gap-3 ${useVision ? 'opacity-50' : ''}`}>
{numberInput('lt-slice-cols', 'Columns', cols, setCols)}
{numberInput('lt-slice-rows', 'Rows', rows, setRows)}
</div>
@@ -179,7 +199,7 @@ function SliceDialog({ dataset, onClose, onSliced }) {
className="px-3 py-2 text-sm rounded bg-port-accent text-white disabled:opacity-50 flex items-center gap-2"
>
{submitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Scissors className="w-4 h-4" />}
- Slice {cols}×{rows}
+ {useVision ? 'Auto-slice' : `Slice ${cols}×${rows}`}
</button>
</div>
</div>
diff --git a/client/src/pages/LoraTraining.jsx b/client/src/pages/LoraTraining.jsx
index 4dd3d867bc..d712ed78ea 100644
--- a/client/src/pages/LoraTraining.jsx
+++ b/client/src/pages/LoraTraining.jsx
@@ -13,6 +13,7 @@ import toast from '../components/ui/Toast';
import Modal from '../components/ui/Modal';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
import UniverseCharacterPicker from '../components/loraTraining/UniverseCharacterPicker';
+import MediaJobsQueue from '../components/media/MediaJobsQueue';
import {
listLoraDatasets,
createLoraDataset,
@@ -186,6 +187,10 @@ export default function LoraTraining() {
))}
</div>
+ <div className="mt-6">
+ <MediaJobsQueue kind="training" />
+ </div>
+
{showNew && (
<NewDatasetDialog
onClose={() => setShowNew(false)}
diff --git a/client/src/services/apiLoraTraining.js b/client/src/services/apiLoraTraining.js
index 98fd02289f..6a438df9eb 100644
--- a/client/src/services/apiLoraTraining.js
+++ b/client/src/services/apiLoraTraining.js
@@ -56,10 +56,18 @@ export const importLoraDatasetGalleryImages = (id, filenames) =>
export const generateLoraDatasetImages = (id, options = {}) =>
request(`/lora-datasets/${id}/generate`, { method: 'POST', body: JSON.stringify(options) });
-export const sliceLoraDatasetRefSheet = (id, { variant, cols, rows } = {}) =>
+// `useVision` (default true) lets a vision model propose a bounding box per
+// figure; the fixed cols×rows grid is the fallback (and what `useVision: false`
+// forces). When omitted, the server auto-resolves a vision model.
+export const sliceLoraDatasetRefSheet = (id, { variant, cols, rows, useVision } = {}) =>
request(`/lora-datasets/${id}/slice-reference-sheet`, {
method: 'POST',
- body: JSON.stringify({ ...(variant ? { variant } : {}), ...(cols ? { cols } : {}), ...(rows ? { rows } : {}) }),
+ body: JSON.stringify({
+ ...(variant ? { variant } : {}),
+ ...(cols ? { cols } : {}),
+ ...(rows ? { rows } : {}),
+ ...(useVision === false ? { useVision: false } : {}),
+ }),
});
export const startLoraCaptionRun = (id, options = {}) =>
diff --git a/server/lib/localModelHeuristics.js b/server/lib/localModelHeuristics.js
index 9468ed47f0..3c740a0b11 100644
--- a/server/lib/localModelHeuristics.js
+++ b/server/lib/localModelHeuristics.js
@@ -58,6 +58,25 @@ const VISION_RE = new RegExp([
'kosmos', 'nanollava',
].join('|'), 'i');
+// CLI providers whose underlying model is vision-capable and whose CLI accepts
+// an image file (codex via `-i`, claude-code via a file in the working dir).
+// CLI providers expose no enumerable model list with capability tags, so this
+// command-based allow-list is how the captioner knows a CLI provider can read
+// images. Keyed on `command` so a renamed/duplicated provider still qualifies.
+const VISION_CLI_COMMANDS = new Set(['codex', 'claude']);
+
+/**
+ * Whether a CLI-type provider can caption images (its model reads vision and
+ * its CLI accepts an image file). Returns false for non-CLI providers.
+ *
+ * @param {{type?:string, command?:string}} provider
+ * @returns {boolean}
+ */
+export function isVisionCapableCliProvider(provider) {
+ if (!provider || provider.type !== 'cli') return false;
+ return VISION_CLI_COMMANDS.has(provider.command);
+}
+
/**
* Detect a vision-capable (multimodal) model from its id and/or backend
* capability metadata. Prefers explicit metadata when present — LM Studio's
diff --git a/server/lib/localModelHeuristics.test.js b/server/lib/localModelHeuristics.test.js
index 53485d0e04..eb7adc7fec 100644
--- a/server/lib/localModelHeuristics.test.js
+++ b/server/lib/localModelHeuristics.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { isEmbeddingModel, isGenerationModel, isVisionModel, recommendEditorialModel } from './localModelHeuristics.js';
+import { isEmbeddingModel, isGenerationModel, isVisionModel, isVisionCapableCliProvider, recommendEditorialModel } from './localModelHeuristics.js';
describe('localModelHeuristics', () => {
describe('isEmbeddingModel', () => {
@@ -99,6 +99,21 @@ describe('localModelHeuristics', () => {
});
});
+ describe('isVisionCapableCliProvider', () => {
+ it('accepts codex / claude CLI providers', () => {
+ expect(isVisionCapableCliProvider({ type: 'cli', command: 'codex' })).toBe(true);
+ expect(isVisionCapableCliProvider({ type: 'cli', command: 'claude' })).toBe(true);
+ });
+
+ it('rejects non-vision CLI commands and non-CLI providers', () => {
+ expect(isVisionCapableCliProvider({ type: 'cli', command: 'agy' })).toBe(false);
+ expect(isVisionCapableCliProvider({ type: 'api', command: 'codex' })).toBe(false);
+ expect(isVisionCapableCliProvider({ type: 'tui', command: 'claude' })).toBe(false);
+ expect(isVisionCapableCliProvider(null)).toBe(false);
+ expect(isVisionCapableCliProvider({})).toBe(false);
+ });
+ });
+
describe('recommendEditorialModel', () => {
it('prefers a large general instruct model over a small one', () => {
const rec = recommendEditorialModel([
diff --git a/server/routes/loraDatasets.js b/server/routes/loraDatasets.js
index d68978d12a..1ad1b92e0d 100644
--- a/server/routes/loraDatasets.js
+++ b/server/routes/loraDatasets.js
@@ -144,6 +144,13 @@ const sliceSchema = z.object({
variant: z.string().max(64).default('standard'),
cols: z.number().int().min(1).max(6).default(3),
rows: z.number().int().min(1).max(6).default(2),
+ // When true (default) a vision-LLM proposes a bounding box per figure and the
+ // grid is the fallback; false forces the deterministic cols×rows grid.
+ useVision: z.boolean().default(true),
+ // Optional explicit vision model for the proposal pass — same provider/model
+ // pair the caption picker uses; omitted = server auto-pick.
+ captionProviderId: z.string().max(128).optional(),
+ captionModel: z.string().max(256).optional(),
});
router.post('/:id/slice-reference-sheet', asyncHandler(async (req, res) => {
const body = validateRequest(sliceSchema, req.body);
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index dd674ea19b..df8fb13fb6 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -31,10 +31,10 @@ import { Readable } from 'stream'
import { PATHS, atomicWrite } from '../lib/fileUtils.js'
import { isBackend, mapModelToBackend } from '../lib/localLlmCatalog.js'
import { sanitizeOllamaName } from '../lib/localLlmDisk.js'
-import { recommendEditorialModel, isVisionModel } from '../lib/localModelHeuristics.js'
+import { recommendEditorialModel, isVisionModel, isVisionCapableCliProvider } from '../lib/localModelHeuristics.js'
import * as ollamaManager from './ollamaManager.js'
import * as lmStudioManager from './lmStudioManager.js'
-import { getProviderById, updateProvider } from './providers.js'
+import { getProviderById, getAllProviders, updateProvider } from './providers.js'
const execFileAsync = promisify(execFile)
const ENV_PATH = join(PATHS.root, '.env')
@@ -637,9 +637,11 @@ export async function getStatus() {
/**
* Vision-capable installed models across both local backends, tagged with the
- * aiToolkit provider id (`ollama` / `lmstudio`) that serves them. Powers the
- * caption-model picker and the captioner's auto-resolution of a default vision
- * model. Each entry: `{ providerId, backend, id, name, vision: true }`.
+ * aiToolkit provider id (`ollama` / `lmstudio`) that serves them, PLUS
+ * vision-capable CLI providers (codex / claude-code) whose model reads images
+ * via a file. Powers the caption-model picker and the captioner's
+ * auto-resolution of a default vision model. Each entry:
+ * `{ providerId, backend, id, name, vision: true }`.
*/
export async function listVisionModels() {
// Cache-first for both backends (the model-list caches are busted on
@@ -662,7 +664,32 @@ export async function listVisionModels() {
const tag = (backend, models) => models
.filter((m) => m.vision)
.map((m) => ({ providerId: PROVIDER_ID[backend], backend, id: m.id, name: m.name || m.id, vision: true }))
- return [...tag('ollama', ollamaVision), ...tag('lmstudio', lmstudio)]
+ return [
+ ...tag('ollama', ollamaVision),
+ ...tag('lmstudio', lmstudio),
+ ...await listVisionCliModels(),
+ ]
+}
+
+/**
+ * Vision-capable CLI providers (codex / claude-code), expanded to one entry per
+ * configured model so the caption picker can offer e.g. "codex / gpt-5" or
+ * "claude-code / claude-opus-4-8". A disabled provider is skipped. Each entry
+ * mirrors the local-backend shape with `backend: 'cli'`. Best-effort: a load
+ * failure yields no CLI entries rather than breaking the whole picker.
+ */
+async function listVisionCliModels() {
+ const { providers } = await getAllProviders().catch(() => ({ providers: [] }))
+ const entries = []
+ for (const p of providers || []) {
+ if (p.enabled === false) continue
+ if (!isVisionCapableCliProvider(p)) continue
+ const models = Array.isArray(p.models) && p.models.length ? p.models : [p.defaultModel].filter(Boolean)
+ for (const id of models) {
+ entries.push({ providerId: p.id, backend: 'cli', id, name: `${p.name || p.id} / ${id}`, vision: true })
+ }
+ }
+ return entries
}
// ---- install / delete --------------------------------------------------------
diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.js
index 1c65ffd315..151731fd49 100644
--- a/server/services/localLlm.test.js
+++ b/server/services/localLlm.test.js
@@ -44,6 +44,7 @@ const mocks = vi.hoisted(() => ({
},
providers: {
getProviderById: vi.fn(async () => ({ id: 'ollama', enabled: false })),
+ getAllProviders: vi.fn(async () => ({ providers: [] })),
updateProvider: vi.fn(async () => ({}))
}
}));
@@ -328,5 +329,25 @@ describe('localLlm', () => {
expect(models.map((m) => m.id)).toEqual(['qwen2.5-vl:7b']);
expect(mocks.ollama.getModelCapabilities).not.toHaveBeenCalled();
});
+
+ it('appends vision-capable CLI providers (codex / claude), one entry per model', async () => {
+ mocks.providers.getAllProviders.mockResolvedValueOnce({
+ providers: [
+ { id: 'codex', type: 'cli', command: 'codex', enabled: true, models: ['gpt-5'], defaultModel: 'gpt-5' },
+ { id: 'claude-code', type: 'cli', command: 'claude', enabled: true, name: 'Claude Code', models: ['claude-opus-4-8', 'claude-sonnet-4-6'] },
+ { id: 'antigravity-cli', type: 'cli', command: 'agy', enabled: true, models: ['x'] }, // not vision-capable → excluded
+ { id: 'lmstudio', type: 'api', enabled: true, models: [] }, // api handled elsewhere → excluded here
+ { id: 'codex-off', type: 'cli', command: 'codex', enabled: false, models: ['gpt-5'] }, // disabled → excluded
+ ],
+ });
+
+ const models = await svc.listVisionModels();
+ const cli = models.filter((m) => m.backend === 'cli');
+ expect(cli).toEqual([
+ { providerId: 'codex', backend: 'cli', id: 'gpt-5', name: 'codex / gpt-5', vision: true },
+ { providerId: 'claude-code', backend: 'cli', id: 'claude-opus-4-8', name: 'Claude Code / claude-opus-4-8', vision: true },
+ { providerId: 'claude-code', backend: 'cli', id: 'claude-sonnet-4-6', name: 'Claude Code / claude-sonnet-4-6', vision: true },
+ ]);
+ });
});
});
diff --git a/server/services/loraDatasetCaption.test.js b/server/services/loraDatasetCaption.test.js
index c11851d463..cf8a8e86e1 100644
--- a/server/services/loraDatasetCaption.test.js
+++ b/server/services/loraDatasetCaption.test.js
@@ -62,6 +62,27 @@ describe('resolveCaptionModel', () => {
await expect(resolveCaptionModel({ listVision }))
.rejects.toMatchObject({ status: 409, code: 'LORA_CAPTION_NO_VISION_MODEL' });
});
+
+ it('accepts a CLI provider/model the scan reports (codex / claude vision)', async () => {
+ // CLI model ids (e.g. claude-opus-4-8) aren't matched by the VLM id regex,
+ // so the resolver scans — and listVisionModels now surfaces vision-capable
+ // CLI providers, so the explicit pick is confirmed rather than rejected.
+ const listVision = vi.fn(async () => [
+ ...VISION,
+ { providerId: 'claude-code', backend: 'cli', id: 'claude-opus-4-8', name: 'Claude Code / claude-opus-4-8', vision: true },
+ ]);
+ const out = await resolveCaptionModel({ providerId: 'claude-code', model: 'claude-opus-4-8', listVision });
+ expect(out).toEqual({ providerId: 'claude-code', model: 'claude-opus-4-8' });
+ expect(listVision).toHaveBeenCalledOnce();
+ });
+
+ it('auto-picks a CLI vision provider when it is the only one available', async () => {
+ const listVision = vi.fn(async () => [
+ { providerId: 'codex', backend: 'cli', id: 'gpt-5', name: 'Codex / gpt-5', vision: true },
+ ]);
+ const out = await resolveCaptionModel({ listVision });
+ expect(out).toEqual({ providerId: 'codex', model: 'gpt-5' });
+ });
});
describe('buildCaption', () => {
diff --git a/server/services/loraDatasetGenerate.js b/server/services/loraDatasetGenerate.js
index d18ff17f56..e24993f40f 100644
--- a/server/services/loraDatasetGenerate.js
+++ b/server/services/loraDatasetGenerate.js
@@ -15,14 +15,17 @@
* timeout. See that module for the rationale on each piece.
*/
-import { copyFile } from 'fs/promises';
+import { copyFile, readFile } from 'fs/promises';
import { join, basename } from 'path';
import sharp from 'sharp';
import { PATHS, ensureDir, shortId } from '../lib/fileUtils.js';
import { ServerError } from '../lib/errorHandler.js';
import { v4 as uuidv4 } from '../lib/uuid.js';
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 { getSettings } from './settings.js';
import { getUniverse } from './universeBuilder.js';
import { buildStyleClause } from './universeCanon.js';
@@ -413,13 +416,129 @@ export async function generateDatasetImages(datasetId, options = {}) {
return { images: launched, mode: activeMode, modelId };
}
+// Crops smaller than this on either axis are below FLUX's training floor and
+// (for vision proposals) usually a label strip or palette swatch the model
+// mistook for a panel — reject them. Mirrors the grid path's 64px guard.
+const MIN_CROP_PX = 64;
+
+// Ask the vision model to locate each distinct figure on the turnaround sheet
+// and return its bounding box. Normalized [0,1] fractions (not pixels) so the
+// model doesn't need to reason about the exact resolution — we scale to pixels
+// ourselves. The JSON-only instruction + example keeps the reply parseable by
+// extractJson, which already tolerates CLI banners and code fences.
+export const CROP_PROPOSAL_PROMPT = [
+ 'This is a character/object reference sheet — a turnaround grid with several',
+ 'distinct figures (front, side, back views, expression heads, etc.).',
+ 'Return a tight bounding box around EACH separate figure so it can be cropped',
+ 'into its own training image. Ignore label text, color-palette swatches, and',
+ 'empty background. Reply with ONLY a JSON object of the form',
+ '{"boxes":[{"x":0.0,"y":0.0,"w":0.33,"h":0.5}, ...]} where x,y is the',
+ 'top-left corner and w,h the width/height, all as fractions of the image',
+ '(0.0–1.0). No prose, no code fence.',
+].join(' ');
+
+/**
+ * Validate + clamp the vision model's normalized bounding boxes against the
+ * sheet's real pixel dimensions, returning sharp-ready
+ * `{ left, top, width, height }` extract rects. Pure — exported for tests.
+ *
+ * Drops a box when it: isn't a finite {x,y,w,h}; falls fully outside the image;
+ * or clamps to a region smaller than `MIN_CROP_PX` on either axis (label strips
+ * / swatches the model mistook for a figure). Returns `[]` when nothing
+ * survives so the caller can fall back to the fixed grid — an empty/garbage
+ * vision reply must never produce zero crops silently.
+ *
+ * @param {unknown} parsed — the parsed `{ boxes: [...] }` (or a bare array)
+ * @param {{width:number,height:number}} dims — the sheet's pixel dimensions
+ */
+export function normalizeCropProposals(parsed, { width, height } = {}) {
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return [];
+ const boxes = Array.isArray(parsed) ? parsed : (Array.isArray(parsed?.boxes) ? parsed.boxes : null);
+ if (!Array.isArray(boxes)) return [];
+
+ const rects = [];
+ for (const b of boxes) {
+ if (!b || typeof b !== 'object') continue;
+ const { x, y, w, h } = b;
+ if (![x, y, w, h].every((n) => typeof n === 'number' && Number.isFinite(n))) continue;
+ // Clamp the normalized rect into [0,1] before scaling, so a box that
+ // overhangs the edge (common — the model rounds generously) is trimmed
+ // to the sheet rather than throwing in sharp.extract.
+ const left = Math.round(Math.max(0, Math.min(1, x)) * width);
+ const top = Math.round(Math.max(0, Math.min(1, y)) * height);
+ const right = Math.round(Math.max(0, Math.min(1, x + w)) * width);
+ const bottom = Math.round(Math.max(0, Math.min(1, y + h)) * height);
+ const cw = right - left;
+ const ch = bottom - top;
+ if (cw < MIN_CROP_PX || ch < MIN_CROP_PX) continue;
+ rects.push({ left, top, width: cw, height: ch });
+ }
+ return rects;
+}
+
/**
- * Slice the subject's existing reference-sheet turnaround into a fixed
- * `cols × rows` grid of training crops. Each crop lands as a `ready`
- * dataset image with source 'refsheet-slice' — the user prunes bad crops
- * (label strips, palette swatches) in the grid UI.
+ * Propose per-figure crop rectangles for a reference sheet via a vision model.
+ * Returns sharp-ready `{ left, top, width, height }` rects, or `[]` on any
+ * failure (no vision model, transport error, unparseable reply, all boxes
+ * rejected) so `sliceReferenceSheet` falls back to the fixed grid. Never
+ * throws — vision slicing is an optional enhancement over the grid.
+ *
+ * `describeImage` / `resolveModel` / `readImage` are injectable for tests.
*/
-export async function sliceReferenceSheet(datasetId, { variant = LEGACY_SHEET_VARIANT_ID, cols = 3, rows = 2 } = {}) {
+export async function proposeCropRegions(sheetPath, dims, {
+ providerId = null, model = null, settings = null,
+ describeImage = describeImageDataUrlDetailed,
+ resolveModel = resolveCaptionModel,
+ readImage = readFile,
+} = {}) {
+ const resolved = await resolveModel({ providerId, model, settings }).catch((err) => {
+ console.log(`⚠️ Vision crop slicing skipped — no vision model: ${err?.message || err}`);
+ return null;
+ });
+ if (!resolved) return [];
+
+ const bytes = await readImage(sheetPath).catch(() => null);
+ if (!bytes) return [];
+ const dataUrl = `data:image/png;base64,${bytes.toString('base64')}`;
+
+ const result = await describeImage({
+ dataUrl,
+ prompt: CROP_PROPOSAL_PROMPT,
+ providerId: resolved.providerId,
+ model: resolved.model,
+ // 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) => {
+ console.log(`⚠️ Vision crop slicing failed (${resolved.model}): ${err?.message || err}`);
+ return null;
+ });
+ if (!result?.text) return [];
+
+ const { value } = extractJson(result.text, {
+ shapePredicate: (v) => Array.isArray(v?.boxes) || Array.isArray(v),
+ });
+ const rects = normalizeCropProposals(value, dims);
+ if (rects.length) {
+ console.log(`🔎 Vision proposed ${rects.length} crop region(s) via ${resolved.model}`);
+ }
+ return rects;
+}
+
+/**
+ * Slice the subject's existing reference-sheet turnaround into individual
+ * training crops. With `useVision` (default), a vision-LLM pass proposes a
+ * bounding box per figure (turnaround layouts are model-generated and
+ * non-deterministic, so a fixed grid mis-cuts them); the fixed `cols × rows`
+ * grid is the fallback when no vision model is available or the pass yields
+ * nothing usable. Each crop lands as a `ready` dataset image with source
+ * 'refsheet-slice' — the user prunes bad crops (label strips, palette
+ * swatches) in the grid UI.
+ */
+export async function sliceReferenceSheet(datasetId, {
+ variant = LEGACY_SHEET_VARIANT_ID, cols = 3, rows = 2, useVision = true,
+ captionProviderId = null, captionModel = null,
+} = {}) {
const dataset = await getDataset(datasetId);
const { subject, entryKind } = await loadDatasetSubject(dataset);
const sheetFilename = readSheetPointer(subject, variant);
@@ -437,42 +556,60 @@ export async function sliceReferenceSheet(datasetId, { variant = LEGACY_SHEET_VA
status: 422, code: 'INVALID_IMAGE',
});
});
- const cellW = Math.floor(meta.width / cols);
- const cellH = Math.floor(meta.height / rows);
- if (cellW < 64 || cellH < 64) {
- throw new ServerError(
- `Grid ${cols}×${rows} produces cells smaller than 64px on this sheet (${meta.width}×${meta.height})`,
- { status: 400, code: 'VALIDATION_ERROR' },
- );
+
+ // Vision-proposed boxes first; fall back to the fixed grid when the pass
+ // returns nothing usable (no model / error / all boxes rejected).
+ let rects = [];
+ let method = 'grid';
+ if (useVision) {
+ const settings = await getSettings();
+ rects = await proposeCropRegions(sheetPath, { width: meta.width, height: meta.height }, {
+ providerId: captionProviderId, model: captionModel, settings,
+ });
+ if (rects.length) method = 'vision';
+ }
+
+ if (!rects.length) {
+ const cellW = Math.floor(meta.width / cols);
+ const cellH = Math.floor(meta.height / rows);
+ if (cellW < MIN_CROP_PX || cellH < MIN_CROP_PX) {
+ throw new ServerError(
+ `Grid ${cols}×${rows} produces cells smaller than ${MIN_CROP_PX}px on this sheet (${meta.width}×${meta.height})`,
+ { status: 400, code: 'VALIDATION_ERROR' },
+ );
+ }
+ for (let r = 0; r < rows; r += 1) {
+ for (let c = 0; c < cols; c += 1) {
+ rects.push({ left: c * cellW, top: r * cellH, width: cellW, height: cellH });
+ }
+ }
}
await ensureDir(datasetImagesDir(datasetId));
const entries = [];
- for (let r = 0; r < rows; r += 1) {
- for (let c = 0; c < cols; c += 1) {
- const imageId = uuidv4();
- const file = `${imageId}.png`;
- await sharp(sheetPath)
- .extract({ left: c * cellW, top: r * cellH, width: cellW, height: cellH })
- .png()
- .toFile(datasetImagePath(datasetId, file));
- entries.push({
- id: imageId,
- file,
- caption: '',
- captionSource: null,
- captionedAt: null,
- source: 'refsheet-slice',
- sourceJobId: null,
- variation: null,
- status: 'ready',
- width: cellW,
- height: cellH,
- createdAt: new Date().toISOString(),
- });
- }
+ for (const rect of rects) {
+ const imageId = uuidv4();
+ const file = `${imageId}.png`;
+ await sharp(sheetPath)
+ .extract(rect)
+ .png()
+ .toFile(datasetImagePath(datasetId, file));
+ entries.push({
+ id: imageId,
+ file,
+ caption: '',
+ captionSource: null,
+ captionedAt: null,
+ source: 'refsheet-slice',
+ sourceJobId: null,
+ variation: null,
+ status: 'ready',
+ width: rect.width,
+ height: rect.height,
+ createdAt: new Date().toISOString(),
+ });
}
await updateDataset(datasetId, (current) => ({ ...current, images: [...current.images, ...entries] }));
- console.log(`✂️ Dataset ${shortId(datasetId)} ← ${entries.length} crops from ${basename(sheetFilename)} (${cols}×${rows})`);
- return { images: entries, sheet: basename(sheetFilename) };
+ console.log(`✂️ Dataset ${shortId(datasetId)} ← ${entries.length} crops from ${basename(sheetFilename)} (${method}${method === 'grid' ? ` ${cols}×${rows}` : ''})`);
+ return { images: entries, sheet: basename(sheetFilename), method };
}
diff --git a/server/services/loraDatasetGenerate.test.js b/server/services/loraDatasetGenerate.test.js
index 3e170a2e90..351fbd13e9 100644
--- a/server/services/loraDatasetGenerate.test.js
+++ b/server/services/loraDatasetGenerate.test.js
@@ -13,7 +13,10 @@ vi.mock('./universeBuilder.js', async (importOriginal) => ({
getUniverse: vi.fn(),
}));
-import { buildDatasetImagePrompt, deriveVariationAxes, getDatasetVariationAxes } from './loraDatasetGenerate.js';
+import {
+ buildDatasetImagePrompt, deriveVariationAxes, getDatasetVariationAxes,
+ normalizeCropProposals, proposeCropRegions,
+} from './loraDatasetGenerate.js';
import { getDataset } from './loraDatasets.js';
import { getUniverse } from './universeBuilder.js';
@@ -156,3 +159,99 @@ describe('getDatasetVariationAxes', () => {
await expect(getDatasetVariationAxes('ds1')).rejects.toMatchObject({ status: 409 });
});
});
+
+describe('normalizeCropProposals', () => {
+ const dims = { width: 1000, height: 800 };
+
+ it('scales normalized boxes to pixel extract rects', () => {
+ const rects = normalizeCropProposals({ boxes: [{ x: 0, y: 0, w: 0.5, h: 0.5 }] }, dims);
+ expect(rects).toEqual([{ left: 0, top: 0, width: 500, height: 400 }]);
+ });
+
+ it('accepts a bare array of boxes (no wrapper object)', () => {
+ const rects = normalizeCropProposals([{ x: 0.5, y: 0.5, w: 0.5, h: 0.5 }], dims);
+ expect(rects).toEqual([{ left: 500, top: 400, width: 500, height: 400 }]);
+ });
+
+ it('clamps a box that overhangs the sheet edge instead of throwing', () => {
+ const rects = normalizeCropProposals({ boxes: [{ x: 0.8, y: 0.8, w: 0.5, h: 0.5 }] }, dims);
+ // x+w = 1.3 → clamped to 1.0; rect spans the bottom-right corner.
+ expect(rects).toEqual([{ left: 800, top: 640, width: 200, height: 160 }]);
+ });
+
+ it('drops sub-64px boxes (label strips / palette swatches)', () => {
+ const rects = normalizeCropProposals({
+ boxes: [
+ { x: 0, y: 0, w: 0.01, h: 0.5 }, // 10px wide → rejected
+ { x: 0, y: 0, w: 0.5, h: 0.5 }, // kept
+ ],
+ }, dims);
+ expect(rects).toHaveLength(1);
+ expect(rects[0]).toMatchObject({ width: 500 });
+ });
+
+ it('drops boxes with non-finite or missing coordinates', () => {
+ const rects = normalizeCropProposals({
+ boxes: [
+ { x: 0, y: 0, w: 0.5 }, // missing h
+ { x: NaN, y: 0, w: 0.5, h: 0.5 }, // NaN
+ { x: 0.5, y: 0.5, w: 0.5, h: 0.5 }, // kept
+ ],
+ }, dims);
+ expect(rects).toHaveLength(1);
+ });
+
+ it('returns [] for garbage, non-array boxes, or zero dims', () => {
+ expect(normalizeCropProposals(null, dims)).toEqual([]);
+ expect(normalizeCropProposals({ boxes: 'nope' }, dims)).toEqual([]);
+ expect(normalizeCropProposals({ boxes: [{ x: 0, y: 0, w: 0.5, h: 0.5 }] }, { width: 0, height: 0 })).toEqual([]);
+ });
+});
+
+describe('proposeCropRegions', () => {
+ const dims = { width: 900, height: 600 };
+ // Inject readImage so we don't touch disk — the function reads the sheet to
+ // base64 it before the (also-injected) vision call.
+ const readImage = vi.fn().mockResolvedValue(Buffer.from('fake-png'));
+
+ it('returns pixel rects from a clean vision reply', async () => {
+ const describeImage = vi.fn().mockResolvedValue({
+ text: '{"boxes":[{"x":0,"y":0,"w":0.5,"h":1.0}]}',
+ });
+ const resolveModel = vi.fn().mockResolvedValue({ providerId: 'lmstudio', model: 'qwen2.5-vl' });
+ const rects = await proposeCropRegions('/sheet.png', dims, { describeImage, resolveModel, readImage });
+ expect(rects).toEqual([{ left: 0, top: 0, width: 450, height: 600 }]);
+ expect(describeImage).toHaveBeenCalledOnce();
+ });
+
+ it('tolerates a CLI-banner-prefixed / code-fenced reply', async () => {
+ const describeImage = vi.fn().mockResolvedValue({
+ text: 'session id: abc\n```json\n{"boxes":[{"x":0.5,"y":0,"w":0.5,"h":1}]}\n```',
+ });
+ const resolveModel = vi.fn().mockResolvedValue({ providerId: 'codex', model: 'gpt-5' });
+ const rects = await proposeCropRegions('/sheet.png', dims, { describeImage, resolveModel, readImage });
+ expect(rects).toEqual([{ left: 450, top: 0, width: 450, height: 600 }]);
+ });
+
+ it('returns [] (→ grid fallback) when no vision model resolves', async () => {
+ const describeImage = vi.fn();
+ const resolveModel = vi.fn().mockRejectedValue(new Error('no vision model'));
+ const rects = await proposeCropRegions('/sheet.png', dims, { describeImage, resolveModel, readImage });
+ expect(rects).toEqual([]);
+ expect(describeImage).not.toHaveBeenCalled();
+ });
+
+ it('returns [] when the vision call throws (transport error)', async () => {
+ const describeImage = vi.fn().mockRejectedValue(new Error('timeout'));
+ const resolveModel = vi.fn().mockResolvedValue({ providerId: 'lmstudio', model: 'qwen2.5-vl' });
+ const rects = await proposeCropRegions('/sheet.png', dims, { describeImage, resolveModel, readImage });
+ expect(rects).toEqual([]);
+ });
+
+ it('returns [] when the reply has no parseable boxes', async () => {
+ const describeImage = vi.fn().mockResolvedValue({ text: 'I could not find any figures.' });
+ const resolveModel = vi.fn().mockResolvedValue({ providerId: 'lmstudio', model: 'qwen2.5-vl' });
+ const rects = await proposeCropRegions('/sheet.png', dims, { describeImage, resolveModel, readImage });
+ expect(rects).toEqual([]);
+ });
+});
diff --git a/server/services/visionCli.js b/server/services/visionCli.js
new file mode 100644
index 0000000000..e51fb0d338
--- /dev/null
+++ b/server/services/visionCli.js
@@ -0,0 +1,146 @@
+/**
+ * Vision via CLI providers (codex / claude-code with vision).
+ *
+ * The API-provider vision path (`describeImageDataUrlDetailed` in
+ * `visionTest.js`) POSTs a base64 `image_url` block to an OpenAI-compatible
+ * `/chat/completions`. CLI providers have no such endpoint — they read a prompt
+ * from stdin and (for the vision-capable ones) an image from a FILE. So this
+ * module decodes the in-memory data URL to a temp PNG, attaches it the way each
+ * CLI expects, spawns the provider, and returns the model's text in the SAME
+ * `{ text, finishReason, usage, reasoning }` shape the API path returns — so
+ * `loraDatasetCaption.js` consumes either provider type uniformly.
+ *
+ * Attachment conventions (mirrors `imageGen/codex.js` for codex):
+ * - codex: `codex exec -i <file> '<prompt>'` — the `-i` flag feeds the file
+ * to the model; the prompt is a positional arg.
+ * - others (claude-code): the image is written into a fresh temp dir that
+ * becomes the spawn cwd, and the prompt (over stdin) references it by
+ * basename so the CLI can read it with its file tools in print mode.
+ *
+ * CLI providers don't report `finish_reason` / token usage / reasoning, so
+ * those come back null/'' — the caption diagnostics degrade gracefully (an
+ * empty CLI reply is reported as a plain refusal rather than a token-budget
+ * guess).
+ */
+
+import { spawn } from 'child_process';
+import { writeFile, rm, mkdtemp } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { buildCliArgs } from '../lib/cliProviderArgs.js';
+
+const CLI_VISION_TIMEOUT_MS = 120000;
+const IMAGE_BASENAME = 'vision-input.png';
+
+// Codex matches on id OR command so a renamed/duplicated codex provider still
+// takes the `-i` path. Everything else uses the cwd-local-file convention.
+const isCodexProvider = (provider) => provider?.id === 'codex' || provider?.command === 'codex';
+
+/**
+ * Decode a `data:image/...;base64,...` URL to raw bytes. Throws on a malformed
+ * URL (same contract as the API path's up-front data-URL check). Pure —
+ * exported for tests.
+ */
+export function decodeImageDataUrl(dataUrl) {
+ if (typeof dataUrl !== 'string' || !dataUrl.startsWith('data:image/')) {
+ throw new Error('dataUrl must be a base64 image data URL');
+ }
+ const comma = dataUrl.indexOf(',');
+ const base64 = comma >= 0 ? dataUrl.slice(comma + 1) : '';
+ if (!base64) throw new Error('dataUrl has no base64 payload');
+ return Buffer.from(base64, 'base64');
+}
+
+/**
+ * Build the spawn invocation (command, argv, stdin, cwd) for a vision CLI call.
+ * `imageDir` is the temp dir holding `IMAGE_BASENAME`. Pure — exported so the
+ * per-provider attachment convention is unit-testable without spawning.
+ *
+ * @returns {{ command: string, args: string[], stdin: string|null, cwd: string }}
+ */
+export function buildCliVisionInvocation(provider, model, imageDir, prompt) {
+ const imagePath = join(imageDir, IMAGE_BASENAME);
+ if (isCodexProvider(provider)) {
+ const baseArgs = Array.isArray(provider.args) ? provider.args : [];
+ const hasExec = baseArgs.includes('exec');
+ const args = [
+ ...(hasExec ? baseArgs : [...baseArgs, 'exec']),
+ '--skip-git-repo-check',
+ '-i', imagePath,
+ ...(model ? ['-m', String(model)] : []),
+ prompt,
+ ];
+ return { command: provider.command || 'codex', args, stdin: null, cwd: imageDir };
+ }
+
+ // Claude Code (and any other stdin CLI): buildCliArgs gives the `-p -`
+ // stdin convention + `--model`; the image rides in the spawn cwd so the CLI
+ // can open it by basename with its file tools.
+ const args = buildCliArgs({ ...provider, defaultModel: model });
+ const stdin = `${prompt}\n\nThe image to analyze is the file "${IMAGE_BASENAME}" in the current directory.`;
+ return { command: provider.command, args, stdin, cwd: imageDir };
+}
+
+/**
+ * Run a vision prompt against a CLI provider and resolve with the model's text
+ * in the API-compatible diagnostic shape. `spawnImpl` is injectable for tests.
+ *
+ * @param {object} opts
+ * @param {object} opts.provider — a CLI-type provider object
+ * @param {string} opts.dataUrl — base64 image data URL
+ * @param {string} opts.prompt — what to ask about the image
+ * @param {string} [opts.model] — model override (defaults to provider.defaultModel)
+ * @param {number} [opts.timeout]
+ * @param {Function} [opts.spawnImpl] — child_process.spawn replacement (tests)
+ * @returns {Promise<{ text:string, finishReason:null, usage:null, reasoning:string }>}
+ */
+export async function describeImageViaCli({
+ provider, dataUrl, prompt, model, timeout = CLI_VISION_TIMEOUT_MS, spawnImpl = spawn,
+}) {
+ const visionModel = model || provider?.defaultModel || null;
+ const bytes = decodeImageDataUrl(dataUrl);
+
+ // Fresh per-call temp dir so concurrent caption runs never collide on the
+ // image file, and cleanup is a single recursive rm.
+ const dir = await mkdtemp(join(tmpdir(), 'portos-vision-'));
+ try {
+ await writeFile(join(dir, IMAGE_BASENAME), bytes);
+ const { command, args, stdin, cwd } = buildCliVisionInvocation(provider, visionModel, dir, prompt);
+
+ const text = await new Promise((resolve, reject) => {
+ const child = spawnImpl(command, args, {
+ cwd,
+ env: (() => { const e = { ...process.env, ...provider?.envVars }; delete e.CLAUDECODE; return e; })(),
+ windowsHide: true,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ });
+ let out = '';
+ let err = '';
+ const timer = timeout > 0 ? setTimeout(() => {
+ if (!child.killed) child.kill('SIGTERM');
+ }, timeout) : null;
+ timer?.unref?.();
+
+ child.on('error', (e) => { if (timer) clearTimeout(timer); 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);
+ 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}` : ''}`));
+ });
+
+ if (stdin != null) {
+ child.stdin?.write(stdin);
+ child.stdin?.end();
+ } else {
+ child.stdin?.end();
+ }
+ });
+
+ return { text, finishReason: null, usage: null, reasoning: '' };
+ } finally {
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
+ }
+}
diff --git a/server/services/visionCli.test.js b/server/services/visionCli.test.js
new file mode 100644
index 0000000000..fca1d583d4
--- /dev/null
+++ b/server/services/visionCli.test.js
@@ -0,0 +1,128 @@
+import { describe, it, expect, vi } from 'vitest';
+import { EventEmitter } from 'events';
+import {
+ decodeImageDataUrl,
+ buildCliVisionInvocation,
+ describeImageViaCli,
+} from './visionCli.js';
+
+const PNG_DATA_URL = `data:image/png;base64,${Buffer.from('fake-png').toString('base64')}`;
+
+describe('decodeImageDataUrl', () => {
+ it('decodes the base64 payload to bytes', () => {
+ expect(decodeImageDataUrl(PNG_DATA_URL).toString()).toBe('fake-png');
+ });
+
+ it('throws on a non-image / malformed data URL', () => {
+ expect(() => decodeImageDataUrl('not-a-data-url')).toThrow(/base64 image data URL/);
+ expect(() => decodeImageDataUrl('data:image/png;base64,')).toThrow(/no base64 payload/);
+ });
+});
+
+describe('buildCliVisionInvocation', () => {
+ it('attaches the image via -i and a positional prompt for codex', () => {
+ const inv = buildCliVisionInvocation(
+ { id: 'codex', command: 'codex', args: [] }, 'gpt-5', '/tmp/x', 'describe',
+ );
+ expect(inv.command).toBe('codex');
+ expect(inv.args).toContain('-i');
+ expect(inv.args).toContain('/tmp/x/vision-input.png');
+ expect(inv.args).toContain('-m');
+ expect(inv.args).toContain('gpt-5');
+ expect(inv.args[inv.args.length - 1]).toBe('describe'); // prompt is positional
+ expect(inv.stdin).toBeNull();
+ expect(inv.cwd).toBe('/tmp/x');
+ });
+
+ it('does not double-add exec when the provider args already pin it', () => {
+ const inv = buildCliVisionInvocation(
+ { id: 'codex', command: 'codex', args: ['exec'] }, null, '/tmp/x', 'p',
+ );
+ expect(inv.args.filter((a) => a === 'exec')).toHaveLength(1);
+ });
+
+ it('uses stdin + cwd-local file reference for claude-code', () => {
+ const inv = buildCliVisionInvocation(
+ { id: 'claude-code', command: 'claude', args: [] }, 'claude-opus-4-8', '/tmp/y', 'describe',
+ );
+ expect(inv.command).toBe('claude');
+ expect(inv.args).toEqual(expect.arrayContaining(['-p', '-', '--model', 'claude-opus-4-8']));
+ expect(inv.stdin).toContain('describe');
+ expect(inv.stdin).toContain('vision-input.png');
+ expect(inv.cwd).toBe('/tmp/y');
+ });
+});
+
+// A minimal child-process double: an EventEmitter with stdin/stdout/stderr.
+function makeFakeChild() {
+ const child = new EventEmitter();
+ child.killed = false;
+ child.kill = vi.fn(() => { child.killed = true; });
+ child.stdin = { write: vi.fn(), end: vi.fn() };
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ return child;
+}
+
+describe('describeImageViaCli', () => {
+ it('returns the trimmed stdout text in the API-compatible shape on exit 0', async () => {
+ const child = makeFakeChild();
+ const spawnImpl = vi.fn(() => child);
+ const promise = describeImageViaCli({
+ provider: { id: 'codex', command: 'codex', args: [] },
+ dataUrl: PNG_DATA_URL,
+ prompt: 'caption this',
+ model: 'gpt-5',
+ spawnImpl,
+ });
+ // Let the mkdtemp/writeFile awaits settle before emitting process events.
+ await new Promise((r) => setTimeout(r, 10));
+ child.stdout.emit('data', Buffer.from(' a woman in a red cloak '));
+ child.emit('close', 0);
+ const result = await promise;
+ expect(result).toEqual({
+ text: 'a woman in a red cloak', finishReason: null, usage: null, reasoning: '',
+ });
+ expect(spawnImpl).toHaveBeenCalledOnce();
+ });
+
+ it('rejects with a tail of stderr on a non-zero exit', async () => {
+ const child = makeFakeChild();
+ const spawnImpl = vi.fn(() => child);
+ const promise = describeImageViaCli({
+ provider: { id: 'claude-code', command: 'claude', args: [] },
+ dataUrl: PNG_DATA_URL,
+ prompt: 'caption',
+ spawnImpl,
+ });
+ await new Promise((r) => setTimeout(r, 10));
+ child.stderr.emit('data', Buffer.from('vision unavailable'));
+ child.emit('close', 1);
+ await expect(promise).rejects.toThrow(/exited 1.*vision unavailable/s);
+ });
+
+ it('rejects when the process fails to spawn', async () => {
+ const child = makeFakeChild();
+ const spawnImpl = vi.fn(() => child);
+ const promise = describeImageViaCli({
+ provider: { id: 'codex', command: 'codex', args: [] },
+ dataUrl: PNG_DATA_URL,
+ prompt: 'p',
+ spawnImpl,
+ });
+ await new Promise((r) => setTimeout(r, 10));
+ child.emit('error', new Error('ENOENT'));
+ await expect(promise).rejects.toThrow(/Failed to spawn codex.*ENOENT/s);
+ });
+
+ it('throws on a malformed data URL before spawning', async () => {
+ const spawnImpl = vi.fn();
+ await expect(describeImageViaCli({
+ provider: { id: 'codex', command: 'codex', args: [] },
+ dataUrl: 'garbage',
+ prompt: 'p',
+ spawnImpl,
+ })).rejects.toThrow(/base64 image data URL/);
+ expect(spawnImpl).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/visionTest.js b/server/services/visionTest.js
index b4ba065891..4601503617 100644
--- a/server/services/visionTest.js
+++ b/server/services/visionTest.js
@@ -12,6 +12,7 @@ import { getProviderById } from './providers.js';
import { PATHS } from '../lib/fileUtils.js';
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';
+import { describeImageViaCli } from './visionCli.js';
const SCREENSHOTS_DIR = PATHS.screenshots;
const DEFAULT_VISION_TIMEOUT_MS = 60000;
@@ -256,6 +257,15 @@ export async function describeImageDataUrlDetailed({ dataUrl, prompt, providerId
}
const provider = await getProviderById(providerId);
if (!provider) throw new Error(`Provider '${providerId}' not found`);
+ // CLI providers (codex / claude-code with vision) read the image from a file
+ // rather than an `image_url` block — delegate to the CLI vision path, which
+ // returns the same { text, finishReason, usage, reasoning } shape. maxTokens
+ // has no CLI analogue (the CLI manages its own budget) so it's dropped.
+ if (provider.type === 'cli') {
+ return describeImageViaCli({
+ provider, dataUrl, prompt: prompt || 'Describe what you see in this image.', model,
+ });
+ }
if (provider.type !== 'api') throw new Error(`Provider '${providerId}' is not an API provider (type: ${provider.type})`);
const visionModel = model || provider.defaultModel;
if (!visionModel) throw new Error('No model specified and provider has no default model');
diff --git a/server/services/visionTest.test.js b/server/services/visionTest.test.js
index 9e31b04dde..1ccd0229f9 100644
--- a/server/services/visionTest.test.js
+++ b/server/services/visionTest.test.js
@@ -6,6 +6,12 @@ vi.mock('./providers.js', () => ({
getProviderById: vi.fn()
}));
+// Mock the CLI vision path so the CLI-dispatch branch is asserted without
+// spawning a real child process.
+vi.mock('./visionCli.js', () => ({
+ describeImageViaCli: vi.fn(),
+}));
+
// Mock fs/promises for image loading and directory listing
vi.mock('fs/promises', () => ({
readFile: vi.fn(),
@@ -19,6 +25,7 @@ vi.mock('fs', () => ({
// Import mocked modules
import { getProviderById } from './providers.js';
+import { describeImageViaCli } from './visionCli.js';
import { readFile, readdir } from 'fs/promises';
import { existsSync } from 'fs';
@@ -299,6 +306,23 @@ describe('Vision Test Service', () => {
expect(out.text).toBe('');
expect(out.reasoning).toBe('I should refuse');
});
+
+ it('delegates a CLI provider to the CLI vision path (not the API call)', async () => {
+ getProviderById.mockResolvedValue({ id: 'codex', type: 'cli', command: 'codex', defaultModel: 'gpt-5' });
+ describeImageViaCli.mockResolvedValue({ text: 'a portrait', finishReason: null, usage: null, reasoning: '' });
+ const out = await describeImageDataUrlDetailed({ dataUrl: DATA_URL, prompt: 'caption', providerId: 'codex' });
+ expect(out.text).toBe('a portrait');
+ expect(describeImageViaCli).toHaveBeenCalledWith(expect.objectContaining({
+ provider: expect.objectContaining({ id: 'codex' }), dataUrl: DATA_URL, prompt: 'caption',
+ }));
+ expect(global.fetch).not.toHaveBeenCalled();
+ });
+
+ it('still rejects a non-api / non-cli provider (e.g. tui)', async () => {
+ getProviderById.mockResolvedValue({ id: 'codex-tui', type: 'tui', command: 'codex' });
+ await expect(describeImageDataUrlDetailed({ dataUrl: DATA_URL, prompt: 'x', providerId: 'codex-tui' }))
+ .rejects.toThrow(/not an API provider/);
+ });
});
describe('checkVisionHealth', () => {