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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: honor Brain model for Catalog handoffs
Adam Eivy1dbd1fc05dc5
diff --git a/client/src/components/brain/tabs/InboxTab.jsx b/client/src/components/brain/tabs/InboxTab.jsxindex 7e61abdb56..e069de6e82 100644--- a/client/src/components/brain/tabs/InboxTab.jsx+++ b/client/src/components/brain/tabs/InboxTab.jsx@@ -293,7 +293,14 @@ export default function InboxTab({ onRefresh, settings }) {.filter(Boolean).join('\n\n---\n\n');const creativeNoteIds = creativeEntries.map(e => e.id);- navigate('/catalog/ingest', { state: { prefill: { title: 'Creative notes from Brain', rawText, creativeNoteIds } } });+ const prefill = {+ title: 'Creative notes from Brain',+ rawText,+ creativeNoteIds,+ ...(settings?.defaultProvider ? { providerOverride: settings.defaultProvider } : {}),+ ...(settings?.defaultModel ? { modelOverride: settings.defaultModel } : {}),+ };+ navigate('/catalog/ingest', { state: { prefill } });};if (loading) {diff --git a/client/src/components/brain/tabs/InboxTab.test.jsx b/client/src/components/brain/tabs/InboxTab.test.jsxindex cb43735a20..1f3ebf81c2 100644--- a/client/src/components/brain/tabs/InboxTab.test.jsx+++ b/client/src/components/brain/tabs/InboxTab.test.jsx@@ -1,6 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { fireEvent, render, screen, waitFor } from '@testing-library/react';-import { MemoryRouter } from 'react-router';+import { MemoryRouter, useLocation } from 'react-router';vi.mock('../../../services/api', () => ({getBrainInbox: vi.fn(),@@ -47,6 +47,11 @@ vi.mock('../RepoIntakeOptions', () => ({ default: () => null }));import { captureBrainThought, getBrainInbox } from '../../../services/api';import InboxTab from './InboxTab';+function LocationProbe() {+ const location = useLocation();+ return <output data-testid="location-state">{JSON.stringify(location.state || {})}</output>;+}+beforeEach(() => {vi.clearAllMocks();getBrainInbox.mockResolvedValue({ entries: [], counts: {} });@@ -80,4 +85,34 @@ describe('Brain inbox capture', () => {note: 'Share this with the team',});});++ it('carries the Brain provider and model into the creative Catalog handoff', async () => {+ getBrainInbox.mockResolvedValue({+ entries: [{+ id: 'inbox-creative-1',+ capturedText: 'A captured story fragment.',+ creative: true,+ status: 'filed',+ capturedAt: '2026-01-01T00:00:00.000Z',+ }],+ counts: {},+ });++ render(+ <MemoryRouter>+ <InboxTab settings={{ defaultProvider: 'ollama', defaultModel: 'example-model' }} />+ <LocationProbe />+ </MemoryRouter>,+ );++ await waitFor(() => expect(screen.getByRole('button', { name: 'Send to Catalog' })).toBeTruthy());+ fireEvent.click(screen.getByRole('button', { name: 'Send to Catalog' }));++ await waitFor(() => expect(JSON.parse(screen.getByTestId('location-state').textContent)).toMatchObject({+ prefill: expect.objectContaining({+ providerOverride: 'ollama',+ modelOverride: 'example-model',+ }),+ }));+ });});diff --git a/client/src/pages/CatalogIngest.jsx b/client/src/pages/CatalogIngest.jsxindex f9a35ecc5d..8dc334642e 100644--- a/client/src/pages/CatalogIngest.jsx+++ b/client/src/pages/CatalogIngest.jsx@@ -139,6 +139,11 @@ export default function CatalogIngest() {// scrap, so switching to URL/File/Voice (a different scrap) and committing that// never marks the original Brain notes consumed.const creativeNoteScrapIdRef = useRef(null);+ // A Brain inbox handoff carries the Brain-selected route explicitly. The+ // normal Catalog flow remains stage-configured; this route only exists to+ // keep a Brain-selected provider/model from being replaced by a stale+ // catalog stage pin.+ const brainRouteRef = useRef(null);// Stop the mic if the page unmounts mid-recording (navigating away), so the// MediaRecorder stream isn't left live with no UI to stop it.@@ -217,6 +222,7 @@ export default function CatalogIngest() {// a later commit of unrelated text must NOT mark the original notes consumed.creativeNoteIdsRef.current = [];creativeNoteScrapIdRef.current = null;+ brainRouteRef.current = null;recorderRef.current?.cancel?.();recorderRef.current = null;setRecording(false);@@ -281,7 +287,7 @@ export default function CatalogIngest() {if (creativeNoteIdsRef.current.length) creativeNoteScrapIdRef.current = created.scrap.id;const result = await (babble? pruneCatalogScrap(created.scrap.id, { providerId: picker.selectedProviderId, model: picker.selectedModel, ...(effort ? { effort } : {}) }, { silent: true })- : extractFromCatalogScrap(created.scrap.id, {}, { silent: true }))+ : extractFromCatalogScrap(created.scrap.id, brainRouteRef.current || {}, { silent: true })).catch((err) => { toast.error(err?.message || 'Extraction failed'); return null; });setSubmitting(false);enterReviewFromResult(result, babble ? 'babble' : 'paste');@@ -315,9 +321,9 @@ export default function CatalogIngest() {// Handle inbound router-state handoffs once on mount:// - brainIngest { brainType, brainId } → run the brain-bridge extract→review.- // - prefill { title, rawText } → drop the text into the paste box so- // the user reviews/edits it, then clicks Extract (the creative-notes batch- // send from the brain inbox uses this).+ // - prefill { title, rawText, providerOverride?, modelOverride? } → drop the+ // text into the paste box and retain an explicit Brain route for the+ // eventual extraction (the creative-notes batch send uses this).// Either way we clear the history state afterwards so a refresh/back doesn't// re-trigger the handoff (and, for brainIngest, a second LLM-billed run).useEffect(() => {@@ -333,6 +339,10 @@ export default function CatalogIngest() {setSourceMode('paste');setTitle(prefill.title || '');setRawText(prefill.rawText);+ brainRouteRef.current = {+ ...(prefill.providerOverride ? { providerOverride: prefill.providerOverride } : {}),+ ...(prefill.modelOverride ? { modelOverride: prefill.modelOverride } : {}),+ };if (Array.isArray(prefill.creativeNoteIds)) {creativeNoteIdsRef.current = prefill.creativeNoteIds.filter(Boolean);}diff --git a/client/src/pages/CatalogIngest.test.jsx b/client/src/pages/CatalogIngest.test.jsxindex fece642ca0..2c1d87a4f1 100644--- a/client/src/pages/CatalogIngest.test.jsx+++ b/client/src/pages/CatalogIngest.test.jsx@@ -2,12 +2,12 @@ import { it, expect, vi } from 'vitest';import { render, screen, fireEvent, waitFor } from '@testing-library/react';import { MemoryRouter } from 'react-router';import CatalogIngest from './CatalogIngest';-import { createCatalogScrap, pruneCatalogScrap, commitCatalogScrapDraft, ingestCatalogBrain } from '../services/apiCatalog';+import { createCatalogScrap, extractFromCatalogScrap, pruneCatalogScrap, commitCatalogScrapDraft, ingestCatalogBrain } from '../services/apiCatalog';import { listUniverseNames } from '../services/apiUniverseBuilder';vi.mock('../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));vi.mock('../hooks/useProviderModels', () => ({ default: () => ({ providers: [], selectedProviderId: 'example-provider', selectedModel: 'example-model', availableModels: [], loading: false }) }));vi.mock('../components/ProviderModelSelector', () => ({ default: ({ onEffortChange }) => <button type="button" onClick={() => onEffortChange('high')}>High effort</button> }));-vi.mock('../services/apiCatalog', () => ({ createCatalogScrap: vi.fn(), pruneCatalogScrap: vi.fn(), commitCatalogScrapDraft: vi.fn(), ingestCatalogBrain: vi.fn() }));+vi.mock('../services/apiCatalog', () => ({ createCatalogScrap: vi.fn(), extractFromCatalogScrap: vi.fn(), pruneCatalogScrap: vi.fn(), commitCatalogScrapDraft: vi.fn(), ingestCatalogBrain: vi.fn() }));vi.mock('../services/apiUniverseBuilder', () => ({ listUniverseNames: vi.fn().mockResolvedValue([]) }));it('prunes only on request, keeps the brainstorm, and saves edited selected suggestions', async () => {createCatalogScrap.mockResolvedValue({ scrap: { id: 'example-scrap' } });@@ -28,6 +28,39 @@ it('prunes only on request, keeps the brainstorm, and saves edited selected suggawait waitFor(() => expect(commitCatalogScrapDraft).toHaveBeenCalledWith('example-scrap', [expect.objectContaining({ name: 'The lost moon', type: 'idea' })], expect.anything()));});+it('carries the Brain-selected provider and model into a creative inbox handoff', async () => {+ createCatalogScrap.mockResolvedValue({ scrap: { id: 'brain-notes-scrap' } });+ extractFromCatalogScrap.mockResolvedValue({+ scrap: { id: 'brain-notes-scrap' },+ draft: { ideas: [{ name: 'A captured idea', summary: 'A useful fragment.' }] },+ });++ render(+ <MemoryRouter initialEntries={[{+ pathname: '/catalog/ingest',+ state: {+ prefill: {+ title: 'Creative notes from Brain',+ rawText: 'A captured idea.',+ providerOverride: 'ollama',+ modelOverride: 'example-model',+ },+ },+ }]}>+ <CatalogIngest />+ </MemoryRouter>,+ );++ await screen.findByDisplayValue('A captured idea.');+ fireEvent.click(screen.getByRole('button', { name: 'Ingest' }));++ await waitFor(() => expect(extractFromCatalogScrap).toHaveBeenCalledWith(+ 'brain-notes-scrap',+ { providerOverride: 'ollama', modelOverride: 'example-model' },+ expect.anything(),+ ));+});+// Regression (#7615): the brain-bridge handoff runs from the mount effect, so// reading the universe list out of component STATE there captures the// pre-load empty array and the capture-source Reality default never resolves —diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.jsindex b9b8ea31ff..0d778e589c 100644--- a/server/lib/catalogValidation.js+++ b/server/lib/catalogValidation.js@@ -416,10 +416,11 @@ export const catalogScrapCommitSchema = z.object({role: z.string().trim().min(1).max(64).optional(),}).strict();-// /scraps/:id/extract — optional provider override (e.g., force a specific-// LLM provider for this extraction). Empty body is valid.+// /scraps/:id/extract — optional provider/model override (e.g., a Brain+// handoff carrying the user's selected local route). Empty body is valid.export const catalogExtractRequestSchema = z.object({providerOverride: z.string().trim().min(1).max(64).optional(),+ modelOverride: z.string().trim().min(1).max(200).optional(),}).strict();// Babble is deliberately bounded to one provider call; never silently truncate it.diff --git a/server/routes/catalog.js b/server/routes/catalog.jsindex 2d53da02b8..e3ecbc915b 100644--- a/server/routes/catalog.js+++ b/server/routes/catalog.js@@ -114,6 +114,7 @@ router.post('/scraps/:id/extract', asyncHandler(async (req, res) => {const draft = await extractIngredientsForScrap({scrapId: scrap.id,providerOverride: body.providerOverride,+ modelOverride: body.modelOverride,});res.json({ scrap, draft });}));diff --git a/server/services/catalogExtraction.js b/server/services/catalogExtraction.jsindex 7721854404..972f938829 100644--- a/server/services/catalogExtraction.js+++ b/server/services/catalogExtraction.js@@ -179,13 +179,14 @@ function sanitizeLightEntry(kind, raw) {* malformed response logs and yields empty arrays, mirroring extractBible's* sanitizeBibleList tolerance for missing keys.*/-async function extractIdeasScenesConcepts({ corpus, providerOverride, promptContext = {} }) {+async function extractIdeasScenesConcepts({ corpus, providerOverride, modelOverride, promptContext = {} }) {const result = await runStagedLLM('catalog-ideas-scenes-concepts', {...promptContext,draftBody: corpus,returnsJson: true,}, {providerOverride,+ modelOverride,returnsJson: true,source: 'catalog-extract-ideas-scenes-concepts',});@@ -211,6 +212,7 @@ async function extractIdeasScenesConcepts({ corpus, providerOverride, promptCont* @param {string} args.rawText The scrap body to extract from.* @param {string} [args.scrapId] Scrap id to attach to progress frames.* @param {string} [args.providerOverride] Override the staged-llm provider.+ * @param {string} [args.modelOverride] Override the staged-llm model.* @param {object} [args.context] Extraction lens — `{ title, sourceKind, factual }`* from `scrapExtractionContext`. Fills the prompts'* framing slots and gates the factual sections.@@ -249,7 +251,7 @@ function neutralizeFenceDelimiters(text) {// omitted, a fresh runId is minted (the normal single-scrap path). `emitStart`// lets the chunked path suppress the per-child `start` frame, which would// otherwise reset the client's stage checklist on every chunk.-export async function extractIngredients({ rawText, scrapId = null, providerOverride, runId = randomUUID(), emitStart = true, context = {} } = {}) {+export async function extractIngredients({ rawText, scrapId = null, providerOverride, modelOverride, runId = randomUUID(), emitStart = true, context = {} } = {}) {if (typeof rawText !== 'string' || !rawText.trim()) {throw new Error('extractIngredients: rawText is required');}@@ -287,7 +289,7 @@ export async function extractIngredients({ rawText, scrapId = null, providerOveremit({ type: 'stage', id: stage.id, status: 'running' });try {if (stage.id === LIGHT_STAGE_ID) {- const out = await extractIdeasScenesConcepts({ corpus, providerOverride, promptContext });+ const out = await extractIdeasScenesConcepts({ corpus, providerOverride, modelOverride, promptContext });const count = LIGHT_TYPE_IDS.reduce((n, id) => n + (out[lightDraftKey(id)]?.length || 0), 0);emit({ type: 'stage', id: stage.id, status: 'completed', count });return { id: stage.id, light: out, error: null };@@ -298,6 +300,7 @@ export async function extractIngredients({ rawText, scrapId = null, providerOverexisting: [],context: promptContext,providerOverride,+ modelOverride,source: `catalog-extract-${stage.id}`,});// A real person additionally earns `real-person`, which is what keeps@@ -411,8 +414,9 @@ const CHUNK_EXTRACT_CONCURRENCY = 2;* @param {object} args* @param {string} args.scrapId Parent scrap id.* @param {string} [args.providerOverride] Override the staged-llm provider.+ * @param {string} [args.modelOverride] Override the staged-llm model.*/-export async function extractIngredientsForScrap({ scrapId, providerOverride } = {}) {+export async function extractIngredientsForScrap({ scrapId, providerOverride, modelOverride } = {}) {const parent = await getScrap(scrapId);if (!parent) throw new Error(`extractIngredientsForScrap: scrap ${scrapId} not found`);@@ -423,7 +427,7 @@ export async function extractIngredientsForScrap({ scrapId, providerOverride } =const children = await listChildScraps(parent.id);if (children.length === 0) {- return extractIngredients({ rawText: parent.rawText, scrapId: parent.id, providerOverride, context });+ return extractIngredients({ rawText: parent.rawText, scrapId: parent.id, providerOverride, modelOverride, context });}// One shared run id for the whole chunked extraction so every child's@@ -444,7 +448,7 @@ export async function extractIngredientsForScrap({ scrapId, providerOverride } =// union the per-child drafts. Progress frames carry the parent scrapId + the// shared runId so the UI's existing live checklist keeps tracking one scrap.const childDrafts = await mapWithConcurrency(children, CHUNK_EXTRACT_CONCURRENCY, (child) =>- extractIngredients({ rawText: child.rawText, scrapId: parent.id, providerOverride, runId, emitStart: false, context }),+ extractIngredients({ rawText: child.rawText, scrapId: parent.id, providerOverride, modelOverride, runId, emitStart: false, context }),);const merged = dedupDrafts(childDrafts);diff --git a/server/services/catalogExtraction.test.js b/server/services/catalogExtraction.test.jsindex d031875b1f..9d347ce77b 100644--- a/server/services/catalogExtraction.test.js+++ b/server/services/catalogExtraction.test.js@@ -131,17 +131,18 @@ describe('catalogExtraction — extractIngredients', () => {}});- it('forwards providerOverride to every stage', async () => {+ it('forwards the provider and model overrides to every stage', async () => {bibleExtractor.extractBible.mockResolvedValue({ extracted: [] });- await extractIngredients({ rawText: 'prose', providerOverride: 'codex' });+ await extractIngredients({ rawText: 'prose', providerOverride: 'ollama', modelOverride: 'example-model' });for (const call of bibleExtractor.extractBible.mock.calls) {- expect(call[0].providerOverride).toBe('codex');+ expect(call[0].providerOverride).toBe('ollama');+ expect(call[0].modelOverride).toBe('example-model');}- // The light stage also receives the override (third positional arg).+ // The light stage receives the same route (third positional arg).expect(stageRunner.runStagedLLM).toHaveBeenCalledWith('catalog-ideas-scenes-concepts',expect.any(Object),- expect.objectContaining({ providerOverride: 'codex' }),+ expect.objectContaining({ providerOverride: 'ollama', modelOverride: 'example-model' }),);});