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: deliver persistent mind image turns (#5171)
[._.]/ Adam Eivyfd5e06c6560c
diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.jsindex 6bf496a7cc..069a8d1e48 100644--- a/server/routes/cosMindRoutes.js+++ b/server/routes/cosMindRoutes.js@@ -34,6 +34,7 @@ import {} from '../services/persistentMindContext.js';import { getProviderById } from '../services/providers.js';import { persistentMindHarnessInfo } from '../services/persistentMindAdapter.js';+import { resolvePersistentMindImageCapability } from '../services/persistentMindImageCapability.js';import { readPersistentMindTaskCatalog } from '../services/persistentMindTaskCapability.js';import { inspectPersistentMindRuntime } from '../services/persistentMindRuntime.js';import { readPersistentMindVisibility } from '../services/persistentMindVisibility.js';@@ -157,6 +158,7 @@ router.get('/mind', asyncHandler(async (req, res) => {const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);const capabilities = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);const provider = profile.providerId ? await getProviderById(profile.providerId) : null;+ const imageCapability = await resolvePersistentMindImageCapability({ provider, model: profile.model });const { snapshot: _snapshot, ...publicHistory } = history;res.json({...publicHistory,@@ -170,6 +172,7 @@ router.get('/mind', asyncHandler(async (req, res) => {},capabilities,harness: persistentMindHarnessInfo(provider),+ imageCapability,autonomyMode: getDomainMode(root.config, 'cos'),});}));diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.jsindex 1082a127a9..6d2f1848be 100644--- a/server/routes/cosMindRoutes.test.js+++ b/server/routes/cosMindRoutes.test.js@@ -26,6 +26,7 @@ const mocks = vi.hoisted(() => ({inspectPersistentMindRuntime: vi.fn(),readPersistentMindVisibility: vi.fn(),readPersistentMindTaskCatalog: vi.fn(),+ resolveImageCapability: vi.fn(),}));vi.mock('../services/agentRunEventLog.js', () => ({@@ -51,6 +52,9 @@ vi.mock('../services/persistentMindAdapter.js', () => ({detail: 'Structured provider harness.',}),}));+vi.mock('../services/persistentMindImageCapability.js', () => ({+ resolvePersistentMindImageCapability: (...args) => mocks.resolveImageCapability(...args),+}));vi.mock('../services/persistentMindTaskCapability.js', () => ({readPersistentMindTaskCatalog: mocks.readPersistentMindTaskCatalog,}));@@ -102,6 +106,7 @@ describe('persistent mind routes', () => {persistentMindPrompt: { schemaVersion: 1, identity: 'Resident mind', instructions: 'Stay grounded.' },} });mocks.getProviderById.mockResolvedValue({ id: 'demo', type: 'api' });+ mocks.resolveImageCapability.mockResolvedValue({ status: 'unknown', reason: 'No authoritative metadata.', settingsPath: '/settings?tab=ai-providers' });mocks.readPersistentMindMemories.mockResolvedValue([{ id: 'memory-1', content: 'A durable fact', sourceAgentId: 'cos-persistent-mind' }]);mocks.readPersistentMindRollups.mockResolvedValue([]);mocks.preparePersistentMindContext.mockResolvedValue({ text: '# Context', chars: 9, approximateTokens: 3, summaryState: 'empty' });@@ -161,6 +166,7 @@ describe('persistent mind routes', () => {profile: { enabled: true, providerId: 'demo', model: 'demo-model', effort: 'high', thinkingInterface: 'text' },capabilities: { schemaVersion: 2, createTasks: true, readPortos: false, writePortos: false },harness: { type: 'api', recommendation: 'recommended' },+ imageCapability: { status: 'unknown' },autonomyMode: 'execute',});expect(res.body.profile).not.toHaveProperty('credential');diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.jsindex a20c397e50..47742f7706 100644--- a/server/services/persistentMindAdapter.js+++ b/server/services/persistentMindAdapter.js@@ -18,14 +18,14 @@ import { PERSISTENT_MIND_ID } from '../lib/persistentMindTrajectory.js';import { COS_TOOL_CALL_LIMITS, persistentMindToolCallSchema } from '../lib/cosToolContracts.js';import { parseLLMJSON } from '../lib/llmText.js';import { canonicalStringify } from '../lib/objects.js';-import { sha256Text } from '../lib/fileUtils.js';+import { resolveScreenshot, sha256Text } from '../lib/fileUtils.js';import { loadState } from './cosState.js';import {createPersistentMindMemoryFromCandidate,readPersistentMindMemories,} from './persistentMindContext.js';import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';-import { runPromptThroughProvider } from './promptRunner.js';+import { assertVisionRunUsedImages, runPromptThroughProvider } from './promptRunner.js';import { stopRun } from './runner.js';import {buildPersistentMindTaskCapabilityPrompt,@@ -206,7 +206,9 @@ export function persistentMindHarnessInfo(provider) {const currentWakeText = (wake) => {if (wake?.kind === 'message') {- return `A human message is waiting. Reply directly to it.\nmessageId=${wake.message?.id || 'unknown'}\n${wake.message?.text || ''}`;+ const imageCount = Array.isArray(wake.message?.images) ? wake.message.images.length : 0;+ const attachmentNote = imageCount > 0 ? `\n[${imageCount} image${imageCount === 1 ? '' : 's'} attached]` : '';+ return `A human message is waiting. Reply directly to it.\nmessageId=${wake.message?.id || 'unknown'}\n${wake.message?.text || ''}${attachmentNote}`;}return `This is a self-directed wake. Continue one worthwhile thread from the trajectory.\nreason=${wake?.reason || 'scheduled reflection'}`;};@@ -245,7 +247,7 @@ export function buildPersistentMindSummaryPrompt({ events, previousSummary }) {return `Summarize this older portion of one persistent mind's life in first person. Preserve concrete decisions, unresolved questions, user preferences, and causal links. Do not invent facts. Return plain text only, no heading.\n\n${previousSummary ? `Prior cumulative summary:\n${previousSummary}\n\n` : ''}New trajectory events:\n${summaryEventLines(events)}`;}-async function runPinnedPrompt({ provider, model, effort, prompt, signal, responseSchema, heartbeat }) {+async function runPinnedPrompt({ provider, model, effort, prompt, screenshots = [], signal, responseSchema, heartbeat }) {if (signal?.aborted) throw new Error(String(signal.reason || 'Persistent mind turn interrupted'));if (typeof heartbeat === 'function') await heartbeat();let activeRunId = null;@@ -272,11 +274,15 @@ async function runPinnedPrompt({ provider, model, effort, prompt, signal, responprompt,source: 'cos-persistent-mind',allowFallback: false,+ screenshots,responseSchema,onRunCreated: (runId) => {activeRunId = runId;if (signal?.aborted) interrupt();},+ }).then((result) => {+ if (screenshots.length > 0) assertVisionRunUsedImages(result, provider);+ return result;}).finally(async () => {if (heartbeatTimer) clearInterval(heartbeatTimer);signal?.removeEventListener('abort', interrupt);@@ -332,6 +338,11 @@ export function createPersistentMindTurnAdapter() {});const visibilityPrompt = buildPersistentMindVisibilityPrompt(visibility);const toolCapabilityPrompt = buildPersistentMindToolPrompt(taskAccess);+ const screenshots = (Array.isArray(wake?.message?.images) ? wake.message.images : []).map((image) => {+ const path = resolveScreenshot(image?.filename);+ if (!path) throw new Error('A Persistent Mind image attachment no longer resolves under the screenshots directory');+ return path;+ });const basePrompt = buildPersistentMindTurnPrompt({context,wake,@@ -353,6 +364,7 @@ export function createPersistentMindTurnAdapter() {effort,signal,heartbeat,+ screenshots,prompt: providerPrompt,responseSchema: persistentMindResponseSchema,});diff --git a/server/services/persistentMindAdapter.test.js b/server/services/persistentMindAdapter.test.jsindex 9b9d5fdcd8..a7a4618a4d 100644--- a/server/services/persistentMindAdapter.test.js+++ b/server/services/persistentMindAdapter.test.js@@ -5,6 +5,7 @@ const mock = vi.hoisted(() => ({memories: [{ id: 'memory-1', type: 'fact', content: 'A durable fact.', sourceAgentId: 'cos-persistent-mind', status: 'active' }],runPrompt: vi.fn(),stopRun: vi.fn(),+ assertVision: vi.fn(),readTaskCatalog: vi.fn(),executeTaskRequests: vi.fn(),executeToolCall: vi.fn(),@@ -17,11 +18,18 @@ const mock = vi.hoisted(() => ({}));vi.mock('./cosState.js', () => ({ loadState: vi.fn(async () => mock.root) }));+vi.mock('../lib/fileUtils.js', async (importOriginal) => ({+ ...(await importOriginal()),+ resolveScreenshot: vi.fn((filename) => filename ? `/tmp/portos-screenshots/${filename}` : null),+}));vi.mock('./persistentMindContext.js', () => ({createPersistentMindMemoryFromCandidate: (...args) => mock.createPersistentMindMemoryFromCandidate(...args),readPersistentMindMemories: vi.fn(async () => mock.memories),}));-vi.mock('./promptRunner.js', () => ({ runPromptThroughProvider: (...args) => mock.runPrompt(...args) }));+vi.mock('./promptRunner.js', () => ({+ runPromptThroughProvider: (...args) => mock.runPrompt(...args),+ assertVisionRunUsedImages: (...args) => mock.assertVision(...args),+}));vi.mock('./runner.js', () => ({ stopRun: (...args) => mock.stopRun(...args) }));vi.mock('./persistentMindTaskCapability.js', () => ({buildPersistentMindTaskCapabilityPrompt: ({ enabled }) => `Task access: ${enabled ? 'ON' : 'OFF'}`,@@ -49,6 +57,7 @@ beforeEach(() => {mock.readVisibility.mockResolvedValue({ readiness: 'ready', workspaces: [] });mock.executeTaskRequests.mockResolvedValue([]);mock.executeToolCall.mockResolvedValue({ state: 'completed', result: { ok: true, count: 1 } });+ mock.assertVision.mockImplementation((result, provider) => result?.provider || provider);mock.runPrompt.mockResolvedValue({ text: JSON.stringify({thinkingSummary: 'I connected the new request to the durable fact.',message: 'Here is the answer.',@@ -373,6 +382,35 @@ describe('persistent mind adapter', () => {expect(recordCapabilityEvent.mock.calls.filter(([event]) => event.kind === 'result' && event.data.success === false)).toHaveLength(3);});+ it('passes every current-message image to the pinned provider and verifies consumption', async () => {+ const imageProfile = { provider: { id: 'codex', type: 'cli', command: 'codex' }, model: 'gpt-5', effort: 'high' };+ const wake = {+ kind: 'message',+ message: {+ id: 'message-images',+ text: 'Compare these.',+ images: [+ { filename: 'mind-example-one.png' },+ { filename: 'mind-example-two.jpg' },+ ],+ },+ };+ await createPersistentMindTurnAdapter().run({+ turnId: 'turn-images', wake, ...imageProfile,+ signal: new AbortController().signal,+ context: { text: '# Context' },+ });+ expect(mock.runPrompt).toHaveBeenCalledWith(expect.objectContaining({+ screenshots: expect.arrayContaining([+ expect.stringContaining('mind-example-one.png'),+ expect.stringContaining('mind-example-two.jpg'),+ ]),+ allowFallback: false,+ }));+ expect(mock.assertVision).toHaveBeenCalledWith(expect.any(Object), imageProfile.provider);+ expect(mock.runPrompt.mock.calls[0][0].prompt).toContain('[2 images attached]');+ });+it('executes bounded typed task requests through the supervised capability', async () => {const taskRequest = {description: 'Audit the local configuration contract',diff --git a/server/services/persistentMindImageCapability.js b/server/services/persistentMindImageCapability.jsnew file mode 100644index 0000000000..8b9831c138--- /dev/null+++ b/server/services/persistentMindImageCapability.js@@ -0,0 +1,79 @@+/** Resolve whether the pinned Persistent Mind provider/model can consume images. */++import { isVisionCapableCliProvider, isVisionModel } from '../lib/localModelHeuristics.js';+import { listModels } from './localLlm.js';+import * as ollamaManager from './ollamaManager.js';++export const PERSISTENT_MIND_IMAGE_CAPABILITY = Object.freeze({+ SUPPORTED: 'supported',+ UNSUPPORTED: 'unsupported',+ UNKNOWN: 'unknown',+});++const result = (status, reason) => ({+ status,+ reason,+ settingsPath: '/settings?tab=ai-providers',+});++const localBackend = (provider) => {+ if (provider?.id === 'ollama') return 'ollama';+ if (provider?.id === 'lmstudio') return 'lmstudio';+ return null;+};++const modelId = (model) => (typeof model === 'string' ? model.trim() : '');++export function imageCapabilityAllowsAttempt(capability, provider) {+ return capability?.status === PERSISTENT_MIND_IMAGE_CAPABILITY.SUPPORTED+ || (capability?.status === PERSISTENT_MIND_IMAGE_CAPABILITY.UNKNOWN && provider?.type === 'api');+}++export async function resolvePersistentMindImageCapability(+ { provider, model },+ { listBackendModels = listModels, getOllamaCapabilities = ollamaManager.getModelCapabilities } = {},+) {+ if (!provider) return result('unsupported', 'Choose a Persistent Mind provider before attaching images.');+ if (provider.type === 'tui') {+ return result('unsupported', 'Interactive TUI providers cannot receive Persistent Mind image attachments.');+ }+ if (provider.type === 'cli') {+ return isVisionCapableCliProvider(provider)+ ? result('supported', 'This headless CLI accepts image attachments through its normal run lifecycle.')+ : result('unsupported', 'This headless CLI cannot receive Persistent Mind image attachments. Choose Codex, Claude Code, or a vision API provider.');+ }+ if (provider.type !== 'api') return result('unsupported', 'This provider transport cannot receive image attachments.');++ const selectedModel = modelId(model || provider.defaultModel);+ if (!selectedModel) return result('unknown', 'The API provider has no pinned model to verify for image support.');+ const backend = localBackend(provider);+ if (backend) {+ const models = await listBackendModels(backend).catch(() => null);+ if (!models) return result('unknown', `PortOS could not read the ${backend} model inventory to verify image support.`);+ const card = models.find((entry) => (entry?.id || entry?.name) === selectedModel);+ if (!card) return result('unknown', `The pinned model is not present in the ${backend} inventory.`);+ if (backend === 'ollama') {+ const capabilities = await getOllamaCapabilities(selectedModel).catch(() => null);+ if (!Array.isArray(capabilities) || capabilities.length === 0) {+ return result('unknown', 'Ollama did not report capabilities for the pinned model.');+ }+ return isVisionModel({ id: selectedModel, capabilities })+ ? result('supported', 'Ollama reports vision support for the pinned model.')+ : result('unsupported', 'Ollama reports that the pinned model is text-only.');+ }+ return isVisionModel(card)+ ? result('supported', 'LM Studio reports the pinned model as vision-capable.')+ : result('unsupported', 'LM Studio reports the pinned model as text-only.');+ }++ const declared = (Array.isArray(provider.models) ? provider.models : [])+ .find((entry) => (typeof entry === 'string' ? entry : entry?.id || entry?.name) === selectedModel);+ if (declared && typeof declared === 'object' && (declared.type || Array.isArray(declared.capabilities))) {+ return isVisionModel(declared)+ ? result('supported', 'The provider catalog reports vision support for the pinned model.')+ : result('unsupported', 'The provider catalog reports that the pinned model is text-only.');+ }+ return isVisionModel(selectedModel)+ ? result('supported', 'The pinned API model is a known vision model family.')+ : result('unknown', 'The API provider does not expose authoritative image-capability metadata for this model.');+}diff --git a/server/services/persistentMindImageCapability.test.js b/server/services/persistentMindImageCapability.test.jsnew file mode 100644index 0000000000..e08509231f--- /dev/null+++ b/server/services/persistentMindImageCapability.test.js@@ -0,0 +1,32 @@+import { describe, expect, it, vi } from 'vitest';+import {+ imageCapabilityAllowsAttempt,+ resolvePersistentMindImageCapability,+} from './persistentMindImageCapability.js';++describe('Persistent Mind image capability', () => {+ it('supports Codex and Claude CLI providers but rejects other CLI and TUI transports', async () => {+ await expect(resolvePersistentMindImageCapability({ provider: { type: 'cli', command: 'codex' }, model: 'gpt-5' })).resolves.toMatchObject({ status: 'supported' });+ await expect(resolvePersistentMindImageCapability({ provider: { type: 'cli', command: 'claude' }, model: 'claude-opus' })).resolves.toMatchObject({ status: 'supported' });+ await expect(resolvePersistentMindImageCapability({ provider: { type: 'cli', command: 'opencode' }, model: 'example' })).resolves.toMatchObject({ status: 'unsupported' });+ await expect(resolvePersistentMindImageCapability({ provider: { type: 'tui' }, model: 'example' })).resolves.toMatchObject({ status: 'unsupported' });+ });++ it('prefers authoritative local inventory and capability metadata', async () => {+ const listBackendModels = vi.fn(async () => [{ id: 'example-vlm', type: 'llm' }]);+ const getOllamaCapabilities = vi.fn(async () => ['completion', 'vision']);+ await expect(resolvePersistentMindImageCapability(+ { provider: { id: 'ollama', type: 'api' }, model: 'example-vlm' },+ { listBackendModels, getOllamaCapabilities },+ )).resolves.toMatchObject({ status: 'supported' });+ expect(getOllamaCapabilities).toHaveBeenCalledWith('example-vlm');+ });++ it('leaves an unenumerated API model attemptable without claiming support', async () => {+ const provider = { id: 'example-api', type: 'api', models: ['example-model'] };+ const capability = await resolvePersistentMindImageCapability({ provider, model: 'example-model' });+ expect(capability.status).toBe('unknown');+ expect(imageCapabilityAllowsAttempt(capability, provider)).toBe(true);+ expect(imageCapabilityAllowsAttempt(capability, { type: 'cli' })).toBe(false);+ });+});diff --git a/server/services/persistentMindSupervisor.attachments.test.js b/server/services/persistentMindSupervisor.attachments.test.jsindex ef6266ea96..d9a1606714 100644--- a/server/services/persistentMindSupervisor.attachments.test.js+++ b/server/services/persistentMindSupervisor.attachments.test.js@@ -17,9 +17,9 @@ const mocks = vi.hoisted(() => ({readFile: vi.fn(),unlink: vi.fn(),appendMindEvent: vi.fn(async (event) => ({ appended: true, event })),- prepareContext: vi.fn(async () => ({ text: '', chars: 0, summaryState: 'empty' })),acquireSlot: vi.fn(async () => ({ ok: true, release: vi.fn() })),updateInProgress: false,+ imageCapability: { status: 'supported', reason: 'Supported.' },}));vi.mock('./cosState.js', () => ({@@ -89,6 +89,12 @@ vi.mock('./persistentMindProfile.js', () => ({effort: 'high',})),}));+vi.mock('./providers.js', () => ({ getProviderById: vi.fn(async () => ({ id: 'example-cloud', type: 'api' })) }));+vi.mock('./persistentMindImageCapability.js', () => ({+ resolvePersistentMindImageCapability: vi.fn(async () => mocks.imageCapability),+ imageCapabilityAllowsAttempt: (capability, provider) => capability?.status === 'supported'+ || (capability?.status === 'unknown' && provider?.type === 'api'),+}));const supervisor = await import('./persistentMindSupervisor.js');@@ -106,7 +112,11 @@ const uploadRecord = (overrides = {}) => ({const makeRoot = () => ({paused: false,- config: { domainAutonomy: { cos: 'execute' }, maxConcurrentAgents: 3 },+ config: {+ domainAutonomy: { cos: 'execute' },+ maxConcurrentAgents: 3,+ persistentMindProfile: { enabled: true, providerId: 'example-cloud', model: 'example-model', effort: 'high' },+ },agents: {},persistentMind: createDefaultPersistentMindState(),});@@ -142,6 +152,7 @@ describe('persistent mind image attachment lifecycle', () => {mocks.unlink.mockResolvedValue(undefined);mocks.appendMindEvent.mockClear();mocks.acquireSlot.mockClear();+ mocks.imageCapability = { status: 'supported', reason: 'Supported.' };supervisor.__resetPersistentMindSupervisorForTests();});@@ -212,6 +223,20 @@ describe('persistent mind image attachment lifecycle', () => {expect(mocks.appendMindEvent).toHaveBeenCalledTimes(2);});+ it('rejects known text-only providers before claiming a pending attachment', async () => {+ const uploaded = await supervisor.createPersistentMindAttachment({ filename: 'diagram.png', data: 'encoded-image' });+ mocks.imageCapability = { status: 'unsupported', reason: 'The pinned model is text-only.' };+ await expect(supervisor.enqueuePersistentMindMessage({+ id: 'message-text-only', images: [uploaded.attachment.attachmentId],+ })).resolves.toMatchObject({+ success: false,+ code: 'IMAGE_CAPABILITY_UNSUPPORTED',+ status: 422,+ });+ expect(mocks.root.persistentMind.queuedMessages).toEqual([]);+ expect(mocks.root.persistentMind.pendingAttachments[0].claimedBy).toBeNull();+ });+it('removes the pending marker when image persistence rejects', async () => {mocks.saveImageUpload.mockRejectedValue(new Error('Invalid image file'));diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.jsindex d009662aa9..fa93b21c6a 100644--- a/server/services/persistentMindSupervisor.js+++ b/server/services/persistentMindSupervisor.js@@ -47,6 +47,12 @@ import { preparePersistentMindContext } from './persistentMindContext.js';import { resolvePersistentMindProfile } from './persistentMindProfile.js';import { isUpdateInProgress } from './updateChecker.js';import { publicPersistentMindState } from '../lib/persistentMindPublic.js';+import { normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';+import { getProviderById } from './providers.js';+import {+ imageCapabilityAllowsAttempt,+ resolvePersistentMindImageCapability,+} from './persistentMindImageCapability.js';export const PERSISTENT_MIND_WAKE_EVENT_ID = 'cos-persistent-mind-wake';export const PERSISTENT_MIND_WATCHDOG_EVENT_ID = 'cos-persistent-mind-watchdog';@@ -873,6 +879,16 @@ async function runOnePersistentMindTurn() {await parkActiveTurn(turn.id, 'Persistent mind adapter did not honor the pinned provider profile', 'degraded');return;}+ if (turn.wake.kind === 'message' && Array.isArray(turn.wake.message?.images) && turn.wake.message.images.length > 0) {+ const imageCapability = await resolvePersistentMindImageCapability({+ provider: prepared.provider,+ model: prepared.model,+ });+ if (!imageCapabilityAllowsAttempt(imageCapability, prepared.provider)) {+ await parkActiveTurn(turn.id, imageCapability.reason, 'degraded');+ return;+ }+ }await recordTurnProfile(turn.id, prepared);if (!await turnCanContinue(turn.id, generation, controller.signal)) return;@@ -1158,6 +1174,15 @@ export async function enqueuePersistentMindMessage({ id = randomUUID(), text, imif (!messageId || attachmentIds === null || (!messageText && attachmentIds.length === 0)) {return attachmentFailure('Message id and text or at least one image are required', { code: 'VALIDATION_ERROR' });}+ if (attachmentIds.length > 0) {+ const root = await loadState();+ const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);+ const provider = profile.providerId ? await getProviderById(profile.providerId) : null;+ const imageCapability = await resolvePersistentMindImageCapability({ provider, model: profile.model });+ if (!imageCapabilityAllowsAttempt(imageCapability, provider)) {+ return attachmentFailure(imageCapability.reason, { code: 'IMAGE_CAPABILITY_UNSUPPORTED', status: 422 });+ }+ }const messageCreatedAt = typeof createdAt === 'string' && Number.isFinite(Date.parse(createdAt))? new Date(createdAt).toISOString(): nowIso();diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.jsindex f428955bc0..4ba70e0110 100644--- a/server/services/persistentMindSupervisor.test.js+++ b/server/services/persistentMindSupervisor.test.js@@ -24,6 +24,7 @@ const mock = vi.hoisted(() => ({effort: 'high',thinkingInterface: 'text',},+ imageCapability: { status: 'supported', reason: 'Supported.' },}));vi.mock('./cosState.js', () => ({@@ -66,6 +67,12 @@ vi.mock('./persistentMindContext.js', () => ({vi.mock('./persistentMindProfile.js', () => ({resolvePersistentMindProfile: vi.fn(async () => mock.profile),}));+vi.mock('./providers.js', () => ({ getProviderById: vi.fn(async () => mock.profile.provider) }));+vi.mock('./persistentMindImageCapability.js', () => ({+ resolvePersistentMindImageCapability: vi.fn(async () => mock.imageCapability),+ imageCapabilityAllowsAttempt: (capability, provider) => capability?.status === 'supported'+ || (capability?.status === 'unknown' && provider?.type === 'api'),+}));vi.mock('./updateChecker.js', () => ({isUpdateInProgress: vi.fn(() => mock.updateInProgress),@@ -102,11 +109,12 @@ describe('persistent mind supervisor', () => {mock.recordUsage.mockClear();mock.profile = {ok: true,- provider: { id: 'example-cloud' },+ provider: { id: 'example-cloud', type: 'api' },model: 'example-model',effort: 'high',thinkingInterface: 'text',};+ mock.imageCapability = { status: 'supported', reason: 'Supported.' };mock.acquireSlot.mockReset();mock.acquireSlot.mockResolvedValue({ ok: true, release: vi.fn() });mock.appendMindEvent.mockClear();@@ -175,7 +183,7 @@ describe('persistent mind supervisor', () => {expect(prepare).toHaveBeenCalledTimes(1);expect(prepare).toHaveBeenCalledWith(expect.objectContaining({- profile: expect.objectContaining({ provider: { id: 'example-cloud' }, model: 'example-model', effort: 'high' }),+ profile: expect.objectContaining({ provider: expect.objectContaining({ id: 'example-cloud' }), model: 'example-model', effort: 'high' }),}));expect(mock.acquireSlot).toHaveBeenCalledTimes(1);expect(mock.root.persistentMind.activeTurn).toBeNull();@@ -313,6 +321,30 @@ describe('persistent mind supervisor', () => {expect(mock.acquireSlot).not.toHaveBeenCalled();});+ it('revalidates image capability before inference and retains the claimed message', async () => {+ const run = vi.fn();+ await supervisor.registerPersistentMindTurnAdapter({+ prepare: vi.fn(async () => ({ ok: true, provider: mock.profile.provider })),+ run,+ });+ mock.root.persistentMind = {+ ...mock.root.persistentMind,+ enabled: true,+ started: true,+ status: 'waiting',+ queuedMessages: [{+ id: 'message-image', text: '', createdAt: new Date().toISOString(),+ images: [{ attachmentId: 'attachment-1', filename: 'mind-example.png', originalName: 'example.png', mimeType: 'image/png', size: 10, uploadedAt: new Date().toISOString() }],+ }],+ };+ mock.imageCapability = { status: 'unsupported', reason: 'The pinned model is now text-only.' };+ await supervisor.drainPersistentMind();+ expect(run).not.toHaveBeenCalled();+ expect(mock.root.persistentMind.status).toBe('degraded');+ expect(mock.root.persistentMind.pauseReason).toBe('The pinned model is now text-only.');+ expect(mock.root.persistentMind.queuedMessages.map((message) => message.id)).toEqual(['message-image']);+ });+it('holds queued work durably when the CoS budget is exhausted', async () => {const prepare = vi.fn();const run = vi.fn();diff --git a/server/services/promptRunner.js b/server/services/promptRunner.jsindex 40fd6833f8..4977769233 100644--- a/server/services/promptRunner.js+++ b/server/services/promptRunner.js@@ -33,7 +33,7 @@ import { ServerError } from '../lib/errorHandler.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { analyzeError, ERROR_CATEGORIES, isRunCanceledError } from '../lib/aiToolkit/errorDetection.js';import { isSchemaTypeCategory, resolveProviderBench } from '../lib/providerCooldown.js';-import { isGenerationModel } from '../lib/localModelHeuristics.js';+import { isGenerationModel, isVisionCapableCliProvider } from '../lib/localModelHeuristics.js';import { getAIToolkitInstance } from '../lib/aiToolkitState.js';import { createSingleFlight } from '../lib/singleFlight.js';import { extractJson } from '../lib/jsonExtract.js';@@ -447,14 +447,15 @@ export function assertProvider(provider, { message, code, status = 503 } = {}) {}/**- * Guard a vision run against a silent fallback to a non-API provider.+ * Guard a vision run against a transport that did not receive images.*- * Vision only works on the API path (executeApiRun base64-inlines images);- * CLI/TUI providers drop the images and return a completion hallucinated from- * the text prompt alone. `runPromptThroughProvider` can swap the provider two- * ways — a proactive swap inside createRun (`result.provider`) or a retry- * fallback after failure (`result.fallbackProvider`) — so the provider that- * ACTUALLY ran is the first of those, else the requested one. Throw+ * API providers base64-inline images, while the shared CLI lifecycle stages+ * file attachments for Codex and Claude Code. TUI and other CLI providers must+ * not be accepted because they would answer from the text prompt alone.+ * `runPromptThroughProvider` can swap the provider two ways — a proactive swap+ * inside createRun (`result.provider`) or a retry fallback after failure+ * (`result.fallbackProvider`) — so the provider that ACTUALLY ran is the first+ * of those, else the requested one. Throw* VISION_FALLBACK_DROPPED_IMAGES when it isn't an API provider so callers don't* report image-grounded output that was really text-only.*@@ -466,7 +467,8 @@ export function assertProvider(provider, { message, code, status = 503 } = {}) {*/export function assertVisionRunUsedImages(result, requestedProvider) {const ran = result?.provider || result?.fallbackProvider || requestedProvider;- if (ran?.type && ran.type !== 'api') {+ const usedImages = ran?.type === 'api' || isVisionCapableCliProvider(ran);+ if (ran?.type && !usedImages) {// Name both providers so the cause is actionable. The usual trigger is a// proactive/retry swap because the requested API provider is in a temporary// cooldown (e.g. a prior model-not-found benched it for several minutes) —@@ -524,12 +526,9 @@ export function assertVisionRunUsedImages(result, requestedProvider) {* attempt resolves or rejects. Observational; callback errors are ignored.* @param {string[]} [args.screenshots] — image paths for a vision/multimodal* call (relative to the runner's screenshots dir, or absolute). API providers- * only: the toolkit's executeApiRun base64-encodes each and sends them as- * `image_url` content blocks ahead of the prompt text. CLI/TUI providers- * ignore them (no vision path), so callers needing vision must resolve an- * API provider up front. On a fallback to a non-API provider the images are- * silently dropped — the fallback only fires after the primary API call has- * already failed.+ * base64-encode each into `image_url` blocks. Codex and Claude Code CLI+ * providers receive staged file attachments through executeCliRun. Other CLI+ * and all TUI providers are rejected before a run record is created.* @param {number} [args.timeout] — per-call timeout in ms; falls back to* `provider.timeout`, then DEFAULT_TIMEOUT_MS. Callers like the loop* runner expose a user-configurable timeout that isn't a provider attr.@@ -1151,6 +1150,14 @@ async function executeProviderRunOnce({outputReserveTokens,allowFallback = true,}) {+ if (screenshots.length > 0+ && provider.type !== PROVIDER_TYPES.API+ && !isVisionCapableCliProvider(provider)) {+ throw new ServerError(+ 'The selected provider cannot receive image attachments. Choose Codex, Claude Code, or a vision API provider.',+ { status: 422, code: 'VISION_PROVIDER_UNSUPPORTED' },+ );+ }// Resolve the model that'll actually run BEFORE creating the run record// so the record reflects reality. resolveEffectiveModel handles both// the override-honored fallback chain AND the args-baked-CLI case@@ -1324,7 +1331,7 @@ async function executeProviderRunOnce({: effectiveProvider;if (effectiveProvider.type === PROVIDER_TYPES.CLI) {- executeCliRun({ runId, provider: providerForRun, prompt, workspacePath: effectiveCwd, onData, onComplete, timeout: effectiveTimeout }).catch(safeReject);+ executeCliRun({ runId, provider: providerForRun, prompt, workspacePath: effectiveCwd, screenshots, onData, onComplete, timeout: effectiveTimeout }).catch(safeReject);} else if (effectiveProvider.type === PROVIDER_TYPES.API) {// API runs take model as a first-class arg — no clone needed. The// toolkit's executeApiRun now owns the primary wall-clock timeout (itdiff --git a/server/services/promptRunner.test.js b/server/services/promptRunner.test.jsindex bea2be984a..ee6c9be909 100644--- a/server/services/promptRunner.test.js+++ b/server/services/promptRunner.test.js@@ -64,7 +64,7 @@ const autoFixer = await import('./autoFixer.js');const toolkitState = await import('../lib/aiToolkitState.js');const { ERROR_CATEGORIES } = await import('../lib/aiToolkit/errorDetection.js');const { CREATIVE_LATITUDE_HEADING, withCreativeLatitude } = await import('../lib/creativeLatitude.js');-const { runPromptThroughProvider, resolveProviderAndModel, resolveEffectiveModel, pickConfigCorrectedModel, normalizeResponseSchema, coerceResponseToSchema, isSchemaTypeCategory, buildRequestCapabilities } = await import('./promptRunner.js');+const { runPromptThroughProvider, resolveProviderAndModel, resolveEffectiveModel, pickConfigCorrectedModel, normalizeResponseSchema, coerceResponseToSchema, isSchemaTypeCategory, buildRequestCapabilities, assertVisionRunUsedImages } = await import('./promptRunner.js');const apiProvider = (extra = {}) => ({id: 'mock-api', type: 'api', defaultModel: 'm-default', ...extra,@@ -112,6 +112,28 @@ describe('promptRunner — happy paths', () => {expect(runner.executeApiRun).not.toHaveBeenCalled();});+ it('forwards images through the ordinary Codex CLI lifecycle and rejects unsupported CLIs', async () => {+ const codex = cliProvider({ command: 'codex' });+ runner.executeCliRun.mockImplementation(async ({ screenshots, onComplete }) => {+ expect(screenshots).toEqual(['/tmp/example.png']);+ onComplete({ success: true });+ });+ const output = await runPromptThroughProvider({+ provider: codex,+ prompt: 'Inspect the image.',+ source: 'test',+ screenshots: ['/tmp/example.png'],+ allowFallback: false,+ });+ expect(assertVisionRunUsedImages(output, codex)).toBe(codex);+ await expect(runPromptThroughProvider({+ provider: cliProvider({ command: 'opencode' }),+ prompt: 'Inspect the image.',+ source: 'test',+ screenshots: ['/tmp/example.png'],+ })).rejects.toMatchObject({ code: 'VISION_PROVIDER_UNSUPPORTED' });+ });+it('routes API providers through executeApiRun, accumulates text, resolves { text, runId, model }', async () => {runner.executeApiRun.mockImplementation(async ({ onData, onComplete }) => {onData('foo');diff --git a/server/services/runner.js b/server/services/runner.jsindex 06a4fabf9d..c2cc961f3f 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -256,7 +256,7 @@ const describeSpawnFailure = (spawnError, command) =>* `.cmd`/`.bat` spawn under `shell:false` fails outright post-CVE-2024-27980,* and why the `cmd.exe` wrapper avoids DEP0190's unescaped-join hazard).*/-export async function executeCliRun({ runId, provider, prompt, workspacePath, onData, onComplete, timeout }) {+export async function executeCliRun({ runId, provider, prompt, workspacePath, screenshots = [], onData, onComplete, timeout }) {const toolkit = requireToolkit();const runsPath = join(runnerConfig.dataDir, 'runs');@@ -293,8 +293,19 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on});if (failure) return;+ const prepareVision = screenshots.length > 0 ? await import('./visionCli.js') : null;+ const vision = prepareVision+ ? await prepareVision.prepareCliVisionRun({+ provider,+ imagePaths: screenshots,+ prompt,+ model: provider.defaultModel || null,+ effort: provider.effort || null,+ })+ : null;+ const cleanupVisionFiles = vision?.cleanup || (() => Promise.resolve());// Build provider-specific args for prompt delivery- const builtArgs = buildCliArgs(provider);+ const builtArgs = vision?.invocation.args || buildCliArgs(provider);// Rewrite the argv for prompt delivery and learn whether to still write stdin:// - Antigravity (`agy`): prompt spliced in as the --print VALUE (agy doesn't// read stdin) → useStdin=false.@@ -302,8 +313,11 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on// rewritten to a temp file on Windows → useStdin=false.// - Every other provider: unchanged, prompt over stdin → useStdin=true.// cleanupPromptFile removes any temp file after the run (no-op otherwise).- const { args, useStdin, cleanup: cleanupPromptFile } = prepareCliPrompt(provider.command, builtArgs, prompt);- console.log(`🚀 Executing CLI: ${provider.command} (${prompt.length} chars via ${useStdin ? 'stdin' : 'argv'})`);+ const promptInput = vision ? vision.invocation.stdin : prompt;+ const { args, useStdin, cleanup: cleanupPromptFile } = vision+ ? { args: builtArgs, useStdin: promptInput != null, cleanup: () => {} }+ : prepareCliPrompt(provider.command, builtArgs, promptInput);+ console.log(`🚀 Executing CLI: ${provider.command} (${prompt.length} chars via ${useStdin ? 'stdin' : 'argv'}${vision ? `, ${screenshots.length} images` : ''})`);// Ollama-backed CLIs (claude-ollama, opencode-ollama) reach the daemon// themselves, so the toolkit's per-request `num_ctx` never applies to them —@@ -322,25 +336,27 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on// shared daemon.const childEnv = buildCliChildEnv({provider,- cwd: effectiveCwd,+ cwd: vision?.invocation.cwd || effectiveCwd,guard: true,});// See the executeCliRun docblock above for why this is a resolve+wrap, not// a shell:true. Resolved against `childEnv` (not bare process.env) so a// provider-configured PATH override is honored.- const resolvedCommand = resolveWindowsExecutable(provider.command, undefined, childEnv) || provider.command;+ const runCommand = vision?.invocation.command || provider.command;+ const runCwd = vision?.invocation.cwd || effectiveCwd;+ const resolvedCommand = resolveWindowsExecutable(runCommand, undefined, childEnv) || runCommand;const { command: spawnCommand, args: spawnArgs } = prepareWindowsSafeSpawn(resolvedCommand, args);childProcess = spawn(spawnCommand, spawnArgs, {- cwd: effectiveCwd,+ cwd: runCwd,env: childEnv});// Pass prompt via stdin to avoid OS argv limits. When grok is delivered via a// Windows temp file (useStdin === false) the prompt is already on disk, so// just close stdin.- if (useStdin) childProcess.stdin.write(prompt);+ if (useStdin) childProcess.stdin.write(promptInput);childProcess.stdin.end();// Track active run via the toolkit's declared external-run registry so its@@ -415,6 +431,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, onif (timeoutHandle) clearTimeout(timeoutHandle);toolkit.services.runner.unregisterExternalRun(runId);cleanupPromptFile();+ await cleanupVisionFiles().catch((error) => console.error(`❌ Failed to clean CLI vision files: ${error.message}`));if (spawnError) console.error(`❌ Run ${runId} spawn error: ${spawnError.message}`);await writeFile(outputPath, output);diff --git a/server/services/visionCli.js b/server/services/visionCli.jsindex 75050f7e29..e4875032d3 100644--- a/server/services/visionCli.js+++ b/server/services/visionCli.js@@ -112,6 +112,30 @@ export function buildCliVisionInvocation(provider, model, imageDir, prompt, optsreturn { command: provider.command, args, stdin, cwd: imageDir };}+/**+ * Stage already-validated image files for the ordinary CLI runner.+ * The caller owns the returned cleanup function and must keep the directory+ * alive until the child process has reached a terminal state.+ */+export async function prepareCliVisionRun({ provider, imagePaths, prompt, model, effort }) {+ const paths = (Array.isArray(imagePaths) ? imagePaths : []).filter((value) => typeof value === 'string' && value);+ if (!paths.length) throw new Error('At least one image path is required');+ for (const imagePath of paths) {+ if (!existsSync(imagePath)) throw new Error(`Vision image not found: ${imagePath}`);+ }+ const dir = await mkdtemp(join(tmpdir(), 'portos-vision-run-'));+ const imageNames = [];+ for (let index = 0; index < paths.length; index += 1) {+ const name = `vision-${index + 1}${extname(paths[index]) || '.jpg'}`;+ await copyFile(paths[index], join(dir, name));+ imageNames.push(name);+ }+ return {+ invocation: buildCliVisionInvocation(provider, model, dir, prompt, { imageNames, effort }),+ cleanup: () => rm(dir, { recursive: true, force: true }),+ };+}+/*** Run a vision prompt against a CLI provider and resolve with the model's text* in the API-compatible diagnostic shape. `spawnImpl` is injectable for tests.@@ -170,34 +194,18 @@ export async function describeImageViaCli({export async function describeImagesFromPaths({provider, imagePaths, prompt, model, effort, timeout = CLI_VISION_TIMEOUT_MS, spawnImpl = spawn,}) {- const paths = (Array.isArray(imagePaths) ? imagePaths : []).filter((p) => typeof p === 'string' && p);- if (!paths.length) throw new Error('At least one image path is required');- for (const p of paths) {- if (!existsSync(p)) throw new Error(`Vision image not found: ${p}`);- }-const visionModel = model || provider?.defaultModel || null;- const dir = await mkdtemp(join(tmpdir(), 'portos-vision-'));+ const prepared = await prepareCliVisionRun({ provider, imagePaths, prompt, model: visionModel, effort });let cleanupPromptFile = () => {};try {- const imageNames = [];- for (let i = 0; i < paths.length; i += 1) {- const ext = extname(paths[i]) || '.jpg';- const name = `vision-${i + 1}${ext}`;- await copyFile(paths[i], join(dir, name));- imageNames.push(name);- }- const invocation = buildCliVisionInvocation(- provider, visionModel, dir, prompt, { imageNames, effort },- );const text = await runCliVisionSpawn({- provider, model: visionModel, invocation, timeout, spawnImpl,+ provider, model: visionModel, invocation: prepared.invocation, timeout, spawnImpl,setCleanup: (fn) => { cleanupPromptFile = fn; },});return { text, finishReason: null, usage: null, reasoning: '' };} finally {cleanupPromptFile();- await rm(dir, { recursive: true, force: true }).catch(() => {});+ await prepared.cleanup().catch(() => {});}}diff --git a/server/services/visionCli.test.js b/server/services/visionCli.test.jsindex e60afe829f..7b601ea1d0 100644--- a/server/services/visionCli.test.js+++ b/server/services/visionCli.test.js@@ -2,6 +2,9 @@ import { describe, it, expect, vi } from 'vitest';import { posixPath } from '../lib/testHelper.js';import { EventEmitter } from 'events';+import { mkdtemp, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';// Wrap the REAL resolveWindowsExecutable/prepareWindowsSafeSpawn in spies// (not stubs) so every existing test below is unaffected (both are no-op@@ -20,6 +23,7 @@ vi.mock('../lib/bufferedSpawn.js', async (importOriginal) => {const {decodeImageDataUrl,buildCliVisionInvocation,+ prepareCliVisionRun,describeImageViaCli,} = await import('./visionCli.js');const { resolveWindowsExecutable, prepareWindowsSafeSpawn } = await import('../lib/bufferedSpawn.js');@@ -111,6 +115,30 @@ describe('buildCliVisionInvocation', () => {});});+describe('prepareCliVisionRun', () => {+ it('stages multiple files for the shared runner and removes them on cleanup', async () => {+ const sourceDir = await mkdtemp(join(tmpdir(), 'portos-vision-source-'));+ try {+ const first = join(sourceDir, 'first.png');+ const second = join(sourceDir, 'second.jpg');+ await Promise.all([writeFile(first, 'one'), writeFile(second, 'two')]);+ const prepared = await prepareCliVisionRun({+ provider: { id: 'codex', command: 'codex', args: [] },+ imagePaths: [first, second],+ prompt: 'compare',+ model: 'gpt-5',+ effort: 'high',+ });+ expect(prepared.invocation.args.filter((arg) => arg === '-i')).toHaveLength(2);+ expect(prepared.invocation.cwd).toMatch(/portos-vision-run-/);+ await prepared.cleanup();+ await expect(import('fs/promises').then(({ stat }) => stat(prepared.invocation.cwd))).rejects.toMatchObject({ code: 'ENOENT' });+ } finally {+ await rm(sourceDir, { recursive: true, force: true });+ }+ });+});+// A minimal child-process double: an EventEmitter with stdin/stdout/stderr.function makeFakeChild() {const child = new EventEmitter();