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

fail TUI runs on a terminal model-id rejection instead of scraping the error screen

[._.]/ Adam Eivy72dd1642d824
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f5a1c69151..6ab35574e4 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Ship a "Claude Code TUI: Bedrock" provider option.** Installs that run Claude Code against Amazon Bedrock can now drive the interactive TUI on Bedrock without hand-editing `providers.json` — the seed (`data.reference/providers.json`, plus the toolkit fallback sample) now includes a `claude-code-tui-bedrock` provider alongside the existing `claude-code-tui` (Anthropic-native) and `claude-code-bedrock` (Bedrock CLI), completing the native/Bedrock × CLI/TUI matrix. Like the Bedrock CLI it ships **disabled with an empty `AWS_BEARER_TOKEN_BEDROCK`** (opt-in; no secret in git) and its `secretEnvVars` marks the token so the UI masks it and cross-install sync withholds it. Existing installs pick it up via `setup-data.js`'s `providers` merge on the next run, without touching their customized providers. (`data.reference/providers.json`, `server/lib/aiToolkit/defaults/providers.sample.json`)
+
- **Video LoRAs now fuse on the bf16 LTX-2.3 Unified Beta (mlx_video runtime), not just dgrauet** — Previously a video LoRA like `ltx2.3-audio-reactive-lora` only worked on the dgrauet `ltx2` runtime; selecting the higher-quality **LTX-2.3 Unified Beta** (notapalindrome's `mlx_video` runtime) silently hid the LoRA picker. The stock `mlx_video.generate_av` CLI has no `--lora` flag, but the `mlx-video-with-audio` package ships an LTX-aware LoRA subsystem (`mlx_video.lora`) that's simply never called from the AV generator. A new wrapper (`scripts/generate_av_lora.py`) closes that gap without reimplementing the ~1000-line generation loop: it loads the user LoRAs, monkeypatches generate_av's two transformer-weight load seams to merge the LoRA deltas into the transformer (bf16, `quantization_bits=0`), then runs generate_av's own `main()` — so the SSE progress protocol is byte-for-byte identical to the non-LoRA path. The VideoGen picker now appears for non-quantized LTX-2.x `mlx_video` models too (gated by `isMlxVideoLtxLoraCapable`); if a LoRA's keys don't match the model the render fails loudly rather than silently producing a base video. Scoped to bf16 — the quantized Distilled Q4/Q8 variants stay on the dgrauet path for now and show an inline hint pointing at the supported models. (`scripts/generate_av_lora.py`, `server/lib/runners.js`, `server/services/videoGen/local.js`, `server/routes/videoGen.js`, `client/src/lib/runnerFamilies.js`, `client/src/pages/VideoGen.jsx`)
- **"Format" button on each manuscript section cleans up pasted-PDF artifacts.** Text pasted out of a PDF export arrives hard-wrapped at the page margin (every visual line a real `\n`), with stylized drop-caps split onto their own line ("T\nhe dawn …"), words hyphenated across the wrap ("approxi-\nmating"), and closing quotes orphaned from the text they terminate (alone on a line, wrapped to the next line, or with a stray space before them) — so a paragraph reads as a column of ragged lines. A new **Format** button in each section's header (both Live and Review modes) normalizes the section: it rejoins drop-caps, repairs hyphen splits, strips trailing whitespace, and collapses runaway blank lines for every stage, and — for **prose** only — re-attaches orphaned closing quotes, drops a stray opening-quote fragment the export duplicated onto its own line (`"I\n"I need …` → `"I need …`, guarded so genuine back-to-back dialogue is untouched), and reflows the soft-wrapped lines back into paragraphs (comic/teleplay keep their structural line breaks). The reflow joins a line onto the previous one only when it begins with a lowercase letter — a real sentence/paragraph/heading never starts lowercase, so headings and attributions keep their own line and two paragraphs are never fused (a global line-width threshold is unsound on documents that mix already-joined and still-wrapped paragraphs). The prior text is snapshotted server-side, so History ▸ Revert undoes a format in one click. (`client/src/lib/manuscriptFormat.js`, `client/src/components/pipeline/manuscript/ManuscriptSectionFrame.jsx`, `client/src/pages/PipelineManuscriptEditor.jsx`)
@@ -10,6 +12,8 @@
## Changed
+- **AI provider failures now log the actual reason inline.** The `🤖 AI provider error detected` line in pm2 logs previously printed only the provider name and run id, so diagnosing a failed run meant opening `data/runs/<id>/metadata.json` to find the captured error. It now includes the model, error category, exit code, and the (single-line, capped) error text — e.g. `… Claude Code CLI (claude-opus-4-8) [model-not-found] exit=1 - run f95b8af2: API Error (claude-opus-4-8): 400 The provided model identifier is invalid.` — so the "why" is visible at a glance. The full untruncated text still lives in the run record. (`server/services/autoFixer.js`)
+
- **Deploying a LoRA checkpoint with no preview now auto-renders one.** A training run only writes preview thumbnails at the `sampleEvery` cadence, so a checkpoint whose step doesn't land on it — most often the final step (e.g. step 1188 with sampleEvery 300) — showed "no preview" in the picker, including on the deployed card. Promoting such a checkpoint now renders a thumbnail in the background from the just-deployed LoRA (the run's neutral trigger prompt + seed, on the LoRA's own 9B/4B base) and joins it to the checkpoint by step, so the deployed option gets a real image instead of a blank. The render is fire-and-forget — promote stays responsive and a render failure (OOM, restart) never fails the deploy, since the LoRA is already registered. The picker backstop-polls after promoting a preview-less checkpoint to surface the thumbnail once it's ready (~minutes on 9B), unmount-guarded. (`server/services/loraTraining/index.js` `ensureCheckpointPreview`, `client/src/components/loraTraining/CheckpointPicker.jsx`)
- **LoRA training defaults now reflect what actually trains a clean character LoRA on Apple Silicon.** The Train LoRA form previously seeded weak/cautious values (4B base, 600 steps, rank 16, lr 5e-5) — the 4B-first and low-lr choices were leftovers from misdiagnosing an early "divergence" (the real cause was captions over-describing invariant identity, so it bound to words rather than the trigger token, not the learning rate). Validated end-to-end on a 44-image real-face dataset: the form now defaults to **9B base · 1200 steps · rank 32 · lr 1e-4 · 768px · checkpoint/sample every 300**, which binds identity cleanly and fast. The base-model picker prefers the 9B Klein id (it captures identity better than 4B and trains via the panic-safe 4-bit QLoRA tier the server forces) and avoids the heavy `*-bf16` variant. Per-run values remain fully editable in the form. (`server/services/loraTraining/runtimes.js` `TRAINING_DEFAULTS`, `client/src/components/loraTraining/TrainingPanel.jsx`)
@@ -20,4 +24,6 @@
## Fixed
+- **A TUI run whose model id is rejected by the backend now fails (and falls back) instead of returning a screen-scrape of the error.** When a Claude Code TUI run hit a non-recoverable model-id rejection — e.g. a bare Anthropic id like `claude-opus-4-8` passed to a Bedrock-backed Claude Code, which answers `API Error (…): 400 The provided model identifier is invalid` and suggests `global.anthropic.…` — the TUI just sat at an unanswered prompt. The one-shot runner saw output go idle, marked the run `success`, and (no `tui-response.txt` having been written) scraped the error *screen* and returned it as the model's "response." Downstream that surfaced as a baffling failure: AI manuscript Reformat reported `AI reformat changed the wording` (its integrity guard correctly rejecting the screen garbage), while other TUI-backed stages silently consumed the noise. The runner's immediate-fallback detector now recognizes Claude Code's terminal model-id rejection (Bedrock 400 "model identifier is invalid" and Anthropic 404 `not_found_error`) and fails the run as `MODEL_NOT_FOUND`, so `runPromptThroughProvider` benches the provider and retries its configured fallback (e.g. `claude-code-tui` → `claude-code-bedrock`, whose Bedrock ids are valid) — turning a silent corruption into a transparent recovery, or, with no fallback, an actionable error. The signal is anchored on the literal `API Error` + a 400/404 status so an agent merely *printing* the phrase in its own output can't trip it, and only this terminal class fires (a retryable 429/500 Claude Code auto-retries is left alone). (`server/lib/aiToolkit/errorDetection.js`, `server/lib/tuiPromptRunner.js`)
+
- **The "Verify arc" hover tooltip on the series arc page no longer renders behind the nav.** The `VerifyScopeTooltip` panel in `ArcCanvas.jsx` was at `z-30`, which loses to the sidebar nav (`z-50`), so the tooltip's overflow was clipped under the nav. Bumped to `z-[60]` — the layer the app's other floating dropdowns use. (`client/src/components/pipeline/ArcCanvas.jsx`)
diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.js
index 56b8ec9dbe..81761d906d 100644
--- a/server/lib/aiToolkit/errorDetection.js
+++ b/server/lib/aiToolkit/errorDetection.js
@@ -67,7 +67,13 @@ const ERROR_PATTERNS = [
suggestedFix: 'Check API key configuration for this provider'
},
{
- pattern: /model.*(not found|does not exist|unavailable)|invalid model/i,
+ // "model identifier is invalid" is Bedrock's wording when the runner passes
+ // a model id the backend doesn't recognize (e.g. a bare Anthropic id like
+ // `claude-opus-4-8` to a Bedrock-backed Claude Code, which wants
+ // `global.anthropic.claude-opus-4-8`). Categorize it alongside the
+ // not-found/invalid-model phrasings so the cooldown + fallback path treats
+ // it as the config problem it is.
+ pattern: /model.*(not found|does not exist|unavailable)|invalid model|model identifier is invalid/i,
category: ERROR_CATEGORIES.MODEL_NOT_FOUND,
requiresFallback: true,
actionable: true,
@@ -103,6 +109,24 @@ const IMMEDIATE_FALLBACK_SIGNALS = [
category: ERROR_CATEGORIES.USAGE_LIMIT,
message: 'Provider switched to extra usage',
suggestedFix: 'Provider usage limit reached. Using fallback provider or wait for limit reset.'
+ },
+ {
+ // Claude Code renders a non-recoverable *model id* rejection inline as
+ // `API Error (<model>): 400 The provided model identifier is invalid…`
+ // (Bedrock) or `API Error: 404 … not_found_error` (Anthropic) and then sits
+ // at an unanswered prompt — it does NOT auto-retry the way it does a 429/500.
+ // Without an early-fail signal the one-shot TUI runner idles out, reports
+ // success, and scrapes the error screen as a bogus "response" (which then
+ // trips downstream guards like the manuscript-reformat integrity check).
+ // Anchored on the literal `API Error` + a 400/404 status so an agent merely
+ // *printing* the phrase "model identifier is invalid" in its own work output
+ // can't trip it; terminal + model-specific, so failing the run immediately
+ // (to fall back / surface an actionable error) never aborts a run that would
+ // have recovered.
+ pattern: /API Error[^\n]{0,100}\b(?:400|404)\b[^\n]{0,160}(?:model identifier is invalid|not[_\s]?found)/i,
+ category: ERROR_CATEGORIES.MODEL_NOT_FOUND,
+ message: 'Provider rejected the configured model id',
+ suggestedFix: 'The provider does not recognize this model id — check the model name/availability for this provider; retrying with a fallback model.'
}
];
diff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.js
index 56814e2535..7a6bb48ff2 100644
--- a/server/lib/aiToolkit/errorDetection.test.js
+++ b/server/lib/aiToolkit/errorDetection.test.js
@@ -83,6 +83,13 @@ describe('Error Detection', () => {
expect(result.requiresFallback).toBe(true);
});
+ it('classifies a Bedrock "model identifier is invalid" rejection as model-not-found', () => {
+ const result = analyzeError('API Error (claude-opus-4-8): 400 The provided model identifier is invalid.. Try /model to switch to us.anthropic.claude-opus-4-1-20250805-v1:0.');
+ expect(result.hasError).toBe(true);
+ expect(result.category).toBe(ERROR_CATEGORIES.MODEL_NOT_FOUND);
+ expect(result.requiresFallback).toBe(true);
+ });
+
it('should detect network errors', () => {
const result = analyzeError('Error: ECONNREFUSED 127.0.0.1:8080');
expect(result.hasError).toBe(true);
@@ -149,6 +156,35 @@ describe('Error Detection', () => {
requiresFallback: true
});
});
+
+ it('detects Claude Code\'s terminal "model identifier is invalid" (Bedrock 400) error line', () => {
+ const result = detectImmediateFallbackSignal('⏺ API Error (claude-opus-4-8): 400 The provided model identifier is invalid.. Try /model to switch to us.anthropic.claude-opus-4-1-20250805-v1:0.');
+ expect(result).toMatchObject({
+ hasError: true,
+ category: ERROR_CATEGORIES.MODEL_NOT_FOUND,
+ requiresFallback: true
+ });
+ });
+
+ it('detects an Anthropic 404 not_found_error model rejection', () => {
+ const result = detectImmediateFallbackSignal('API Error: 404 {"type":"error","error":{"type":"not_found_error","message":"model: claude-9"}}');
+ expect(result).toMatchObject({
+ hasError: true,
+ category: ERROR_CATEGORIES.MODEL_NOT_FOUND,
+ requiresFallback: true
+ });
+ });
+
+ it('does NOT early-fail a recoverable 429/500 (Claude Code auto-retries those)', () => {
+ expect(detectImmediateFallbackSignal('⏺ API Error (claude-opus-4-8): 429 rate limited, retrying…')).toBeNull();
+ expect(detectImmediateFallbackSignal('⏺ API Error (claude-opus-4-8): 500 internal server error, retrying…')).toBeNull();
+ });
+
+ it('does NOT trip on an agent merely printing the phrase without the API Error prefix', () => {
+ // A CoS agent editing this very fix would print "model identifier is invalid"
+ // in its own output — that must not kill its run.
+ expect(detectImmediateFallbackSignal('The Bedrock backend says the model identifier is invalid when you pass a bare id.')).toBeNull();
+ });
});
describe('extractWaitTime', () => {
diff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.js
index 2b341edd8b..31dcecb59d 100644
--- a/server/lib/tuiPromptRunner.test.js
+++ b/server/lib/tuiPromptRunner.test.js
@@ -680,6 +680,32 @@ describe('executeTuiRun', () => {
}));
});
+ it('early-fails with reason "fallback-signal" when the model id is rejected (Bedrock invalid identifier) instead of idling to a bogus-scrape success', async () => {
+ const provider = { id: 'claude', type: 'tui', command: 'claude' };
+ const onComplete = vi.fn();
+ const promise = executeTuiRun({ runId: 'run-bad-model', provider, prompt: 'a prompt long enough', workspacePath: '/cwd', onData: undefined, onComplete, timeout: 60000 });
+ await flushAsync();
+
+ // Claude Code renders the terminal model-id rejection inline and then sits
+ // idle — without the early-fail signal this would idle-complete as success
+ // and scrape the error screen as the "response".
+ ptyInstances[0].emitData('⏺ API Error (claude-opus-4-8): 400 The provided model identifier is invalid.. Try /model to switch to us.anthropic.claude-opus-4-1-20250805-v1:0.\n');
+
+ await promise;
+ expect(ptyInstances[0].kill).toHaveBeenCalled();
+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({
+ runId: 'run-bad-model',
+ success: false,
+ exitCode: 1,
+ error: expect.stringContaining('model identifier is invalid'),
+ extras: expect.objectContaining({ completionReason: 'fallback-signal' }),
+ }));
+ expect(onComplete).toHaveBeenCalledWith(expect.objectContaining({
+ success: false,
+ completionReason: 'fallback-signal',
+ }));
+ });
+
it('finishes with reason "exit" + exitCode 0 when the PTY closes cleanly', async () => {
const provider = { id: 'claude', type: 'tui', command: 'echo' };
const promise = executeTuiRun({ runId: 'run-exit', provider, prompt: 'a prompt long enough', workspacePath: '/cwd', onData: undefined, onComplete: undefined, timeout: 60000 });
diff --git a/server/services/autoFixer.js b/server/services/autoFixer.js
index a1cdb3c1a6..c34b2ada18 100644
--- a/server/services/autoFixer.js
+++ b/server/services/autoFixer.js
@@ -36,6 +36,14 @@ const inFlightFallbacks = new Set(); // errorKey
// Store pending tasks when CoS is not running (for later pickup)
const pendingAutoFixTasks = [];
+// Collapse a (possibly multi-line) error string to one capped line for logging
+// — the single-line logging convention forbids multi-line blobs; the untruncated
+// text always remains in the run record's `error` field.
+const oneLine = (s, max = 300) => {
+ const t = String(s ?? '').replace(/\s+/g, ' ').trim();
+ return t.length > max ? `${t.slice(0, max - 1)}…` : t;
+};
+
function aiProviderErrorKey(providerName, model) {
// NUL separator: provider names ("Claude Code CLI") and model ids
// ("gpt-4o-mini") both commonly contain `-`, so a `-`-joined key would
@@ -218,7 +226,13 @@ async function handleAIProviderError(error) {
return;
}
- console.log(`🤖 AI provider error detected: ${ctx.provider} - run ${ctx.runId} (deferring ${TASK_DEFER_MS}ms for possible fallback retry)`);
+ // Surface the actual failure reason + category inline so pm2 logs explain
+ // WHY a run failed without spelunking into data/runs/<id>/metadata.json. The
+ // reason is collapsed to a single line and capped (logging convention: no
+ // multi-line blobs) — the full text stays in the run record's `error` field.
+ const reason = oneLine(ctx.errorDetails || ctx.errorAnalysis?.message) || 'no error text captured';
+ const category = ctx.errorAnalysis?.category || 'unknown';
+ console.log(`🤖 AI provider error detected: ${ctx.provider} (${ctx.model}) [${category}] exit=${ctx.exitCode ?? '?'} - run ${ctx.runId}: ${reason} (deferring ${TASK_DEFER_MS}ms for possible fallback retry)`);
const timer = setTimeout(() => {
deferredTasks.delete(errorKey);
diff --git a/server/services/autoFixer.test.js b/server/services/autoFixer.test.js
index 8a54e19a80..2a6bb99c64 100644
--- a/server/services/autoFixer.test.js
+++ b/server/services/autoFixer.test.js
@@ -70,6 +70,35 @@ describe('autoFixer — defer + noteFallbackHandled', () => {
});
});
+ it('logs the actual failure reason + category + exit code inline (not just the provider)', async () => {
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ errorEvents.emit('error', {
+ code: 'AI_PROVIDER_EXECUTION_FAILED',
+ message: 'AI provider Claude Code CLI execution failed: …',
+ severity: 'error',
+ canAutoFix: true,
+ timestamp: Date.now(),
+ context: {
+ runId: 'run-bad-model',
+ provider: 'Claude Code CLI',
+ providerId: 'claude-code',
+ model: 'claude-opus-4-8',
+ exitCode: 1,
+ errorDetails: 'API Error (claude-opus-4-8): 400 The provided model identifier is invalid.',
+ errorAnalysis: { category: 'model-not-found', message: 'API Error (claude-opus-4-8): 400 The provided model identifier is invalid.' },
+ },
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ const line = logSpy.mock.calls.map((c) => c[0]).find((m) => typeof m === 'string' && m.includes('AI provider error detected'));
+ expect(line).toBeTruthy();
+ expect(line).toContain('model identifier is invalid'); // the real reason, inline
+ expect(line).toContain('model-not-found'); // the category
+ expect(line).toContain('exit=1');
+ expect(line).toContain('claude-opus-4-8'); // the model
+ logSpy.mockRestore();
+ });
+
it('never creates an investigation task for a content/safety refusal', async () => {
// A refusal is self-explanatory (the model declined the prompt) — there's
// nothing for a CoS agent to investigate, and the fallback path handles