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): strip leaked inline <think>, test reasoning extraction

[._.]/ Adam Eivycb36b5a17afd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2c38bf06a2..3990ee836d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -24,7 +24,7 @@
- **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 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 N completion tokens, the model-reported count) 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`)
diff --git a/server/services/visionTest.js b/server/services/visionTest.js
index 89332acf66..b4ba065891 100644
--- a/server/services/visionTest.js
+++ b/server/services/visionTest.js
@@ -270,8 +270,15 @@ export async function describeImageDataUrlDetailed({ dataUrl, prompt, providerId
...(maxTokens != null ? { maxTokens } : {}),
});
const choice = apiResponse.choices?.[0];
+ // A reasoning model that leaks its chain-of-thought inline emits
+ // `<think>…</think>` followed by the real answer; strip a LEADING think block
+ // so the returned text is the caption (or JSON, for the digital-twin caller),
+ // not the caption with the model's reasoning glued to the front. Anchored to
+ // the start so legitimate mid-text never gets clipped; the reasoning itself is
+ // still surfaced via `reasoning` for the diagnostic.
+ const rawContent = choice?.message?.content || '';
return {
- text: choice?.message?.content || '',
+ text: rawContent.replace(/^\s*<think>[\s\S]*?<\/think>\s*/i, '').trim(),
finishReason: choice?.finish_reason || null,
usage: apiResponse.usage || null,
reasoning: extractReasoning(choice?.message),
diff --git a/server/services/visionTest.test.js b/server/services/visionTest.test.js
index 8a60100150..9e31b04dde 100644
--- a/server/services/visionTest.test.js
+++ b/server/services/visionTest.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { testVision, runVisionTestSuite, checkVisionHealth } from './visionTest.js';
+import { testVision, runVisionTestSuite, checkVisionHealth, describeImageDataUrlDetailed } from './visionTest.js';
// Mock the providers module
vi.mock('./providers.js', () => ({
@@ -252,6 +252,55 @@ describe('Vision Test Service', () => {
});
});
+ describe('describeImageDataUrlDetailed', () => {
+ const DATA_URL = 'data:image/png;base64,Zm9v';
+ const callWith = async (message, extra = {}) => {
+ getProviderById.mockResolvedValue(mockProvider);
+ global.fetch.mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve({ choices: [{ message, ...extra }], usage: extra.usage }),
+ });
+ return describeImageDataUrlDetailed({ dataUrl: DATA_URL, prompt: 'caption this' });
+ };
+
+ it('surfaces finish_reason and usage alongside the text', async () => {
+ const out = await callWith(
+ { content: 'a calm portrait, soft light' },
+ { finish_reason: 'stop', usage: { completion_tokens: 12 } },
+ );
+ expect(out.text).toBe('a calm portrait, soft light');
+ expect(out.finishReason).toBe('stop');
+ expect(out.usage).toEqual({ completion_tokens: 12 });
+ expect(out.reasoning).toBe('');
+ });
+
+ it('maps a length cutoff to finishReason for the empty-caption diagnosis', async () => {
+ const out = await callWith({ content: '' }, { finish_reason: 'length', usage: { completion_tokens: 600 } });
+ expect(out.text).toBe('');
+ expect(out.finishReason).toBe('length');
+ expect(out.usage.completion_tokens).toBe(600);
+ });
+
+ it('extracts reasoning from each backend field shape (Ollama / LM Studio / native)', async () => {
+ expect((await callWith({ content: '', reasoning: 'ollama thoughts' })).reasoning).toBe('ollama thoughts');
+ expect((await callWith({ content: '', reasoning_content: 'lmstudio thoughts' })).reasoning).toBe('lmstudio thoughts');
+ expect((await callWith({ content: '', thinking: 'native thoughts' })).reasoning).toBe('native thoughts');
+ });
+
+ it('pulls reasoning out of an inline <think> block and strips it from the caption text', async () => {
+ const out = await callWith({ content: '<think>she is facing left</think>bust shot, looking left' });
+ expect(out.reasoning).toBe('she is facing left');
+ // the leaked reasoning must NOT pollute the persisted caption
+ expect(out.text).toBe('bust shot, looking left');
+ });
+
+ it('returns empty text (not a stray tag) when the reply is only a think block', async () => {
+ const out = await callWith({ content: '<think>I should refuse</think>' }, { finish_reason: 'stop' });
+ expect(out.text).toBe('');
+ expect(out.reasoning).toBe('I should refuse');
+ });
+ });
+
describe('checkVisionHealth', () => {
it('should return unavailable when provider not found', async () => {
getProviderById.mockResolvedValue(null);