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
feat: Grok-box free local Persistent Mind setup (Ollama + Qwen2.5 7B)
atomanticagent5c2c8830ba88
diff --git a/client/src/components/cos/PersistentMindProfileControls.jsx b/client/src/components/cos/PersistentMindProfileControls.jsxindex 1787982f5c..0a08aa2581 100644--- a/client/src/components/cos/PersistentMindProfileControls.jsx+++ b/client/src/components/cos/PersistentMindProfileControls.jsx@@ -6,6 +6,7 @@ import { modelCapabilityInfo } from '../../utils/providers.js';import ModelCapabilitySummary from '../models/ModelCapabilitySummary.jsx';import ProviderModelSelector from '../ProviderModelSelector';import toast from '../ui/Toast';+import LocalPersistentMindSetupCard from '../settings/LocalPersistentMindSetupCard.jsx';const DEFAULT_PROFILE = {schemaVersion: 1,@@ -156,6 +157,19 @@ export default function PersistentMindProfileControls({return (<div className="space-y-3">+ <LocalPersistentMindSetupCard+ compact+ onApplied={(result) => {+ if (!result?.profile) return;+ const next = normalizeProfile(result.profile);+ draftRef.current = next;+ publishedProfileRef.current = next;+ setDraft(next);+ setSelectedProviderId(next.providerId);+ setSelectedModel(next.model);+ onSaved?.(next);+ }}+ /><div className="flex items-start justify-between gap-4"><div><label htmlFor={enabledId} className="text-sm text-port-text">Enable persistent mind profile</label>diff --git a/client/src/components/settings/LocalLlmRuntimesView.jsx b/client/src/components/settings/LocalLlmRuntimesView.jsxindex 44481c8e15..a23efdacb1 100644--- a/client/src/components/settings/LocalLlmRuntimesView.jsx+++ b/client/src/components/settings/LocalLlmRuntimesView.jsx@@ -14,6 +14,7 @@ import RuntimeServersCard from './RuntimeServersCard.jsx';import MtplxServerCard from './MtplxServerCard.jsx';import SlotstreamServerCard from './SlotstreamServerCard.jsx';import HardwareLlmRecommendation from './HardwareLlmRecommendation.jsx';+import LocalPersistentMindSetupCard from './LocalPersistentMindSetupCard.jsx';import LocalLlmBackendCard from './LocalLlmBackendCard.jsx';import DownloadPreflightConfirm from '../models/DownloadPreflightConfirm.jsx';import { LOCAL_LLM_BACKENDS as BACKENDS, localLlmBackendLabel as labelFor } from '../../lib/localLlmBackends.js';@@ -647,6 +648,7 @@ export default function LocalLlmRuntimesView() {return (<section id="llm-management-panel-runtimes" role="tabpanel" aria-labelledby="tab-runtimes" className="space-y-4"><HardwareLlmRecommendation />+ <LocalPersistentMindSetupCard />{/* One start/stop/install surface for every local server PortOS can run */}<RuntimeServersCardstatus={status}diff --git a/client/src/components/settings/LocalPersistentMindSetupCard.jsx b/client/src/components/settings/LocalPersistentMindSetupCard.jsxnew file mode 100644index 0000000000..dbe29f36c1--- /dev/null+++ b/client/src/components/settings/LocalPersistentMindSetupCard.jsx@@ -0,0 +1,270 @@+/**+ * Grok-box / CPU-only free Persistent Mind setup path.+ *+ * Shown when the host fits the local Ollama + Qwen2.5 7B Instruct default.+ * Install / start / pull reuse the existing local-LLM APIs; enable + mind pin+ * go through `/api/local-llm/persistent-mind-setup/apply`. Coding stays on+ * Cursor Agent / OpenCode Zen — this card never recommends 27B / vLLM presets.+ */++import { useCallback, useEffect, useState } from 'react';+import { Link } from 'react-router';+import {+ AlertTriangle,+ Bot,+ CheckCircle2,+ Cpu,+ Download,+ Play,+ RefreshCw,+ Sparkles,+ Wand2,+} from 'lucide-react';+import Banner from '../ui/Banner';+import BrailleSpinner from '../BrailleSpinner';+import toast from '../ui/Toast';+import {+ applyLocalPersistentMindSetup,+ controlOllamaService,+ getLocalPersistentMindSetup,+ installLocalLlmBackend,+ installLocalLlmModel,+} from '../../services/api';++const STEP_ICON = {+ ready: CheckCircle2,+ todo: Cpu,+ blocked: AlertTriangle,+ skipped: CheckCircle2,+};++export default function LocalPersistentMindSetupCard({+ className = '',+ compact = false,+ onApplied,+}) {+ const [setup, setSetup] = useState(null);+ const [loading, setLoading] = useState(true);+ const [busy, setBusy] = useState(null);++ const refresh = useCallback(async () => {+ try {+ const next = await getLocalPersistentMindSetup({ silent: true });+ setSetup(next);+ } catch {+ setSetup(null);+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ let cancelled = false;+ (async () => {+ try {+ const next = await getLocalPersistentMindSetup({ silent: true });+ if (!cancelled) setSetup(next);+ } catch {+ if (!cancelled) setSetup(null);+ } finally {+ if (!cancelled) setLoading(false);+ }+ })();+ return () => { cancelled = true; };+ }, []);++ const run = async (key, fn, successMessage) => {+ setBusy(key);+ try {+ const result = await fn();+ if (successMessage) toast.success(successMessage);+ await refresh();+ onApplied?.(result);+ } catch (error) {+ toast.error(error?.message || 'Setup step failed');+ await refresh();+ } finally {+ setBusy(null);+ }+ };++ if (loading) {+ return (+ <div className={`bg-port-card border border-port-border rounded-xl p-4 text-xs text-gray-500 ${className}`}>+ Checking whether this host should use a free local Persistent Mind…+ </div>+ );+ }++ if (!setup?.applicable || !setup.recommendation) return null;++ const { recommendation, steps = [], ready } = setup;+ const modelStep = steps.find((s) => s.id === 'model-present');+ const installStep = steps.find((s) => s.id === 'ollama-installed');+ const runningStep = steps.find((s) => s.id === 'ollama-running');++ return (+ <section+ className={`bg-port-accent/5 border border-port-accent/40 rounded-xl p-4 sm:p-5 space-y-3 ${className}`}+ aria-labelledby="local-persistent-mind-setup-title"+ data-testid="local-persistent-mind-setup"+ >+ <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="flex items-center gap-2 text-port-accent">+ <Sparkles size={16} />+ <h2 id="local-persistent-mind-setup-title" className="text-sm font-semibold">+ Free local Persistent Mind+ </h2>+ </div>+ <p className="text-xs text-gray-400 mt-1">+ Default for Grok Bot boxes and other CPU-only / no-GPU hosts: {recommendation.machine}+ </p>+ </div>+ <span className="text-[11px] px-2 py-1 rounded border border-port-accent/30 text-port-accent shrink-0">+ {recommendation.modelLabel}+ </span>+ </div>++ {!compact && (+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 text-xs">+ <div className="bg-port-bg/70 rounded-lg p-2.5 min-w-0">+ <span className="text-gray-500">Runtime</span>+ <p className="text-gray-200 mt-0.5 font-medium">{recommendation.runtime}</p>+ </div>+ <div className="bg-port-bg/70 rounded-lg p-2.5 min-w-0">+ <span className="text-gray-500">Mind</span>+ <p className="text-gray-200 mt-0.5 font-medium">{recommendation.mindRole}</p>+ </div>+ <div className="bg-port-bg/70 rounded-lg p-2.5 min-w-0">+ <span className="text-gray-500">Coding</span>+ <p className="text-gray-200 mt-0.5 font-medium">{recommendation.codingHarnesses}</p>+ </div>+ </div>+ )}++ <div className="text-xs text-gray-300 space-y-1.5 leading-relaxed">+ <p className="flex gap-2">+ <Bot size={14} className="text-port-success shrink-0 mt-0.5" />+ <span>+ <strong className="text-gray-200">Topology:</strong> {recommendation.topology}.{' '}+ {recommendation.note}+ </span>+ </p>+ <p className="text-gray-500">{recommendation.alternatives}</p>+ </div>++ {recommendation.warnings?.length > 0 && (+ <Banner tone="warning" size="sm" icon={AlertTriangle} title="CPU / RAM guardrails">+ <ul className="mt-1 space-y-1 list-disc pl-4">+ {recommendation.warnings.map((warning) => (+ <li key={warning}>{warning}</li>+ ))}+ </ul>+ </Banner>+ )}++ <ul className="space-y-1.5 text-xs">+ {steps.filter((s) => s.id !== 'recommendation').map((s) => {+ const Icon = STEP_ICON[s.status] || Cpu;+ const tone = s.status === 'ready'+ ? 'text-port-success'+ : s.status === 'blocked'+ ? 'text-port-warning'+ : 'text-gray-400';+ return (+ <li key={s.id} className="flex items-start gap-2">+ <Icon size={14} className={`${tone} shrink-0 mt-0.5`} />+ <span className="text-gray-300 break-words">{s.detail}</span>+ </li>+ );+ })}+ </ul>++ <div className="flex flex-wrap items-center gap-2 pt-1">+ {installStep?.action?.kind === 'install-backend' && (+ <button+ type="button"+ disabled={Boolean(busy)}+ onClick={() => run('install', () => installLocalLlmBackend('ollama'), 'Ollama install started')}+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 text-xs font-medium disabled:opacity-50"+ >+ {busy === 'install' ? <BrailleSpinner /> : <Download size={12} />}+ Install Ollama+ </button>+ )}+ {runningStep?.action?.kind === 'start-ollama' && (+ <button+ type="button"+ disabled={Boolean(busy)}+ onClick={() => run('start', () => controlOllamaService('start'), 'Ollama start requested')}+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 text-xs font-medium disabled:opacity-50"+ >+ {busy === 'start' ? <BrailleSpinner /> : <Play size={12} />}+ Start Ollama+ </button>+ )}+ {modelStep?.action?.kind === 'pull-model' && (+ <button+ type="button"+ disabled={Boolean(busy)}+ onClick={() => run(+ 'pull',+ () => installLocalLlmModel('ollama', modelStep.action.modelId, { silent: true }),+ `Pulling ${recommendation.modelLabel}`,+ )}+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 text-xs font-medium disabled:opacity-50"+ >+ {busy === 'pull' ? <BrailleSpinner /> : <Download size={12} />}+ Pull {recommendation.modelLabel}+ </button>+ )}+ <button+ type="button"+ disabled={Boolean(busy)}+ onClick={() => run(+ 'enable',+ () => applyLocalPersistentMindSetup({ setMindProfile: false }, { silent: true }),+ 'Ollama provider enabled',+ )}+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 text-xs font-medium disabled:opacity-50"+ >+ {busy === 'enable' ? <BrailleSpinner /> : <Wand2 size={12} />}+ Enable Ollama provider+ </button>+ <button+ type="button"+ disabled={Boolean(busy)}+ onClick={() => run(+ 'mind',+ () => applyLocalPersistentMindSetup({ setMindProfile: true }, { silent: true }),+ 'Persistent Mind profile pinned to Ollama',+ )}+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-port-accent text-white hover:bg-port-accent/80 text-xs font-medium disabled:opacity-50"+ >+ {busy === 'mind' ? <BrailleSpinner /> : <Bot size={12} />}+ Enable provider + set Mind profile+ </button>+ <button+ type="button"+ disabled={Boolean(busy)}+ onClick={() => { setLoading(true); refresh(); }}+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded border border-port-border text-gray-400 hover:text-white text-xs disabled:opacity-50"+ aria-label="Refresh local Persistent Mind setup"+ >+ <RefreshCw size={12} className={busy ? 'animate-spin' : ''} />+ Refresh+ </button>+ </div>++ <div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-xs">+ {ready+ ? <span className="text-port-success inline-flex items-center gap-1"><CheckCircle2 size={12} /> Required setup steps are complete</span>+ : <span className="text-gray-500">Complete install / start / pull, then enable the provider.</span>}+ <Link to="/ai" className="text-port-accent hover:underline">AI Providers</Link>+ <Link to="/cos/mind" className="text-port-accent hover:underline">Persistent Mind</Link>+ <Link to="/models/llms" className="text-port-accent hover:underline">Models → LLMs</Link>+ </div>+ </section>+ );+}diff --git a/client/src/components/settings/LocalPersistentMindSetupCard.test.jsx b/client/src/components/settings/LocalPersistentMindSetupCard.test.jsxnew file mode 100644index 0000000000..864e866647--- /dev/null+++ b/client/src/components/settings/LocalPersistentMindSetupCard.test.jsx@@ -0,0 +1,103 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor, fireEvent } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++vi.mock('../../services/api', () => ({+ getLocalPersistentMindSetup: vi.fn(),+ applyLocalPersistentMindSetup: vi.fn(),+ installLocalLlmBackend: vi.fn(),+ installLocalLlmModel: vi.fn(),+ controlOllamaService: vi.fn(),+}));+vi.mock('../ui/Toast', () => ({+ default: Object.assign(vi.fn(), {+ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn(),+ }),+}));++import {+ getLocalPersistentMindSetup,+ applyLocalPersistentMindSetup,+} from '../../services/api';+import LocalPersistentMindSetupCard from './LocalPersistentMindSetupCard.jsx';++const applicableSetup = {+ applicable: true,+ ready: false,+ recommendation: {+ machine: 'CPU-only host (~16 GB RAM)',+ modelLabel: 'Qwen2.5 7B Instruct (Q4)',+ runtime: 'Ollama',+ mindRole: 'Persistent Mind (free, local, tool-capable)',+ codingHarnesses: 'Cursor Agent / OpenCode Zen (cloud CLIs) for coding tasks',+ topology: 'Local Ollama Persistent Mind + cloud coding CLIs',+ note: 'Default for Grok Bot boxes and other CPU-only / no-GPU installs.',+ alternatives: 'Do not enable vLLM or Qwen3.8-27B presets on this host.',+ warnings: ['This host has no usable NVIDIA GPU — inference runs on CPU and will be slower than a GPU box.'],+ },+ steps: [+ { id: 'recommendation', status: 'ready', detail: 'recommended' },+ { id: 'ollama-installed', status: 'ready', detail: 'Ollama CLI is on PATH.' },+ { id: 'ollama-running', status: 'ready', detail: 'Ollama daemon is answering.' },+ {+ id: 'model-present',+ status: 'todo',+ detail: 'Pull qwen2.5:7b-instruct',+ action: { kind: 'pull-model', backend: 'ollama', modelId: 'qwen2.5:7b-instruct', label: 'Pull' },+ },+ { id: 'provider-enabled', status: 'todo', detail: 'Enable provider' },+ { id: 'mind-profile', status: 'todo', detail: 'Optionally pin mind' },+ ],+};++beforeEach(() => {+ vi.clearAllMocks();+ getLocalPersistentMindSetup.mockResolvedValue(applicableSetup);+ applyLocalPersistentMindSetup.mockResolvedValue({+ success: true,+ profile: { enabled: true, providerId: 'ollama', model: 'qwen2.5:7b-instruct' },+ });+});++describe('LocalPersistentMindSetupCard', () => {+ it('renders the Grok-box topology and guardrails when applicable', async () => {+ render(+ <MemoryRouter>+ <LocalPersistentMindSetupCard />+ </MemoryRouter>,+ );+ expect(await screen.findByRole('heading', { name: /free local persistent mind/i })).toBeTruthy();+ expect(screen.getAllByText(/Grok Bot boxes/i).length).toBeGreaterThan(0);+ expect(screen.getAllByText(/Cursor Agent \/ OpenCode Zen/i).length).toBeGreaterThan(0);+ expect(screen.getByText(/no usable NVIDIA GPU/i)).toBeTruthy();+ expect(screen.getByText(/Do not enable vLLM or Qwen3.8-27B/i)).toBeTruthy();+ expect(screen.getByRole('button', { name: /pull qwen2\.5 7b instruct/i })).toBeTruthy();+ });++ it('renders nothing when the host is outside the free local-mind path', async () => {+ getLocalPersistentMindSetup.mockResolvedValue({ applicable: false, recommendation: null, steps: [] });+ const { container } = render(+ <MemoryRouter>+ <LocalPersistentMindSetupCard />+ </MemoryRouter>,+ );+ await waitFor(() => expect(getLocalPersistentMindSetup).toHaveBeenCalled());+ expect(container.querySelector('[data-testid="local-persistent-mind-setup"]')).toBeNull();+ });++ it('applies the mind profile pin when requested', async () => {+ const onApplied = vi.fn();+ render(+ <MemoryRouter>+ <LocalPersistentMindSetupCard onApplied={onApplied} />+ </MemoryRouter>,+ );+ await screen.findByRole('heading', { name: /free local persistent mind/i });+ fireEvent.click(screen.getByRole('button', { name: /enable provider \+ set mind profile/i }));+ await waitFor(() => expect(applyLocalPersistentMindSetup).toHaveBeenCalledWith(+ { setMindProfile: true },+ { silent: true },+ ));+ await waitFor(() => expect(onApplied).toHaveBeenCalled());+ });+});diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex 933782c50d..6aa385c2a7 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -21,6 +21,7 @@ import ProviderForm from '../components/providers/ProviderForm';import CollapsibleSection from '../components/ui/CollapsibleSection';import FleetProviderSetup from '../components/providers/FleetProviderSetup';import FleetHostSetup from '../components/providers/FleetHostSetup';+import LocalPersistentMindSetupCard from '../components/settings/LocalPersistentMindSetupCard.jsx';import ProviderConnections from '../components/providers/ProviderConnections';// The two local apps an API provider can front. Their installer lives on the@@ -776,6 +777,7 @@ export default function AIProviders() {<div className="flex-1 overflow-auto p-4 space-y-6">+ <LocalPersistentMindSetupCard compact onApplied={loadData} /><FleetHostSetup compact providers={providers} />{/* Sample Providers Panel */}diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex c0073cc604..e1d6b08df5 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -391,3 +391,14 @@ export const getModelCapabilityTestResult = (backend, modelId, testId, options)// stored verdict describes weights that are no longer installed.export const deleteModelCapabilityTest = (backend, modelId, testId, options) =>request('/local-llm/capability-tests/delete', { method: 'POST', body: JSON.stringify({ backend, modelId, testId }), ...options });++// Grok-box / CPU-only free Persistent Mind checklist (Ollama + Qwen2.5 7B).+export const getLocalPersistentMindSetup = (options) =>+ request('/local-llm/persistent-mind-setup', options);++export const applyLocalPersistentMindSetup = (body = {}, options = {}) =>+ request('/local-llm/persistent-mind-setup/apply', {+ method: 'POST',+ body: JSON.stringify(body),+ ...options,+ });diff --git a/docs/README.md b/docs/README.mdindex c2f807215e..0752b94a90 100644--- a/docs/README.md+++ b/docs/README.md@@ -40,7 +40,7 @@ Start with the [product surface map](./features/product-surfaces.md) for a complApp management: [app-wizard](./features/app-wizard.md) · [autofixer](./features/autofixer.md) · [browser](./features/browser.md) · [error-handling](./features/error-handling.md) · [jira-sprint-manager](./features/jira-sprint-manager.md)-Chief of Staff: [chief-of-staff](./features/chief-of-staff.md) · [cos-agent-runner](./features/cos-agent-runner.md) · [cos-enhancement](./features/cos-enhancement.md) · [agent-context](./features/agent-context.md) · [agent-skills](./features/agent-skills.md) · [memory-system](./features/memory-system.md) · [claude-ollama](./features/claude-ollama.md) · [fleet-llm-host](./features/fleet-llm-host.md) · [mtplx](./features/mtplx.md) · [slotstream](./features/slotstream.md) · [dflash2](./features/dflash2.md) ([DSpark vs DFlash 2](./research/2026-08-19-dspark-vs-dflash2.md)) · [qwen38-rtx3090](./features/qwen38-rtx3090.md) ([3090 bring-up](./research/2026-08-21-qwen38-rtx3090-vllm.md)) · [sglang-qwen38](./features/sglang-qwen38.md) ([SGLang Hopper/Blackwell evaluation](./research/2026-08-21-sglang-qwen38-27b.md)) · [prompt-manager](./features/prompt-manager.md)+Chief of Staff: [chief-of-staff](./features/chief-of-staff.md) · [cos-agent-runner](./features/cos-agent-runner.md) · [cos-enhancement](./features/cos-enhancement.md) · [agent-context](./features/agent-context.md) · [agent-skills](./features/agent-skills.md) · [memory-system](./features/memory-system.md) · [claude-ollama](./features/claude-ollama.md) · [grok-box-local-mind](./features/grok-box-local-mind.md) · [fleet-llm-host](./features/fleet-llm-host.md) · [mtplx](./features/mtplx.md) · [slotstream](./features/slotstream.md) · [dflash2](./features/dflash2.md) ([DSpark vs DFlash 2](./research/2026-08-19-dspark-vs-dflash2.md)) · [qwen38-rtx3090](./features/qwen38-rtx3090.md) ([3090 bring-up](./research/2026-08-21-qwen38-rtx3090-vllm.md)) · [sglang-qwen38](./features/sglang-qwen38.md) ([SGLang Hopper/Blackwell evaluation](./research/2026-08-21-sglang-qwen38-27b.md)) · [prompt-manager](./features/prompt-manager.md)Identity & self: [digital-twin](./features/digital-twin.md) · [identity-system](./features/identity-system.md) · [soul-system](./features/soul-system.md) · [privacy-center](./features/privacy-center.md) · [post](./features/post.md) (insights design spike: [plans/2026-06-03](./plans/2026-06-03-cross-domain-insights-engine.md))diff --git a/docs/SETUP.md b/docs/SETUP.mdindex 905ddc2d51..4b4d965469 100644--- a/docs/SETUP.md+++ b/docs/SETUP.md@@ -66,3 +66,12 @@ npm run pm2:restart # activate a newly provisioned certificate```For HTTPS without Tailscale, `npm run setup:cert -- --self-signed` remains an explicit fallback. Browsers will warn because that certificate is not publicly trusted, and a stable MagicDNS URL is still preferable for remote use.++## Grok Bot box / CPU-only Persistent Mind++On a **CPU-only ~16 GB** host (for example a Grok Bot box with no GPU), prefer a+**free local Persistent Mind** on Ollama + `qwen2.5:7b-instruct`, and keep+**Cursor Agent / OpenCode Zen** for coding. PortOS offers that setup on+**AI Providers**, **Models → LLMs**, and **Persistent Mind → Settings**. See+[features/grok-box-local-mind.md](./features/grok-box-local-mind.md).+diff --git a/docs/features/grok-box-local-mind.md b/docs/features/grok-box-local-mind.mdnew file mode 100644index 0000000000..88add9f5e4--- /dev/null+++ b/docs/features/grok-box-local-mind.md@@ -0,0 +1,56 @@+# Grok Bot box — free local Persistent Mind++**Audience:** PortOS installs running on a **Grok Bot box** (CPU-only, ~16 GB RAM, no GPU) and similar modest hosts.++## Recommended topology++| Role | Where it runs | Default |+| --- | --- | --- |+| **Persistent Mind** | Local **Ollama** API provider | **Qwen2.5 7B Instruct (Q4)** — `qwen2.5:7b-instruct` (alias: `qwen2.5:7b`) |+| **Coding tasks** | Cloud CLIs / harnesses | **Cursor Agent** / **OpenCode Zen** (and other subscription CLIs you enable) |++Keep the mind free and local. Do **not** point coding agents at a CPU-bound 27B/vLLM stack on this host — those presets need a GPU workstation (see [Recommended coding-agent setup](./qwen38-rtx3090.md), [SGLang](./sglang-qwen38.md), [Fleet LLM host](./fleet-llm-host.md)).++## Why this default++- Persistent Mind is an always-on conversational agent with optional tool grants. A tool-capable ~7B instruct model fits ~16 GB RAM at Q4 and stays responsive enough for wake turns.+- Cursor / OpenCode Zen already own the coding harness (worktrees, tools, PRs). Using them for coding avoids pretending a CPU box is a 27B coding workstation.+- The built-in `ollama` provider is a Direct API lane — the reliability path Persistent Mind prefers over TUI scraping.++## Setup UI++PortOS surfaces a **Free local Persistent Mind** card when the host fits this path (CPU-only / no usable NVIDIA GPU, or low RAM / modest Apple Silicon without a curated 48 GB+ coding preset):++- **AI Providers** (`/ai`)+- **Models → LLMs → Runtimes** (`/models/llms`)+- **Chief of Staff → Persistent Mind → Settings** (AI profile drawer)++The card:++1. Detects whether Ollama is installed and answering.+2. Offers **Install Ollama** / **Start Ollama** / **Pull Qwen2.5 7B Instruct** via the existing local-LLM APIs.+3. Enables the built-in `ollama` provider and pins the recommended model.+4. Optionally sets the Persistent Mind profile to that provider/model.++Copy on the card states that this is the default for **Grok-box / CPU-only / no-GPU** hosts, and warns against 27B / vLLM presets.++### API++| Method | Path | Purpose |+| --- | --- | --- |+| `GET` | `/api/local-llm/persistent-mind-setup` | Checklist + recommendation (or `applicable: false`) |+| `POST` | `/api/local-llm/persistent-mind-setup/apply` | Enable `ollama` + pin model; optional `{ setMindProfile: true }` |++Apply never downloads weights. Install / start / pull stay on `/api/local-llm/install-backend`, `/ollama-service`, and `/install`.++## Guardrails++- **No GPU / low RAM:** the recommendation includes explicit warnings; expect slower CPU inference.+- **Heavy presets suppressed:** hosts on this path should not be steered to Qwen3.8-27B, vLLM, or SGLang as the default. Curated GPU coding hosts keep [Hardware LLM recommendation](../../client/src/components/settings/HardwareLlmRecommendation.jsx) instead and do not get this card.+- Hardware gates on catalog entries (e.g. 27B `minMemoryGb: 32`, vLLM `requiresNvidiaGpu`) still hide unavailable options in the library.++## Related++- [Claude Ollama](./claude-ollama.md) — local model behind the Claude Code harness (optional coding path once Ollama is up)+- [Persistent Mind / CoS enhancement](./cos-enhancement.md)+- [Product surfaces](./product-surfaces.md)diff --git a/server/lib/localLlmCatalog.js b/server/lib/localLlmCatalog.jsindex 17a65fd74a..bf7fd438ba 100644--- a/server/lib/localLlmCatalog.js+++ b/server/lib/localLlmCatalog.js@@ -154,6 +154,24 @@ export const LOCAL_LLM_CATALOG = [ollama: 'lfm2.5-thinking:1.2b',lmstudio: 'lmstudio-community/LFM2.5-1.2B-Thinking-GGUF'},+ {+ key: 'qwen2.5-7b-instruct',+ name: 'Qwen2.5 7B Instruct',+ category: 'general',+ recommendedFor: ['chat', 'general', 'lightweight'],+ featured: {+ label: 'Grok-box Persistent Mind',+ description: 'Default free local mind on CPU-only / ~16 GB hosts: tool-capable instruct build via Ollama. Keep Cursor / OpenCode Zen for coding.'+ },+ params: '7B',+ size: '4.7 GB',+ family: 'qwen',+ description: 'Qwen2.5 7B Instruct (Q4) — the default free Persistent Mind on Grok Bot boxes and other CPU-only / no-GPU hosts. Tool-capable; pair with cloud CLIs for coding tasks.',+ capabilities: ['chat', 'tools', 'multilingual'],+ context: 131072,+ ollama: 'qwen2.5:7b-instruct',+ lmstudio: 'lmstudio-community/Qwen2.5-7B-Instruct-GGUF'+ },{key: 'qwen2.5-3b',name: 'Qwen2.5 3B',diff --git a/server/lib/localPersistentMindRecommendation.js b/server/lib/localPersistentMindRecommendation.jsnew file mode 100644index 0000000000..435924b16f--- /dev/null+++ b/server/lib/localPersistentMindRecommendation.js@@ -0,0 +1,184 @@+/**+ * Curated Persistent Mind defaults for CPU-only / low-RAM hosts (Grok Bot boxes).+ *+ * HardwareLlmRecommendation owns GPU coding-agent presets (Apple 48GB+, RTX 3090+ * + Qwen3.8-27B). Those hosts must not be steered toward a 7B Ollama mind as the+ * primary story. This module is the complementary path: a free local mind on+ * Ollama with a tool-capable ~7B instruct model, while Cursor Agent / OpenCode+ * Zen (cloud CLIs) stay the coding harnesses.+ *+ * Pure and dependency-free so the setup service, routes, and unit tests share+ * one source of truth without probing the host.+ */++/** Default Ollama tag — Qwen2.5 7B Instruct (Q4 in the official Ollama library). */+export const LOCAL_PERSISTENT_MIND_MODEL = 'qwen2.5:7b-instruct';++/**+ * Installed ids that satisfy the recommendation. Ollama's library also ships+ * `qwen2.5:7b` as the instruct build; either tag is fine once pulled.+ */+export const LOCAL_PERSISTENT_MIND_MODEL_ALIASES = Object.freeze([+ 'qwen2.5:7b-instruct',+ 'qwen2.5:7b',+ 'qwen2.5:7b-instruct-q4_0',+ 'qwen2.5:7b-instruct-q4_K_M',+]);++export const LOCAL_PERSISTENT_MIND_PROVIDER_ID = 'ollama';++/** Rough ceiling for "low RAM" warnings and the Grok-box default path. */+export const LOCAL_PERSISTENT_MIND_LOW_RAM_GB = 20;++/** Catalog / UI size claim for the recommended pull (Q4). */+export const LOCAL_PERSISTENT_MIND_MODEL_SIZE = '~4.7 GB';++const positiveNumber = (value) => {+ const number = Number(value);+ return Number.isFinite(number) && number > 0 ? number : null;+};++/**+ * True when an installed model id matches the recommended Persistent Mind pull+ * (exact tag or a known alias / `:latest` sibling).+ */+export function matchesLocalPersistentMindModel(modelId) {+ if (typeof modelId !== 'string' || !modelId.trim()) return false;+ const normalized = modelId.trim().toLowerCase();+ const bare = normalized.replace(/:latest$/, '');+ return LOCAL_PERSISTENT_MIND_MODEL_ALIASES.some((alias) => {+ const a = alias.toLowerCase();+ return normalized === a || bare === a || bare.startsWith(`${a}-`) || bare.startsWith(`${a}:`);+ });+}++/**+ * NVIDIA CUDA is present with usable VRAM. `absent` / empty lists are CPU-only;+ * `unknown` is not treated as "has a GPU" (a failed probe must not hide the+ * free local-mind path).+ */+export function hasUsableNvidiaGpu(capabilities) {+ const cuda = capabilities?.cuda;+ if (!cuda || cuda.status !== 'available') return false;+ const vram = positiveNumber(cuda.maxVramGb);+ return vram != null && vram > 0;+}++/** Hosts that already have a curated local coding-agent preset. */+export function isCuratedGpuCodingHost(capabilities) {+ if (!capabilities || typeof capabilities !== 'object') return false;+ const memory = positiveNumber(capabilities.totalMemoryGb);+ if (capabilities.appleSilicon === true && memory != null && memory >= 48) return true;+ if (capabilities.platform === 'win32' && hasUsableNvidiaGpu(capabilities)) {+ const gpuNames = (capabilities.cuda?.gpus || []).map((gpu) => gpu?.name || '').join(' ');+ const maxVram = positiveNumber(capabilities.cuda?.maxVramGb);+ if (/rtx\s*3090/i.test(gpuNames) && maxVram != null && maxVram >= 24) return true;+ }+ return false;+}++/**+ * CPU-only / no usable discrete GPU. Apple Silicon without a CUDA probe still+ * has a GPU (unified memory) — those are not "CPU-only", but low-RAM Apple+ * boxes still get the free local-mind recommendation below.+ */+export function isCpuOnlyHost(capabilities) {+ if (!capabilities || typeof capabilities !== 'object') return false;+ if (capabilities.appleSilicon === true) return false;+ return !hasUsableNvidiaGpu(capabilities);+}++export function isLowRamHost(capabilities, thresholdGb = LOCAL_PERSISTENT_MIND_LOW_RAM_GB) {+ const memory = positiveNumber(capabilities?.totalMemoryGb);+ return memory != null && memory <= thresholdGb;+}++/**+ * Whether this install should be offered the free Ollama Persistent Mind path+ * as the default local recommendation (Grok Bot box and similar).+ */+export function hostFitsLocalPersistentMindDefault(capabilities) {+ if (!capabilities || typeof capabilities !== 'object') return false;+ if (isCuratedGpuCodingHost(capabilities)) return false;+ if (isCpuOnlyHost(capabilities)) return true;+ if (isLowRamHost(capabilities)) return true;+ // Modest Apple Silicon (< 48 GB) has no curated 27B coding preset either.+ if (capabilities.appleSilicon === true) {+ const memory = positiveNumber(capabilities.totalMemoryGb);+ return memory == null || memory < 48;+ }+ return false;+}++/**+ * Heavy 27B / vLLM / SGLang presets must not be the suggested path on these+ * hosts — they thrash CPU RAM or require a GPU that is not there.+ */+export function shouldSuppressHeavyLocalPresets(capabilities) {+ if (!capabilities || typeof capabilities !== 'object') return false;+ if (isCuratedGpuCodingHost(capabilities)) return false;+ if (hasUsableNvidiaGpu(capabilities)) {+ const vram = positiveNumber(capabilities.cuda?.maxVramGb);+ // A card under 24 GB cannot run the curated vLLM 27B path honestly.+ return vram == null || vram < 24;+ }+ if (capabilities.appleSilicon === true) {+ const memory = positiveNumber(capabilities.totalMemoryGb);+ return memory == null || memory < 32;+ }+ return true;+}++/**+ * @param {object|null|undefined} capabilities — `detectSystemCapabilities()` shape+ * @returns {object|null} recommendation profile, or null when another path owns the host+ */+export function localPersistentMindRecommendation(capabilities) {+ if (!hostFitsLocalPersistentMindDefault(capabilities)) return null;++ const memory = positiveNumber(capabilities?.totalMemoryGb);+ const cpuOnly = isCpuOnlyHost(capabilities);+ const lowRam = isLowRamHost(capabilities);+ const warnings = [];+ if (cpuOnly) {+ warnings.push('This host has no usable NVIDIA GPU — inference runs on CPU and will be slower than a GPU box.');+ }+ if (lowRam) {+ warnings.push(+ memory != null+ ? `About ${Math.round(memory)} GB RAM detected — keep the mind on a ~7B Q4 model; do not pull 27B or vLLM presets here.`+ : 'Low RAM host — keep the mind on a ~7B Q4 model; do not pull 27B or vLLM presets here.',+ );+ } else if (shouldSuppressHeavyLocalPresets(capabilities)) {+ warnings.push('Skip 27B / vLLM / SGLang presets on this machine — they need a GPU (or ≥32 GB unified memory on Apple Silicon).');+ }++ const machine = cpuOnly+ ? (memory != null+ ? `CPU-only host (~${Math.round(memory)} GB RAM)`+ : 'CPU-only host (no NVIDIA GPU)')+ : (memory != null+ ? `Modest local host (~${Math.round(memory)} GB RAM)`+ : 'Modest local host');++ return Object.freeze({+ id: 'grok-box-ollama-mind',+ audience: 'grok-box',+ machine,+ providerId: LOCAL_PERSISTENT_MIND_PROVIDER_ID,+ providerLabel: 'Ollama',+ model: LOCAL_PERSISTENT_MIND_MODEL,+ modelLabel: 'Qwen2.5 7B Instruct (Q4)',+ modelSize: LOCAL_PERSISTENT_MIND_MODEL_SIZE,+ runtime: 'Ollama',+ mindRole: 'Persistent Mind (free, local, tool-capable)',+ codingHarnesses: 'Cursor Agent / OpenCode Zen (cloud CLIs) for coding tasks',+ topology: 'Local Ollama Persistent Mind + cloud coding CLIs',+ note: 'Default for Grok Bot boxes and other CPU-only / no-GPU installs: a free local Persistent Mind on Ollama, with Cursor / OpenCode Zen reserved for coding.',+ alternatives: 'Do not enable vLLM or Qwen3.8-27B presets on this host. When you later add a GPU workstation, use Models → LLMs → Recommended coding-agent setup instead.',+ warnings: Object.freeze(warnings),+ suppressHeavyLocalPresets: shouldSuppressHeavyLocalPresets(capabilities),+ cpuOnly,+ lowRam,+ });+}diff --git a/server/lib/localPersistentMindRecommendation.test.js b/server/lib/localPersistentMindRecommendation.test.jsnew file mode 100644index 0000000000..2edf9832d9--- /dev/null+++ b/server/lib/localPersistentMindRecommendation.test.js@@ -0,0 +1,110 @@+import { describe, expect, it } from 'vitest';+import {+ LOCAL_PERSISTENT_MIND_MODEL,+ LOCAL_PERSISTENT_MIND_PROVIDER_ID,+ hasUsableNvidiaGpu,+ hostFitsLocalPersistentMindDefault,+ isCpuOnlyHost,+ isCuratedGpuCodingHost,+ isLowRamHost,+ localPersistentMindRecommendation,+ matchesLocalPersistentMindModel,+ shouldSuppressHeavyLocalPresets,+} from './localPersistentMindRecommendation.js';++const grokBox = Object.freeze({+ platform: 'linux',+ arch: 'x64',+ appleSilicon: false,+ totalMemoryGb: 15.6,+ cpuCount: 4,+ cuda: { status: 'absent', gpus: [], maxVramGb: null },+});++const apple64 = Object.freeze({+ platform: 'darwin',+ arch: 'arm64',+ appleSilicon: true,+ totalMemoryGb: 64,+ cuda: { status: 'absent', gpus: [], maxVramGb: null },+});++const rtx3090 = Object.freeze({+ platform: 'win32',+ appleSilicon: false,+ totalMemoryGb: 64,+ cuda: {+ status: 'available',+ maxVramGb: 24,+ gpus: [{ name: 'NVIDIA GeForce RTX 3090', vramGb: 24 }],+ },+});++describe('localPersistentMindRecommendation helpers', () => {+ it('recognizes the recommended model and common Ollama aliases', () => {+ expect(matchesLocalPersistentMindModel(LOCAL_PERSISTENT_MIND_MODEL)).toBe(true);+ expect(matchesLocalPersistentMindModel('qwen2.5:7b')).toBe(true);+ expect(matchesLocalPersistentMindModel('qwen2.5:7b-instruct:latest')).toBe(true);+ expect(matchesLocalPersistentMindModel('qwen3.8:27b')).toBe(false);+ expect(matchesLocalPersistentMindModel('')).toBe(false);+ });++ it('classifies a Grok Bot box as CPU-only, low-RAM, and default-fit', () => {+ expect(isCpuOnlyHost(grokBox)).toBe(true);+ expect(isLowRamHost(grokBox)).toBe(true);+ expect(hasUsableNvidiaGpu(grokBox)).toBe(false);+ expect(isCuratedGpuCodingHost(grokBox)).toBe(false);+ expect(hostFitsLocalPersistentMindDefault(grokBox)).toBe(true);+ expect(shouldSuppressHeavyLocalPresets(grokBox)).toBe(true);+ });++ it('leaves curated GPU coding hosts to HardwareLlmRecommendation', () => {+ expect(isCuratedGpuCodingHost(apple64)).toBe(true);+ expect(hostFitsLocalPersistentMindDefault(apple64)).toBe(false);+ expect(localPersistentMindRecommendation(apple64)).toBeNull();+ expect(isCuratedGpuCodingHost(rtx3090)).toBe(true);+ expect(localPersistentMindRecommendation(rtx3090)).toBeNull();+ expect(shouldSuppressHeavyLocalPresets(rtx3090)).toBe(false);+ });++ it('recommends Ollama + Qwen2.5 7B Instruct for a Grok Bot box', () => {+ const profile = localPersistentMindRecommendation(grokBox);+ expect(profile).toMatchObject({+ id: 'grok-box-ollama-mind',+ audience: 'grok-box',+ providerId: LOCAL_PERSISTENT_MIND_PROVIDER_ID,+ model: LOCAL_PERSISTENT_MIND_MODEL,+ runtime: 'Ollama',+ cpuOnly: true,+ lowRam: true,+ suppressHeavyLocalPresets: true,+ });+ expect(profile.codingHarnesses).toMatch(/Cursor/i);+ expect(profile.codingHarnesses).toMatch(/OpenCode/i);+ expect(profile.warnings.some((w) => /no usable NVIDIA GPU/i.test(w))).toBe(true);+ expect(profile.warnings.some((w) => /7B|27B|vLLM/i.test(w))).toBe(true);+ expect(profile.alternatives).toMatch(/vLLM|27B/i);+ });++ it('treats a failed CUDA probe as not having a GPU', () => {+ const unknownCuda = {+ ...grokBox,+ cuda: { status: 'unknown', gpus: [], maxVramGb: null },+ };+ expect(hasUsableNvidiaGpu(unknownCuda)).toBe(false);+ expect(localPersistentMindRecommendation(unknownCuda)?.providerId).toBe('ollama');+ });++ it('offers the free mind path on modest Apple Silicon without a 27B coding preset', () => {+ const apple16 = {+ platform: 'darwin',+ appleSilicon: true,+ totalMemoryGb: 16,+ cuda: { status: 'absent', gpus: [], maxVramGb: null },+ };+ expect(isCpuOnlyHost(apple16)).toBe(false);+ expect(hostFitsLocalPersistentMindDefault(apple16)).toBe(true);+ expect(shouldSuppressHeavyLocalPresets(apple16)).toBe(true);+ expect(localPersistentMindRecommendation(apple16)?.model).toBe(LOCAL_PERSISTENT_MIND_MODEL);+ });+});diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.jsindex 56b23c299b..3f21689ea2 100644--- a/server/lib/mediaValidation.js+++ b/server/lib/mediaValidation.js@@ -148,6 +148,10 @@ export const localLlmMigrateSchema = z.object({mode: z.enum(['link', 'copy']).optional().default('link'),});export const localLlmInstallBackendSchema = z.object({ backend: localLlmBackendSchema });+export const localPersistentMindSetupApplySchema = z.object({+ setMindProfile: z.boolean().optional(),+ modelId: z.string().trim().max(200).optional(),+}).strict();export const localLlmOllamaServiceSchema = z.object({ action: z.enum(['start', 'stop', 'enable', 'disable']) });// LM Studio's own server has no enable/disable equivalent (the app owns its// launch-at-login), so this is start/stop only — deliberately NOT reusing thediff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 15af0000c6..9ed74824cf 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -41,6 +41,7 @@ import {localLlmMtplxRemoveSchema,localLlmSpecModelDownloadSchema,localLlmDownloadPreflightSchema,+ localPersistentMindSetupApplySchema,} from '../lib/validation.js'import {getLlamaServerStatus,@@ -81,6 +82,10 @@ import { runOpenCodeAgentBenchmark } from '../services/localModelAgentBenchmark.import { getCapabilityTestReport, getCapabilityTestResult, runCapabilityTest } from '../services/modelCapabilityTests.js'import { deleteResult as deleteCapabilityTestResult } from '../services/modelCapabilityTestStore.js'import { listUserModels } from '../services/audioModels.js'+import {+ describeLocalPersistentMindSetup,+ applyLocalPersistentMindSetup,+} from '../services/localPersistentMindSetup.js'import { ENGINES } from '../services/pipeline/musicGen.js'import { abortSignalFromResponse } from '../lib/requestAbort.js'import { awaitWritableDrain } from '../lib/streamBackpressure.js'@@ -102,6 +107,30 @@ const emitter = (req) => {return (event, message, extra) => io?.emit('localLlm:progress', { event, message, ...extra })}++// GET /api/local-llm/persistent-mind-setup — Grok-box / CPU-only free local+// Persistent Mind checklist (Ollama + Qwen2.5 7B Instruct). Applicable hosts+// only; curated GPU coding hosts get applicable:false.+router.get('/persistent-mind-setup', asyncHandler(async (_req, res) => {+ res.json(await describeLocalPersistentMindSetup())+}))++// POST /api/local-llm/persistent-mind-setup/apply — enable the ollama provider+// and optionally pin the Persistent Mind profile. Never installs Ollama or+// pulls weights (those stay on install-backend / install / ollama-service).+router.post('/persistent-mind-setup/apply', asyncHandler(async (req, res) => {+ const body = validateRequest(localPersistentMindSetupApplySchema, req.body || {})+ const result = await applyLocalPersistentMindSetup(body)+ if (!result.success) {+ throw new ServerError(result.error || 'Could not apply local Persistent Mind setup', {+ status: 400,+ context: { applicable: result.status?.applicable === true },+ })+ }+ resetProviderReadinessCache()+ res.json(result)+}))+// GET /api/local-llm/status — both backends + active markerrouter.get('/status', asyncHandler(async (req, res) => {res.json(await getStatus())diff --git a/server/services/localPersistentMindSetup.js b/server/services/localPersistentMindSetup.jsnew file mode 100644index 0000000000..ecd33c0db8--- /dev/null+++ b/server/services/localPersistentMindSetup.js@@ -0,0 +1,259 @@+/**+ * Status + apply for the free local Persistent Mind path (Ollama + 7B).+ *+ * Detect / install / pull stay on the existing local-LLM surfaces+ * (`installBackend`, `controlOllamaServer`, `installModel`). This module only+ * answers "where is this host on the Grok-box mind checklist?" and applies the+ * PortOS-side pins: enable the `ollama` provider, set its default model, and+ * optionally write the Persistent Mind profile. It never downloads weights and+ * never starts a mind turn.+ */++import { detectSystemCapabilities } from '../lib/systemCapabilities.js';+import {+ LOCAL_PERSISTENT_MIND_MODEL,+ LOCAL_PERSISTENT_MIND_PROVIDER_ID,+ localPersistentMindRecommendation,+ matchesLocalPersistentMindModel,+} from '../lib/localPersistentMindRecommendation.js';+import { normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';+import { findCommandOnPath } from '../lib/processEnv.js';+import { getProviderById, updateProvider } from './providers.js';+import { listModels } from './localLlm.js';+import * as ollamaManager from './ollamaManager.js';+import { getConfig, updateConfig } from './cos.js';++const STEP_IDS = Object.freeze([+ 'recommendation',+ 'ollama-installed',+ 'ollama-running',+ 'model-present',+ 'provider-enabled',+ 'mind-profile',+]);++const step = (id, status, detail = null, action = null) => ({+ id,+ status, // 'ready' | 'todo' | 'blocked' | 'skipped'+ detail,+ action,+});++async function probeOllamaInstalled(findCommand = findCommandOnPath) {+ const resolved = await findCommand('ollama');+ return Boolean(resolved);+}++async function probeOllamaRunning() {+ const status = await ollamaManager.getStatus().catch(() => null);+ return status?.available === true;+}++function resolveInstalledModelId(models) {+ const ids = (Array.isArray(models) ? models : [])+ .map((m) => (typeof m === 'string' ? m : m?.id || m?.name))+ .filter((id) => typeof id === 'string' && id.trim());+ return ids.find((id) => matchesLocalPersistentMindModel(id)) || null;+}++/**+ * Describe the Grok-box / CPU-only Persistent Mind setup checklist.+ *+ * @param {{ capabilities?: object, findCommand?: Function }} [deps]+ */+export async function describeLocalPersistentMindSetup(deps = {}) {+ const capabilities = deps.capabilities || await detectSystemCapabilities();+ const recommendation = localPersistentMindRecommendation(capabilities);+ const steps = [];++ if (!recommendation) {+ steps.push(step(+ 'recommendation',+ 'skipped',+ 'This host has a curated GPU coding-agent path (or otherwise does not use the free local Persistent Mind default). Use Models → LLMs → Recommended coding-agent setup when applicable.',+ ));+ return {+ applicable: false,+ recommendation: null,+ steps,+ stepIds: STEP_IDS,+ ready: false,+ };+ }++ steps.push(step(+ 'recommendation',+ 'ready',+ `${recommendation.machine}: ${recommendation.topology}. Coding stays on ${recommendation.codingHarnesses}.`,+ ));++ const installed = await probeOllamaInstalled(deps.findCommand || findCommandOnPath);+ steps.push(step(+ 'ollama-installed',+ installed ? 'ready' : 'todo',+ installed ? 'Ollama CLI is on PATH.' : 'Ollama is not installed (or not on PortOS PATH).',+ installed ? null : { kind: 'install-backend', backend: 'ollama', label: 'Install Ollama' },+ ));++ let running = false;+ if (installed) {+ running = await probeOllamaRunning();+ steps.push(step(+ 'ollama-running',+ running ? 'ready' : 'todo',+ running ? 'Ollama daemon is answering on the local endpoint.' : 'Ollama is installed but not answering yet.',+ running ? null : { kind: 'start-ollama', label: 'Start Ollama' },+ ));+ } else {+ steps.push(step(+ 'ollama-running',+ 'blocked',+ 'Install Ollama before starting the daemon.',+ ));+ }++ let matchedModel = null;+ if (running) {+ const models = await listModels('ollama').catch(() => []);+ matchedModel = resolveInstalledModelId(models);+ steps.push(step(+ 'model-present',+ matchedModel ? 'ready' : 'todo',+ matchedModel+ ? `Recommended model is present as \`${matchedModel}\`.`+ : `Pull \`${LOCAL_PERSISTENT_MIND_MODEL}\` (${recommendation.modelSize}) — tool-capable instruct build for the mind.`,+ matchedModel+ ? null+ : {+ kind: 'pull-model',+ backend: 'ollama',+ modelId: LOCAL_PERSISTENT_MIND_MODEL,+ label: `Pull ${recommendation.modelLabel}`,+ },+ ));+ } else {+ steps.push(step(+ 'model-present',+ 'blocked',+ 'Start Ollama before pulling the recommended model.',+ ));+ }++ const provider = await getProviderById(LOCAL_PERSISTENT_MIND_PROVIDER_ID).catch(() => null);+ const providerEnabled = provider?.enabled === true;+ const providerModelOk = matchedModel+ ? matchesLocalPersistentMindModel(provider?.defaultModel)+ : false;++ let providerStatus = 'todo';+ let providerDetail = 'Enable the built-in Ollama API provider and pin the recommended model.';+ if (!provider) {+ providerStatus = 'blocked';+ providerDetail = 'The built-in `ollama` provider record is missing.';+ } else if (providerEnabled && matchedModel && providerModelOk) {+ providerStatus = 'ready';+ providerDetail = `Ollama provider is enabled with default \`${provider.defaultModel}\`.`;+ } else if (providerEnabled && matchedModel && !providerModelOk) {+ providerStatus = 'todo';+ providerDetail = `Ollama provider is enabled — set default model to \`${matchedModel}\`.`;+ } else if (providerEnabled && !matchedModel) {+ providerStatus = 'ready';+ providerDetail = 'Ollama provider is enabled. Pull the recommended model next (or apply after the pull).';+ }++ steps.push(step(+ 'provider-enabled',+ providerStatus,+ providerDetail,+ provider+ ? { kind: 'enable-provider', providerId: LOCAL_PERSISTENT_MIND_PROVIDER_ID, label: 'Enable Ollama provider' }+ : null,+ ));++ const config = await getConfig().catch(() => null);+ const profile = normalizePersistentMindProfile(config?.persistentMindProfile);+ const mindReady = profile.enabled === true+ && profile.providerId === LOCAL_PERSISTENT_MIND_PROVIDER_ID+ && matchesLocalPersistentMindModel(profile.model);+ steps.push(step(+ 'mind-profile',+ mindReady ? 'ready' : 'todo',+ mindReady+ ? `Persistent Mind profile pins \`${profile.providerId}\` / \`${profile.model}\`.`+ : 'Optionally pin Persistent Mind to the Ollama provider and recommended model.',+ { kind: 'set-mind-profile', label: 'Set Persistent Mind profile', optional: true },+ ));++ const requiredReady = steps+ .filter((s) => s.id !== 'mind-profile')+ .every((s) => s.status === 'ready' || s.status === 'skipped');++ return {+ applicable: true,+ recommendation,+ steps,+ stepIds: STEP_IDS,+ ready: requiredReady,+ matchedModel,+ providerEnabled,+ mindProfileReady: mindReady,+ };+}++/**+ * Enable the Ollama provider (and pin its default model when known). Optionally+ * write the Persistent Mind profile. Does not install Ollama or pull weights.+ *+ * @param {{ setMindProfile?: boolean, modelId?: string }} [options]+ */+export async function applyLocalPersistentMindSetup(options = {}) {+ const setMindProfile = options.setMindProfile === true;+ const status = await describeLocalPersistentMindSetup();+ if (!status.applicable) {+ return {+ success: false,+ error: 'This host is not on the free local Persistent Mind default path.',+ status,+ };+ }++ const modelId = (typeof options.modelId === 'string' && options.modelId.trim())+ || status.matchedModel+ || LOCAL_PERSISTENT_MIND_MODEL;++ const provider = await getProviderById(LOCAL_PERSISTENT_MIND_PROVIDER_ID).catch(() => null);+ if (!provider) {+ return { success: false, error: 'Built-in ollama provider is missing.', status };+ }++ const models = Array.isArray(provider.models) ? [...provider.models] : [];+ if (!models.includes(modelId)) models.unshift(modelId);++ await updateProvider(LOCAL_PERSISTENT_MIND_PROVIDER_ID, {+ enabled: true,+ defaultModel: modelId,+ models,+ });++ let profile = null;+ if (setMindProfile) {+ const config = await getConfig();+ const nextProfile = normalizePersistentMindProfile({+ ...(config?.persistentMindProfile || {}),+ enabled: true,+ providerId: LOCAL_PERSISTENT_MIND_PROVIDER_ID,+ model: modelId,+ });+ const saved = await updateConfig({ persistentMindProfile: nextProfile });+ profile = normalizePersistentMindProfile(saved?.persistentMindProfile);+ }++ const nextStatus = await describeLocalPersistentMindSetup();+ return {+ success: true,+ providerId: LOCAL_PERSISTENT_MIND_PROVIDER_ID,+ modelId,+ profile,+ status: nextStatus,+ };+}diff --git a/server/services/localPersistentMindSetup.test.js b/server/services/localPersistentMindSetup.test.jsnew file mode 100644index 0000000000..70cab1666f--- /dev/null+++ b/server/services/localPersistentMindSetup.test.js@@ -0,0 +1,132 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('../lib/systemCapabilities.js', () => ({+ detectSystemCapabilities: vi.fn(),+}));+vi.mock('../lib/processEnv.js', () => ({+ findCommandOnPath: vi.fn(),+}));+vi.mock('./providers.js', () => ({+ getProviderById: vi.fn(),+ updateProvider: vi.fn(),+}));+vi.mock('./localLlm.js', () => ({+ listModels: vi.fn(),+}));+vi.mock('./ollamaManager.js', () => ({+ getStatus: vi.fn(),+}));+vi.mock('./cos.js', () => ({+ getConfig: vi.fn(),+ updateConfig: vi.fn(),+}));++const { detectSystemCapabilities } = await import('../lib/systemCapabilities.js');+const { findCommandOnPath } = await import('../lib/processEnv.js');+const { getProviderById, updateProvider } = await import('./providers.js');+const { listModels } = await import('./localLlm.js');+const ollamaManager = await import('./ollamaManager.js');+const { getConfig, updateConfig } = await import('./cos.js');+const {+ applyLocalPersistentMindSetup,+ describeLocalPersistentMindSetup,+} = await import('./localPersistentMindSetup.js');++const grokBox = {+ platform: 'linux',+ appleSilicon: false,+ totalMemoryGb: 16,+ cuda: { status: 'absent', gpus: [], maxVramGb: null },+};++const apple64 = {+ platform: 'darwin',+ appleSilicon: true,+ totalMemoryGb: 64,+ cuda: { status: 'absent', gpus: [], maxVramGb: null },+};++beforeEach(() => {+ vi.clearAllMocks();+ detectSystemCapabilities.mockResolvedValue(grokBox);+ findCommandOnPath.mockResolvedValue('/usr/local/bin/ollama');+ ollamaManager.getStatus.mockResolvedValue({ available: true });+ listModels.mockResolvedValue([{ id: 'qwen2.5:7b-instruct' }]);+ getProviderById.mockResolvedValue({+ id: 'ollama',+ enabled: false,+ defaultModel: null,+ models: [],+ });+ getConfig.mockResolvedValue({+ persistentMindProfile: { enabled: false, providerId: '', model: '' },+ });+ updateProvider.mockResolvedValue({ id: 'ollama', enabled: true });+ updateConfig.mockImplementation(async (updates) => ({+ persistentMindProfile: updates.persistentMindProfile,+ }));+});++describe('describeLocalPersistentMindSetup', () => {+ it('skips on curated GPU coding hosts', async () => {+ detectSystemCapabilities.mockResolvedValue(apple64);+ const status = await describeLocalPersistentMindSetup();+ expect(status.applicable).toBe(false);+ expect(status.recommendation).toBeNull();+ expect(status.steps[0].status).toBe('skipped');+ });++ it('reports todo steps on a fresh Grok-box host', async () => {+ listModels.mockResolvedValue([]);+ const status = await describeLocalPersistentMindSetup();+ expect(status.applicable).toBe(true);+ expect(status.recommendation.model).toBe('qwen2.5:7b-instruct');+ expect(status.steps.find((s) => s.id === 'ollama-installed').status).toBe('ready');+ expect(status.steps.find((s) => s.id === 'model-present').status).toBe('todo');+ expect(status.steps.find((s) => s.id === 'model-present').action?.modelId).toBe('qwen2.5:7b-instruct');+ expect(status.steps.find((s) => s.id === 'provider-enabled').status).toBe('todo');+ expect(status.ready).toBe(false);+ });++ it('accepts qwen2.5:7b as satisfying the model step', async () => {+ listModels.mockResolvedValue([{ id: 'qwen2.5:7b' }]);+ getProviderById.mockResolvedValue({+ id: 'ollama',+ enabled: true,+ defaultModel: 'qwen2.5:7b',+ models: ['qwen2.5:7b'],+ });+ const status = await describeLocalPersistentMindSetup();+ expect(status.matchedModel).toBe('qwen2.5:7b');+ expect(status.steps.find((s) => s.id === 'model-present').status).toBe('ready');+ expect(status.steps.find((s) => s.id === 'provider-enabled').status).toBe('ready');+ });+});++describe('applyLocalPersistentMindSetup', () => {+ it('enables the ollama provider and optionally pins the mind profile', async () => {+ const result = await applyLocalPersistentMindSetup({ setMindProfile: true });+ expect(result.success).toBe(true);+ expect(updateProvider).toHaveBeenCalledWith('ollama', expect.objectContaining({+ enabled: true,+ defaultModel: 'qwen2.5:7b-instruct',+ models: expect.arrayContaining(['qwen2.5:7b-instruct']),+ }));+ expect(updateConfig).toHaveBeenCalledWith({+ persistentMindProfile: expect.objectContaining({+ enabled: true,+ providerId: 'ollama',+ model: 'qwen2.5:7b-instruct',+ }),+ });+ expect(result.profile.providerId).toBe('ollama');+ });++ it('refuses apply on hosts outside the free local-mind path', async () => {+ detectSystemCapabilities.mockResolvedValue(apple64);+ const result = await applyLocalPersistentMindSetup({ setMindProfile: true });+ expect(result.success).toBe(false);+ expect(updateProvider).not.toHaveBeenCalled();+ expect(updateConfig).not.toHaveBeenCalled();+ });+});