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

fix: wake MTPLX before toolkit API runs

Adam Eivyba2c0c658ccf
diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.js
index 3550671807..edc1fe654f 100644
--- a/server/lib/aiToolkit/errorDetection.js
+++ b/server/lib/aiToolkit/errorDetection.js
@@ -889,7 +889,11 @@ export function analyzeHttpError(response) {
return {
hasError: true,
category: ERROR_CATEGORIES.UNKNOWN,
- message: statusText || `HTTP ${status}`,
+ // Status 0 is PortOS's sentinel for "no HTTP response" (a fetch rejection
+ // or a failed provider-readiness hook). Preserve that transport detail;
+ // calling it `HTTP 0` discards the only useful diagnosis and HTTP has no
+ // status zero in the first place.
+ message: statusText || (status === 0 && body ? extractErrorMessage(String(body)) : `HTTP ${status}`),
waitTime: null,
requiresFallback: false,
actionable: false,
diff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.js
index 3397efc5a3..c8d0ba4251 100644
--- a/server/lib/aiToolkit/errorDetection.test.js
+++ b/server/lib/aiToolkit/errorDetection.test.js
@@ -706,6 +706,20 @@ describe('Error Detection', () => {
expect(result.category).toBe(ERROR_CATEGORIES.MODEL_NOT_FOUND);
});
+ it('preserves a status-zero readiness failure instead of inventing HTTP 0', () => {
+ const result = analyzeHttpError({
+ status: 0,
+ statusText: '',
+ body: 'MTPLX could not start: checkpoint failed to load'
+ });
+
+ expect(result).toMatchObject({
+ hasError: true,
+ category: ERROR_CATEGORIES.UNKNOWN,
+ message: 'MTPLX could not start: checkpoint failed to load'
+ });
+ });
+
it('should extract wait time from 429 response body', () => {
const result = analyzeHttpError({
status: 429,
diff --git a/server/lib/aiToolkit/internal/preHeaderRetry.js b/server/lib/aiToolkit/internal/preHeaderRetry.js
index 890004fe6d..7171d0d798 100644
--- a/server/lib/aiToolkit/internal/preHeaderRetry.js
+++ b/server/lib/aiToolkit/internal/preHeaderRetry.js
@@ -8,6 +8,28 @@ const REPLAY_SAFE_TRANSPORT_CODES = new Set([
'UND_ERR_SOCKET',
]);
+/**
+ * Flatten a fetch rejection's cause chain for run metadata and classification.
+ * Node/undici otherwise exposes every pre-header transport failure as the same
+ * `TypeError: fetch failed`, with the actionable code nested under `.cause`.
+ * Kept inside the vendored toolkit rather than importing PortOS's equivalent
+ * helper, preserving this directory's self-contained contract.
+ */
+export function describeTransportError(error) {
+ const parts = [];
+ const seen = new Set();
+ let current = error;
+ for (let depth = 0; current && typeof current === 'object' && depth < 5; depth += 1) {
+ if (seen.has(current)) break;
+ seen.add(current);
+ if (current.code) parts.push(String(current.code));
+ if (current.message) parts.push(String(current.message));
+ current = current.cause;
+ }
+ if (typeof current === 'string') parts.push(current);
+ return parts.join(': ') || String(error);
+}
+
export function isTransientGatewayStatus(status) {
return TRANSIENT_GATEWAY_STATUSES.has(Number(status));
}
diff --git a/server/lib/aiToolkit/internal/preHeaderRetry.test.js b/server/lib/aiToolkit/internal/preHeaderRetry.test.js
index 8d0b18f10a..bcd0489680 100644
--- a/server/lib/aiToolkit/internal/preHeaderRetry.test.js
+++ b/server/lib/aiToolkit/internal/preHeaderRetry.test.js
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
import {
+ describeTransportError,
fetchWithPreHeaderRetry,
isReplaySafeTransportError,
isReplaySafeLocalRequest,
@@ -9,6 +10,14 @@ import {
const response = (status, cancel = vi.fn()) => ({ status, body: { cancel } });
describe('pre-header retry policy', () => {
+ it('preserves nested transport codes that undici hides under fetch failed', () => {
+ const socketError = Object.assign(new TypeError('fetch failed'), {
+ cause: { code: 'ECONNREFUSED', message: 'connect refused' },
+ });
+
+ expect(describeTransportError(socketError)).toBe('fetch failed: ECONNREFUSED: connect refused');
+ });
+
it('retries only the allowlisted gateway statuses and cancels failed bodies', async () => {
const failed = response(503);
const ok = response(200);
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index af8d44b4c1..cca0ad47be 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -7,7 +7,7 @@ import { spawn, ChildProcess } from 'child_process';
import { randomUUID } from 'crypto';
import { analyzeError, analyzeHttpError, ERROR_CATEGORIES } from './errorDetection.js';
import { apiGenerationOptions } from './internal/generationOptions.js';
-import { fetchWithPreHeaderRetry, isReplaySafeLocalRequest } from './internal/preHeaderRetry.js';
+import { describeTransportError, fetchWithPreHeaderRetry, isReplaySafeLocalRequest } from './internal/preHeaderRetry.js';
// npm-installed CLI providers (claude, codex, opencode, …) are .cmd/.bat
// shims on Windows; Node's spawn() can't execute those without going through
@@ -692,8 +692,8 @@ export function createRunnerService(config = {}) {
}), {
signal: controller.signal,
allowReplay: isReplaySafeLocalRequest(provider),
- }).catch(err => ({ ok: false, error: err.message, status: 0 }))
- : { ok: false, error: `Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}`, status: 0 };
+ }).catch(err => ({ ok: false, error: describeTransportError(err), status: 0 }))
+ : { ok: false, error: ready.error || 'Provider readiness check failed', status: 0 };
if (!response.ok) {
// Read the (possibly stalled) error body BEFORE claiming settlement so
diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.js
index 923107c67c..ac666d6c22 100644
--- a/server/lib/aiToolkit/runner.test.js
+++ b/server/lib/aiToolkit/runner.test.js
@@ -153,10 +153,44 @@ describe('AI Toolkit runner service', () => {
);
expect(metadata).toMatchObject({
success: false,
+ error: 'service offline',
errorCategory: 'unknown'
});
});
+ it('records the nested cause of a pre-header transport failure', async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
+ tempDirs.push(dataDir);
+ const socketError = Object.assign(new TypeError('fetch failed'), {
+ cause: { code: 'ECONNREFUSED', message: 'connect ECONNREFUSED 192.0.2.10:8000' },
+ });
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(socketError));
+
+ const runner = createRunnerService({
+ dataDir,
+ hooks: { ensureProviderReady: async () => ({ success: true }) }
+ });
+ let done;
+ const completed = new Promise((resolve) => { done = resolve; });
+
+ await runner.executeApiRun({
+ runId: 'run-transport-failure',
+ provider: runReady({ endpoint: 'https://api.example.com/v1' }),
+ model: null,
+ prompt: 'hello',
+ workspacePath: process.cwd(),
+ screenshots: [],
+ onData: undefined,
+ onComplete: (metadata) => done(metadata)
+ });
+
+ await expect(completed).resolves.toMatchObject({
+ success: false,
+ errorCategory: 'network-error',
+ error: expect.stringContaining('ECONNREFUSED')
+ });
+ });
+
const stubStreamingFetch = () => {
const encoder = new TextEncoder();
const chunks = [
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 56f25f82ad..dc50e0c8b5 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -50,7 +50,8 @@ import {
} from './bootstrapSequence.js';
import { ensureBackendProvider, getBackend as getLocalLlmBackend } from './localLlm.js';
-import { ensureProviderReady as ensureOllamaProviderReady, ensureRunning as ensureOllamaRunning } from './ollamaManager.js';
+import { ensureRunning as ensureOllamaRunning } from './ollamaManager.js';
+import { ensureProviderReadyForExecution } from './providerExecutionReadiness.js';
import { recordSession } from './usage.js';
import { recordCompletedRunUsage } from './usageReconciler.js';
import { setAIToolkit as setProvidersToolkit } from './providers.js';
@@ -158,7 +159,7 @@ import { prerequisitesMetForRouting } from './providerPrerequisites.js';
export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverDir }) => {
// Lifecycle hooks shared between AI Toolkit and PortOS runner shim
const aiToolkitHooks = {
- ensureProviderReady: (provider) => ensureOllamaProviderReady(provider),
+ ensureProviderReady: (provider) => ensureProviderReadyForExecution(provider),
onRunCreated: (metadata) => {
recordSession(metadata.providerId, metadata.providerName, metadata.model).catch(err => {
console.error(`❌ Failed to record usage session: ${err.message}`);
diff --git a/server/services/providerExecutionReadiness.js b/server/services/providerExecutionReadiness.js
new file mode 100644
index 0000000000..695428623e
--- /dev/null
+++ b/server/services/providerExecutionReadiness.js
@@ -0,0 +1,33 @@
+/**
+ * Wake a PortOS-managed local provider before the shared AI Toolkit runner
+ * sends its request.
+ *
+ * The individual managers own provider recognition and lifecycle policy. This
+ * module only gives the runner one provider-agnostic hook, so adding lazy start
+ * for a daemon cannot leave the toolkit path behind while direct AI calls work.
+ */
+
+import { ensureProviderReady as ensureOllamaProviderReady, isOllamaProvider } from './ollamaManager.js';
+import { ensureMtplxProviderReady, isMtplxProvider } from './mtplxServerManager.js';
+
+const failedReadiness = (runtime, result) => ({
+ ...result,
+ error: `${runtime} is not running and PortOS could not start it: ${result?.error || 'unknown error'}`,
+});
+
+/**
+ * @returns {Promise<{success:boolean,error?:string}>}
+ */
+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);
+ }
+
+ return { success: true };
+}
diff --git a/server/services/providerExecutionReadiness.test.js b/server/services/providerExecutionReadiness.test.js
new file mode 100644
index 0000000000..ff0cf5a12f
--- /dev/null
+++ b/server/services/providerExecutionReadiness.test.js
@@ -0,0 +1,67 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ ensureOllama: vi.fn(),
+ ensureMtplx: vi.fn(),
+ isOllama: vi.fn(),
+ isMtplx: vi.fn(),
+}));
+
+vi.mock('./ollamaManager.js', () => ({
+ ensureProviderReady: mocks.ensureOllama,
+ isOllamaProvider: mocks.isOllama,
+}));
+
+vi.mock('./mtplxServerManager.js', () => ({
+ ensureMtplxProviderReady: mocks.ensureMtplx,
+ isMtplxProvider: mocks.isMtplx,
+}));
+
+const { ensureProviderReadyForExecution } = await import('./providerExecutionReadiness.js');
+
+describe('provider execution readiness', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.ensureOllama.mockResolvedValue({ success: true });
+ mocks.ensureMtplx.mockResolvedValue({ success: true });
+ mocks.isOllama.mockReturnValue(false);
+ mocks.isMtplx.mockReturnValue(false);
+ });
+
+ it('leaves providers without a managed local daemon alone', async () => {
+ const provider = { id: 'remote', type: 'api' };
+
+ await expect(ensureProviderReadyForExecution(provider)).resolves.toEqual({ success: true });
+ expect(mocks.ensureOllama).not.toHaveBeenCalled();
+ expect(mocks.ensureMtplx).not.toHaveBeenCalled();
+ });
+
+ it('uses Ollama readiness for an Ollama provider', async () => {
+ const provider = { id: 'ollama', type: 'api' };
+ mocks.isOllama.mockReturnValue(true);
+
+ await expect(ensureProviderReadyForExecution(provider)).resolves.toEqual({ success: true });
+ expect(mocks.ensureOllama).toHaveBeenCalledWith(provider);
+ expect(mocks.ensureMtplx).not.toHaveBeenCalled();
+ });
+
+ it('wakes MTPLX for an MTPLX provider', async () => {
+ const provider = { id: 'mtplx', type: 'api' };
+ mocks.isMtplx.mockReturnValue(true);
+
+ await expect(ensureProviderReadyForExecution(provider)).resolves.toEqual({ success: true });
+ expect(mocks.ensureMtplx).toHaveBeenCalledWith(provider);
+ expect(mocks.ensureOllama).not.toHaveBeenCalled();
+ });
+
+ it('keeps the failing runtime in the error shown by the runner', async () => {
+ const provider = { id: 'mtplx', type: 'api' };
+ mocks.isMtplx.mockReturnValue(true);
+ mocks.ensureMtplx.mockResolvedValue({ success: false, error: 'checkpoint failed to load' });
+
+ await expect(ensureProviderReadyForExecution(provider)).resolves.toEqual({
+ success: false,
+ error: 'MTPLX is not running and PortOS could not start it: checkpoint failed to load',
+ });
+ });
+});