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

diagnose empty LoRA captions: reasoning model vs refusal, not a fixed guess

[._.]/ Adam Eivy4cdf4e106f60
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f6cb5bc27d..2c38bf06a2 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -24,6 +24,8 @@
- **LoRA auto-captions no longer silently come back as just the trigger word** — When a vision model returned an empty reply (common when it refuses a realistic close-up face, or when a thinking model spends its whole token budget reasoning), the captioner prefixed that empty string with the trigger word and saved the result — so the image was bound but undescribed, yet the run still logged it as captioned. A blank model reply is now treated as a per-image failure: it's surfaced in the caption run's progress (with the model name and a hint to try a different vision model or caption manually) and never persisted, so the image stays un-captioned and a re-run re-attempts it instead of leaving a degenerate trigger-word-only caption. (`server/services/loraDatasetCaption.js`)
+- **LoRA caption failures now name the real cause — reasoning model vs. refusal — instead of always blaming a refusal** — A blank vision reply used to fail with one fixed message ("it may have refused this image"), which was usually wrong: capability-tagged reasoning models (a `qwen3.6:35b`-style MoE, thinking Gemma builds) emit a hidden `<think>` block FIRST and, at the old 300-token caption budget, routinely hit the budget mid-reasoning and return *empty* content — a token-exhaustion problem, not a refusal. The captioner now reads the response's `finish_reason`, token usage, and any out-of-band reasoning (`describeImageDataUrlDetailed`) and writes the diagnosis into the failure: "it spent its whole token budget on hidden reasoning (spent 600 completion tokens) and ran out before writing a caption — this is a reasoning model, not a vision model. Pick a dedicated VLM (Qwen2.5-VL, LLaVA, MiniCPM-V, Llama 3.2 Vision)" for a thinking model, a plain truncation message when cut off with no reasoning trace, and the original refusal wording only when there's genuinely no diagnostic signal. The per-image reason now also reaches the dataset-workbench toast (not just the generic tally), so a single-image run tells you exactly what to do. The caption token budget was also raised 300→600 to give a borderline reasoning model enough headroom to finish; dedicated VLMs stop well before it, so it costs them nothing. (`server/services/visionTest.js`, `server/services/loraDatasetCaption.js`, `client/src/pages/LoraDatasetDetail.jsx`)
+
- **LoRA caption-model picker now sees vision-capable Ollama models whose name lacks a `vl`/`vision` token** — The picker showed "none installed" even with a vision model like the `qwen3.6:35b` MoE installed, because Ollama's `/api/tags` carries no vision flag and the id heuristic only matches names containing a `vl`/`vision`/known-family token. Ollama *does* report `capabilities: ["…","vision",…]` via `/api/show`, but PortOS only consulted that for LM Studio. `listVisionModels` now enriches each Ollama model the id heuristic doesn't already catch with its `/api/show` capabilities (cached per model, busted on delete), so capability-tagged vision models surface in the picker — and, through the same path, in the captioner's auto-pick and explicit-model validation. (`server/services/ollamaManager.js`, `server/services/localLlm.js`)
- **TUI agents no longer leave the prompt sitting unsent in the input box** — CoS agents that run inside a terminal-UI provider (Claude Code, Codex) bracketed-paste their task prompt and then send a single Enter to submit it. On a large multi-line prompt that one `\r` could arrive while the TUI was still reflowing the paste and get swallowed — so the prompt sat typed-but-unsubmitted, the agent did no work, idled out after 3 minutes, and was (wrongly) recorded as a successful run. You'd see it only by opening the Shell tab and hitting Enter yourself. The submit Enter now fires a few times spaced ~700ms apart so one lands after the paste settles; re-sending is safe because once the prompt submits the input box is empty and a bare Enter is a no-op. Applies to both the long-running agent path and the one-shot TUI runner. (`server/lib/tuiHandshake.js`, `server/services/agentTuiSpawning.js`, `server/lib/tuiPromptRunner.js`)
diff --git a/client/src/pages/LoraDatasetDetail.jsx b/client/src/pages/LoraDatasetDetail.jsx
index 7e56aaefbf..25ee6bdef8 100644
--- a/client/src/pages/LoraDatasetDetail.jsx
+++ b/client/src/pages/LoraDatasetDetail.jsx
@@ -187,21 +187,28 @@ export default function LoraDatasetDetail() {
useEffect(() => {
if (!captionRun || !captionSse.closed) return;
const last = captionSse.latest;
+ // The per-image `progress` frames carry the specific failure reason (refusal
+ // vs. a reasoning model that exhausted its token budget). The terminal frame
+ // only has a tally, so pull the most recent per-image error to surface the
+ // actionable detail — invaluable when a single-image run fails.
+ const lastImageError = [...(captionSse.frames || [])]
+ .reverse().find((f) => f?.type === 'progress' && f.error)?.error;
if (last?.type === 'error') {
// Whole run failed up front (e.g. every image refused) — show the
// actionable server message verbatim.
toast.error(last.message || 'Captioning failed');
} else if (last?.type === 'complete' && last.failed > 0) {
const noun = last.failed === 1 ? 'image' : 'images';
+ const detail = lastImageError ? ` ${lastImageError}` : '';
toast.error(last.done > 0
- ? `Captioned ${last.done}/${last.total} — ${last.failed} ${noun} failed (model refused or returned an empty description). Re-caption individually or pick another vision model.`
- : `All ${last.failed} ${noun} failed to caption — the vision model refused or returned nothing. Try another vision model.`);
+ ? `Captioned ${last.done}/${last.total} — ${last.failed} ${noun} failed.${detail || ' Re-caption individually or pick another vision model.'}`
+ : `All ${last.failed} ${noun} failed to caption.${detail || ' The vision model refused or returned nothing — try another vision model.'}`);
} else if (last?.type === 'complete' && last.done > 0) {
toast.success(`Captioned ${last.done} image${last.done === 1 ? '' : 's'}`);
}
setCaptionRun(null);
refresh();
- }, [captionRun, captionSse.closed, captionSse.latest, refresh]);
+ }, [captionRun, captionSse.closed, captionSse.latest, captionSse.frames, refresh]);
const onImagesChange = (mutate) => setDataset((prev) => (prev ? { ...prev, images: mutate(prev.images) } : prev));
diff --git a/server/services/loraDatasetCaption.js b/server/services/loraDatasetCaption.js
index 7ce04769d9..bb5171239f 100644
--- a/server/services/loraDatasetCaption.js
+++ b/server/services/loraDatasetCaption.js
@@ -28,7 +28,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';
import { prefixCaption } from '../lib/loraDataset.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';
import { createMutex } from '../lib/asyncMutex.js';
-import { describeImageDataUrl } from './visionTest.js';
+import { describeImageDataUrlDetailed } from './visionTest.js';
import { getSettings } from './settings.js';
import { listVisionModels } from './localLlm.js';
import { isVisionModel } from '../lib/localModelHeuristics.js';
@@ -42,7 +42,14 @@ export const CAPTION_PROMPT = [
'an illustration.',
].join(' ');
-const CAPTION_MAX_TOKENS = 300;
+// A comma-separated caption fits well under 300, but reasoning models (Qwen3,
+// thinking Gemma builds) spend tokens on a hidden <think> block FIRST and only
+// then emit the caption — at 300 they routinely hit the budget mid-reasoning
+// and return empty content. The extra headroom lets those produce a caption
+// instead of failing; dedicated VLMs stop well before it, so it costs them
+// nothing. The real fix for a reasoning model is to pick a VLM (the failure
+// message now says so), but this keeps a borderline case from failing outright.
+const CAPTION_MAX_TOKENS = 600;
// Module-level mutex serializing every vision call across ALL caption runs.
// Within one run the loop is already sequential, but nothing stops a user (or
@@ -129,6 +136,38 @@ export async function resolveCaptionModel({
return { providerId: pick.providerId, model: pick.id };
}
+/**
+ * Diagnose WHY a vision reply came back blank, from the response metadata, so
+ * the failure message names the real cause instead of always blaming a refusal.
+ * `meta` is the `{ finishReason, usage, reasoning }` from describeImageDataUrlDetailed.
+ *
+ * The three cases we can tell apart:
+ * - Reasoning model burned the budget: it emitted hidden reasoning and the
+ * reply was cut off (`finish_reason: 'length'`) before any caption. The fix
+ * is a dedicated VLM, not a retry — say so.
+ * - Plain truncation: cut off at the budget with no reasoning trace — raising
+ * the budget or a faster model helps.
+ * - Reasoning with room to spare: it chose to only reason — a non-thinking
+ * vision model is the answer.
+ * Everything else falls back to the original "it may have refused" wording.
+ */
+function diagnoseEmptyCaption(meta = {}) {
+ const { finishReason = null, usage = null, reasoning = '' } = meta || {};
+ const truncated = finishReason === 'length';
+ const completionTokens = usage?.completion_tokens ?? null;
+ const tokenNote = completionTokens != null ? ` (spent ${completionTokens} completion tokens)` : '';
+ if (reasoning && truncated) {
+ return `it spent its whole token budget on hidden reasoning${tokenNote} and ran out before writing a caption — this is a reasoning model, not a vision model. Pick a dedicated VLM (Qwen2.5-VL, LLaVA, MiniCPM-V, Llama 3.2 Vision) on the dataset`;
+ }
+ if (truncated) {
+ return `the reply was cut off at the token budget${tokenNote} before any caption text — raise the caption token budget or use a faster vision model`;
+ }
+ if (reasoning) {
+ return `it returned only reasoning and no caption${tokenNote} — use a non-thinking vision model`;
+ }
+ return 'it may have refused this image; try a different vision model or caption it manually';
+}
+
/**
* Build the persisted caption from a vision model's raw reply.
*
@@ -138,11 +177,12 @@ export async function resolveCaptionModel({
* when they refuse a realistic close-up face (or a thinking model spends its
* whole token budget reasoning). Throwing here routes blank output through the
* loop's failure path, so it's surfaced and re-attemptable rather than saved as
- * a trigger-word-only caption.
+ * a trigger-word-only caption. `meta` (when supplied) lets the error name the
+ * real cause — refusal vs. token-budget exhaustion by a reasoning model.
*/
-export function buildCaption(triggerWord, text, model = 'vision model') {
+export function buildCaption(triggerWord, text, model = 'vision model', meta = null) {
if (!text || !text.trim()) {
- throw new Error(`${model} returned an empty description — it may have refused this image; try a different vision model or caption it manually`);
+ throw new Error(`${model} returned an empty description — ${diagnoseEmptyCaption(meta)}`);
}
return prefixCaption(triggerWord, text);
}
@@ -198,14 +238,14 @@ export async function startCaptionRun(datasetId, {
try {
const bytes = await readFile(datasetImagePath(datasetId, img.file));
const dataUrl = `data:image/png;base64,${bytes.toString('base64')}`;
- const text = await withCaptionVisionLock(() => describeImageDataUrl({
+ const result = await withCaptionVisionLock(() => describeImageDataUrlDetailed({
dataUrl,
prompt: CAPTION_PROMPT,
providerId: resolvedProvider,
model: resolvedModel,
maxTokens: CAPTION_MAX_TOKENS,
}));
- caption = buildCaption(dataset.triggerWord, text, `vision model "${resolvedModel}"`);
+ caption = buildCaption(dataset.triggerWord, result.text, `vision model "${resolvedModel}"`, result);
} catch (err) {
failed += 1;
console.error(`❌ Caption failed [${shortId(runId)} ${img.id}]: ${err?.message || err}`);
diff --git a/server/services/loraDatasetCaption.test.js b/server/services/loraDatasetCaption.test.js
index 9db56bda06..c11851d463 100644
--- a/server/services/loraDatasetCaption.test.js
+++ b/server/services/loraDatasetCaption.test.js
@@ -83,6 +83,27 @@ describe('buildCaption', () => {
expect(() => buildCaption('tamsin_reed', '', 'vision model "llava:7b"'))
.toThrow(/llava:7b/);
});
+
+ it('blames a reasoning model (not a refusal) when it burned the budget thinking', () => {
+ // Qwen3/thinking-Gemma symptom: hidden reasoning + finish_reason 'length'.
+ // The message must point at picking a real VLM, not "it refused".
+ const meta = { finishReason: 'length', usage: { completion_tokens: 600 }, reasoning: 'Let me analyze…' };
+ expect(() => buildCaption('tamsin_reed', '', 'vision model "qwen3:35b"', meta))
+ .toThrow(/hidden reasoning.*600 completion tokens.*reasoning model.*VLM/s);
+ });
+
+ it('calls out plain truncation when cut off with no reasoning trace', () => {
+ const meta = { finishReason: 'length', usage: { completion_tokens: 600 }, reasoning: '' };
+ expect(() => buildCaption('tamsin_reed', '', 'vision model "llava:7b"', meta))
+ .toThrow(/cut off at the token budget.*raise the caption token budget/s);
+ });
+
+ it('falls back to the refusal wording when there is no diagnostic signal', () => {
+ expect(() => buildCaption('tamsin_reed', '', 'vision model "llava:7b"', { finishReason: 'stop' }))
+ .toThrow(/may have refused this image/);
+ // and with no meta at all (back-compat 3-arg callers)
+ expect(() => buildCaption('tamsin_reed', '')).toThrow(/may have refused this image/);
+ });
});
describe('withCaptionVisionLock', () => {
diff --git a/server/services/visionTest.js b/server/services/visionTest.js
index 52af14dbd0..89332acf66 100644
--- a/server/services/visionTest.js
+++ b/server/services/visionTest.js
@@ -223,7 +223,34 @@ export async function testVision({ imagePath, prompt, expectedContent, providerI
* default when asking the model for a long/structured reply (see callVisionAPI).
* @returns {Promise<string>} - The model's description text
*/
-export async function describeImageDataUrl({ dataUrl, prompt, providerId = 'lmstudio', model, maxTokens }) {
+export async function describeImageDataUrl(opts) {
+ return (await describeImageDataUrlDetailed(opts)).text;
+}
+
+// Pull any hidden chain-of-thought a reasoning model emitted out of band, so an
+// empty `content` can be explained ("it reasoned but produced no caption")
+// rather than mislabeled as a refusal. Backends surface this differently:
+// Ollama's OpenAI-compat puts it on `message.reasoning`, LM Studio on
+// `message.reasoning_content`, and some models leak an inline `<think>…</think>`
+// block into `content`. Returns the reasoning text (trimmed) or ''.
+function extractReasoning(message) {
+ if (!message || typeof message !== 'object') return '';
+ const direct = message.reasoning || message.reasoning_content || message.thinking;
+ if (typeof direct === 'string' && direct.trim()) return direct.trim();
+ const content = typeof message.content === 'string' ? message.content : '';
+ const inline = content.match(/<think>([\s\S]*?)<\/think>/i);
+ return inline ? inline[1].trim() : '';
+}
+
+/**
+ * Like {@link describeImageDataUrl} but returns the model's text alongside the
+ * diagnostics that explain a blank reply — `finishReason` ('length' = cut off
+ * at the token budget), token `usage`, and any out-of-band `reasoning`. The
+ * caption loop uses these to tell a real refusal apart from a reasoning model
+ * that burned its whole budget thinking and returned no caption.
+ * @returns {Promise<{ text: string, finishReason: string|null, usage: object|null, reasoning: string }>}
+ */
+export async function describeImageDataUrlDetailed({ dataUrl, prompt, providerId = 'lmstudio', model, maxTokens }) {
if (typeof dataUrl !== 'string' || !dataUrl.startsWith('data:image/')) {
throw new Error('dataUrl must be a base64 image data URL');
}
@@ -242,7 +269,13 @@ export async function describeImageDataUrl({ dataUrl, prompt, providerId = 'lmst
timeout: provider.timeout || DEFAULT_VISION_TIMEOUT_MS,
...(maxTokens != null ? { maxTokens } : {}),
});
- return apiResponse.choices?.[0]?.message?.content || '';
+ const choice = apiResponse.choices?.[0];
+ return {
+ text: choice?.message?.content || '',
+ finishReason: choice?.finish_reason || null,
+ usage: apiResponse.usage || null,
+ reasoning: extractReasoning(choice?.message),
+ };
}
/**