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
Refresh Ollama-backed provider model lists on install/delete
[._.]/ Adam Eivydbe39d117029
diff --git a/PLAN.md b/PLAN.mdindex 64b8704bba..386442ab1f 100644--- a/PLAN.md+++ b/PLAN.md@@ -269,3 +269,10 @@ Deferred from the PR that clamped CoS task text (`client/src/components/ui/Colla- [ ] **Consolidate `AgentCard`'s duplicate collapse affordance** (`client/src/components/cos/tabs/AgentCard.jsx` ~line 80). `TaskDescription` is a second "long task text with a Show more toggle" implementation one directory over, using a `text.length > 200` heuristic + `max-h-[3.5rem]` + gradient fade instead of measured `line-clamp-2`, and its toggle carries no `aria-expanded`/`aria-controls`. Not consolidated in that PR because `AgentCard` renders *markdown blocks* via `MarkdownOutput`, which `line-clamp` can't clamp — `CollapsibleText` would need a `children`-based max-height variant, and switching would visibly change that card's fade treatment. Wants a deliberate design call on which affordance wins.- [ ] **`metadata.context` is overloaded** — the same key carries a one-line human note (`server/routes/cosJobRoutes.js` ~line 182, `server/services/cosTaskStore.js` ~line 920 escalation context) and a multi-thousand-character agent prompt (`server/services/cosTaskGenerator.js` ~lines 1357-1378, `server/routes/cosTaskRoutes.js` ~line 197). The prompt lives there because `generateTasksMarkdown` flattens `description` to one line and `parseTasksMarkdown` only matches a `- [ ]` block's first line, so newlines in `description` corrupt COS-TASKS.md. Splitting into `metadata.prompt` (payload) + `metadata.context` (note) would touch the markdown round-trip, `LEGACY_DIRECT_FIELDS` in `cosTaskStore.js` ~line 52, `cosTaskMerge.js` ~line 200, the agent prompt builder, and every on-disk task — i.e. a migration. Deferred as disproportionate to what was a presentational problem; the UI clamp handles both shapes correctly today.++### Ollama-backed provider refresh follow-ups (post-install/delete auto-refresh)++Deferred from the fix that makes `server/services/localLlm.js#installModel`/`deleteModel` push a live `refreshProviderModels` call to every Ollama-backed provider after a successful install/delete (`refreshOllamaBackedProviders`, ~line 811).++- [ ] **Dedup the refresh fan-out by daemon base URL instead of by provider.** When N providers (the built-in `ollama` provider plus one or more Claude/Codex/Gemini-over-Ollama CLI/TUI providers) all resolve to the same Ollama daemon (commonly the shared `http://localhost:11434` default — see `ollamaBaseFromProvider` in `server/lib/aiToolkit/providers.js` ~line 124), `refreshOllamaBackedProviders`'s `Promise.all` currently calls `refreshProviderModels(p.id)` once per provider, each independently re-fetching `/api/tags` and re-running the full per-model `/api/show` tool-capability probe against the identical daemon/model set. Fix by grouping providers by normalized base URL, computing the tool-capable model list once per unique base, and applying it to every provider sharing that base. Flagged by the `/simplify` efficiency review — deferred because it needs a "compute without persisting" variant exposed from `server/lib/aiToolkit/providers.js` (see next item), which is a larger surface change than a `localLlm.js`-only fix.+- [ ] **`refreshProviderModels` does one full `providers.json` write per call — batch writes when refreshing multiple providers.** `server/lib/aiToolkit/providers.js#refreshProviderModels` (~line 646) does `loadProviders()` → mutate → `saveProviders(data)` per call, and `saveProviders` invalidates the provider cache and `atomicWrite`s the entire file. `refreshOllamaBackedProviders`'s concurrent fan-out means N Ollama-backed providers produce N full-file writes landing in quick succession (each superseded by the next) and N cache invalidate/repopulate cycles for any concurrent `getAllProviders()`/`getProviderById()` reader. Fix by adding a batch-refresh entry point to the toolkit's provider service that computes all the new model lists first, then applies + persists once. Flagged by the `/simplify` efficiency review — deferred as an `aiToolkit/providers.js` API change, out of scope for the triggering bug fix.diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsxindex dfe3e879bf..02b99183ef 100644--- a/client/src/components/cos/tabs/ScheduleTab.jsx+++ b/client/src/components/cos/tabs/ScheduleTab.jsx@@ -11,10 +11,13 @@ import AppTaskTypeSection from './schedule/AppTaskTypeSection';import TaskConfigDrawer from './schedule/TaskConfigDrawer';import { TASK_FILTERS, DEFAULT_FILTER_ID } from './schedule/scheduleConstants';-export default function ScheduleTab({ apps }) {+// `providers` is owned by ChiefOfStaff (30s poll, see useAutoRefetch there) and+// passed down — same convention as TasksTab/AgentsTab — so this tab's provider/+// model pickers stay live without standing up a second independent poll of the+// same data.+export default function ScheduleTab({ apps, providers }) {const [searchParams, setSearchParams] = useSearchParams();const [schedule, setSchedule] = useState(null);- const [providers, setProviders] = useState(null);const [loading, setLoading] = useState(true);const filterParam = searchParams.get('filter');@@ -41,15 +44,9 @@ export default function ScheduleTab({ apps }) {setLoading(false);}, []);- const fetchProviders = useCallback(async () => {- const data = await api.getProviders().catch(() => null);- setProviders(data?.providers || []);- }, []);-useEffect(() => {fetchSchedule();- fetchProviders();- }, [fetchSchedule, fetchProviders]);+ }, [fetchSchedule]);const handleUpdateTask = async (taskType, settings) => {const result = await api.updateCosTaskInterval(taskType, settings, { silent: true }).catch(err => {diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex 570fe376cc..3203299ecf 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -927,7 +927,7 @@ export default function ChiefOfStaff() {)}{activeTab === 'schedule' && (<div role="tabpanel" id="tabpanel-schedule" aria-labelledby="tab-schedule">- <ScheduleTab apps={apps} />+ <ScheduleTab apps={apps} providers={providers} /></div>)}{activeTab === 'workflow' && (diff --git a/server/lib/aiToolkit/index.js b/server/lib/aiToolkit/index.jsindex 08df786b0e..afbae99683 100644--- a/server/lib/aiToolkit/index.js+++ b/server/lib/aiToolkit/index.js@@ -6,7 +6,7 @@import { fileURLToPath } from 'url';import { dirname, join } from 'path';-import { createProviderService } from './providers.js';+import { createProviderService, isOllamaBackedProvider } from './providers.js';import { createRunnerService } from './runner.js';import { createPromptsService } from './prompts.js';import { createProviderStatusService } from './providerStatus.js';@@ -25,6 +25,7 @@ export * from './validation.js';export * from './errorDetection.js';export * from './constants.js';export { createProviderService, createRunnerService, createPromptsService, createProviderStatusService };+export { isOllamaBackedProvider };export { createProvidersRoutes, createRunsRoutes, createPromptsRoutes, createProviderStatusRoutes };export function createAIToolkit(config = {}) {diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex bac763db5c..9d39638fd2 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -108,15 +108,23 @@ const TOOL_USE_RE = new RegExp([].join('|'), 'i');/**- * A `claude` CLI/TUI provider is "Ollama-backed" — the Claude Ollama- * pattern — when it carries the `ollamaBacked` marker or its ANTHROPIC_BASE_URL- * points at an Ollama daemon. Such a provider runs the full Claude Code harness- * but generates tokens from a local model, so its model list must come from- * Ollama (filtered to tool-use-capable models) rather than the static Anthropic list.+ * Whether `provider` is served by an Ollama daemon rather than its nominal+ * cloud/CLI backend. Covers three shapes: the built-in `ollama` API provider+ * itself (id match — its `endpoint` carries the daemon URL, not `envVars`);+ * an `api`-type provider whose `endpoint` points at Ollama (generic local+ * setups); and the Claude-Ollama CLI/TUI pattern — a `claude` process that+ * carries the `ollamaBacked` marker or an `ANTHROPIC_BASE_URL` pointed at+ * Ollama, running the full Claude Code harness but generating tokens from a+ * local model, so its model list must come from Ollama (filtered to+ * tool-use-capable models) rather than the static Anthropic list. Exported+ * (re-exported by `server/services/providers.js`) so hosts can classify+ * providers the same way this module's own refresh dispatch does, instead of+ * re-deriving the shape check and risking drift.*/-function isOllamaBackedProvider(provider) {+export function isOllamaBackedProvider(provider) {+ if (provider?.id === 'ollama') return true;if (provider?.ollamaBacked === true) return true;- const base = String(provider?.envVars?.ANTHROPIC_BASE_URL || '');+ const base = String(provider?.envVars?.ANTHROPIC_BASE_URL || provider?.endpoint || '');return /:11434\b/.test(base) || /ollama/i.test(base);}diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.jsindex 7739fe2f16..8a5ab436e4 100644--- a/server/lib/aiToolkit/providers.test.js+++ b/server/lib/aiToolkit/providers.test.js@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { mkdir, rm, writeFile } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';-import { createProviderService } from './providers.js';+import { createProviderService, isOllamaBackedProvider } from './providers.js';const TEST_DATA_DIR = join(process.cwd(), 'test-data');@@ -800,3 +800,30 @@ describe('Provider Service', () => {});});});++describe('isOllamaBackedProvider', () => {+ it('matches the built-in ollama API provider by id, regardless of endpoint/envVars', () => {+ expect(isOllamaBackedProvider({ id: 'ollama', type: 'api', endpoint: 'http://localhost:11434/v1', envVars: {} })).toBe(true);+ });++ it('matches an api-type provider whose endpoint points at an Ollama daemon', () => {+ expect(isOllamaBackedProvider({ id: 'local-llm', type: 'api', endpoint: 'http://192.168.1.5:11434/v1' })).toBe(true);+ expect(isOllamaBackedProvider({ id: 'renamed', type: 'api', endpoint: 'https://my-ollama-box.example.com/v1' })).toBe(true);+ });++ it('matches a cli/tui provider carrying the ollamaBacked marker or an Ollama ANTHROPIC_BASE_URL', () => {+ expect(isOllamaBackedProvider({ id: 'claude-ollama', type: 'tui', ollamaBacked: true })).toBe(true);+ expect(isOllamaBackedProvider({ id: 'claude', type: 'cli', envVars: { ANTHROPIC_BASE_URL: 'http://localhost:11434' } })).toBe(true);+ });++ it('does not match a cloud provider with an unrelated endpoint', () => {+ expect(isOllamaBackedProvider({ id: 'anthropic', type: 'api', endpoint: 'https://api.anthropic.com' })).toBe(false);+ expect(isOllamaBackedProvider({ id: 'openai', type: 'api', endpoint: 'https://api.openai.com/v1' })).toBe(false);+ });++ it('handles missing/null provider input without throwing', () => {+ expect(isOllamaBackedProvider(null)).toBe(false);+ expect(isOllamaBackedProvider(undefined)).toBe(false);+ expect(isOllamaBackedProvider({})).toBe(false);+ });+});diff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex d60938107d..1dc3f90bd8 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -35,7 +35,7 @@ import { sanitizeOllamaName } from '../lib/localLlmDisk.js'import { recommendEditorialModel, isVisionModel, isVisionCapableCliProvider, isToolUseModel } from '../lib/localModelHeuristics.js'import * as ollamaManager from './ollamaManager.js'import * as lmStudioManager from './lmStudioManager.js'-import { getProviderById, getAllProviders, updateProvider } from './providers.js'+import { getProviderById, getAllProviders, updateProvider, refreshProviderModels, isOllamaBackedProvider } from './providers.js'const execFileAsync = promisify(execFile)const ENV_PATH = join(PATHS.root, '.env')@@ -808,6 +808,27 @@ async function listVisionCliModels() {// ---- install / delete --------------------------------------------------------+/**+ * Push a live model-list refresh to every provider backed by the Ollama daemon,+ * so an install/delete on the Local LLMs tab is immediately reflected in every+ * provider/model picker (task scheduler, pipeline stages, etc.) without the user+ * having to find and click "Refresh Models" on the AI Providers page. Fire-and-+ * forget from the caller's perspective — the install/delete response shouldn't+ * wait on an extra round-trip to Ollama per matching provider. Best-effort per+ * provider — one failing refresh (e.g. Ollama briefly unreachable mid-pull)+ * must not block the others.+ */+function refreshOllamaBackedProviders() {+ getAllProviders().then(({ providers }) => {+ const targets = (providers || []).filter(isOllamaBackedProvider)+ return Promise.all(targets.map((p) => refreshProviderModels(p.id).catch((err) => {+ console.error(`⚠️ Failed to refresh models for provider ${p.id} after Ollama model change: ${err.message}`)+ })))+ }).catch((err) => {+ console.error(`⚠️ Failed to list providers for post-install Ollama refresh: ${err.message}`)+ })+}+/*** Install (pull/download) a model on a backend.* @param {(p) => void} [onProgress] - streaming progress (Ollama only)@@ -815,7 +836,9 @@ async function listVisionCliModels() {export async function installModel(backend, modelId, onProgress) {if (!isBackend(backend)) return { success: false, error: `Unknown backend: ${backend}` }if (backend === 'ollama') {- return ollamaManager.pullModel(modelId, onProgress)+ const result = await ollamaManager.pullModel(modelId, onProgress)+ if (result.success) refreshOllamaBackedProviders()+ return result}// LM Studio: prefer the `lms` CLI (real, blocking download), fall back to the// REST hook.@@ -842,7 +865,9 @@ export async function installModel(backend, modelId, onProgress) {export async function deleteModel(backend, modelId) {if (!isBackend(backend)) return { success: false, error: `Unknown backend: ${backend}` }if (backend === 'ollama') {- return ollamaManager.deleteModel(modelId)+ const result = await ollamaManager.deleteModel(modelId)+ if (result.success) refreshOllamaBackedProviders()+ return result}// LM Studio has no delete in its REST API and the `lms` CLI has no `rm`// command — deleteModel removes the model's on-disk folder directly.diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.jsindex 81f80c2c57..9e938280cb 100644--- a/server/services/localLlm.test.js+++ b/server/services/localLlm.test.js@@ -46,7 +46,16 @@ const mocks = vi.hoisted(() => ({providers: {getProviderById: vi.fn(async () => ({ id: 'ollama', enabled: false })),getAllProviders: vi.fn(async () => ({ providers: [] })),- updateProvider: vi.fn(async () => ({}))+ updateProvider: vi.fn(async () => ({})),+ refreshProviderModels: vi.fn(async (id) => ({ id, models: [] })),+ // Mirrors the real aiToolkit/providers.js predicate (not a spy — tests+ // assert against refreshProviderModels calls, not this classification).+ isOllamaBackedProvider: (provider) => {+ if (provider?.id === 'ollama') return true;+ if (provider?.ollamaBacked === true) return true;+ const base = String(provider?.envVars?.ANTHROPIC_BASE_URL || provider?.endpoint || '');+ return /:11434\b/.test(base) || /ollama/i.test(base);+ }}}));vi.mock('./ollamaManager.js', () => mocks.ollama);@@ -91,6 +100,11 @@ const fakeChild = ({ code = 0, lines = [] } = {}) => {const writeEnv = (content) => fs.writeFileSync(path.join(state.root, '.env'), content);+// A `setTimeout` macrotask always fires after every microtask queued before+// it — including chained promise `.then()`s a fire-and-forget call kicked off+// — so this reliably waits out an unwaited async chain in tests.+const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 0));+let svc;beforeEach(async () => {vi.clearAllMocks(); // clears calls, keeps the default impls defined above@@ -177,6 +191,43 @@ describe('localLlm', () => {it('rejects an unknown backend', async () => {expect((await svc.installModel('nope', 'x')).success).toBe(false);});+ it('refreshes Ollama-backed providers after a successful install', async () => {+ mocks.providers.getAllProviders.mockResolvedValueOnce({+ providers: [+ { id: 'ollama' },+ { id: 'claude-ollama', type: 'tui', ollamaBacked: true },+ { id: 'anthropic', type: 'api', endpoint: 'https://api.anthropic.com' }+ ]+ });+ const result = await svc.installModel('ollama', 'llama3.2');+ expect(result.success).toBe(true);+ // The refresh is fire-and-forget (doesn't block the install response) —+ // flush the microtask queue so the async chain it kicks off has settled.+ await flushMicrotasks();+ expect(mocks.providers.refreshProviderModels).toHaveBeenCalledWith('ollama');+ expect(mocks.providers.refreshProviderModels).toHaveBeenCalledWith('claude-ollama');+ expect(mocks.providers.refreshProviderModels).not.toHaveBeenCalledWith('anthropic');+ });+ it('refreshes Ollama-backed providers after a successful delete', async () => {+ mocks.providers.getAllProviders.mockResolvedValueOnce({ providers: [{ id: 'ollama' }] });+ await svc.deleteModel('ollama', 'llama3.2');+ await flushMicrotasks();+ expect(mocks.providers.refreshProviderModels).toHaveBeenCalledWith('ollama');+ });+ it('does not refresh providers when the Ollama pull fails', async () => {+ mocks.ollama.pullModel.mockResolvedValueOnce({ success: false, error: 'boom' });+ mocks.providers.getAllProviders.mockResolvedValueOnce({ providers: [{ id: 'ollama' }] });+ await svc.installModel('ollama', 'llama3.2');+ await flushMicrotasks();+ expect(mocks.providers.refreshProviderModels).not.toHaveBeenCalled();+ });+ it('does not fail install when a provider refresh throws', async () => {+ mocks.providers.getAllProviders.mockResolvedValueOnce({ providers: [{ id: 'ollama' }] });+ mocks.providers.refreshProviderModels.mockRejectedValueOnce(new Error('unreachable'));+ const result = await svc.installModel('ollama', 'llama3.2');+ expect(result.success).toBe(true);+ await flushMicrotasks(); // let the rejection be caught internally, not surface as unhandled+ });});describe('controlOllamaServer', () => {diff --git a/server/services/providers.js b/server/services/providers.jsindex 4cfb2e7ceb..08eebb8001 100644--- a/server/services/providers.js+++ b/server/services/providers.js@@ -10,6 +10,11 @@ import { setAIToolkitInstance, requireToolkit } from '../lib/aiToolkitState.js';// providers / runner / promptService all observe the same instance.export const setAIToolkit = setAIToolkitInstance;+// Pure classification helper, not a toolkit-instance method — a direct+// re-export (no requireToolkit() indirection needed) so callers can classify+// a provider shape without an initialized toolkit instance.+export { isOllamaBackedProvider } from '../lib/aiToolkit/providers.js';+export async function getAllProviders() {return requireToolkit().services.providers.getAllProviders();}