Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: route every inference call through one managed-runtime wake (#8104)

[._.]/ Adam Eivyecbda9d0d87d
diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.js
index 5ab1a9d445..840977da62 100644
--- a/server/routes/localLlm.test.js
+++ b/server/routes/localLlm.test.js
@@ -57,6 +57,12 @@ vi.mock('../services/ollamaManager.js', () => ({
getLastLoadedModelsError: vi.fn(() => null),
getLoadedModels: vi.fn(async () => []),
unloadModel: vi.fn(),
+ // Reached via providerExecutionReadiness.js's managed-runtime table
+ // (issue #8104) whenever an unmocked module transitively imports
+ // aiProvider.js — this suite never drives that path, so a no-op stub keeps
+ // the module graph loadable.
+ ensureProviderReady: vi.fn(async () => ({ success: true })),
+ isOllamaProvider: vi.fn(() => false),
}));
vi.mock('../services/lmStudioManager.js', () => ({
diff --git a/server/services/aiProvider.js b/server/services/aiProvider.js
index b464b515e8..8ea5e0ebf4 100644
--- a/server/services/aiProvider.js
+++ b/server/services/aiProvider.js
@@ -5,9 +5,7 @@
import { getAllProviders } from './providers.js';
import { startAIOp } from './aiStatusEvents.js';
-import { ensureProviderReady as ensureOllamaProviderReady, isOllamaProvider } from './ollamaManager.js';
-import { ensureMtplxProviderReady, isMtplxProvider } from './mtplxServerManager.js';
-import { ensureSlotstreamProviderReady, isSlotstreamProvider } from './slotstreamServerManager.js';
+import { ensureManagedRuntimeReady } from './providerExecutionReadiness.js';
// localModelHealing is lazy-imported at its (rare, error-recovery) call site
// below — a static import here pulls its notifications/providers deps (which
// eagerly import fileUtils `PATHS`) into every aiProvider consumer's module
@@ -498,40 +496,17 @@ export async function callProviderAISimple(provider, model, prompt, options = {}
});
}
- if (isOllamaProvider(provider)) {
- statusOp.update('provider:starting', 'Starting Ollama if needed…', { providerId: provider.id });
- const ready = await ensureOllamaProviderReady(provider).catch((err) => ({ success: false, error: err.message }));
- if (!ready.success) {
- const error = `Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}`;
- statusOp.error(error);
- return { error };
- }
- }
-
- // The idle reaper may have stopped MTPLX to release its checkpoint. This is
- // the lazy half of that bargain — and the only place the idle clock is
- // refreshed, so a run that takes an hour still counts as use throughout.
- if (isMtplxProvider(provider)) {
- statusOp.update('provider:starting', 'Starting MTPLX if needed…', { providerId: provider.id });
- const ready = await ensureMtplxProviderReady(provider).catch((err) => ({ success: false, error: err.message }));
- if (!ready.success) {
- const error = `MTPLX is not running and PortOS could not start it: ${ready.error || 'unknown error'}`;
- statusOp.error(error);
- return { error };
- }
- }
-
- // Same bargain for Slotstream: this is the only place a simple call refreshes
- // its idle clock, so without this branch the reaper would stop the daemon
- // mid-session and the next call would get a bare connection refusal.
- if (isSlotstreamProvider(provider)) {
- statusOp.update('provider:starting', 'Starting Slotstream if needed…', { providerId: provider.id });
- const ready = await ensureSlotstreamProviderReady(provider).catch((err) => ({ success: false, error: err.message }));
- if (!ready.success) {
- const error = `Slotstream is not running and PortOS could not start it: ${ready.error || 'unknown error'}`;
- statusOp.error(error);
- return { error };
- }
+ // The idle reaper may stop a managed local runtime (Ollama, MTPLX,
+ // Slotstream) to release memory/checkpoint. This is the lazy half of that
+ // bargain — the only place a simple call refreshes the idle clock, so a
+ // run that takes an hour still counts as use throughout, and the next call
+ // doesn't get a bare connection refusal.
+ const ready = await ensureManagedRuntimeReady(provider, {
+ onStarting: (label) => statusOp.update('provider:starting', `Starting ${label} if needed…`, { providerId: provider.id }),
+ });
+ if (!ready.success) {
+ statusOp.error(ready.error);
+ return { error: ready.error };
}
const first = await postChatCompletion(provider, model, body, opts);
diff --git a/server/services/askService.js b/server/services/askService.js
index e7100f5ab1..334cc75bb8 100644
--- a/server/services/askService.js
+++ b/server/services/askService.js
@@ -40,7 +40,7 @@ import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';
import { applyCredentialBootstrap, needsProcessGroup, trackDetachedGroup } from '../lib/credentialBootstrap.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
-import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';
+import { ensureManagedRuntimeReady } from './providerExecutionReadiness.js';
import { evaluateSecretEndpoint } from '../lib/aiToolkit/endpointGuard.js';
import { iterateOpenAiChat } from '../lib/openAiChatStream.js';
@@ -460,9 +460,9 @@ async function* streamCompletion(provider, model, prompt, signal) {
throw new Error(`Provider endpoint blocked: ${guard.reason}`);
}
}
- const ready = await ensureOllamaProviderReady(provider);
+ const ready = await ensureManagedRuntimeReady(provider);
if (!ready.success) {
- throw new Error(`Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}`);
+ throw new Error(ready.error);
}
for await (const chunk of iterateOpenAiChat({
endpoint: provider.endpoint,
diff --git a/server/services/askService.test.js b/server/services/askService.test.js
index 693b69013f..4f1f1e8e20 100644
--- a/server/services/askService.test.js
+++ b/server/services/askService.test.js
@@ -10,6 +10,17 @@ vi.mock('./providers.js', () => ({
getProviderById: vi.fn(),
}));
+// Issue #8104: `streamCompletion` routes every API-shaped provider through the
+// single shared managed-runtime wake instead of an Ollama-only check, so
+// MTPLX/Slotstream get woken (and their idle clock refreshed) too. Mocked here
+// so these tests assert the DISPATCH — that askService consults the shared
+// gate for any provider and never sends the chat request when it fails —
+// without depending on the real MTPLX/Slotstream/Ollama manager modules,
+// which are covered on their own terms in providerExecutionReadiness.test.js.
+vi.mock('./providerExecutionReadiness.js', () => ({
+ ensureManagedRuntimeReady: vi.fn(),
+}));
+
vi.mock('../lib/childProcess.js', async (importOriginal) => {
const actual = await importOriginal();
return { ...actual, spawn: vi.fn() };
@@ -68,6 +79,7 @@ const identity = await import('./identity.js');
const character = await import('./character.js');
const calendarSync = await import('./calendarSync.js');
const providers = await import('./providers.js');
+const providerExecutionReadiness = await import('./providerExecutionReadiness.js');
const askService = await import('./askService.js');
@@ -85,6 +97,7 @@ beforeEach(() => {
character.getCharacter.mockResolvedValue({ name: 'Adam', class: 'Developer' });
calendarSync.getEvents.mockResolvedValue({ events: [] });
catalogDB.hybridSearchIngredients.mockResolvedValue([]);
+ providerExecutionReadiness.ensureManagedRuntimeReady.mockResolvedValue({ success: true });
});
describe('gatherSources', () => {
@@ -764,4 +777,56 @@ describe('runAsk', () => {
expect(callCount).toBe(1);
});
});
+
+ describe('managed-runtime wake (issue #8104)', () => {
+ // Before this fix, `streamCompletion` only called `ensureProviderReady`
+ // from ollamaManager.js — a daemon stopped by the idle reaper (MTPLX,
+ // Slotstream) was never woken for an Ask turn and every request against
+ // it failed with a bare connection refusal instead. It now routes through
+ // the shared `ensureManagedRuntimeReady`, which recognizes all three.
+ it('consults the shared managed-runtime gate before sending the chat request', async () => {
+ providers.getActiveProvider.mockResolvedValue(fakeStreamProvider());
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(buildSSEResponse(['Hello.']));
+
+ const events = [];
+ for await (const evt of askService.runAsk({ question: 'hi' })) events.push(evt);
+
+ expect(providerExecutionReadiness.ensureManagedRuntimeReady).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'fake' }),
+ );
+ // The gate ran before the chat request went out, not after. (Read the
+ // call order BEFORE mockRestore(), which also resets the recorded calls.)
+ expect(fetchSpy.mock.calls.length).toBeGreaterThan(0);
+ const gateOrder = providerExecutionReadiness.ensureManagedRuntimeReady.mock.invocationCallOrder[0];
+ const fetchOrder = fetchSpy.mock.invocationCallOrder[0];
+ fetchSpy.mockRestore();
+ expect(gateOrder).toBeLessThan(fetchOrder);
+ });
+
+ // Covers MTPLX and Slotstream (and any future managed runtime) through the
+ // one shared contract, rather than re-deriving each manager's own
+ // recognition logic here — that's `providerExecutionReadiness.test.js`'s
+ // job. What Ask owns is: a failed wake must stop the turn before fetch,
+ // and the runtime's own error message must reach the caller unmodified.
+ it('never sends the chat request when the managed runtime fails to wake, and surfaces its error', async () => {
+ providers.getActiveProvider.mockResolvedValue(fakeStreamProvider());
+ providerExecutionReadiness.ensureManagedRuntimeReady.mockResolvedValue({
+ success: false,
+ error: 'MTPLX is not running and PortOS could not start it: checkpoint failed to load',
+ });
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(buildSSEResponse(['should not reach here']));
+
+ const events = [];
+ for await (const evt of askService.runAsk({ question: 'hi' })) events.push(evt);
+ const callCount = fetchSpy.mock.calls.length;
+ fetchSpy.mockRestore();
+
+ const errorEvt = events.find((e) => e.type === 'error');
+ expect(errorEvt?.error).toBe(
+ 'Provider stream failed: MTPLX is not running and PortOS could not start it: checkpoint failed to load',
+ );
+ expect(events.find((e) => e.type === 'done')).toBeUndefined();
+ expect(callCount).toBe(0);
+ });
+ });
});
diff --git a/server/services/insightsService.test.js b/server/services/insightsService.test.js
index 295a0e9f8c..7637a3ce21 100644
--- a/server/services/insightsService.test.js
+++ b/server/services/insightsService.test.js
@@ -1,8 +1,10 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-// Mock the provider-readiness check so any code path that touches it runs offline.
-vi.mock('./ollamaManager.js', () => ({
- ensureProviderReady: vi.fn().mockResolvedValue({ success: true }),
+// Mock the shared managed-runtime wake (issue #8104) so any code path that
+// touches it runs offline instead of reaching the real Ollama/MTPLX/Slotstream
+// manager modules.
+vi.mock('./providerExecutionReadiness.js', () => ({
+ ensureManagedRuntimeReady: vi.fn().mockResolvedValue({ success: true }),
}));
// generateThemeAnalysis/refreshCrossDomainNarrative call the shared
// aiProvider.callProviderAISimple transport (see aiProvider.test.js for its own
diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.js
index ecadc40be3..996e45684c 100644
--- a/server/services/localLlmPlayground.js
+++ b/server/services/localLlmPlayground.js
@@ -3,7 +3,7 @@ import { createRun, finalizeRunRecord } from './runner.js';
import { ensureBackendProvider } from './localLlm.js';
import { getProviderById } from './providers.js';
import { markProviderAvailable } from './providerStatus.js';
-import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';
+import { ensureManagedRuntimeReady } from './providerExecutionReadiness.js';
import { anyAbortSignal } from '../lib/requestAbort.js';
// The SSE read loop lives in `lib/openAiChatStream.js` so the assessments
// service can measure a bare loopback daemon that has no provider record.
@@ -124,9 +124,9 @@ async function resolveLocalProvider(backend) {
async function streamChatCompletion({ provider, backend, modelId, prompt, systemPrompt, images, temperature, maxTokens, extraBody = {}, signal, onChunk, onStats, nativeOllamaUsage = false }) {
if (backend === 'ollama') {
- const ready = await ensureOllamaProviderReady(provider).catch((err) => ({ success: false, error: err.message }));
+ const ready = await ensureManagedRuntimeReady(provider);
if (!ready.success) {
- throw new Error(`Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}`);
+ throw new Error(ready.error);
}
}
diff --git a/server/services/localLlmPlayground.test.js b/server/services/localLlmPlayground.test.js
index 105ef00483..96180c575b 100644
--- a/server/services/localLlmPlayground.test.js
+++ b/server/services/localLlmPlayground.test.js
@@ -4,7 +4,7 @@ vi.mock('./runner.js', () => ({ createRun: vi.fn(), finalizeRunRecord: vi.fn() }
vi.mock('./localLlm.js', () => ({ ensureBackendProvider: vi.fn(() => Promise.resolve()) }));
vi.mock('./providers.js', () => ({ getProviderById: vi.fn() }));
vi.mock('./providerStatus.js', () => ({ markProviderAvailable: vi.fn(() => Promise.resolve()) }));
-vi.mock('./ollamaManager.js', () => ({ ensureProviderReady: vi.fn(() => Promise.resolve({ success: true })) }));
+vi.mock('./providerExecutionReadiness.js', () => ({ ensureManagedRuntimeReady: vi.fn(() => Promise.resolve({ success: true })) }));
import { buildPrompt, summarizeTimings, runLocalLlmTest } from './localLlmPlayground.js';
import { __resetUsageSupport } from '../lib/openAiChatStream.js';
diff --git a/server/services/providerExecutionReadiness.js b/server/services/providerExecutionReadiness.js
index 9440c5106e..5e24f8a506 100644
--- a/server/services/providerExecutionReadiness.js
+++ b/server/services/providerExecutionReadiness.js
@@ -21,6 +21,36 @@ const failedReadiness = (runtime, result) => ({
error: `${runtime} is not running and PortOS could not start it: ${result?.error || 'unknown error'}`,
});
+// Single ordered table of every managed local runtime this install can wake
+// before an inference call. Every call site (toolkit runner, aiProvider,
+// askService, visionTest, localLlmPlayground) routes through
+// `ensureManagedRuntimeReady` instead of hand-rolling its own subset of these
+// rows — see issue #8104. Recognition (`is*Provider`) and lifecycle policy
+// (`ensure*Ready`) stay owned by each manager module; this table only orders
+// them and gives them one shared error/notify contract.
+const MANAGED_RUNTIMES = [
+ { label: 'Ollama', matches: isOllamaProvider, ensure: ensureOllamaProviderReady },
+ { label: 'MTPLX', matches: isMtplxProvider, ensure: ensureMtplxProviderReady },
+ { label: 'Slotstream', matches: isSlotstreamProvider, ensure: ensureSlotstreamProviderReady },
+];
+
+/**
+ * Wake the managed local runtime (if any) that owns `provider`, before an
+ * inference call reaches it. A provider that no row recognizes (a public API
+ * provider, or a private-network endpoint PortOS doesn't manage) is a no-op
+ * success. `onStarting(label)` fires just before the matching row's `ensure`
+ * runs, so a caller can surface a "Starting <label> if needed…" status.
+ * @returns {Promise<{success:boolean,error?:string}>}
+ */
+export async function ensureManagedRuntimeReady(provider, { onStarting } = {}) {
+ const runtime = MANAGED_RUNTIMES.find((row) => row.matches(provider));
+ if (!runtime) return { success: true };
+
+ onStarting?.(runtime.label);
+ const result = await runtime.ensure(provider).catch((err) => ({ success: false, error: err.message }));
+ return result.success ? result : failedReadiness(runtime.label, result);
+}
+
/**
* @returns {Promise<{success:boolean,error?:string}>}
*/
@@ -35,20 +65,5 @@ export async function ensureProviderReadyForExecution(provider) {
};
}
- if (isOllamaProvider(provider)) {
- const result = await ensureOllamaProviderReady(provider);
- return result.success ? result : failedReadiness('Ollama', result);
- }
-
- if (isMtplxProvider(provider)) {
- const result = await ensureMtplxProviderReady(provider);
- return result.success ? result : failedReadiness('MTPLX', result);
- }
-
- if (isSlotstreamProvider(provider)) {
- const result = await ensureSlotstreamProviderReady(provider);
- return result.success ? result : failedReadiness('Slotstream', result);
- }
-
- return { success: true };
+ return ensureManagedRuntimeReady(provider);
}
diff --git a/server/services/providerExecutionReadiness.test.js b/server/services/providerExecutionReadiness.test.js
index b7649c704e..6431816718 100644
--- a/server/services/providerExecutionReadiness.test.js
+++ b/server/services/providerExecutionReadiness.test.js
@@ -1,4 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { readdirSync, readFileSync, statSync } from 'fs';
+import { dirname, join, relative } from 'path';
+import { fileURLToPath } from 'url';
const mocks = vi.hoisted(() => ({
ensureOllama: vi.fn(),
@@ -24,7 +27,7 @@ vi.mock('./slotstreamServerManager.js', () => ({
isSlotstreamProvider: mocks.isSlotstream,
}));
-const { ensureProviderReadyForExecution } = await import('./providerExecutionReadiness.js');
+const { ensureProviderReadyForExecution, ensureManagedRuntimeReady } = await import('./providerExecutionReadiness.js');
describe('provider execution readiness', () => {
beforeEach(() => {
@@ -107,3 +110,84 @@ describe('provider execution readiness', () => {
});
});
});
+
+describe('ensureManagedRuntimeReady', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.ensureOllama.mockResolvedValue({ success: true });
+ mocks.ensureMtplx.mockResolvedValue({ success: true });
+ mocks.isOllama.mockReturnValue(false);
+ mocks.isMtplx.mockReturnValue(false);
+ mocks.ensureSlotstream.mockResolvedValue({ success: true });
+ mocks.isSlotstream.mockReturnValue(false);
+ });
+
+ it('is a no-op success for a provider no row recognizes', async () => {
+ const provider = { id: 'remote', type: 'api', endpoint: 'https://api.example.com/v1' };
+ await expect(ensureManagedRuntimeReady(provider)).resolves.toEqual({ success: true });
+ expect(mocks.ensureOllama).not.toHaveBeenCalled();
+ expect(mocks.ensureMtplx).not.toHaveBeenCalled();
+ expect(mocks.ensureSlotstream).not.toHaveBeenCalled();
+ });
+
+ it('fires onStarting with the matched runtime label before waking it', async () => {
+ const provider = { id: 'mtplx', type: 'api', endpoint: 'http://127.0.0.1:8000/v1' };
+ mocks.isMtplx.mockReturnValue(true);
+ const onStarting = vi.fn();
+
+ await expect(ensureManagedRuntimeReady(provider, { onStarting })).resolves.toEqual({ success: true });
+ expect(onStarting).toHaveBeenCalledWith('MTPLX');
+ expect(mocks.ensureMtplx).toHaveBeenCalledWith(provider);
+ });
+
+ it('turns a rejected ensure() into a failed-readiness result instead of throwing', async () => {
+ const provider = { id: 'ollama', type: 'api', endpoint: 'http://localhost:11434/v1' };
+ mocks.isOllama.mockReturnValue(true);
+ mocks.ensureOllama.mockRejectedValue(new Error('spawn ENOENT'));
+
+ await expect(ensureManagedRuntimeReady(provider)).resolves.toEqual({
+ success: false,
+ error: 'Ollama is not running and PortOS could not start it: spawn ENOENT',
+ });
+ });
+});
+
+describe('managed-runtime wake ownership (issue #8104)', () => {
+ // `bootstrap.js`'s boot-time `ensureRunning` import from `ollamaManager.js`
+ // is a different symbol (the daemon's own startup hook, not a per-call
+ // readiness gate) and stays allowed — this only guards the three symbols
+ // `providerExecutionReadiness.js` wraps into `ensureManagedRuntimeReady`.
+ const GUARDED_IMPORTS = [
+ { module: './ollamaManager.js', symbol: 'ensureProviderReady' },
+ { module: './mtplxServerManager.js', symbol: 'ensureMtplxProviderReady' },
+ { module: './slotstreamServerManager.js', symbol: 'ensureSlotstreamProviderReady' },
+ ];
+
+ const servicesDir = dirname(fileURLToPath(import.meta.url));
+
+ function listServiceFiles(dir) {
+ return readdirSync(dir).flatMap((name) => {
+ const full = join(dir, name);
+ const stat = statSync(full);
+ if (stat.isDirectory()) return listServiceFiles(full);
+ if (!name.endsWith('.js') || name.endsWith('.test.js')) return [];
+ return [full];
+ });
+ }
+
+ it('lets only providerExecutionReadiness.js import the raw per-runtime wake functions', () => {
+ const offenders = [];
+ for (const file of listServiceFiles(servicesDir)) {
+ if (relative(servicesDir, file) === 'providerExecutionReadiness.js') continue;
+ const source = readFileSync(file, 'utf8');
+ for (const { module, symbol } of GUARDED_IMPORTS) {
+ const escapedModule = module.replace(/[.]/g, '\\.');
+ const importLine = new RegExp(`import\\s*\\{[^}]*\\b${symbol}\\b[^}]*\\}\\s*from\\s*['"]${escapedModule}['"]`);
+ if (importLine.test(source)) {
+ offenders.push(`${relative(servicesDir, file)} imports ${symbol} from ${module}`);
+ }
+ }
+ }
+ expect(offenders).toEqual([]);
+ });
+});
diff --git a/server/services/visionTest.frameGuard.test.js b/server/services/visionTest.frameGuard.test.js
index a2a5c99493..d4dc25eeb1 100644
--- a/server/services/visionTest.frameGuard.test.js
+++ b/server/services/visionTest.frameGuard.test.js
@@ -17,7 +17,7 @@ vi.mock('./providers.js', () => ({
})),
}));
vi.mock('../lib/fetchWithTimeout.js', () => ({ fetchWithTimeout: vi.fn() }));
-vi.mock('./ollamaManager.js', () => ({ ensureProviderReady: vi.fn(async () => ({ success: true })) }));
+vi.mock('./providerExecutionReadiness.js', () => ({ ensureManagedRuntimeReady: vi.fn(async () => ({ success: true })) }));
vi.mock('./visionCli.js', () => ({ describeImageViaCli: vi.fn() }));
vi.mock('../lib/aiToolkit/endpointGuard.js', () => ({
assertSecretEndpoint: vi.fn(),
diff --git a/server/services/visionTest.js b/server/services/visionTest.js
index 7517fb22e7..4aae14b6f5 100644
--- a/server/services/visionTest.js
+++ b/server/services/visionTest.js
@@ -11,7 +11,6 @@ import { getProviderById } from './providers.js';
import { PATHS, resolveScreenshot } from '../lib/fileUtils.js';
import { describeFrameStats, isDegenerateFrame } from '../lib/imageFrameStats.js';
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
-import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';
import { describeImageViaCli } from './visionCli.js';
import { assertSecretEndpoint, evaluateSecretEndpoint } from '../lib/aiToolkit/endpointGuard.js';
@@ -67,6 +66,11 @@ async function loadImageAsBase64(imagePath) {
/**
* Call LM Studio API with vision request
* @param {Object} options - Request options
+ * @param {Object} [options.provider] - The full provider record, so a managed
+ * local runtime (Ollama, MTPLX, Slotstream) on a non-default endpoint is
+ * still recognized by id/name, not just its default port. Falls back to
+ * `{ endpoint }` when omitted, matching the recognition PortOS could do
+ * before this parameter existed.
* @param {string} options.endpoint - API endpoint
* @param {string} options.apiKey - API key
* @param {string} options.model - Model to use
@@ -79,14 +83,19 @@ async function loadImageAsBase64(imagePath) {
* truncates mid-output and fails to parse.
* @returns {Promise<Object>} - API response
*/
-async function callVisionAPI({ endpoint, apiKey, allowCustomEndpoint, model, imageDataUrl, prompt, timeout = DEFAULT_VISION_TIMEOUT_MS, maxTokens = 500 }) {
+async function callVisionAPI({ provider, endpoint, apiKey, allowCustomEndpoint, model, imageDataUrl, prompt, timeout = DEFAULT_VISION_TIMEOUT_MS, maxTokens = 500 }) {
// Never send the API key to an arbitrary/metadata host (SSRF / key
// exfiltration). Keyless local-LLM calls skip this guard entirely.
assertSecretEndpoint(endpoint, { hasSecret: Boolean(apiKey), allowCustomEndpoint: allowCustomEndpoint === true });
- await ensureOllamaProviderReady({ endpoint }).then((ready) => {
- if (!ready.success) throw new Error(`Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}`);
- });
+ // Deferred so visionTest.js's static import closure stays flat — it has
+ // many importers, and importScoping.test.js enforces the budget.
+ // See root AGENTS.md's #8104 pattern: every inference entry point routes
+ // through this one managed-runtime wake instead of hand-rolling Ollama-only
+ // dispatch.
+ const { ensureManagedRuntimeReady } = await import('./providerExecutionReadiness.js');
+ const ready = await ensureManagedRuntimeReady(provider || { endpoint });
+ if (!ready.success) throw new Error(ready.error);
const response = await fetchWithTimeout(`${endpoint}/chat/completions`, {
method: 'POST',
@@ -189,6 +198,7 @@ export async function testVision({ imagePath, prompt, expectedContent, providerI
// Call vision API
const apiResponse = await callVisionAPI({
+ provider,
endpoint: provider.endpoint,
apiKey: provider.apiKey,
allowCustomEndpoint: provider.allowCustomEndpoint,
@@ -292,6 +302,7 @@ export async function describeImageDataUrlDetailed({ dataUrl, prompt, providerId
if (!visionModel) throw new Error('No model specified and provider has no default model');
const apiResponse = await callVisionAPI({
+ provider,
endpoint: provider.endpoint,
apiKey: provider.apiKey,
allowCustomEndpoint: provider.allowCustomEndpoint,
diff --git a/server/services/visionTest.test.js b/server/services/visionTest.test.js
index ffb17e3b31..59faa6a559 100644
--- a/server/services/visionTest.test.js
+++ b/server/services/visionTest.test.js
@@ -12,6 +12,13 @@ vi.mock('./visionCli.js', () => ({
describeImageViaCli: vi.fn(),
}));
+// Mock the shared managed-runtime wake (issue #8104) so this suite's fixtures
+// never depend on the real MTPLX/Slotstream/Ollama manager modules (and the
+// heavier deps they in turn statically import, e.g. `sleep` from fileUtils.js).
+vi.mock('./providerExecutionReadiness.js', () => ({
+ ensureManagedRuntimeReady: vi.fn(() => Promise.resolve({ success: true })),
+}));
+
// Mock fs/promises for image loading and directory listing
vi.mock('fs/promises', () => ({
readFile: vi.fn(),
@@ -32,6 +39,7 @@ import { getProviderById } from './providers.js';
import { describeImageViaCli } from './visionCli.js';
import { readFile, readdir } from 'fs/promises';
import { resolveScreenshot } from '../lib/fileUtils.js';
+import { ensureManagedRuntimeReady } from './providerExecutionReadiness.js';
describe('Vision Test Service', () => {
const mockProvider = {
@@ -368,6 +376,64 @@ describe('Vision Test Service', () => {
await describeImageDataUrlDetailed({ dataUrl: DATA_URL, prompt: 'caption', providerId: 'codex' });
expect(describeImageViaCli).toHaveBeenCalledWith(expect.objectContaining({ timeout: 300000 }));
});
+
+ // Issue #8104: before this fix, the vision path only recognized Ollama on
+ // its DEFAULT port (it called `ensureOllamaProviderReady({ endpoint })`,
+ // dropping the provider's id/name) and never woke MTPLX or Slotstream at
+ // all. `callVisionAPI` now passes the full provider record through the
+ // shared `ensureManagedRuntimeReady`, so recognition (by id/name, not just
+ // the default port) and MTPLX/Slotstream coverage are both the shared
+ // gate's job, not a vision-specific copy.
+ describe('managed-runtime wake', () => {
+ it('wakes an MTPLX-recognized API provider before calling it', async () => {
+ const mtplxProvider = {
+ id: 'mtplx', name: 'MTPLX', type: 'api', endpoint: 'http://127.0.0.1:8000/v1', defaultModel: 'mtplx-vision',
+ };
+ getProviderById.mockResolvedValue(mtplxProvider);
+ global.fetch.mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve({ choices: [{ message: { content: 'a scene' } }] }),
+ });
+
+ await describeImageDataUrlDetailed({ dataUrl: DATA_URL, prompt: 'caption', providerId: 'mtplx' });
+
+ expect(ensureManagedRuntimeReady).toHaveBeenCalledWith(expect.objectContaining({ id: 'mtplx' }));
+ });
+
+ // The provider carries its id/name alongside a non-default port — the
+ // shared gate (not vision-specific string matching on `:11434`) is what
+ // makes this recognizable as Ollama.
+ it('passes the full provider record (not just { endpoint }) so an Ollama provider on a non-default port is still recognized', async () => {
+ const ollamaProvider = {
+ id: 'ollama', name: 'Ollama', type: 'api', endpoint: 'http://127.0.0.1:41434/v1', defaultModel: 'llava',
+ };
+ getProviderById.mockResolvedValue(ollamaProvider);
+ global.fetch.mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve({ choices: [{ message: { content: 'a scene' } }] }),
+ });
+
+ await describeImageDataUrlDetailed({ dataUrl: DATA_URL, prompt: 'caption', providerId: 'ollama' });
+
+ expect(ensureManagedRuntimeReady).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'ollama', endpoint: 'http://127.0.0.1:41434/v1' }),
+ );
+ });
+
+ it('never calls the vision endpoint when the managed runtime fails to wake', async () => {
+ getProviderById.mockResolvedValue({
+ id: 'mtplx', type: 'api', endpoint: 'http://127.0.0.1:8000/v1', defaultModel: 'mtplx-vision',
+ });
+ ensureManagedRuntimeReady.mockResolvedValueOnce({
+ success: false,
+ error: 'MTPLX is not running and PortOS could not start it: checkpoint failed to load',
+ });
+
+ await expect(describeImageDataUrlDetailed({ dataUrl: DATA_URL, prompt: 'caption', providerId: 'mtplx' }))
+ .rejects.toThrow('MTPLX is not running and PortOS could not start it: checkpoint failed to load');
+ expect(global.fetch).not.toHaveBeenCalled();
+ });
+ });
});
describe('checkVisionHealth', () => {