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
let Brain config pick the embedding provider/model and reprocess on demand
[._.]/ Adam Eivy3bda7736eee2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b3006cbe48..2ce83422ac 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **Choose your embedding provider + model in Brain config, and reprocess on demand** — Memory's semantic search (pgvector) was hardwired to LM Studio with a fixed embedding model name, so an install running **Ollama** got silent embedding failures — records imported/captured fine but landed with a NULL embedding (unsearchable), and there was no UI to point embeddings elsewhere. Brain → Config gains an **Embeddings (semantic search)** card: pick the embedding **provider** (any OpenAI-compatible backend — Ollama, LM Studio, …) and **model** (e.g. `nomic-embed-text` on Ollama, 768-dim — matches the `vector(768)` column), with a live reachability/model-present status line and a **Reprocess all embeddings** button that re-embeds every brain record (the existing `bridge-sync?refresh` path, which drains sequentially in the background). The embedding service is now **provider-aware**: the LM-Studio-only model discover/load dance (`/api/v0/models` + `/api/v1/models/load`) is skipped for other backends (which serve `/v1/embeddings` directly and don't implement those endpoints — previously it 404'd every call and never latched), and a non-LM-Studio provider's configured model id is authoritative instead of being guessed from a substring match. (`server/services/memoryEmbeddings.js`, `client/src/components/brain/tabs/ConfigTab.jsx`)+- **Import your whole ChatGPT export — images, voice clips, and files included** — The Brain → Import ChatGPT wizard now takes the **entire export `.zip`** instead of just `conversations.json`, removing the old 50 MB upload cap (the JSON was parsed in the browser and POSTed as a body; the ZIP streams straight to your PortOS like the Apple Health importer, with no size limit). It handles the **modern multi-file export** (conversations split across `conversations-NNN.json` shards) and **extracts every asset** — the `.dat` image / voice-audio / PDF files — into a served directory, sniffing each file's real type from its magic bytes and naming it from the export's asset map. Each conversation's archived transcript is rendered as **markdown with inline images** (`image_asset_pointer` parts resolve to the extracted image), plus `🔊`/`🎙️` links for voice clips and `📎` links for attached files; assets ChatGPT omitted from the export degrade to a plain placeholder rather than a broken link. Imported conversations render rich in Brain → Memory with a **View full conversation** viewer (the Memory entry keeps a truncated preview; the full thread + assets live in the archive). A lone `conversations.json` still works as before (just without images). (`server/services/chatgptZipImport.js`, `server/services/chatgptImport.js`, `server/routes/brainImport.js`, `server/lib/fileUtils.js`, `server/index.js`, `client/src/components/brain/tabs/ImportTab.jsx`, `client/src/components/brain/tabs/MemoryTab.jsx`, `client/src/components/brain/ConversationViewer.jsx`, `client/src/components/cos/MarkdownOutput.jsx`, `client/src/services/apiBrain.js`)- **Jump to the Importer from the Series Pipeline — with the universe & series carried over** — Starting a series and realizing you already have a manuscript no longer means hunting for the Importer. The Series Pipeline index gains an **Import** button beside **New Series**, the create form carries an inline "Already have a manuscript? **Import it instead**" link (deep-linking your in-progress universe + typed series name), and a series detail page gains an **Import** action that opens the Importer pre-targeted at *that* universe and series. The Importer's **Universe Name** and **Series Name** fields are now **autocomplete comboboxes** — the same match-or-create UX as the Universe creator — so you land an exact match instead of guessing the spelling; the series picker is scoped to the matched universe (its existing series, or type a new name). Deep links resolve via `?universeId=…&seriesId=…` (with raw `universe`/`series` name params as a fallback), where a `seriesId` also pins its parent universe so the pair can't drift. The autocomplete itself is extracted into a shared `EntityCombobox` (the Universe creator's selector now wraps it). (`client/src/components/EntityCombobox.jsx`, `client/src/pages/Importer.jsx`, `client/src/pages/Pipeline.jsx`, `client/src/pages/PipelineSeries.jsx`, `client/src/pages/UniverseBuilder.jsx`)diff --git a/client/src/components/brain/tabs/ConfigTab.jsx b/client/src/components/brain/tabs/ConfigTab.jsxindex 1709938ea7..eec48f594a 100644--- a/client/src/components/brain/tabs/ConfigTab.jsx+++ b/client/src/components/brain/tabs/ConfigTab.jsx@@ -7,7 +7,10 @@ import {Settings,Clock,Calendar,TrendingUp,- CheckCircle} from 'lucide-react';+ CheckCircle,+ Database,+ AlertTriangle,+ RefreshCw} from 'lucide-react';import BrailleSpinner from '../../BrailleSpinner';import toast from '../../ui/Toast';@@ -32,15 +35,27 @@ export default function ConfigTab({ onRefresh }) {const [dailyDigestTime, setDailyDigestTime] = useState('09:00');const [weeklyReviewDay, setWeeklyReviewDay] = useState('sunday');const [weeklyReviewTime, setWeeklyReviewTime] = useState('16:00');+ // Embedding config lives in CoS config (embeddingProviderId/embeddingModel),+ // separate from the brain settings above — it drives semantic search /+ // pgvector, not classification.+ const [embeddingProvider, setEmbeddingProvider] = useState('');+ const [embeddingModel, setEmbeddingModel] = useState('');+ const [savedEmbeddingProvider, setSavedEmbeddingProvider] = useState('');+ const [savedEmbeddingModel, setSavedEmbeddingModel] = useState('');+ const [embeddingStatus, setEmbeddingStatus] = useState(null);+ const [savingEmbedding, setSavingEmbedding] = useState(false);+ const [reprocessing, setReprocessing] = useState(false);useEffect(() => {fetchData();}, []);const fetchData = async () => {- const [settingsData, providersData] = await Promise.all([+ const [settingsData, providersData, cosConfig, embStatus] = await Promise.all([api.getBrainSettings().catch(() => null),- api.getProviders().catch(() => ({ providers: [] }))+ api.getProviders().catch(() => ({ providers: [] })),+ api.getCosConfig().catch(() => null),+ api.getEmbeddingStatus().catch(() => null)]);if (settingsData) {@@ -57,9 +72,60 @@ export default function ConfigTab({ onRefresh }) {setProviders(providersData.providers || []);}+ if (cosConfig) {+ setEmbeddingProvider(cosConfig.embeddingProviderId || '');+ setEmbeddingModel(cosConfig.embeddingModel || '');+ setSavedEmbeddingProvider(cosConfig.embeddingProviderId || '');+ setSavedEmbeddingModel(cosConfig.embeddingModel || '');+ }+ if (embStatus) setEmbeddingStatus(embStatus);+setLoading(false);};+ const refreshEmbeddingStatus = async () => {+ const embStatus = await api.getEmbeddingStatus().catch(() => null);+ if (embStatus) setEmbeddingStatus(embStatus);+ };++ // Models offered for the EMBEDDING provider. We don't filter to "embed"-named+ // models — provider model lists vary — but surface the whole selectable list+ // so the user can pick e.g. nomic-embed-text on Ollama.+ const getEmbeddingModels = () => {+ if (!embeddingProvider) return [];+ const provider = providers.find(p => p.id === embeddingProvider);+ return filterSelectableModels(provider?.models);+ };++ const embeddingDirty = () =>+ embeddingProvider !== savedEmbeddingProvider || embeddingModel !== savedEmbeddingModel;++ const handleSaveEmbedding = async () => {+ setSavingEmbedding(true);+ const result = await api+ .updateCosConfig({ embeddingProviderId: embeddingProvider, embeddingModel })+ .catch(err => { toast.error(err.message || 'Failed to save embedding config'); return null; });+ setSavingEmbedding(false);+ if (result) {+ setSavedEmbeddingProvider(embeddingProvider);+ setSavedEmbeddingModel(embeddingModel);+ toast.success('Embedding config saved');+ // The server reinitializes embeddings on this PUT — re-probe availability.+ await refreshEmbeddingStatus();+ }+ };++ const handleReprocess = async () => {+ setReprocessing(true);+ const result = await api+ .syncBrainData({ refresh: true }, { silent: true })+ .catch(err => { toast.error(err.message || 'Reprocess failed'); return null; });+ setReprocessing(false);+ if (result) {+ toast.success(`Reprocessed embeddings: ${result.synced} synced, ${result.skipped} skipped, ${result.errors} errors`);+ }+ };+const handleSave = async () => {setSaving(true);@@ -217,6 +283,120 @@ export default function ConfigTab({ onRefresh }) {</div></section>+ {/* Embedding Provider & Model — drives semantic search (pgvector). This+ is a SEPARATE provider/model from the classification one above; many+ installs run classification on a chat model and embeddings on a small+ dedicated embedding model (e.g. Ollama nomic-embed-text). */}+ <section className="p-4 bg-port-card border border-port-border rounded-lg space-y-4">+ <div className="flex items-center gap-2 mb-1">+ <Database className="w-5 h-5 text-port-accent" />+ <h3 className="text-md font-semibold text-white">Embeddings (semantic search)</h3>+ </div>++ {/* Live backend status */}+ {embeddingStatus && (+ embeddingStatus.available && embeddingStatus.modelPresent !== false ? (+ <div className="flex items-center gap-2 text-xs text-port-success">+ <CheckCircle size={14} />+ <span>Reachable — model <span className="font-mono">{embeddingStatus.embeddingModel || '—'}</span></span>+ </div>+ ) : (+ <div className="flex items-start gap-2 text-xs text-port-warning">+ <AlertTriangle size={14} className="mt-0.5 flex-shrink-0" />+ <span>+ {embeddingStatus.available+ ? `Backend reachable but model "${embeddingModel}" isn't available there — pick an installed model (e.g. nomic-embed-text on Ollama).`+ : `Embedding backend unreachable: ${embeddingStatus.error || 'unknown error'}`}+ </span>+ </div>+ )+ )}++ <div className="space-y-4">+ {/* Embedding Provider */}+ <div>+ <label htmlFor="embeddingProvider" className="block text-sm font-medium text-gray-300 mb-2">+ Embedding Provider+ </label>+ <select+ id="embeddingProvider"+ value={embeddingProvider}+ onChange={(e) => {+ setEmbeddingProvider(e.target.value);+ const np = providers.find(p => p.id === e.target.value);+ const models = filterSelectableModels(np?.models);+ // Prefer an embedding-named model if the provider lists one.+ const embed = models.find(m => /embed|nomic|bge|minilm|mxbai/i.test(m));+ setEmbeddingModel(embed || np?.defaultModel || models[0] || '');+ }}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:outline-hidden focus:ring-2 focus:ring-port-accent"+ >+ <option value="">Select a provider...</option>+ {providers.map(provider => (+ <option key={provider.id} value={provider.id}>+ {provider.name} ({provider.type})+ </option>+ ))}+ </select>+ <p className="mt-1 text-xs text-gray-500">+ Backend that generates vector embeddings (must serve an OpenAI-compatible <span className="font-mono">/v1/embeddings</span>)+ </p>+ </div>++ {/* Embedding Model */}+ <div>+ <label htmlFor="embeddingModel" className="block text-sm font-medium text-gray-300 mb-2">+ Embedding Model+ </label>+ <select+ id="embeddingModel"+ value={embeddingModel}+ onChange={(e) => setEmbeddingModel(e.target.value)}+ disabled={!embeddingProvider || getEmbeddingModels().length === 0}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:outline-hidden focus:ring-2 focus:ring-port-accent disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {getEmbeddingModels().length === 0 ? (+ <option value="">No models available</option>+ ) : (+ <>+ <option value="">Select a model...</option>+ {getEmbeddingModels().map(model => (+ <option key={model} value={model}>{model}</option>+ ))}+ </>+ )}+ </select>+ <p className="mt-1 text-xs text-gray-500">+ Changing the model can change vector dimensions — reprocess after switching so all entries share one space.+ </p>+ </div>++ {/* Save + Reprocess */}+ <div className="flex flex-wrap items-center gap-2 pt-1">+ <button+ onClick={handleSaveEmbedding}+ disabled={!embeddingDirty() || savingEmbedding}+ className="flex items-center gap-2 px-3 py-2 bg-port-accent text-white rounded-lg text-sm hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {savingEmbedding ? <BrailleSpinner /> : <Save size={14} />}+ Save embedding config+ </button>+ <button+ onClick={handleReprocess}+ disabled={reprocessing || embeddingDirty()}+ title={embeddingDirty() ? 'Save the embedding config first' : 'Re-embed every brain record'}+ className="flex items-center gap-2 px-3 py-2 bg-port-bg border border-port-border text-white rounded-lg text-sm hover:bg-port-card disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {reprocessing ? <BrailleSpinner /> : <RefreshCw size={14} />}+ Reprocess all embeddings+ </button>+ </div>+ <p className="text-xs text-gray-500">+ Reprocess re-embeds every brain record (memories, people, projects, ideas, daily log) — run it after importing or switching models. It drains sequentially in the background.+ </p>+ </div>+ </section>+{/* Classification Settings */}<section className="p-4 bg-port-card border border-port-border rounded-lg space-y-4"><div className="flex items-center gap-2 mb-4">diff --git a/server/services/memoryEmbeddings.js b/server/services/memoryEmbeddings.jsindex 8f57c71936..4f7b021aee 100644--- a/server/services/memoryEmbeddings.js+++ b/server/services/memoryEmbeddings.js@@ -29,10 +29,24 @@ function getBaseUrl(config) {/*** Discover and auto-load an embedding model in LM Studio.* Uses the REST API to find downloaded embedding models and load one if needed.+ *+ * This dance is LM-Studio-specific: LM Studio lazy-loads models and exposes a+ * native `/api/v0/models` + `/api/v1/models/load` API to discover and pin one.+ * Other OpenAI-compatible embedding backends (Ollama, etc.) serve+ * `/v1/embeddings` directly with no load step and don't implement those+ * endpoints — so for them we skip the dance and trust the configured model id.+ * Without this guard, an Ollama-backed config would 404 the LMS-only URLs on+ * every call (modelEnsured never latches → repeated failed probes per embed).*/async function ensureEmbeddingModelLoaded(config) {if (modelEnsured) return;+ // Only LM Studio needs (and implements) the discover-and-load dance.+ if (config.embeddingProvider !== 'lmstudio') {+ modelEnsured = true;+ return;+ }+const baseUrl = getBaseUrl(config);// Query LM Studio's native API for all downloaded models@@ -110,10 +124,15 @@ async function initConfig() {: `${provider.endpoint}/v1/embeddings`;embeddingConfig = {...DEFAULT_MEMORY_CONFIG,+ // Track which provider backs embeddings so the LM-Studio-only model+ // auto-load dance (ensureEmbeddingModelLoaded) is skipped for others.+ embeddingProvider: providerId,embeddingEndpoint: endpoint,+ // The model id MUST come from config for a non-LM-Studio provider: the+ // DEFAULT model is an LM Studio model name that Ollama doesn't have....(configModel ? { embeddingModel: configModel } : {})};- console.log(`📚 Memory embeddings using provider ${providerId}: ${endpoint}`);+ console.log(`📚 Memory embeddings using provider ${providerId} (model: ${embeddingConfig.embeddingModel}): ${endpoint}`);}}@@ -132,7 +151,9 @@ export function setEmbeddingConfig(config) {}/**- * Check if LM Studio is available and ensure embedding model is loaded+ * Check if the embedding backend is reachable and an embedding model is usable.+ * Works for any OpenAI-compatible backend (LM Studio, Ollama, …) — all serve+ * `GET /v1/models`.*/export async function checkAvailability() {await initConfig();@@ -144,13 +165,29 @@ export async function checkAvailability() {}).catch(err => ({ ok: false, _err: err.message }));if (!response.ok) {- return { available: false, error: response._err || `LM Studio returned ${response.status}`, endpoint: config.embeddingEndpoint };+ return { available: false, error: response._err || `Embedding backend returned ${response.status}`, endpoint: config.embeddingEndpoint };}const data = await readResponseJson(response);const models = data.data?.map(m => m.id) || [];- // If no embedding models are loaded, try to auto-load one+ // For a non-LM-Studio provider (Ollama, etc.) the configured model id is+ // authoritative — don't guess from `.includes('embed')` (it could latch onto+ // the wrong listed model). Just confirm it's present; the load dance is a+ // no-op for these backends.+ if (config.embeddingProvider !== 'lmstudio') {+ modelEnsured = true;+ const present = models.some(id => id === config.embeddingModel || id.startsWith(`${config.embeddingModel}:`));+ return {+ available: true,+ models,+ embeddingModel: config.embeddingModel,+ modelPresent: present,+ endpoint: config.embeddingEndpoint+ };+ }++ // LM Studio: if no embedding model is loaded, try to auto-load one.const hasEmbeddingModel = models.some(id => id.includes('embed'));if (!hasEmbeddingModel) {await ensureEmbeddingModelLoaded(config).catch(err =>diff --git a/server/services/memoryEmbeddings.test.js b/server/services/memoryEmbeddings.test.jsnew file mode 100644index 0000000000..dcbd7f5e7b--- /dev/null+++ b/server/services/memoryEmbeddings.test.js@@ -0,0 +1,99 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++// Mocks for the config sources memoryEmbeddings reads in initConfig().+const getCosConfig = vi.fn();+const getProviderById = vi.fn();++vi.mock('./cos.js', () => ({ getConfig: getCosConfig }));+vi.mock('./providers.js', () => ({ getProviderById }));+// memoryBackend pulls in the DB; stub it to just the default config export.+vi.mock('./memoryBackend.js', () => ({+ DEFAULT_MEMORY_CONFIG: {+ embeddingProvider: 'lmstudio',+ embeddingEndpoint: 'http://localhost:1234/v1/embeddings',+ embeddingModel: 'text-embedding-nomic-embed-text-v2-moe',+ embeddingDimension: 768,+ },+}));++let embeddings;+let fetchSpy;++beforeEach(async () => {+ vi.resetModules();+ vi.clearAllMocks();+ embeddings = await import('./memoryEmbeddings.js');+ embeddings.reinitialize(); // clear cached config between tests+});++afterEach(() => {+ fetchSpy?.mockRestore();+});++// Build a fake `GET /v1/models` response. readResponseJson() reads the body via+// `.text()` (it tolerates non-JSON), so the payload must be the JSON string.+const mockModelsResponse = (ids) => {+ const body = JSON.stringify({ data: ids.map((id) => ({ id })) });+ return { ok: true, json: async () => JSON.parse(body), text: async () => body };+};++describe('memoryEmbeddings — provider-aware config (Ollama vs LM Studio)', () => {+ it('uses the configured model for a non-LM-Studio provider and reports modelPresent', async () => {+ getCosConfig.mockResolvedValue({ embeddingProviderId: 'ollama', embeddingModel: 'nomic-embed-text' });+ getProviderById.mockResolvedValue({ id: 'ollama', endpoint: 'http://localhost:11434/v1' });+ // Ollama's /v1/models lists installed models tagged with :latest.+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ mockModelsResponse(['nomic-embed-text:latest', 'llama3.2:latest'])+ );++ const status = await embeddings.checkAvailability();++ // Probed /v1/models on the OLLAMA endpoint, not LM Studio's :1234.+ expect(fetchSpy).toHaveBeenCalledWith(+ 'http://localhost:11434/v1/models',+ expect.objectContaining({ method: 'GET' })+ );+ expect(status.available).toBe(true);+ // Configured model is authoritative (not guessed from `.includes('embed')`).+ expect(status.embeddingModel).toBe('nomic-embed-text');+ // ':latest'-tagged install counts as present.+ expect(status.modelPresent).toBe(true);+ });++ it('flags modelPresent:false when the configured model is not installed on the provider', async () => {+ getCosConfig.mockResolvedValue({ embeddingProviderId: 'ollama', embeddingModel: 'mxbai-embed-large' });+ getProviderById.mockResolvedValue({ id: 'ollama', endpoint: 'http://localhost:11434/v1' });+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ mockModelsResponse(['nomic-embed-text:latest'])+ );++ const status = await embeddings.checkAvailability();++ expect(status.available).toBe(true);+ expect(status.modelPresent).toBe(false);+ });++ it('does NOT hit LM Studio model-load endpoints for a non-LM-Studio provider', async () => {+ getCosConfig.mockResolvedValue({ embeddingProviderId: 'ollama', embeddingModel: 'nomic-embed-text' });+ getProviderById.mockResolvedValue({ id: 'ollama', endpoint: 'http://localhost:11434/v1' });+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockModelsResponse(['nomic-embed-text:latest']));++ await embeddings.checkAvailability();++ // The LM-Studio-only discover/load dance (/api/v0/models, /api/v1/models/load)+ // must never be called for Ollama.+ const urls = fetchSpy.mock.calls.map((c) => c[0]);+ expect(urls.some((u) => u.includes('/api/v0/models'))).toBe(false);+ expect(urls.some((u) => u.includes('/api/v1/models/load'))).toBe(false);+ });++ it('reports unreachable when the embedding backend GET fails', async () => {+ getCosConfig.mockResolvedValue({ embeddingProviderId: 'ollama', embeddingModel: 'nomic-embed-text' });+ getProviderById.mockResolvedValue({ id: 'ollama', endpoint: 'http://localhost:11434/v1' });+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: false, status: 503, _err: undefined });++ const status = await embeddings.checkAvailability();+ expect(status.available).toBe(false);+ expect(status.error).toContain('503');+ });+});