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

feat: add Codex CLI as third Image Gen backend

Adam Eivy29e4fd69012e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index af504d6932..ebd0789e96 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -3,3 +3,7 @@
## Added
- **One-click "Enable HTTPS" button on the Instances tab.** The Tailnet DNS & trusted HTTPS explainer used to instruct users to drop into a shell and run `npm run setup:cert`. New button on the same banner runs the same flow at runtime via a new `POST /api/instances/provision-cert` endpoint, which calls `tailscale cert` for the local MagicDNS hostname, writes `data/certs/{cert,key}.pem`, and updates `meta.json`. Failure modes (Tailscale not installed, not running, no MagicDNS hostname, HTTPS Certificates feature disabled in the tailnet admin) surface as toasts with actionable guidance. Because the HTTPS listener type is decided at server boot in `lib/tailscale-https.js`, the response includes `requiresRestart: true` whenever PortOS is currently running over HTTP — the UI then prompts the user to restart so the new cert actually takes effect; if HTTPS was already running, the existing `certRenewer` hot-swap path picks up the renewed cert without a restart. The button is disabled until MagicDNS is detected, mirroring what the underlying CLI requires. Files: `server/services/certProvisioner.js` (new), `server/routes/instances.js`, `client/src/services/apiSystem.js`, `client/src/pages/Instances.jsx`.
+- **Image Gen — third backend: Codex CLI `$imagegen`.** Image Gen can now route generation through the user's locally-installed Codex CLI built-in `image_gen` tool — invoked headlessly with `codex exec --skip-git-repo-check --sandbox workspace-write '$imagegen <prompt>'` so it uses the user's logged-in Codex session (no `OPENAI_API_KEY` required). New provider at `server/services/imageGen/codex.js` mirrors `local.js` (single-job model, SSE progress events) but harvests the resulting PNG from `~/.codex/generated_images/<session-id>/ig_*.png` after parsing the session id out of the codex launch banner — codex's stdout has no machine-readable image path, so banner-parse + dir-poll is the contract. Failure modes are surfaced clearly via `imageGenEvents`: empty session dir → "your Codex account may not allow image_gen", missing session id → "output format may have changed", non-zero exit → tail of stderr. Codex usage is gated by an explicit `Enable Codex Imagegen` setting because not every Codex plan exposes the `image_gen` tool — when disabled the option disappears from settings tile, image-gen page chip, voice tool dispatch, and palette gating up front.
+- **Image Gen — per-render backend chip.** New chip strip on the Image Gen page lets the user flip between Local / External / Codex per-render without changing the saved default. Only viable backends (External URL set, Local Python set, Codex enabled) appear; the strip hides itself when only one backend is configured. Selection is sent as `mode:` in `POST /api/image-gen/generate` and the dispatcher honors the override. Codex mode also hides backend-irrelevant knobs (steps, seed, guidance/CFG, LoRAs, quantize) since the built-in `image_gen` tool decides those internally. `GET /api/image-gen/status?mode=codex` lets the page probe a non-default backend before saving.
+- **CoS / voice — `image_generate` tool.** New voice tool that delegates to the Image Gen dispatcher. Defaults to the user's saved backend; agents pass `provider: 'local' | 'external' | 'codex' | 'auto'` to override. Codex is gated on `imageGen.codex.enabled` — disabled returns `{ ok: false, summary: 'Codex Imagegen is disabled — enable it in Settings → Image Gen first.' }` instead of the friendly server error. Tool joins the new `media` intent group (regex matches creation verbs paired with visual nouns plus `imagegen`) so small tool-use models only see it on imagery turns. Whitelisted in `PALETTE_ACTIONS` as `Generate Image` under section `Create` so `⌘K` exposes it for keyboard invocation.
+- **Image Gen dispatcher — explicit per-request mode override.** `imageGen.generateImage()` now accepts `params.mode` (one of `external`, `local`, `codex`) to force a specific backend independent of `settings.imageGen.mode`. `imageGen.checkConnection({ mode })` similarly probes a specific backend. The dispatcher's SSE attach (`attachSseClient`) and `cancel()` now route across all async providers (local + codex), so `GET /api/image-gen/:jobId/events` and `POST /api/image-gen/cancel` work for codex jobs without needing a separate route. Files: `server/services/imageGen/codex.js` (new), `server/services/imageGen/index.js`, `server/routes/imageGen.js`, `server/services/voice/tools.js`, `server/routes/palette.js`, `client/src/components/settings/ImageGenTab.jsx`, `client/src/pages/ImageGen.jsx`. 10 new codex provider tests + 7 new voice-tool tests; full server suite green at 2812/2812.
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsx
index e603126d79..7ebdcc160d 100644
--- a/client/src/components/settings/ImageGenTab.jsx
+++ b/client/src/components/settings/ImageGenTab.jsx
@@ -7,7 +7,7 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import {
Save, Image as ImageIcon, Zap, Wrench, Cloud, Cpu, Globe, AlertTriangle,
- Sparkles
+ Sparkles, Terminal
} from 'lucide-react';
import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
@@ -18,6 +18,7 @@ import {
} from '../../services/api';
const SDAPI_TOOL_ID = 'sdapi';
+const CODEX_TOOL_ID = 'codex-imagegen';
const DEFAULT_TEST_PROMPT = 'a small cyberpunk fox sitting on a neon-lit rooftop at night, cinematic, highly detailed';
const normalizeUrl = (url) => (url || '').trim().replace(/\/+$/, '');
@@ -30,13 +31,22 @@ export function ImageGenTab() {
const [sdapiUrl, setSdapiUrl] = useState('');
const [pythonPath, setPythonPath] = useState('');
const [exposeA1111, setExposeA1111] = useState(false);
+ // Codex CLI provider config — gated by `codexEnabled` so users without
+ // a paid Codex plan that includes image_gen can hide the option entirely.
+ const [codexEnabled, setCodexEnabled] = useState(false);
+ const [codexPath, setCodexPath] = useState('');
+ const [codexModel, setCodexModel] = useState('');
// Snapshot of saved values so we can show the "dirty" state
- const [saved, setSaved] = useState({ mode: 'external', sdapiUrl: '', pythonPath: '', exposeA1111: false });
+ const [saved, setSaved] = useState({
+ mode: 'external', sdapiUrl: '', pythonPath: '', exposeA1111: false,
+ codexEnabled: false, codexPath: '', codexModel: '',
+ });
const [status, setStatus] = useState(null);
const [checking, setChecking] = useState(false);
const [toolRegistered, setToolRegistered] = useState(false);
+ const [codexToolRegistered, setCodexToolRegistered] = useState(false);
const [testPrompt, setTestPrompt] = useState(DEFAULT_TEST_PROMPT);
const [rendering, setRendering] = useState(false);
@@ -55,12 +65,23 @@ export function ImageGenTab() {
const url = normalizeUrl(ig.external?.sdapiUrl || ig.sdapiUrl);
const py = ig.local?.pythonPath || '';
const expose = ig.expose?.a1111 === true;
+ const cx = ig.codex || {};
+ const cxEnabled = cx.enabled === true;
+ const cxPath = cx.codexPath || '';
+ const cxModel = cx.model || '';
setMode(m);
setSdapiUrl(url);
setPythonPath(py);
setExposeA1111(expose);
- setSaved({ mode: m, sdapiUrl: url, pythonPath: py, exposeA1111: expose });
+ setCodexEnabled(cxEnabled);
+ setCodexPath(cxPath);
+ setCodexModel(cxModel);
+ setSaved({
+ mode: m, sdapiUrl: url, pythonPath: py, exposeA1111: expose,
+ codexEnabled: cxEnabled, codexPath: cxPath, codexModel: cxModel,
+ });
setToolRegistered(tools.some((t) => t.id === SDAPI_TOOL_ID));
+ setCodexToolRegistered(tools.some((t) => t.id === CODEX_TOOL_ID));
})
.catch(() => toast.error('Failed to load image gen settings'))
.finally(() => setLoading(false));
@@ -77,16 +98,22 @@ export function ImageGenTab() {
const isDirty = mode !== saved.mode
|| normalizeUrl(sdapiUrl) !== saved.sdapiUrl
|| pythonPath !== saved.pythonPath
- || exposeA1111 !== saved.exposeA1111;
+ || exposeA1111 !== saved.exposeA1111
+ || codexEnabled !== saved.codexEnabled
+ || codexPath !== saved.codexPath
+ || codexModel !== saved.codexModel;
const handleSave = async () => {
setSaving(true);
const url = normalizeUrl(sdapiUrl) || undefined;
+ const cxPath = codexPath?.trim() || undefined;
+ const cxModel = codexModel?.trim() || undefined;
const patch = {
imageGen: {
mode,
external: { sdapiUrl: url },
local: { pythonPath: pythonPath || undefined },
+ codex: { enabled: codexEnabled, codexPath: cxPath, model: cxModel },
expose: { a1111: exposeA1111 },
// Keep the legacy field populated so anything still reading
// `imageGen.sdapiUrl` directly stays working.
@@ -95,7 +122,10 @@ export function ImageGenTab() {
};
try {
await updateSettings(patch);
- setSaved({ mode, sdapiUrl: url || '', pythonPath, exposeA1111 });
+ setSaved({
+ mode, sdapiUrl: url || '', pythonPath, exposeA1111,
+ codexEnabled, codexPath, codexModel,
+ });
toast.success('Image gen settings saved');
} catch (err) {
toast.error(err.message || 'Failed to save settings');
@@ -103,27 +133,52 @@ export function ImageGenTab() {
return;
}
- // Register/update CoS tool entry. The tool is "enabled" whenever the
- // active provider is configured (external URL set, or local Python set).
- const enabled = mode === 'external' ? !!url : !!pythonPath;
- const toolData = {
- name: mode === 'external' ? 'Stable Diffusion (External)' : 'Stable Diffusion (Local mflux)',
+ // Both tool entries are independent — sync them in parallel so a
+ // tailnet save doesn't pay two sequential HTTP round-trips.
+ const sdEnabled = mode === 'external' ? !!url : (mode === 'local' ? !!pythonPath : false);
+ const sdToolData = {
+ name: mode === 'external' ? 'Stable Diffusion (External)' : (mode === 'local' ? 'Stable Diffusion (Local mflux)' : 'Stable Diffusion'),
category: 'image-generation',
description: 'Generate images via the active PortOS image gen backend',
- enabled,
+ enabled: sdEnabled,
config: { mode, sdapiUrl: url, pythonPath },
promptHints: 'Use POST /api/image-gen/generate with { prompt, negativePrompt, width, height, steps }. Use POST /api/image-gen/avatar for character portraits.',
};
- if (toolRegistered) {
- await updateTool(SDAPI_TOOL_ID, toolData).catch((err) => toast.error(err.message || 'Failed to update CoS tools registry'));
- } else if (enabled) {
- try {
- await registerTool({ id: SDAPI_TOOL_ID, ...toolData });
- setToolRegistered(true);
- } catch (err) {
- toast.error(err.message || 'Failed to register in CoS tools registry');
+ const codexToolData = {
+ name: 'Codex Imagegen',
+ category: 'image-generation',
+ description: 'Generate images via the Codex CLI built-in image_gen tool ($imagegen prompt prefix). Requires a Codex plan that includes image_gen.',
+ enabled: codexEnabled,
+ config: { codexPath: cxPath, model: cxModel },
+ promptHints: 'Use POST /api/image-gen/generate with { prompt, mode: "codex" } — or call the image_generate voice tool with provider: "codex".',
+ };
+
+ const syncTool = async ({ id, registered, data, shouldCreate, onCreated, errLabel }) => {
+ if (registered) {
+ return updateTool(id, data).catch((err) => toast.error(err.message || `Failed to update ${errLabel}`));
}
- }
+ if (shouldCreate) {
+ try {
+ await registerTool({ id, ...data });
+ onCreated?.();
+ } catch (err) {
+ toast.error(err.message || `Failed to register ${errLabel}`);
+ }
+ }
+ };
+
+ await Promise.all([
+ syncTool({
+ id: SDAPI_TOOL_ID, registered: toolRegistered, data: sdToolData,
+ shouldCreate: sdEnabled, onCreated: () => setToolRegistered(true),
+ errLabel: 'CoS tools registry',
+ }),
+ syncTool({
+ id: CODEX_TOOL_ID, registered: codexToolRegistered, data: codexToolData,
+ shouldCreate: codexEnabled, onCreated: () => setCodexToolRegistered(true),
+ errLabel: 'Codex Imagegen tool',
+ }),
+ ]);
setSaving(false);
};
@@ -133,13 +188,16 @@ export function ImageGenTab() {
setRendering(true);
setRenderResult(null);
try {
- const result = await generateImage({ prompt: testPrompt.trim() });
- // Local mode returns immediately after spawning the Python child —
+ // Use the saved mode for the test render. Codex is async like local
+ // (returns a job descriptor immediately) so the SSE branch handles it.
+ const result = await generateImage({ prompt: testPrompt.trim(), mode });
+ // Local + Codex modes return immediately after spawning the child —
// the PNG isn't on disk yet. Subscribe to the per-job SSE and only
// mark the render complete on the `complete` event (or fail on
// `error`). External mode awaits internally and the file is on disk
// by the time generateImage resolves, so we can short-circuit.
- if (result?.mode === 'local' && result?.generationId) {
+ const isAsync = (result?.mode === 'local' || result?.mode === 'codex');
+ if (isAsync && result?.generationId) {
await new Promise((resolve, reject) => {
const es = new EventSource(`/api/image-gen/${result.generationId}/events`);
renderEsRef.current = es;
@@ -201,7 +259,7 @@ export function ImageGenTab() {
generation locally with mflux on this Mac. Pick whichever fits — you can also
expose this PortOS as an A1111-compatible endpoint for other tailnet boxes.
</p>
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <div className={`grid grid-cols-1 sm:grid-cols-2 ${codexEnabled ? 'lg:grid-cols-3' : ''} gap-3`}>
<button
type="button"
onClick={() => setMode('external')}
@@ -224,6 +282,19 @@ export function ImageGenTab() {
</div>
<p className="text-xs text-gray-500 mt-1">Run Flux + LTX models on this machine. Apple Silicon recommended.</p>
</button>
+ {codexEnabled && (
+ <button
+ type="button"
+ onClick={() => setMode('codex')}
+ className={`text-left p-4 rounded-lg border transition-colors ${mode === 'codex' ? 'border-port-accent bg-port-accent/10 text-white' : 'border-port-border text-gray-400 hover:bg-port-border/30 hover:text-white'}`}
+ >
+ <div className="flex items-center gap-2">
+ <Terminal className="w-4 h-4" />
+ <span className="font-medium text-sm">Codex CLI</span>
+ </div>
+ <p className="text-xs text-gray-500 mt-1">Route through the Codex CLI built-in image_gen tool. Counts against your Codex plan.</p>
+ </button>
+ )}
</div>
</div>
@@ -255,6 +326,65 @@ export function ImageGenTab() {
</div>
)}
+ {/* Codex CLI config — always visible (the toggle that enables the
+ option lives here). Codex appears as a backend tile only after
+ the user flips this on. */}
+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4">
+ <div className="flex items-center gap-2 text-white">
+ <Terminal size={18} />
+ <h2 className="text-lg font-semibold">Codex CLI Imagegen</h2>
+ </div>
+ <p className="text-xs text-gray-500">
+ Route image generation through the Codex CLI's built-in
+ <code className="text-gray-400"> image_gen </code> tool — invoked headlessly with a
+ <code className="text-gray-400"> $imagegen </code> prompt. Uses your logged-in Codex session, no
+ OPENAI_API_KEY required. Not every Codex plan exposes
+ <code className="text-gray-400"> image_gen </code>; if yours doesn't, leave this off.
+ </p>
+ <label className="flex items-center gap-3 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={codexEnabled}
+ onChange={(e) => {
+ const v = e.target.checked;
+ setCodexEnabled(v);
+ // If the user just disabled Codex while it was the active
+ // backend, fall back to external so saving doesn't leave the
+ // dispatcher pointing at a disabled provider.
+ if (!v && mode === 'codex') setMode('external');
+ }}
+ className="rounded"
+ />
+ <span className="text-sm text-gray-300">Enable Codex Imagegen</span>
+ </label>
+ {codexEnabled && (
+ <div className="space-y-3 pl-6 border-l-2 border-port-border">
+ <div>
+ <label className="block text-xs font-medium text-gray-400 mb-1">Codex binary path (optional)</label>
+ <input
+ type="text"
+ value={codexPath}
+ onChange={(e) => setCodexPath(e.target.value)}
+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
+ placeholder="codex (uses $PATH)"
+ />
+ <p className="text-xs text-gray-500 mt-1">Leave empty to invoke <code>codex</code> from $PATH.</p>
+ </div>
+ <div>
+ <label className="block text-xs font-medium text-gray-400 mb-1">Model override (optional)</label>
+ <input
+ type="text"
+ value={codexModel}
+ onChange={(e) => setCodexModel(e.target.value)}
+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
+ placeholder="gpt-5.4"
+ />
+ <p className="text-xs text-gray-500 mt-1">Passed as <code>codex exec -m &lt;model&gt;</code>. Leave empty to use Codex's default.</p>
+ </div>
+ </div>
+ )}
+ </div>
+
{/* Save + status */}
<div className="flex items-center gap-3">
<button
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index db98c2fcea..a7b2b200a8 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -17,14 +17,14 @@ import MediaLightbox from '../components/media/MediaLightbox';
import { normalizeImage } from '../components/media/normalize';
import {
Image as ImageIcon, Sparkles, Download, RefreshCw, Settings as SettingsIcon,
- Dice5, AlertTriangle, X, Film
+ Dice5, AlertTriangle, X, Film, Cloud, Cpu, Terminal
} from 'lucide-react';
import toast from '../components/ui/Toast';
import BrailleSpinner from '../components/BrailleSpinner';
import { useImageGenProgress } from '../hooks/useImageGenProgress';
import {
getImageGenStatus, generateImage, listImageModels, listLoras, listImageGallery,
- cancelImageGen, deleteImage, getActiveImageJob,
+ cancelImageGen, deleteImage, getActiveImageJob, getSettings,
} from '../services/api';
import { randomSeed, safeParseJSON } from '../lib/genUtils';
@@ -55,6 +55,9 @@ export default function ImageGen() {
const [gallery, setGallery] = useState([]);
const [preview, setPreview] = useState(null);
+ const [selectedMode, setSelectedMode] = useState(null);
+ const [availableBackends, setAvailableBackends] = useState([]);
+
const [prompt, setPrompt] = useState('');
const [negativePrompt, setNegativePrompt] = useState(DEFAULT_NEGATIVE);
const [modelId, setModelId] = useState('');
@@ -79,7 +82,12 @@ export default function ImageGen() {
// via imageGenEvents so the same UI bits light up).
const { progress: externalProgress, begin: beginGenerate, end: endGenerate, resume: resumeGenerate } = useImageGenProgress();
- const isLocalMode = status?.mode === 'local';
+ // selectedMode is null until settings load — fall back to status.mode
+ // so the form doesn't flicker between defaults.
+ const effectiveMode = selectedMode || status?.mode || 'external';
+ const isLocalMode = effectiveMode === 'local';
+ const isCodexMode = effectiveMode === 'codex';
+ const isAsyncMode = isLocalMode || isCodexMode;
// Prefer the socket-driven hook (carries currentImage for both modes since
// local mflux now writes stepwise frames). Fall back to the local SSE's
// simpler progress shape if the hook hasn't received its first event yet.
@@ -106,6 +114,27 @@ export default function ImageGen() {
}).catch(() => {});
listLoras().then(setAvailableLoras).catch(() => {});
refreshGallery();
+ getSettings().then((s) => {
+ const ig = s?.imageGen || {};
+ const externalUrl = (ig.external?.sdapiUrl || ig.sdapiUrl || '').trim();
+ const pyPath = (ig.local?.pythonPath || '').trim();
+ const codexOn = ig.codex?.enabled === true;
+ const backends = [];
+ if (externalUrl) backends.push({ id: 'external', label: 'External', icon: Cloud });
+ if (pyPath) backends.push({ id: 'local', label: 'Local', icon: Cpu });
+ if (codexOn) backends.push({ id: 'codex', label: 'Codex', icon: Terminal });
+ setAvailableBackends(backends);
+ const saved = ig.mode || 'external';
+ // Pick the saved mode if viable; otherwise the first viable backend
+ // (so a freshly-configured setup with only one provider Just Works).
+ if (backends.find((b) => b.id === saved)) {
+ setSelectedMode(saved);
+ } else if (backends.length) {
+ setSelectedMode(backends[0].id);
+ } else {
+ setSelectedMode(saved);
+ }
+ }).catch(() => {});
// Resume an in-flight job so the user can navigate away mid-render and
// come back to the same prompt + settings + live preview frame.
getActiveImageJob().then(({ activeJob }) => {
@@ -153,7 +182,15 @@ export default function ImageGen() {
const startLocalGeneration = async () => {
setLocalProgress({ progress: 0 });
- const payload = {
+ // Codex shares the SSE-driven async pipeline with local but ignores
+ // local-only knobs (model, LoRAs, quantize, guidance) — the dispatcher
+ // strips them on its way to the codex provider.
+ const payload = isCodexMode ? {
+ prompt: prompt.trim(),
+ negativePrompt: negativePrompt.trim() || undefined,
+ width, height,
+ mode: 'codex',
+ } : {
prompt: prompt.trim(),
negativePrompt: negativePrompt.trim() || undefined,
modelId: modelId || undefined,
@@ -164,6 +201,7 @@ export default function ImageGen() {
quantize,
loraFilenames: selectedLoras.map((l) => l.filename),
loraScales: selectedLoras.map((l) => l.scale),
+ mode: 'local',
};
const data = await generateImage(payload);
@@ -218,7 +256,7 @@ export default function ImageGen() {
beginGenerate();
try {
- if (isLocalMode) {
+ if (isAsyncMode) {
await startLocalGeneration();
} else {
const payload = {
@@ -227,6 +265,7 @@ export default function ImageGen() {
width, height,
steps: steps ? Number(steps) : 25,
cfgScale,
+ mode: 'external',
};
if (seed && Number(seed) >= 0) payload.seed = Number(seed);
const data = await generateImage(payload);
@@ -298,25 +337,44 @@ export default function ImageGen() {
return (
<div className="space-y-6">
<div className="flex items-center justify-between gap-2 text-xs">
- {status ? (
- <span className={`inline-flex items-center gap-1.5 px-2 py-1 rounded-full border ${
- status.connected
- ? 'border-port-success/40 bg-port-success/10 text-port-success'
- : 'border-port-error/40 bg-port-error/10 text-port-error'
- }`}>
- {status.connected ? (
- <><span className="w-2 h-2 rounded-full bg-port-success" /> {status.model || (status.mode === 'local' ? 'mflux/local' : 'external SD API')}</>
- ) : (
- <>
- <AlertTriangle className="w-3 h-3" />
- {status.reason || 'Not connected'} —
- <button type="button" onClick={openSettings} className="underline">Settings</button>
- </>
- )}
- </span>
- ) : (
- <span className="text-gray-500">Checking…</span>
- )}
+ <div className="flex items-center gap-2 flex-wrap">
+ {status ? (
+ <span className={`inline-flex items-center gap-1.5 px-2 py-1 rounded-full border ${
+ status.connected
+ ? 'border-port-success/40 bg-port-success/10 text-port-success'
+ : 'border-port-error/40 bg-port-error/10 text-port-error'
+ }`}>
+ {status.connected ? (
+ <><span className="w-2 h-2 rounded-full bg-port-success" /> {status.model || (status.mode === 'local' ? 'mflux/local' : status.mode === 'codex' ? 'codex CLI' : 'external SD API')}</>
+ ) : (
+ <>
+ <AlertTriangle className="w-3 h-3" />
+ {status.reason || 'Not connected'} —
+ <button type="button" onClick={openSettings} className="underline">Settings</button>
+ </>
+ )}
+ </span>
+ ) : (
+ <span className="text-gray-500">Checking…</span>
+ )}
+ {availableBackends.length > 1 && (
+ <div className="inline-flex items-center gap-1 p-0.5 border border-port-border rounded-full bg-port-bg" role="group" aria-label="Backend">
+ {availableBackends.map(({ id, label, icon: Icon }) => (
+ <button
+ key={id}
+ type="button"
+ onClick={() => setSelectedMode(id)}
+ disabled={generating}
+ className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs transition-colors disabled:opacity-50 ${effectiveMode === id ? 'bg-port-accent text-white' : 'text-gray-400 hover:text-white hover:bg-port-border/40'}`}
+ title={`Use ${label} for the next render`}
+ >
+ <Icon className="w-3 h-3" />
+ {label}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
<div className="flex items-center gap-1">
<button
onClick={refreshStatus}
@@ -391,44 +449,51 @@ export default function ImageGen() {
</select>
</div>
- <div>
- <label className="block text-xs font-medium text-gray-400 mb-1">Seed</label>
- <div className="flex items-center gap-1">
+ {/* Codex's built-in image_gen tool ignores seed/steps/guidance —
+ only the prompt + (optional) resolution hint matter. Hide
+ irrelevant knobs in that mode. */}
+ {!isCodexMode && (
+ <div>
+ <label className="block text-xs font-medium text-gray-400 mb-1">Seed</label>
+ <div className="flex items-center gap-1">
+ <input
+ type="number"
+ value={seed}
+ onChange={(e) => setSeed(e.target.value)}
+ disabled={generating}
+ placeholder="Random"
+ className="flex-1 bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
+ />
+ <button
+ type="button"
+ onClick={handleRandomSeed}
+ disabled={generating}
+ className="p-2 text-gray-400 hover:text-white border border-port-border rounded-lg hover:bg-port-border/50 disabled:opacity-50 min-h-[40px] min-w-[40px] flex items-center justify-center"
+ title="Randomize seed"
+ >
+ <Dice5 className="w-4 h-4" />
+ </button>
+ </div>
+ </div>
+ )}
+
+ {!isCodexMode && (
+ <div>
+ <label className="block text-xs font-medium text-gray-400 mb-1">
+ Steps {currentModel?.steps && `(default: ${currentModel.steps})`}
+ </label>
<input
- type="number"
- value={seed}
- onChange={(e) => setSeed(e.target.value)}
+ type="number" min={1} max={150}
+ value={steps}
+ onChange={(e) => setSteps(e.target.value)}
+ placeholder={String(currentModel?.steps || 25)}
disabled={generating}
- placeholder="Random"
- className="flex-1 bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
/>
- <button
- type="button"
- onClick={handleRandomSeed}
- disabled={generating}
- className="p-2 text-gray-400 hover:text-white border border-port-border rounded-lg hover:bg-port-border/50 disabled:opacity-50 min-h-[40px] min-w-[40px] flex items-center justify-center"
- title="Randomize seed"
- >
- <Dice5 className="w-4 h-4" />
- </button>
</div>
- </div>
-
- <div>
- <label className="block text-xs font-medium text-gray-400 mb-1">
- Steps {currentModel?.steps && `(default: ${currentModel.steps})`}
- </label>
- <input
- type="number" min={1} max={150}
- value={steps}
- onChange={(e) => setSteps(e.target.value)}
- placeholder={String(currentModel?.steps || 25)}
- disabled={generating}
- className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
- />
- </div>
+ )}
- {isLocalMode ? (
+ {!isCodexMode && (isLocalMode ? (
<>
<div>
<label className="block text-xs font-medium text-gray-400 mb-1">
@@ -466,7 +531,7 @@ export default function ImageGen() {
className="w-full accent-port-accent"
/>
</div>
- )}
+ ))}
</div>
{isLocalMode && availableLoras.length > 0 && (
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 263c58b1dc..2a09523b8c 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -12,7 +12,7 @@ import { z } from 'zod';
import { asyncHandler } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import * as imageGen from '../services/imageGen/index.js';
-import { local } from '../services/imageGen/index.js';
+import { local, IMAGE_GEN_MODES } from '../services/imageGen/index.js';
import {
REQUIRED_PACKAGES, detectPython, checkPackages, installPackages,
isExternallyManaged, createVenv, isAllowedPython, pipNameFor,
@@ -25,6 +25,9 @@ const router = Router();
const generateSchema = z.object({
prompt: z.string().min(1).max(2000),
negativePrompt: z.string().max(2000).optional(),
+ // Per-request backend override. If omitted, the dispatcher uses
+ // `imageGen.mode` from settings.json.
+ mode: z.enum(IMAGE_GEN_MODES).optional(),
modelId: z.string().max(64).optional(),
width: z.number().int().min(64).max(2048).optional(),
height: z.number().int().min(64).max(2048).optional(),
@@ -48,8 +51,12 @@ const avatarSchema = z.object({
prompt: z.string().max(2000).optional(),
});
-router.get('/status', asyncHandler(async (_req, res) => {
- res.json(await imageGen.checkConnection());
+router.get('/status', asyncHandler(async (req, res) => {
+ // Optional ?mode= override lets the Image Gen page probe a specific
+ // backend (e.g. when the user flips the per-render chip to Codex but
+ // hasn't saved Codex as the default yet).
+ const mode = IMAGE_GEN_MODES.includes(req.query.mode) ? req.query.mode : undefined;
+ res.json(await imageGen.checkConnection({ mode }));
}));
router.get('/active', asyncHandler(async (_req, res) => {
@@ -79,15 +86,15 @@ router.get('/gallery', asyncHandler(async (_req, res) => {
res.json(await local.listGallery());
}));
-// SSE progress stream for the local backend. EventSource consumers (the
-// ImageGen page) attach here using the jobId returned from POST /generate.
+// SSE progress stream. Local + Codex both produce job-keyed SSE; the
+// dispatcher picks the right provider for whichever owns the job.
router.get('/:jobId/events', (req, res) => {
- const ok = local.attachSseClient(req.params.jobId, res);
+ const ok = imageGen.attachSseClient(req.params.jobId, res);
if (!ok) res.status(404).json({ error: 'Job not found or expired' });
});
router.post('/cancel', (_req, res) => {
- const cancelled = local.cancel();
+ const cancelled = imageGen.cancel();
res.json({ ok: cancelled });
});
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 73c73a836b..78b94ccf84 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -7,12 +7,13 @@ vi.mock('../services/imageGen/index.js', () => ({
checkConnection: vi.fn(),
generateImage: vi.fn(),
generateAvatar: vi.fn(),
+ attachSseClient: vi.fn(() => false),
+ cancel: vi.fn(() => false),
+ IMAGE_GEN_MODES: ['external', 'local', 'codex'],
local: {
listImageModels: vi.fn(() => []),
listLoras: vi.fn(async () => []),
listGallery: vi.fn(async () => []),
- attachSseClient: vi.fn(() => false),
- cancel: vi.fn(() => false),
deleteImage: vi.fn(async () => ({ ok: true })),
},
}));
diff --git a/server/routes/palette.js b/server/routes/palette.js
index 20780c9977..b24f073cfd 100644
--- a/server/routes/palette.js
+++ b/server/routes/palette.js
@@ -42,6 +42,7 @@ const PALETTE_ACTIONS = [
{ id: 'daily_log_read', label: "Read today's log", section: 'Brain' },
{ id: 'daily_log_append', label: 'Append to daily log', section: 'Brain' },
{ id: 'ui_ask', label: 'Ask Yourself', section: 'Ask' },
+ { id: 'image_generate', label: 'Generate Image', section: 'Create' },
{ id: 'time_now', label: 'Current time', section: 'System' },
];
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
new file mode 100644
index 0000000000..59ac918933
--- /dev/null
+++ b/server/services/imageGen/codex.js
@@ -0,0 +1,261 @@
+/**
+ * Image Gen — Codex CLI provider.
+ *
+ * Routes image generation through the user's locally-installed `codex` CLI
+ * (https://github.com/openai/codex). Codex's bundled `imagegen` skill runs
+ * the built-in `image_gen` tool when the prompt starts with `$imagegen` and
+ * uses the user's logged-in Codex session — no OPENAI_API_KEY required.
+ *
+ * Wire format: `codex exec --skip-git-repo-check --sandbox workspace-write
+ * '$imagegen <prompt>'`. Codex prints a `session id: <uuid>` banner on stderr
+ * and writes the final PNG to `~/.codex/generated_images/<session-id>/ig_*.png`
+ * — there's no machine-readable path on stdout, so we parse the banner and
+ * harvest the dir after the child exits.
+ *
+ * The user must explicitly enable this provider in Settings → Image Gen
+ * because not every Codex account has access to the `image_gen` tool. When
+ * disabled the dispatcher rejects up front; this module assumes it's enabled
+ * by the time generateImage() is called.
+ */
+
+import { spawn } from 'child_process';
+import { copyFile, readdir, stat, writeFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { homedir } from 'os';
+import { randomUUID } from 'crypto';
+import { ensureDir, PATHS } from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { imageGenEvents } from '../imageGenEvents.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
+
+// 5 minutes — built-in `image_gen` typically returns in 30–90s, but xhigh
+// reasoning + a queued model can run longer. Bigger than the SD-API timeout
+// because we have no progress signal to short-circuit early on.
+const CODEX_TIMEOUT_MS = 5 * 60 * 1000;
+
+const DEFAULT_BIN = 'codex';
+
+const codexImagesDir = (sessionId) =>
+ join(homedir(), '.codex', 'generated_images', sessionId);
+
+// Per-job clients: jobId -> { clients, status, lastPayload, ... }. Same
+// shape as imageGen/local.js so attachSseClient/broadcastSse just work.
+const jobs = new Map();
+let activeProcess = null;
+let activeJob = null;
+
+export const getActiveJob = () => activeJob;
+
+export const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);
+
+export const cancel = () => {
+ if (!activeProcess) return false;
+ const proc = activeProcess;
+ proc.kill('SIGTERM');
+ setTimeout(() => {
+ if (activeProcess === proc && proc.exitCode === null && proc.signalCode === null) {
+ console.log(`⚠️ codex child didn't exit on SIGTERM — escalating to SIGKILL`);
+ proc.kill('SIGKILL');
+ }
+ }, 5000);
+ return true;
+};
+
+export async function checkConnection({ codexPath } = {}) {
+ // Cheap probe: spawn `codex --version`. Avoids actually invoking image_gen
+ // (which would consume the user's Codex quota); the settings UI just wants
+ // "yes the binary exists and is reachable".
+ const bin = codexPath || DEFAULT_BIN;
+ const proc = spawn(bin, ['--version'], { shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
+ let out = '';
+ proc.stdout.on('data', (c) => { out += c.toString(); });
+ proc.stderr.on('data', (c) => { out += c.toString(); });
+ return new Promise((resolve) => {
+ proc.on('error', (err) => resolve({ connected: false, mode: 'codex', reason: `Codex CLI not found (${err.message})` }));
+ proc.on('close', (code) => {
+ if (code !== 0) return resolve({ connected: false, mode: 'codex', reason: `codex --version exited ${code}` });
+ const versionMatch = out.match(/codex-cli\s+([\d.]+)/i) || out.match(/(\d+\.\d+\.\d+)/);
+ resolve({ connected: true, mode: 'codex', model: versionMatch ? `codex-cli ${versionMatch[1]}` : 'codex-cli' });
+ });
+ });
+}
+
+const SESSION_ID_RE = /^session id:\s*([0-9a-f-]{36})/im;
+
+export async function generateImage({ codexPath, model, prompt, width, height, negativePrompt }) {
+ if (!prompt?.trim()) {
+ throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (activeProcess) {
+ throw new ServerError('A Codex generation is already in progress — cancel it before starting another', { status: 409, code: 'IMAGE_GEN_BUSY' });
+ }
+
+ await ensureDir(PATHS.images);
+
+ const jobId = randomUUID();
+ const filename = `${jobId}.png`;
+ const outputPath = join(PATHS.images, filename);
+
+ // Width/height/negative aren't first-class args for Codex's built-in
+ // image_gen tool — pass them as natural-language hints inside the prompt.
+ // Codex's imagegen skill is prompt-driven; the model decides resolution.
+ const sizeHint = (width && height) ? ` (${width}x${height})` : '';
+ const avoidHint = negativePrompt?.trim() ? `\nAvoid: ${negativePrompt.trim()}` : '';
+ const fullPrompt = `$imagegen ${prompt.trim()}${sizeHint}${avoidHint}`;
+
+ const bin = codexPath || DEFAULT_BIN;
+ const args = [
+ 'exec',
+ '--skip-git-repo-check',
+ '--sandbox', 'workspace-write',
+ ...(model ? ['-m', String(model)] : []),
+ fullPrompt,
+ ];
+
+ const meta = {
+ id: jobId, prompt: prompt.trim(), negativePrompt: negativePrompt || '',
+ width: width ? Number(width) : null, height: height ? Number(height) : null,
+ filename, mode: 'codex', model: model || null,
+ createdAt: new Date().toISOString(),
+ };
+ const job = { ...meta, clients: [], status: 'running' };
+ jobs.set(jobId, job);
+
+ console.log(`🎨 Generating image [${jobId.slice(0, 8)}] codex: ${prompt.slice(0, 60)}…`);
+ imageGenEvents.emit('started', { generationId: jobId, totalSteps: 1 });
+ activeJob = { ...meta, generationId: jobId, totalSteps: 1, step: 0, progress: 0, currentImage: null };
+ broadcastSse(job, { type: 'status', message: 'Spawning codex…' });
+
+ // generateImage returns a job descriptor synchronously; the actual codex
+ // child runs out-of-band so the HTTP response can ship while the client
+ // attaches to the per-job SSE stream (mirrors local.js).
+ runCodex(job, jobId, bin, args, outputPath, filename, meta).catch((err) => {
+ console.log(`❌ codex run failed [${jobId.slice(0, 8)}]: ${err?.message}`);
+ });
+
+ return {
+ jobId, filename, path: `/data/images/${filename}`, generationId: jobId,
+ mode: 'codex', model: model || null,
+ };
+}
+
+async function runCodex(job, jobId, bin, args, outputPath, filename, meta) {
+ const proc = spawn(bin, args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
+ activeProcess = proc;
+
+ let sessionId = null;
+ let stderrTail = '';
+ const STDERR_TAIL_BYTES = 32 * 1024;
+ let timeoutTimer = setTimeout(() => {
+ if (activeProcess === proc) {
+ console.log(`⏱️ codex timed out after ${CODEX_TIMEOUT_MS}ms [${jobId.slice(0, 8)}]`);
+ proc.kill('SIGTERM');
+ setTimeout(() => { if (proc.exitCode === null) proc.kill('SIGKILL'); }, 5000);
+ }
+ }, CODEX_TIMEOUT_MS);
+
+ const captureSession = (text) => {
+ if (sessionId) return;
+ const m = text.match(SESSION_ID_RE);
+ if (m) {
+ sessionId = m[1];
+ broadcastSse(job, { type: 'status', message: `Codex session ${sessionId.slice(0, 8)}…` });
+ }
+ };
+
+ proc.on('error', (err) => {
+ clearTimeout(timeoutTimer);
+ finalizeError(job, jobId, `Failed to spawn ${bin}: ${err.message}`);
+ });
+
+ proc.stdout.on('data', (chunk) => {
+ const text = chunk.toString();
+ captureSession(text);
+ broadcastSse(job, { type: 'status', message: 'Running…' });
+ });
+
+ proc.stderr.on('data', (chunk) => {
+ const text = chunk.toString();
+ captureSession(text);
+ stderrTail += text;
+ if (stderrTail.length > STDERR_TAIL_BYTES) stderrTail = stderrTail.slice(-STDERR_TAIL_BYTES);
+ });
+
+ proc.on('close', async (code, signal) => {
+ clearTimeout(timeoutTimer);
+ activeProcess = null;
+ if (code !== 0) {
+ const reason = signal ? `Killed by signal ${signal}` : `Exit code ${code}`;
+ const tail = stderrTail.trim().split('\n').slice(-6).join('\n');
+ return finalizeError(job, jobId, `Codex generation failed: ${reason}\n${tail}`);
+ }
+ if (!sessionId) {
+ return finalizeError(job, jobId, 'Codex returned no session id — output format may have changed');
+ }
+ // Codex writes the PNG asynchronously while it's wrapping up the turn.
+ // Empirically the file is on disk by the time `codex exec` exits, but
+ // poll for a few seconds in case there's a flush lag on slow disks.
+ const harvested = await harvestLatestImage(sessionId, 5000);
+ if (!harvested) {
+ return finalizeError(
+ job, jobId,
+ 'Codex returned no image — your Codex account may not allow image_gen, or the model declined. Check Settings → Image Gen → Enable Codex Imagegen.',
+ );
+ }
+ await copyFile(harvested, outputPath);
+ // Sidecar metadata so the gallery can recover prompt/seed/etc.
+ const sidecar = join(PATHS.images, `${jobId}.metadata.json`);
+ await writeFile(sidecar, JSON.stringify(meta, null, 2)).catch(() => {});
+ job.status = 'complete';
+ activeJob = null;
+ console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (codex)`);
+ const result = { filename, path: `/data/images/${filename}` };
+ broadcastSse(job, { type: 'complete', result });
+ imageGenEvents.emit('completed', { generationId: jobId, path: `/data/images/${filename}`, filename });
+ closeJobAfterDelay(jobs, jobId);
+ });
+}
+
+const finalizeError = (job, jobId, reason) => {
+ job.status = 'error';
+ activeJob = null;
+ console.log(`❌ codex image generation failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);
+ broadcastSse(job, { type: 'error', error: reason });
+ imageGenEvents.emit('failed', { generationId: jobId, error: reason });
+ closeJobAfterDelay(jobs, jobId);
+};
+
+// Returns the absolute path to the newest ig_*.png in the session dir, or
+// null if none appears within `timeoutMs`. Polls every 250ms — the file
+// usually lands in <1s but the rare slow case is fine.
+async function harvestLatestImage(sessionId, timeoutMs) {
+ const dir = codexImagesDir(sessionId);
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (existsSync(dir)) {
+ const names = await readdir(dir).catch(() => []);
+ const pngs = names.filter((f) => f.startsWith('ig_') && f.endsWith('.png'));
+ if (pngs.length) {
+ const stats = await Promise.all(pngs.map(async (n) => {
+ const s = await stat(join(dir, n)).catch(() => null);
+ return s ? { n, mtimeMs: s.mtimeMs } : null;
+ }));
+ const latest = stats.filter(Boolean).sort((a, b) => b.mtimeMs - a.mtimeMs)[0];
+ if (latest) return join(dir, latest.n);
+ }
+ }
+ await new Promise((r) => setTimeout(r, 250));
+ }
+ return null;
+}
+
+// Tiny helper for unit tests — overrides the homedir lookup so tests can
+// point at a tmpdir-rooted ~/.codex without touching the real one. Not used
+// in production. The function below intentionally keeps state inside this
+// module because the test path is an explicit ergonomic carve-out.
+export const _internals = {
+ codexImagesDir,
+ SESSION_ID_RE,
+ harvestLatestImage,
+};
diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.js
new file mode 100644
index 0000000000..77471e7e9d
--- /dev/null
+++ b/server/services/imageGen/codex.test.js
@@ -0,0 +1,233 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { mkdir, writeFile, rm, readFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { EventEmitter } from 'events';
+
+// Each test runs against a synthetic ~/.codex layout so it never touches
+// the user's real generated_images dir. We mock os.homedir() directly —
+// node's homedir() uses getpwuid() on macOS and ignores $HOME, so just
+// setting the env var isn't enough.
+const TEST_HOME = join(tmpdir(), `portos-codex-test-${process.pid}-${Date.now()}`);
+vi.mock('os', async () => {
+ const actual = await vi.importActual('os');
+ return { ...actual, homedir: () => TEST_HOME };
+});
+
+// Spawn mock — capture every spawn call so tests can assert args, drive
+// stdout/stderr lines, and trigger the close event whenever they want.
+const spawnCalls = [];
+const makeFakeChild = () => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.kill = vi.fn();
+ child.exitCode = null;
+ child.signalCode = null;
+ return child;
+};
+// Partial mock — keep execFile/exec real for fileUtils.dirSize and friends,
+// only swap spawn so we can assert + drive the codex child.
+vi.mock('child_process', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ spawn: vi.fn((bin, args) => {
+ const child = makeFakeChild();
+ spawnCalls.push({ bin, args, child });
+ return child;
+ }),
+ };
+});
+
+// Stable PATHS.images under the fake HOME so the harvest's copyFile lands
+// in a predictable place we can read back.
+const FAKE_IMAGES_DIR = join(TEST_HOME, 'data-images');
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, images: FAKE_IMAGES_DIR },
+ ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),
+ };
+});
+
+// imageGenEvents is fine to import for real, but we don't want stray
+// listeners between tests. Reset its emitter state in beforeEach.
+const codex = await import('./codex.js');
+const { imageGenEvents } = await import('../imageGenEvents.js');
+
+const flush = () => new Promise((r) => setImmediate(r));
+
+beforeEach(async () => {
+ spawnCalls.length = 0;
+ imageGenEvents.removeAllListeners();
+ await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});
+ await mkdir(TEST_HOME, { recursive: true });
+});
+
+afterEach(async () => {
+ await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});
+});
+
+describe('codex provider — generateImage', () => {
+ it('spawns codex exec with $imagegen prompt prefix and the configured model', async () => {
+ const p = codex.generateImage({ prompt: 'a small fox', model: 'gpt-5.4' });
+ // generateImage resolves immediately (fire-and-forget run); resolved
+ // value is the job descriptor.
+ const job = await p;
+ expect(job.mode).toBe('codex');
+ expect(job.filename).toMatch(/^[0-9a-f-]{36}\.png$/);
+ expect(spawnCalls.length).toBe(1);
+ const { bin, args } = spawnCalls[0];
+ expect(bin).toBe('codex');
+ expect(args[0]).toBe('exec');
+ expect(args).toContain('--skip-git-repo-check');
+ expect(args).toContain('--sandbox');
+ expect(args).toContain('workspace-write');
+ expect(args).toContain('-m');
+ expect(args).toContain('gpt-5.4');
+ // The prompt must be prefixed with `$imagegen ` so codex's bundled
+ // imagegen skill triggers the built-in image_gen tool.
+ const promptArg = args[args.length - 1];
+ expect(promptArg.startsWith('$imagegen ')).toBe(true);
+ expect(promptArg).toContain('a small fox');
+
+ // Cleanup: end the spawned child so the tracking state resets.
+ spawnCalls[0].child.exitCode = 1;
+ spawnCalls[0].child.emit('close', 1, null);
+ await flush();
+ });
+
+ it('honors codexPath override (custom binary)', async () => {
+ await codex.generateImage({ prompt: 'a fox', codexPath: '/opt/custom/codex' });
+ expect(spawnCalls[0].bin).toBe('/opt/custom/codex');
+ spawnCalls[0].child.exitCode = 1;
+ spawnCalls[0].child.emit('close', 1, null);
+ await flush();
+ });
+
+ it('rejects when prompt is empty', async () => {
+ await expect(codex.generateImage({ prompt: ' ' })).rejects.toThrow(/Prompt is required/);
+ });
+
+ it('refuses concurrent generations (returns 409 ALREADY_RUNNING)', async () => {
+ await codex.generateImage({ prompt: 'one' });
+ await expect(codex.generateImage({ prompt: 'two' })).rejects.toThrow(/already in progress/);
+ spawnCalls[0].child.exitCode = 1;
+ spawnCalls[0].child.emit('close', 1, null);
+ await flush();
+ });
+});
+
+describe('codex provider — image harvest', () => {
+ it('copies the latest ig_*.png from ~/.codex/generated_images/<session-id>/ into PATHS.images', async () => {
+ const sessionId = '019dd59e-a8da-7bd2-a7d8-4ac6f46e7b07';
+ const codexDir = join(TEST_HOME, '.codex', 'generated_images', sessionId);
+ await mkdir(codexDir, { recursive: true });
+ const fakePngBytes = Buffer.from('fakepngbytes');
+ await writeFile(join(codexDir, 'ig_first.png'), fakePngBytes);
+
+ const completedListener = vi.fn();
+ imageGenEvents.on('completed', completedListener);
+
+ const job = await codex.generateImage({ prompt: 'a fox' });
+ const child = spawnCalls[0].child;
+
+ // Drive the session id banner on stderr (codex prints it there).
+ child.stderr.emit('data', Buffer.from(`session id: ${sessionId}\n`));
+ // Then close cleanly.
+ child.exitCode = 0;
+ child.emit('close', 0, null);
+
+ // Poll until the completed event fires (the harvest is async).
+ const deadline = Date.now() + 3000;
+ while (Date.now() < deadline && completedListener.mock.calls.length === 0) {
+ await new Promise((r) => setTimeout(r, 50));
+ }
+
+ expect(completedListener).toHaveBeenCalledTimes(1);
+ const finalPath = join(FAKE_IMAGES_DIR, job.filename);
+ expect(existsSync(finalPath)).toBe(true);
+ const written = await readFile(finalPath);
+ expect(Buffer.compare(written, fakePngBytes)).toBe(0);
+
+ // Sidecar metadata exists too.
+ const sidecar = join(FAKE_IMAGES_DIR, `${job.generationId}.metadata.json`);
+ expect(existsSync(sidecar)).toBe(true);
+ });
+
+ it('emits a failed event when codex exits 0 but writes no image (likely auth/quota issue)', async () => {
+ const sessionId = '00000000-0000-4000-8000-000000000000';
+ // Create the session dir so the harvest path exists, but leave it
+ // empty — that's the failure mode we surface to users.
+ await mkdir(join(TEST_HOME, '.codex', 'generated_images', sessionId), { recursive: true });
+
+ const failedListener = vi.fn();
+ imageGenEvents.on('failed', failedListener);
+
+ await codex.generateImage({ prompt: 'a fox' });
+ const child = spawnCalls[0].child;
+ child.stderr.emit('data', Buffer.from(`session id: ${sessionId}\n`));
+ child.exitCode = 0;
+ child.emit('close', 0, null);
+
+ // Wait out the harvest poll window (5s) plus a buffer.
+ const deadline = Date.now() + 6000;
+ while (Date.now() < deadline && failedListener.mock.calls.length === 0) {
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ expect(failedListener).toHaveBeenCalledTimes(1);
+ expect(failedListener.mock.calls[0][0].error).toMatch(/no image|account may not allow/i);
+ }, 10000);
+
+ it('emits a failed event when no session id banner is parsed', async () => {
+ const failedListener = vi.fn();
+ imageGenEvents.on('failed', failedListener);
+
+ await codex.generateImage({ prompt: 'a fox' });
+ const child = spawnCalls[0].child;
+ // Stdout/stderr deliberately empty — nothing to match SESSION_ID_RE.
+ child.exitCode = 0;
+ child.emit('close', 0, null);
+ await flush();
+ await new Promise((r) => setTimeout(r, 50));
+ expect(failedListener).toHaveBeenCalledTimes(1);
+ expect(failedListener.mock.calls[0][0].error).toMatch(/no session id/i);
+ });
+
+ it('emits a failed event when codex exits non-zero', async () => {
+ const failedListener = vi.fn();
+ imageGenEvents.on('failed', failedListener);
+
+ await codex.generateImage({ prompt: 'a fox' });
+ const child = spawnCalls[0].child;
+ child.stderr.emit('data', Buffer.from('boom: out of quota\n'));
+ child.exitCode = 1;
+ child.emit('close', 1, null);
+ await flush();
+ await new Promise((r) => setTimeout(r, 50));
+ expect(failedListener).toHaveBeenCalledTimes(1);
+ expect(failedListener.mock.calls[0][0].error).toMatch(/Exit code 1|generation failed/i);
+ });
+});
+
+describe('codex provider — internals', () => {
+ it('SESSION_ID_RE matches the codex banner format', () => {
+ const banner = `OpenAI Codex v0.125.0
+workdir: /tmp/x
+model: gpt-5.5
+session id: 019dd59e-a8da-7bd2-a7d8-4ac6f46e7b07
+something else`;
+ const m = banner.match(codex._internals.SESSION_ID_RE);
+ expect(m).toBeTruthy();
+ expect(m[1]).toBe('019dd59e-a8da-7bd2-a7d8-4ac6f46e7b07');
+ });
+
+ it('codexImagesDir resolves under the user homedir', () => {
+ const dir = codex._internals.codexImagesDir('abc');
+ expect(dir.endsWith(join('.codex', 'generated_images', 'abc'))).toBe(true);
+ });
+});
+
diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.js
index bdbc67f388..c9fe78c1a8 100644
--- a/server/services/imageGen/index.js
+++ b/server/services/imageGen/index.js
@@ -2,42 +2,56 @@
* Image Gen — Mode-aware dispatcher.
*
* Reads settings.imageGen.mode (default 'external' for backward compat) and
- * routes generate/status calls to either the external SD-API client or the
- * local (mflux/diffusers) backend. This module is the public entrypoint —
- * routes/imageGen.js, the A1111 proxy, and the CoS tools registry all go
- * through here so the underlying provider is interchangeable.
+ * routes generate/status calls to one of three providers: external SD-API,
+ * local mflux/diffusers, or the Codex CLI built-in image_gen tool.
+ *
+ * Per-request mode override: callers (the route, the voice tool) may pass
+ * `params.mode` to force a specific backend without changing the saved
+ * default. The Codex backend is also user-gated — even with `mode: 'codex'`
+ * we refuse unless `imageGen.codex.enabled` is true, because that toggle
+ * exists for users whose Codex plan doesn't expose the image_gen tool.
*/
import { getSettings } from '../settings.js';
+import { ServerError } from '../../lib/errorHandler.js';
import * as external from './external.js';
import * as local from './local.js';
+import * as codex from './codex.js';
+export const IMAGE_GEN_MODES = Object.freeze(['external', 'local', 'codex']);
const DEFAULT_MODE = 'external';
const cfg = (s) => s?.imageGen || {};
const sdapiUrl = (s) => cfg(s).external?.sdapiUrl || cfg(s).sdapiUrl || null;
const pythonPath = (s) => cfg(s).local?.pythonPath || null;
+const codexCfg = (s) => cfg(s).codex || {};
export async function getMode() {
const s = await getSettings();
return cfg(s).mode || DEFAULT_MODE;
}
-export async function checkConnection() {
+export async function checkConnection({ mode: modeOverride } = {}) {
const s = await getSettings();
- const mode = cfg(s).mode || DEFAULT_MODE;
+ const mode = modeOverride || cfg(s).mode || DEFAULT_MODE;
if (mode === 'local') {
const py = pythonPath(s);
if (!py) return { connected: false, mode, reason: 'Python path not configured' };
return { connected: true, mode, model: 'mflux/local', pythonPath: py };
}
+ if (mode === 'codex') {
+ const c = codexCfg(s);
+ if (!c.enabled) return { connected: false, mode, reason: 'Codex Imagegen is disabled in settings' };
+ return codex.checkConnection({ codexPath: c.codexPath });
+ }
const status = await external.checkConnection(sdapiUrl(s));
return { ...status, mode };
}
export async function generateImage(params) {
const s = await getSettings();
- const mode = cfg(s).mode || DEFAULT_MODE;
+ const requestedMode = params?.mode;
+ const mode = requestedMode || cfg(s).mode || DEFAULT_MODE;
// Param normalization: A1111 clients (and the /sdapi/v1/txt2img bridge)
// send `cfgScale`; local mflux reads `guidance`. Map cfgScale -> guidance
// when guidance is not explicitly set so both spellings work in both modes.
@@ -45,6 +59,18 @@ export async function generateImage(params) {
if (normalized.guidance == null && normalized.cfgScale != null) {
normalized.guidance = normalized.cfgScale;
}
+ // Strip the dispatcher-only `mode` field — providers don't expect it.
+ delete normalized.mode;
+ if (mode === 'codex') {
+ const c = codexCfg(s);
+ if (!c.enabled) {
+ throw new ServerError(
+ 'Codex Imagegen is disabled — enable it in Settings → Image Gen first',
+ { status: 400, code: 'CODEX_IMAGEGEN_DISABLED' },
+ );
+ }
+ return codex.generateImage({ codexPath: c.codexPath, model: c.model, ...normalized });
+ }
if (mode === 'local') {
return local.generateImage({ pythonPath: pythonPath(s), ...normalized });
}
@@ -63,14 +89,29 @@ export async function generateAvatar({ name, characterClass, prompt }) {
});
}
-// Snapshot of any in-flight generation across both modes — lets the UI
+// Snapshot of any in-flight generation across all modes — lets the UI
// rehydrate prompt + settings + progress + last frame after navigating away
// during a render.
export async function getActiveJob() {
- return local.getActiveJob() || external.getActiveJob() || null;
+ return local.getActiveJob() || external.getActiveJob() || codex.getActiveJob() || null;
}
-// Re-exports so routes can hit the local backend directly when the request
-// is shape-specific (SSE attach, gallery, LoRAs). The dispatcher is for the
-// generic generate/status flow used by both modes.
-export { local, external };
+// Try-each-provider SSE attach + cancel — the route only knows the jobId,
+// not which backend produced it, so we ask each provider in turn and let
+// the first one that owns the job handle the attach.
+export const attachSseClient = (jobId, res) => {
+ if (local.attachSseClient(jobId, res)) return true;
+ if (codex.attachSseClient(jobId, res)) return true;
+ return false;
+};
+
+export const cancel = () => {
+ const cancelled = local.cancel();
+ if (cancelled) return true;
+ return codex.cancel();
+};
+
+// Re-exports so routes can hit a specific backend directly when the request
+// is shape-specific (gallery, LoRAs). The dispatcher is for the generic
+// generate/status flow used by all modes.
+export { local, external, codex };
diff --git a/server/services/voice/tools.js b/server/services/voice/tools.js
index a18ec5a1a0..fee712dc1e 100644
--- a/server/services/voice/tools.js
+++ b/server/services/voice/tools.js
@@ -13,6 +13,9 @@ import { getUserTimezone, todayInTimezone, getLocalParts } from '../../lib/timez
import * as journal from '../brainJournal.js';
import { resolveNavCommand, normalizeLabel } from '../../lib/navManifest.js';
import { runAsk, VALID_MODES as ASK_VALID_MODES } from '../askService.js';
+import * as imageGen from '../imageGen/index.js';
+import { IMAGE_GEN_MODES } from '../imageGen/index.js';
+import { getSettings } from '../settings.js';
const DAILY_LOG_PATH = '/brain/daily-log';
@@ -66,6 +69,7 @@ const TOOL_GROUPS = {
ui_select: 'ui',
ui_check: 'ui',
ui_ask: 'ask',
+ image_generate: 'media',
// UNGROUPED = always-on: time_now, daily_log_append, ui_navigate.
// brain_capture used to be always-on, but that caused form-fill turns
// ("fill description with X") to be misrouted to brain_capture because
@@ -108,6 +112,10 @@ const GROUP_INTENT = {
// want it stealing turns the cheaper tools handle. Catches "advise me",
// "draft a/an X", "what did I decide", "what's on my plate", "ask myself".
ask: /\b(?:ask my ?self|advise me|coach me|draft (?:a|an|my|me|something)|what(?:'s| is) on my plate|what (?:did|do|should) i (?:decide|think|believe|say|want|do)|why did i|when did i|recall (?:my|that|when))\b/i,
+ // Imagery verbs that should surface image_generate. Tight-ish: avoids
+ // common false positives like "imagine if" or "show me a picture of the
+ // page" by anchoring on creation verbs paired with visual nouns.
+ media: /\b(?:generate|render|create|draw|sketch|paint|illustrate|make|design|produce)\b[^.!?\n]{0,30}\b(?:image|picture|photo|illustration|art(?:work)?|render|drawing|sketch|portrait|wallpaper|scene|asset|graphic|logo|icon)\b|\bimagegen\b/i,
ui: UI_INTENT_RE,
};
@@ -1054,6 +1062,64 @@ const TOOLS = [
},
},
+ {
+ name: 'image_generate',
+ description:
+ 'Generate an image from a text prompt and save it to the user\'s gallery. Defaults to the user\'s saved Image Gen backend (Local mflux, External SD API, or Codex CLI). Pass `provider` to override per-call: "local" for fast Flux drafts, "external" for an A1111-compatible server, "codex" for the Codex CLI built-in image_gen tool (subject to the user enabling it in Settings). Returns the saved file path.',
+ parameters: {
+ type: 'object',
+ properties: {
+ prompt: {
+ type: 'string',
+ description: 'What to draw, in natural language. Be specific about subject, style, and mood.',
+ },
+ provider: {
+ type: 'string',
+ enum: ['auto', ...IMAGE_GEN_MODES],
+ description: '"auto" (default) uses the user\'s saved backend. Override only when the user explicitly asks for a specific one or the task strongly favors it.',
+ },
+ negativePrompt: {
+ type: 'string',
+ description: 'Optional list of things to avoid (e.g. "watermark, low quality").',
+ },
+ width: { type: 'integer', description: 'Optional pixel width (64-2048).' },
+ height: { type: 'integer', description: 'Optional pixel height (64-2048).' },
+ },
+ required: ['prompt'],
+ },
+ execute: async ({ prompt, provider, negativePrompt, width, height } = {}) => {
+ if (typeof prompt !== 'string' || !prompt.trim()) {
+ return { ok: false, summary: 'prompt is required' };
+ }
+ const requestedMode = (provider && provider !== 'auto') ? provider : undefined;
+ // Codex is gated separately — it costs against the user's Codex plan,
+ // and not every plan exposes image_gen. The dispatcher would also
+ // reject this, but catching it here lets us return a friendlier
+ // summary to the voice agent / palette.
+ if (requestedMode === 'codex') {
+ const s = await getSettings();
+ if (!s?.imageGen?.codex?.enabled) {
+ return { ok: false, summary: 'Codex Imagegen is disabled — enable it in Settings → Image Gen first.' };
+ }
+ }
+ const result = await imageGen.generateImage({
+ prompt: prompt.trim(),
+ negativePrompt: negativePrompt?.trim() || undefined,
+ width: width || undefined,
+ height: height || undefined,
+ mode: requestedMode,
+ });
+ const usedMode = result?.mode || requestedMode || 'default';
+ return {
+ ok: true,
+ path: result?.path,
+ filename: result?.filename,
+ mode: usedMode,
+ summary: `Generating image (${usedMode}): ${result?.filename || 'pending'}`,
+ };
+ },
+ },
+
{
name: 'time_now',
description:
diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.js
index 30e4848f64..94299aaf16 100644
--- a/server/services/voice/tools.test.js
+++ b/server/services/voice/tools.test.js
@@ -32,6 +32,20 @@ vi.mock('../feeds.js', () => ({
markItemRead: vi.fn(async () => ({ updated: true })),
markAllRead: vi.fn(async () => ({ marked: 0 })),
}));
+// imageGen dispatcher — tests pin the dispatch and let us assert what mode
+// the voice tool forwards. The settings mock controls the codex-enabled gate.
+const generateImageMock = vi.fn(async (params) => ({
+ filename: 'mock.png', path: '/data/images/mock.png', mode: params?.mode || 'external',
+}));
+const codexEnabledRef = { value: false };
+vi.mock('../imageGen/index.js', () => ({
+ generateImage: (...args) => generateImageMock(...args),
+ IMAGE_GEN_MODES: ['external', 'local', 'codex'],
+}));
+vi.mock('../settings.js', () => ({
+ getSettings: vi.fn(async () => ({ imageGen: { codex: { enabled: codexEnabledRef.value } } })),
+}));
+
// askService.runAsk is an async generator. Default mock yields a small
// synthetic stream so ui_ask tests don't need to spin up real providers.
vi.mock('../askService.js', () => ({
@@ -421,3 +435,59 @@ describe('getToolSpecsForIntent — ui_ask gating', () => {
expect(names(specs)).not.toContain('ui_ask');
});
});
+
+// image_generate uses imageGen.generateImage under the hood; mocked
+// above. The codexEnabledRef toggle drives the disabled-gate test.
+describe("image_generate", () => {
+ it("rejects empty prompt", async () => {
+ const r = await dispatchTool("image_generate", { prompt: " " });
+ expect(r.ok).toBe(false);
+ expect(r.summary).toMatch(/prompt is required/);
+ });
+
+ it("forwards prompt to dispatcher with no mode by default (auto)", async () => {
+ generateImageMock.mockClear();
+ const r = await dispatchTool("image_generate", { prompt: "a fox" });
+ expect(r.ok).toBe(true);
+ expect(generateImageMock).toHaveBeenCalledTimes(1);
+ const args = generateImageMock.mock.calls[0][0];
+ expect(args.prompt).toBe("a fox");
+ expect(args.mode).toBeUndefined();
+ });
+
+ it("treats provider=auto the same as no provider", async () => {
+ generateImageMock.mockClear();
+ await dispatchTool("image_generate", { prompt: "a fox", provider: "auto" });
+ expect(generateImageMock.mock.calls[0][0].mode).toBeUndefined();
+ });
+
+ it("forwards provider=local as mode=local", async () => {
+ generateImageMock.mockClear();
+ await dispatchTool("image_generate", { prompt: "a fox", provider: "local" });
+ expect(generateImageMock.mock.calls[0][0].mode).toBe("local");
+ });
+
+ it("rejects provider=codex when codex is disabled in settings", async () => {
+ codexEnabledRef.value = false;
+ generateImageMock.mockClear();
+ const r = await dispatchTool("image_generate", { prompt: "a fox", provider: "codex" });
+ expect(r.ok).toBe(false);
+ expect(r.summary).toMatch(/Codex Imagegen is disabled/);
+ expect(generateImageMock).not.toHaveBeenCalled();
+ });
+
+ it("forwards provider=codex when codex is enabled", async () => {
+ codexEnabledRef.value = true;
+ generateImageMock.mockClear();
+ const r = await dispatchTool("image_generate", { prompt: "a fox", provider: "codex" });
+ expect(r.ok).toBe(true);
+ expect(generateImageMock.mock.calls[0][0].mode).toBe("codex");
+ codexEnabledRef.value = false;
+ });
+
+ it("includes the saved file path in summary", async () => {
+ const r = await dispatchTool("image_generate", { prompt: "a fox" });
+ expect(r.path).toBe("/data/images/mock.png");
+ expect(r.filename).toBe("mock.png");
+ });
+});