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 Agy image generation backend

[._.]/ Adam Eivy2ca291701562
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9cd4d87c27..00a5eed02d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -9,6 +9,9 @@
- **[issue-3180] Agents no longer run in the PortOS folder when your app's repository path is wrong** — picking an app as the workspace (in a CoS task, or Settings → Providers → Run Prompt) and asking the agent to create a file could put the file in the PortOS directory instead of your app. If the app's Repository Path was empty, mistyped, or pointed somewhere that no longer exists, PortOS quietly fell back to its own folder and said nothing, so the run looked like it had worked. Now PortOS names the directory it chose for every run and in the CoS task log; a run whose workspace doesn't exist stops with a message telling you which path to fix; and a CoS task whose app has no usable Repository Path is blocked before the agent starts, rather than turned loose in the PortOS checkout. A path saved as `~/Projects/MyApp` is also accepted. Troubleshooting steps — including why `PORTOS_WORKSPACE_ROOTS` is unrelated to this — are in `docs/TROUBLESHOOTING.md`.
- **[issue-3180] Agent terminals on Windows get a working environment** — the environment filter for agent shell sessions was written for macOS/Linux and dropped variables Windows needs, including `Path` itself (Windows spells it mixed-case, which the filter didn't match), plus `SystemRoot`, `ComSpec`, `TEMP`, and the per-user `APPDATA` folders where the coding CLIs keep their configuration and credentials. Windows sessions now keep those while still withholding API keys and tokens.
+## Image generation
+
+- **[issue-3186] Agy CLI is now an opt-in image-generation backend.** Users can enable Antigravity in Image Gen settings, select an installed or custom model, and send text-to-image work through its `generate_image` tool with queue progress, cancellation, gallery metadata, cleaner options, and CoS tool registration. Each render runs in an isolated scratch directory and only a signature-verified directed image is imported; image-edit surfaces continue to use an edit-capable backend.
## Quota burn
diff --git a/client/src/components/imageGen/ImageGenSettingsForm.jsx b/client/src/components/imageGen/ImageGenSettingsForm.jsx
index d56f960c63..dbd1a9f7d6 100644
--- a/client/src/components/imageGen/ImageGenSettingsForm.jsx
+++ b/client/src/components/imageGen/ImageGenSettingsForm.jsx
@@ -57,13 +57,14 @@ export default function ImageGenSettingsForm({
const merge = (patch) => onChange?.({ ...cfg, ...patch });
const isCodex = cfg.mode === IMAGE_GEN_MODE.CODEX;
const isGrok = cfg.mode === IMAGE_GEN_MODE.GROK;
+ const isAgy = cfg.mode === IMAGE_GEN_MODE.AGY;
const isLocal = cfg.mode === IMAGE_GEN_MODE.LOCAL;
const labelCls = 'block text-xs font-medium text-gray-400 mb-1';
const textareaCls = '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 resize-y';
const noBackend = availableBackends.length === 0 ? (
<div className="text-[11px] text-port-warning bg-port-warning/10 border border-port-warning/40 rounded px-2 py-1.5">
- No image gen backend configured. Open Settings → Image Gen to enable Local mflux or Codex <code className="text-gray-400">$imagegen</code>.
+ No image gen backend configured. Open Settings → Image Gen to enable a local, external, or cloud CLI backend.
</div>
) : null;
@@ -87,6 +88,10 @@ export default function ImageGenSettingsForm({
<p className="text-[10px] text-gray-500 mt-1">
Grok's <code className="text-gray-400">image_gen</code> picks model, steps, and seed internally. Resolution maps to the nearest supported aspect ratio; style fields apply.
</p>
+ ) : isAgy ? (
+ <p className="text-[10px] text-gray-500 mt-1">
+ Agy uses the model selected in Settings and supports text-to-image only. Resolution and style fields apply.
+ </p>
) : null}
</div>
) : null;
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsx
index 9b2d713158..93078b614c 100644
--- a/client/src/components/media/MediaJobsQueue.jsx
+++ b/client/src/components/media/MediaJobsQueue.jsx
@@ -55,6 +55,12 @@ function modelLabel(params) {
const ratio = (typeof params.aspectRatio === 'string' ? params.aspectRatio.trim() : '');
return ratio ? `grok · ${ratio}` : 'grok';
}
+ if (params.mode === IMAGE_GEN_MODE.AGY) {
+ const model = (typeof params.model === 'string' ? params.model.trim() : '');
+ return model && model !== 'antigravity-configured-default'
+ ? `agy / ${model}`
+ : 'agy / configured default';
+ }
const id = (params.modelId || '').trim();
if (!id) return 'local';
const tail = id.includes('/') ? id.slice(id.lastIndexOf('/') + 1) : id;
diff --git a/client/src/components/pipeline/stages/VisualGenSettings.jsx b/client/src/components/pipeline/stages/VisualGenSettings.jsx
index e00f858eaf..92dd20a2f9 100644
--- a/client/src/components/pipeline/stages/VisualGenSettings.jsx
+++ b/client/src/components/pipeline/stages/VisualGenSettings.jsx
@@ -88,12 +88,15 @@ const loadLookups = () => {
const resolveAutoLabel = (s) => {
const codexEnabled = s?.imageGen?.codex?.enabled === true;
const grokEnabled = s?.imageGen?.grok?.enabled === true;
+ const agyEnabled = s?.imageGen?.agy?.enabled === true;
const pinned = s?.imageGen?.mode;
if (pinned === IMAGE_GEN_MODE.CODEX && codexEnabled) return 'Codex';
if (pinned === IMAGE_GEN_MODE.GROK && grokEnabled) return 'Grok';
+ if (pinned === IMAGE_GEN_MODE.AGY && agyEnabled) return 'Agy';
if (pinned === IMAGE_GEN_MODE.LOCAL) return 'Local diffusion';
if (codexEnabled) return 'Codex';
if (grokEnabled) return 'Grok';
+ if (agyEnabled) return 'Agy';
if (s?.imageGen?.local?.pythonPath) return 'Local diffusion';
return 'Local diffusion (not configured)';
};
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsx
index 8acbc4126e..bc9335b56d 100644
--- a/client/src/components/settings/ImageGenTab.jsx
+++ b/client/src/components/settings/ImageGenTab.jsx
@@ -20,7 +20,7 @@ import { isLoopbackHost } from '../../lib/loopbackHost.js';
import {
getSettings, updateSettings, getImageGenStatus, generateImage,
registerTool, updateTool, getToolsList,
- saveHfToken, clearHfToken,
+ saveHfToken, clearHfToken, listAgyImageModels,
} from '../../services/api';
import { isCloudCliMode, IMAGE_GEN_MODE, CODEX_IMAGEGEN_DEFAULT_EFFORT, GROK_ASPECT_RATIOS } from '../../lib/imageGenBackends';
import { resolveCleanersFromConfig } from '../../lib/imageCleaners';
@@ -31,6 +31,7 @@ import { CODEX_EFFORT_LEVELS } from '../../utils/providers';
const SDAPI_TOOL_ID = 'sdapi';
const CODEX_TOOL_ID = 'codex-imagegen';
const GROK_TOOL_ID = 'grok-imagegen';
+const AGY_TOOL_ID = 'agy-imagegen';
// Mirror of server/services/imageGen/modes.js — shown as placeholder/default
// hints so the user sees what a blank Model / Effort field will actually use.
// The server owns the real default; these are display-only. The effort default
@@ -59,6 +60,7 @@ const MEDIA_TABS = [
{ id: 'local', label: 'Local', icon: Cpu },
{ id: 'codex', label: 'Codex CLI', icon: Terminal },
{ id: 'grok', label: 'Grok CLI', icon: Sparkles },
+ { id: 'agy', label: 'Agy CLI', icon: Terminal },
{ id: 'tokens', label: 'Tokens', icon: Key },
{ id: 'expose', label: 'Expose', icon: Globe },
{ id: 'test', label: 'Test', icon: Sparkles },
@@ -106,6 +108,12 @@ export function ImageGenTab() {
const [grokPath, setGrokPath] = useState('');
// Empty = let the caller's width/height (or the tool default) decide.
const [grokAspectRatio, setGrokAspectRatio] = useState('');
+ const [agyEnabled, setAgyEnabled] = useState(false);
+ const [agyPath, setAgyPath] = useState('');
+ const [agyModel, setAgyModel] = useState('');
+ const [agyModels, setAgyModels] = useState([]);
+ const [agyModelsError, setAgyModelsError] = useState(null);
+ const [agyModelsLoading, setAgyModelsLoading] = useState(false);
// Per-provider cleaner toggles. Both run after the PNG lands and before
// the SSE complete event so subscribers see the cleaned bytes. SynthID
// (the gpt-image / Imagen / Gemini pixel-level watermark) is unaffected
@@ -115,8 +123,8 @@ export function ImageGenTab() {
// provenance chunk. Lossless — pixels untouched.
// - denoise (default OFF): median(3) + sharpen pass for AI-artifact
// reduction. LOSSY: blurs annotation text and small details.
- const [cleanC2PAByMode, setCleanC2PAByMode] = useState({ external: true, local: true, codex: true, grok: false });
- const [denoiseByMode, setDenoiseByMode] = useState({ external: false, local: false, codex: false, grok: false });
+ const [cleanC2PAByMode, setCleanC2PAByMode] = useState({ external: true, local: true, codex: true, grok: false, agy: false });
+ const [denoiseByMode, setDenoiseByMode] = useState({ external: false, local: false, codex: false, grok: false, agy: false });
const setCleanC2PAFor = (m) => (v) => setCleanC2PAByMode((p) => ({ ...p, [m]: v }));
const setDenoiseFor = (m) => (v) => setDenoiseByMode((p) => ({ ...p, [m]: v }));
// Raw string held while the user is typing in the parallel-limit input.
@@ -134,14 +142,18 @@ export function ImageGenTab() {
const codexParallelId = useId();
const grokPathId = useId();
const grokRatioId = useId();
+ const agyPathId = useId();
+ const agyModelId = useId();
+ const agyModelsListId = useId();
// Snapshot of saved values so we can show the "dirty" state
const [saved, setSaved] = useState({
mode: IMAGE_GEN_MODE.EXTERNAL, sdapiUrl: '', pythonPath: '', exposeA1111: false,
codexEnabled: false, codexPath: '', codexModel: '', codexEffort: '', codexParallelLimit: 1,
grokEnabled: false, grokPath: '', grokAspectRatio: '',
- cleanC2PAByMode: { external: true, local: true, codex: true, grok: false },
- denoiseByMode: { external: false, local: false, codex: false, grok: false },
+ agyEnabled: false, agyPath: '', agyModel: '',
+ cleanC2PAByMode: { external: true, local: true, codex: true, grok: false, agy: false },
+ denoiseByMode: { external: false, local: false, codex: false, grok: false, agy: false },
});
const [status, setStatus] = useState(null);
@@ -149,6 +161,7 @@ export function ImageGenTab() {
const [toolRegistered, setToolRegistered] = useState(false);
const [codexToolRegistered, setCodexToolRegistered] = useState(false);
const [grokToolRegistered, setGrokToolRegistered] = useState(false);
+ const [agyToolRegistered, setAgyToolRegistered] = useState(false);
const [testPrompt, setTestPrompt] = useState(DEFAULT_TEST_PROMPT);
const [rendering, setRendering] = useState(false);
@@ -216,14 +229,19 @@ export function ImageGenTab() {
const gkEnabled = gk.enabled === true;
const gkPath = gk.grokPath || '';
const gkRatio = gk.aspectRatio || '';
+ const ay = ig.agy || {};
+ const ayEnabled = ay.enabled === true;
+ const ayPath = ay.agyPath || '';
+ const ayModel = ay.model || '';
// Per-mode cleaner reads via the shared helper (mirrored from
// server/lib/imageClean.js).
const codexClean = resolveCleanersFromConfig(cx, IMAGE_GEN_MODE.CODEX);
const grokClean = resolveCleanersFromConfig(gk, IMAGE_GEN_MODE.GROK);
+ const agyClean = resolveCleanersFromConfig(ay, IMAGE_GEN_MODE.AGY);
const localClean = resolveCleanersFromConfig(ig.local, IMAGE_GEN_MODE.LOCAL);
const externalClean = resolveCleanersFromConfig(ig.external, IMAGE_GEN_MODE.EXTERNAL);
- const c2 = { codex: codexClean.cleanC2PA, grok: grokClean.cleanC2PA, local: localClean.cleanC2PA, external: externalClean.cleanC2PA };
- const dn = { codex: codexClean.denoise, grok: grokClean.denoise, local: localClean.denoise, external: externalClean.denoise };
+ const c2 = { codex: codexClean.cleanC2PA, grok: grokClean.cleanC2PA, agy: agyClean.cleanC2PA, local: localClean.cleanC2PA, external: externalClean.cleanC2PA };
+ const dn = { codex: codexClean.denoise, grok: grokClean.denoise, agy: agyClean.denoise, local: localClean.denoise, external: externalClean.denoise };
setMode(m);
setSdapiUrl(url);
setPythonPath(py);
@@ -237,6 +255,9 @@ export function ImageGenTab() {
setGrokEnabled(gkEnabled);
setGrokPath(gkPath);
setGrokAspectRatio(gkRatio);
+ setAgyEnabled(ayEnabled);
+ setAgyPath(ayPath);
+ setAgyModel(ayModel);
setCleanC2PAByMode(c2);
setDenoiseByMode(dn);
setSaved({
@@ -244,16 +265,38 @@ export function ImageGenTab() {
codexEnabled: cxEnabled, codexPath: cxPath, codexModel: cxModel, codexEffort: cxEffort,
codexParallelLimit: cxParallel,
grokEnabled: gkEnabled, grokPath: gkPath, grokAspectRatio: gkRatio,
+ agyEnabled: ayEnabled, agyPath: ayPath, agyModel: ayModel,
cleanC2PAByMode: c2, denoiseByMode: dn,
});
setToolRegistered(tools.some((t) => t.id === SDAPI_TOOL_ID));
setCodexToolRegistered(tools.some((t) => t.id === CODEX_TOOL_ID));
setGrokToolRegistered(tools.some((t) => t.id === GROK_TOOL_ID));
+ setAgyToolRegistered(tools.some((t) => t.id === AGY_TOOL_ID));
})
.catch(() => toast.error('Failed to load image gen settings'))
.finally(() => setLoading(false));
}, []);
+ const refreshAgyModels = useCallback(() => {
+ if (!agyEnabled) return;
+ setAgyModelsLoading(true);
+ setAgyModelsError(null);
+ listAgyImageModels({ silent: true })
+ .then((result) => {
+ setAgyModels(Array.isArray(result?.models) ? result.models : []);
+ setAgyModelsError(result?.error || null);
+ })
+ .catch((err) => {
+ setAgyModels([]);
+ setAgyModelsError(err.message || 'Failed to list Agy models');
+ })
+ .finally(() => setAgyModelsLoading(false));
+ }, [agyEnabled]);
+
+ useEffect(() => {
+ if (mediaTab === 'agy' && agyEnabled) refreshAgyModels();
+ }, [mediaTab, agyEnabled, refreshAgyModels]);
+
const checkStatus = useCallback(() => {
setChecking(true);
getImageGenStatus()
@@ -274,6 +317,11 @@ export function ImageGenTab() {
|| grokEnabled !== saved.grokEnabled
|| grokPath !== saved.grokPath
|| grokAspectRatio !== saved.grokAspectRatio
+ || agyEnabled !== saved.agyEnabled
+ || agyPath !== saved.agyPath
+ || agyModel !== saved.agyModel
+ || cleanC2PAByMode.agy !== saved.cleanC2PAByMode.agy
+ || denoiseByMode.agy !== saved.denoiseByMode.agy
|| cleanC2PAByMode.grok !== saved.cleanC2PAByMode.grok
|| denoiseByMode.grok !== saved.denoiseByMode.grok
|| cleanC2PAByMode.codex !== saved.cleanC2PAByMode.codex
@@ -292,6 +340,8 @@ export function ImageGenTab() {
const cxParallel = clampParallel(codexParallelLimit, parallelBounds);
const gkPath = grokPath?.trim() || undefined;
const gkRatio = grokAspectRatio?.trim() || undefined;
+ const ayPath = agyPath?.trim() || undefined;
+ const ayModel = agyModel?.trim() || undefined;
const patch = {
imageGen: {
mode,
@@ -305,6 +355,10 @@ export function ImageGenTab() {
enabled: grokEnabled, grokPath: gkPath, aspectRatio: gkRatio,
cleanC2PA: cleanC2PAByMode.grok, denoise: denoiseByMode.grok,
},
+ agy: {
+ enabled: agyEnabled, agyPath: ayPath, model: ayModel,
+ cleanC2PA: cleanC2PAByMode.agy, denoise: denoiseByMode.agy,
+ },
expose: { a1111: exposeA1111 },
// Keep the legacy field populated so anything still reading
// `imageGen.sdapiUrl` directly stays working.
@@ -322,6 +376,7 @@ export function ImageGenTab() {
codexEnabled, codexPath: cxPath || '', codexModel: cxModel || '', codexEffort: cxEffort || '',
codexParallelLimit: cxParallel,
grokEnabled, grokPath: gkPath || '', grokAspectRatio: gkRatio || '',
+ agyEnabled, agyPath: ayPath || '', agyModel: ayModel || '',
cleanC2PAByMode, denoiseByMode,
});
if (cxParallel !== codexParallelLimit) {
@@ -335,6 +390,8 @@ export function ImageGenTab() {
if (cxEffort !== codexEffort) setCodexEffort(cxEffort || '');
if (gkPath !== grokPath) setGrokPath(gkPath || '');
if (gkRatio !== grokAspectRatio) setGrokAspectRatio(gkRatio || '');
+ if (ayPath !== agyPath) setAgyPath(ayPath || '');
+ if (ayModel !== agyModel) setAgyModel(ayModel || '');
toast.success('Image gen settings saved');
} catch (err) {
toast.error(err.message || 'Failed to save settings');
@@ -369,6 +426,14 @@ export function ImageGenTab() {
config: { codexPath: cxPath, model: cxModel, effort: cxEffort },
promptHints: 'Use POST /api/image-gen/generate with { prompt, mode: "codex" } — or call the image_generate voice tool with provider: "codex".',
};
+ const agyToolData = {
+ name: 'Agy Imagegen',
+ category: 'image-generation',
+ description: 'Generate text-to-image renders through the Antigravity CLI generate_image tool.',
+ enabled: agyEnabled,
+ config: { agyPath: ayPath, model: ayModel },
+ promptHints: 'Use POST /api/image-gen/generate with { prompt, mode: "agy" } — or call image_generate with provider: "agy". Image editing is not supported.',
+ };
const syncTool = async ({ id, registered, data, shouldCreate, onCreated, errLabel }) => {
if (registered) {
@@ -400,6 +465,11 @@ export function ImageGenTab() {
shouldCreate: grokEnabled, onCreated: () => setGrokToolRegistered(true),
errLabel: 'Grok Imagegen tool',
}),
+ syncTool({
+ id: AGY_TOOL_ID, registered: agyToolRegistered, data: agyToolData,
+ shouldCreate: agyEnabled, onCreated: () => setAgyToolRegistered(true),
+ errLabel: 'Agy Imagegen tool',
+ }),
]);
setSaving(false);
@@ -492,7 +562,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 ${(codexEnabled || grokEnabled) ? 'lg:grid-cols-3' : ''} gap-3`}>
+ <div className={`grid grid-cols-1 sm:grid-cols-2 ${(codexEnabled || grokEnabled || agyEnabled) ? 'lg:grid-cols-3' : ''} gap-3`}>
<button
type="button"
onClick={() => setMode(IMAGE_GEN_MODE.EXTERNAL)}
@@ -541,6 +611,19 @@ export function ImageGenTab() {
<p className="text-xs text-gray-500 mt-1">Route through the Grok Build CLI built-in image_gen tool. Counts against your Grok plan.</p>
</button>
)}
+ {agyEnabled && (
+ <button
+ type="button"
+ onClick={() => setMode(IMAGE_GEN_MODE.AGY)}
+ className={`text-left p-4 rounded-lg border transition-colors ${mode === IMAGE_GEN_MODE.AGY ? '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">Agy CLI</span>
+ </div>
+ <p className="text-xs text-gray-500 mt-1">Text-to-image through Antigravity's generate_image tool and your selected model.</p>
+ </button>
+ )}
</div>
</div>
)}
@@ -780,6 +863,83 @@ export function ImageGenTab() {
</div>
)}
+ {mediaTab === 'agy' && (
+ <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">Agy CLI Imagegen</h2>
+ </div>
+ <p className="text-xs text-gray-500">
+ Route text-to-image generation through Antigravity's built-in
+ <code className="text-gray-400"> generate_image </code> tool. Agy runs in an isolated scratch
+ directory and PortOS imports only the directed image output. Image editing is not supported.
+ </p>
+ <label className="flex items-center gap-3 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={agyEnabled}
+ onChange={(e) => {
+ const enabled = e.target.checked;
+ setAgyEnabled(enabled);
+ if (!enabled && mode === IMAGE_GEN_MODE.AGY) {
+ setMode(pythonPath?.trim() ? IMAGE_GEN_MODE.LOCAL : IMAGE_GEN_MODE.EXTERNAL);
+ }
+ }}
+ className="rounded"
+ />
+ <span className="text-sm text-gray-300">Enable Agy Imagegen</span>
+ </label>
+ {agyEnabled && (
+ <div className="space-y-3 pl-6 border-l-2 border-port-border">
+ <div>
+ <label htmlFor={agyPathId} className="block text-xs font-medium text-gray-400 mb-1">Agy binary path (optional)</label>
+ <input
+ id={agyPathId}
+ type="text"
+ value={agyPath}
+ onChange={(e) => setAgyPath(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="agy (uses $PATH)"
+ />
+ </div>
+ <div>
+ <div className="flex items-end justify-between gap-3 mb-1">
+ <label htmlFor={agyModelId} className="block text-xs font-medium text-gray-400">Image model</label>
+ <button
+ type="button"
+ onClick={refreshAgyModels}
+ disabled={agyModelsLoading}
+ className="text-xs text-port-accent hover:underline disabled:opacity-50"
+ >
+ {agyModelsLoading ? 'Loading…' : 'Refresh models'}
+ </button>
+ </div>
+ <input
+ id={agyModelId}
+ list={agyModelsListId}
+ type="text"
+ value={agyModel}
+ onChange={(e) => setAgyModel(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="Select an installed model or enter a custom id"
+ />
+ <datalist id={agyModelsListId}>
+ {agyModels.map((modelId) => <option key={modelId} value={modelId} />)}
+ </datalist>
+ {agyModelsError && <p className="text-xs text-port-warning mt-1">{agyModelsError}. You can still enter a custom model id.</p>}
+ {!agyModelsError && <p className="text-xs text-gray-500 mt-1">Choose an installed Agy model or enter a custom model id.</p>}
+ </div>
+ <CleanersToggles
+ cleanC2PA={cleanC2PAByMode.agy}
+ denoise={denoiseByMode.agy}
+ onCleanC2PAChange={setCleanC2PAFor(IMAGE_GEN_MODE.AGY)}
+ onDenoiseChange={setDenoiseFor(IMAGE_GEN_MODE.AGY)}
+ />
+ </div>
+ )}
+ </div>
+ )}
+
{/* HuggingFace token — used by local Flux models (FLUX.1-dev, FLUX.2-klein).
Independent of the mode picker because the token persists in settings
and applies whenever local image gen runs. */}
diff --git a/client/src/components/settings/ImageGenTab.test.jsx b/client/src/components/settings/ImageGenTab.test.jsx
index 52ff2df9f4..2e04435018 100644
--- a/client/src/components/settings/ImageGenTab.test.jsx
+++ b/client/src/components/settings/ImageGenTab.test.jsx
@@ -12,6 +12,7 @@ vi.mock('../../services/api', () => ({
getToolsList: vi.fn(),
saveHfToken: vi.fn(),
clearHfToken: vi.fn(),
+ listAgyImageModels: vi.fn(),
}));
vi.mock('../../hooks/useHfTokenStatus', () => ({
useHfTokenStatus: vi.fn(),
@@ -31,7 +32,7 @@ vi.mock('../../hooks/useMediaJobSse', () => ({
}));
import {
- getSettings, getToolsList, updateSettings,
+ getSettings, getToolsList, updateSettings, listAgyImageModels,
} from '../../services/api';
import { useHfTokenStatus } from '../../hooks/useHfTokenStatus';
import { ImageGenTab } from './ImageGenTab';
@@ -60,13 +61,14 @@ beforeEach(() => {
getToolsList.mockResolvedValue([]);
useHfTokenStatus.mockReturnValue({ present: false, source: 'none', refresh: vi.fn() });
updateSettings.mockResolvedValue({});
+ listAgyImageModels.mockResolvedValue({ models: ['gemini-image', 'custom/image-v2'], error: null });
});
describe('ImageGenTab grouped tabs', () => {
- it('renders a pills sub-nav with all eight media-settings groups', async () => {
+ it('renders a pills sub-nav with all media-settings groups', async () => {
await renderTab();
const tabs = screen.getAllByRole('tab').map((t) => t.textContent);
- for (const label of ['Backend', 'External', 'Local', 'Codex CLI', 'Grok CLI', 'Tokens', 'Expose', 'Test']) {
+ for (const label of ['Backend', 'External', 'Local', 'Codex CLI', 'Grok CLI', 'Agy CLI', 'Tokens', 'Expose', 'Test']) {
expect(tabs.some((t) => t.includes(label))).toBe(true);
}
});
@@ -147,10 +149,39 @@ describe('ImageGenTab grouped tabs', () => {
expect(patch.imageGen.mode).toBe('external');
expect(patch.imageGen).toHaveProperty('codex');
expect(patch.imageGen).toHaveProperty('grok');
+ expect(patch.imageGen).toHaveProperty('agy');
expect(patch.imageGen).toHaveProperty('expose');
});
});
+describe('ImageGenTab — Agy CLI section', () => {
+ it('loads installed models, allows a custom model id, and saves the Agy slice', async () => {
+ getSettings.mockResolvedValue({
+ imageGen: {
+ mode: 'agy',
+ agy: { enabled: true, agyPath: '/opt/agy', model: 'gemini-image' },
+ },
+ });
+ await renderTab(['/media/image?mediaTab=agy']);
+ await waitFor(() => expect(listAgyImageModels).toHaveBeenCalledWith({ silent: true }));
+ const modelInput = screen.getByLabelText('Image model');
+ expect(modelInput.value).toBe('gemini-image');
+ fireEvent.change(modelInput, { target: { value: 'custom/image-v3' } });
+ fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
+ await waitFor(() => expect(updateSettings).toHaveBeenCalled());
+ expect(updateSettings.mock.calls[0][0].imageGen.agy).toEqual(expect.objectContaining({
+ enabled: true,
+ agyPath: '/opt/agy',
+ model: 'custom/image-v3',
+ }));
+ });
+
+ it('states that Agy is text-to-image only', async () => {
+ await renderTab(['/media/image?mediaTab=agy']);
+ expect(screen.getByText(/Image editing is not supported/i)).toBeTruthy();
+ });
+});
+
describe('ImageGenTab — Grok CLI section (#2859)', () => {
it('shows the enable toggle and hides the config fields until enabled', async () => {
await renderTab();
diff --git a/client/src/lib/imageGenBackends.js b/client/src/lib/imageGenBackends.js
index f78688e370..bddd955e3d 100644
--- a/client/src/lib/imageGenBackends.js
+++ b/client/src/lib/imageGenBackends.js
@@ -1,6 +1,12 @@
import { Cpu, Terminal, Cloud, Sparkles } from 'lucide-react';
-export const IMAGE_GEN_MODE = Object.freeze({ LOCAL: 'local', CODEX: 'codex', GROK: 'grok', EXTERNAL: 'external' });
+export const IMAGE_GEN_MODE = Object.freeze({
+ LOCAL: 'local',
+ CODEX: 'codex',
+ GROK: 'grok',
+ AGY: 'agy',
+ EXTERNAL: 'external',
+});
// Shipped default Codex reasoning-effort level — the client mirror of the
// server's CODEX_IMAGEGEN_DEFAULT_EFFORT (server/services/imageGen/modes.js).
@@ -18,15 +24,20 @@ const META = {
[IMAGE_GEN_MODE.LOCAL]: { label: 'Local', icon: Cpu },
[IMAGE_GEN_MODE.CODEX]: { label: 'Codex', icon: Terminal },
[IMAGE_GEN_MODE.GROK]: { label: 'Grok', icon: Sparkles },
+ [IMAGE_GEN_MODE.AGY]: { label: 'Agy', icon: Sparkles },
[IMAGE_GEN_MODE.EXTERNAL]: { label: 'External', icon: Cloud },
};
// Client mirror of the server's CLOUD_IMAGE_GEN_MODES (imageGen/modes.js) —
-// cloud-CLI backends (codex, grok) that pick model/steps/seed internally,
+// cloud-CLI backends that pick model/steps/seed internally,
// run through the media queue's parallel cloud lane, and need a prompt for
// text-to-image. Use `isCloudCliMode` instead of hand-rolled
// `mode === CODEX || mode === GROK` disjunctions.
-export const CLOUD_IMAGE_GEN_MODES = Object.freeze([IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]);
+export const CLOUD_IMAGE_GEN_MODES = Object.freeze([
+ IMAGE_GEN_MODE.CODEX,
+ IMAGE_GEN_MODE.GROK,
+ IMAGE_GEN_MODE.AGY,
+]);
export const isCloudCliMode = (mode) => CLOUD_IMAGE_GEN_MODES.includes(mode);
// Backends that support image-to-image (init image / reference editing). The
@@ -55,6 +66,8 @@ export function deriveAvailableBackends(settings, { excludeExternal = false } =
out.push({ id: IMAGE_GEN_MODE.CODEX, ...META[IMAGE_GEN_MODE.CODEX] });
if (ig.grok?.enabled === true)
out.push({ id: IMAGE_GEN_MODE.GROK, ...META[IMAGE_GEN_MODE.GROK] });
+ if (ig.agy?.enabled === true)
+ out.push({ id: IMAGE_GEN_MODE.AGY, ...META[IMAGE_GEN_MODE.AGY] });
if (!excludeExternal && (ig.external?.sdapiUrl || ig.sdapiUrl || '').trim())
out.push({ id: IMAGE_GEN_MODE.EXTERNAL, ...META[IMAGE_GEN_MODE.EXTERNAL] });
return out;
diff --git a/client/src/lib/imageGenBackends.test.js b/client/src/lib/imageGenBackends.test.js
index 4631b4b9c8..d1ca2969b1 100644
--- a/client/src/lib/imageGenBackends.test.js
+++ b/client/src/lib/imageGenBackends.test.js
@@ -8,11 +8,12 @@ import {
} from './imageGenBackends';
describe('I2I_CAPABLE_MODES / isI2iCapableMode', () => {
- it('treats local, codex, and grok as i2i-capable, external as not', () => {
+ it('treats local, codex, and grok as i2i-capable, but not Agy or external', () => {
expect(I2I_CAPABLE_MODES).toEqual([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]);
expect(isI2iCapableMode(IMAGE_GEN_MODE.LOCAL)).toBe(true);
expect(isI2iCapableMode(IMAGE_GEN_MODE.CODEX)).toBe(true);
expect(isI2iCapableMode(IMAGE_GEN_MODE.GROK)).toBe(true);
+ expect(isI2iCapableMode(IMAGE_GEN_MODE.AGY)).toBe(false);
expect(isI2iCapableMode(IMAGE_GEN_MODE.EXTERNAL)).toBe(false);
expect(isI2iCapableMode(undefined)).toBe(false);
});
@@ -42,13 +43,14 @@ describe('deriveAvailableBackends', () => {
imageGen: {
local: { pythonPath: '/usr/bin/python3' },
codex: { enabled: true },
+ agy: { enabled: true },
external: { sdapiUrl: 'http://localhost:7860' },
},
};
expect(deriveAvailableBackends(settings).map((b) => b.id))
- .toEqual([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.EXTERNAL]);
+ .toEqual([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.AGY, IMAGE_GEN_MODE.EXTERNAL]);
expect(deriveAvailableBackends(settings, { excludeExternal: true }).map((b) => b.id))
- .toEqual([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX]);
+ .toEqual([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.AGY]);
expect(deriveAvailableBackends(undefined)).toEqual([]);
});
});
diff --git a/client/src/lib/pipelineImageDefaults.js b/client/src/lib/pipelineImageDefaults.js
index a0ac914aab..3d051a5c3c 100644
--- a/client/src/lib/pipelineImageDefaults.js
+++ b/client/src/lib/pipelineImageDefaults.js
@@ -30,12 +30,13 @@ export function readPipelineImageSettings(settings) {
const stored = settings?.pipeline?.imageGen || {};
const codexEnabled = settings?.imageGen?.codex?.enabled === true;
const grokEnabled = settings?.imageGen?.grok?.enabled === true;
+ const agyEnabled = settings?.imageGen?.agy?.enabled === true;
// Prefer an enabled cloud backend (codex first, then grok — the same order
// as the server's visual-stage resolver) so a cloud-only install doesn't
// default pipeline renders to an unconfigured local diffusion.
const defaultMode = codexEnabled ? IMAGE_GEN_MODE.CODEX
: grokEnabled ? IMAGE_GEN_MODE.GROK
- : PIPELINE_IMAGE_DEFAULTS.mode;
+ : agyEnabled ? IMAGE_GEN_MODE.AGY : PIPELINE_IMAGE_DEFAULTS.mode;
return {
mode: stored.mode || defaultMode,
modelId: stored.modelId || PIPELINE_IMAGE_DEFAULTS.modelId,
diff --git a/client/src/lib/wrImageDefaults.js b/client/src/lib/wrImageDefaults.js
index 2a87479c11..84e0a81a6e 100644
--- a/client/src/lib/wrImageDefaults.js
+++ b/client/src/lib/wrImageDefaults.js
@@ -61,9 +61,10 @@ export function readWrImageSettings(settings, availableBackends = null) {
const stored = settings?.writersRoom?.imageGen || {};
const codexEnabled = settings?.imageGen?.codex?.enabled === true;
const grokEnabled = settings?.imageGen?.grok?.enabled === true;
+ const agyEnabled = settings?.imageGen?.agy?.enabled === true;
const defaultMode = codexEnabled ? IMAGE_GEN_MODE.CODEX
: grokEnabled ? IMAGE_GEN_MODE.GROK
- : WR_IMAGE_DEFAULTS.mode;
+ : agyEnabled ? IMAGE_GEN_MODE.AGY : WR_IMAGE_DEFAULTS.mode;
let mode = stored.mode || defaultMode;
if (Array.isArray(availableBackends) && availableBackends.length > 0
&& !availableBackends.some((b) => b.id === mode)) {
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 61a154f150..2c91874698 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -220,8 +220,10 @@ export default function ImageGen() {
// so the form doesn't flicker between defaults.
const effectiveMode = selectedMode || status?.mode || IMAGE_GEN_MODE.EXTERNAL;
const isLocalMode = effectiveMode === IMAGE_GEN_MODE.LOCAL;
- const isGrokMode = effectiveMode === IMAGE_GEN_MODE.GROK;
const isCloudMode = isCloudCliMode(effectiveMode);
+ const cloudModeLabel = effectiveMode === IMAGE_GEN_MODE.GROK
+ ? 'Grok'
+ : effectiveMode === IMAGE_GEN_MODE.AGY ? 'Agy' : 'Codex';
const isAsyncMode = isLocalMode || isCloudMode;
// Whether the active backend supports image-to-image (init image). Distinct
// concept from isAsyncMode (queued vs sync) even though they coincide today.
@@ -291,9 +293,10 @@ export default function ImageGen() {
local: resolveCleanersFromConfig(s?.imageGen?.local, IMAGE_GEN_MODE.LOCAL),
codex: resolveCleanersFromConfig(s?.imageGen?.codex, IMAGE_GEN_MODE.CODEX),
grok: resolveCleanersFromConfig(s?.imageGen?.grok, IMAGE_GEN_MODE.GROK),
+ agy: resolveCleanersFromConfig(s?.imageGen?.agy, IMAGE_GEN_MODE.AGY),
};
- const c2 = { external: perMode.external.cleanC2PA, local: perMode.local.cleanC2PA, codex: perMode.codex.cleanC2PA, grok: perMode.grok.cleanC2PA };
- const dn = { external: perMode.external.denoise, local: perMode.local.denoise, codex: perMode.codex.denoise, grok: perMode.grok.denoise };
+ const c2 = { external: perMode.external.cleanC2PA, local: perMode.local.cleanC2PA, codex: perMode.codex.cleanC2PA, grok: perMode.grok.cleanC2PA, agy: perMode.agy.cleanC2PA };
+ const dn = { external: perMode.external.denoise, local: perMode.local.denoise, codex: perMode.codex.denoise, grok: perMode.grok.denoise, agy: perMode.agy.denoise };
const saved = s?.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;
// If the user just disabled the currently-selected backend, fall
// through to the first viable one — a just-toggled provider should
@@ -713,7 +716,7 @@ export default function ImageGen() {
prompt: composed.prompt,
negativePrompt: composed.negativePrompt || undefined,
width: w, height: h,
- mode: isGrokMode ? IMAGE_GEN_MODE.GROK : IMAGE_GEN_MODE.CODEX,
+ mode: effectiveMode,
cleanC2PA, denoise,
} : {
prompt: composed.prompt,
@@ -1059,7 +1062,7 @@ export default function ImageGen() {
: '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 === IMAGE_GEN_MODE.LOCAL ? 'mflux/local' : status.mode === IMAGE_GEN_MODE.CODEX ? 'codex CLI' : status.mode === IMAGE_GEN_MODE.GROK ? 'grok CLI' : 'external SD API')}</>
+ <><span className="w-2 h-2 rounded-full bg-port-success" /> {status.model || (status.mode === IMAGE_GEN_MODE.LOCAL ? 'mflux/local' : status.mode === IMAGE_GEN_MODE.CODEX ? 'codex CLI' : status.mode === IMAGE_GEN_MODE.GROK ? 'grok CLI' : status.mode === IMAGE_GEN_MODE.AGY ? 'agy CLI' : 'external SD API')}</>
) : (
<>
<AlertTriangle className="w-3 h-3" />
@@ -1227,7 +1230,7 @@ export default function ImageGen() {
<button
type="submit"
disabled={notConnected || editImageMissing || cloudNeedsPrompt}
- title={editImageMissing ? 'This image-edit model needs a source image — upload one below first' : cloudNeedsPrompt ? `${isGrokMode ? 'Grok' : 'Codex'} text-to-image needs a prompt — add one, or attach a source image to edit` : undefined}
+ title={editImageMissing ? 'This image-edit model needs a source image — upload one below first' : cloudNeedsPrompt ? `${cloudModeLabel} text-to-image needs a prompt` : undefined}
className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg min-h-[40px]"
>
<Sparkles className="w-4 h-4" /> {generating ? 'Queue' : 'Generate'}
@@ -1237,7 +1240,7 @@ export default function ImageGen() {
<span className="text-xs text-port-warning">Upload a source image to use this edit model</span>
)}
{cloudNeedsPrompt && (
- <span className="text-xs text-port-warning">Codex needs a prompt, or attach a source image to edit</span>
+ <span className="text-xs text-port-warning">{cloudModeLabel} text-to-image needs a prompt</span>
)}
{isAsyncMode && (
<label className="flex items-center gap-1.5 text-xs text-gray-400" title="Batch size: number of renders to queue per submit">
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 200010c15f..cd0cde89c6 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -4,6 +4,7 @@ import { request, API_BASE, maybeRedirectToLogin } from './apiCore.js';
// generateImage / getImageGenStatus / generateAvatar live in apiSystem.js for
// backward compatibility with existing call sites.
export const listImageModels = (options) => request('/image-gen/models', options);
+export const listAgyImageModels = (options) => request('/image-gen/agy/models', options);
// Per-model download status: `[{ id, repo, cached, sizeBytes }]`. Drives the
// inline Available/Download badge on the image gen form.
export const getImageModelStatuses = () => request('/image-gen/models/status', { silent: true });
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 0fdc592059..948193d485 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -926,6 +926,21 @@ export const imageGenGrokSettingsSchema = z.object({
denoise: z.boolean().optional(),
});
+const agyImageModelSchema = z.preprocess(
+ (v) => (v === '' ? undefined : v),
+ z.string().trim().max(200)
+ .regex(/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/, 'model must be a valid Agy model id')
+ .optional(),
+);
+
+export const imageGenAgySettingsSchema = z.object({
+ enabled: z.boolean().optional(),
+ agyPath: z.preprocess((v) => (v === '' ? undefined : v), z.string().trim().max(500).optional()),
+ model: agyImageModelSchema,
+ cleanC2PA: z.boolean().optional(),
+ denoise: z.boolean().optional(),
+});
+
// Provider-agnostic embeddings settings. `provider: 'none'` is the default and
// makes embedText() a no-op — rows persist without an embedding and a future
// admin "Re-embed missing" action backfills. Model is optional so the user can
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 423e3c900d..d138b94fc5 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -43,6 +43,7 @@ import { findOrCreateUniverseCollection } from '../services/mediaCollections.js'
import * as characterService from '../services/character.js';
import { randomUUID } from 'crypto';
import { buildUniverseRunTag } from '../services/universeRunTag.js';
+import { getSettings } from '../services/settings.js';
const router = Router();
@@ -295,6 +296,13 @@ router.get('/active', asyncHandler(async (_req, res) => {
res.json({ activeJob: await imageGen.getActiveJob() });
}));
+router.get('/agy/models', asyncHandler(async (_req, res) => {
+ const settings = await getSettings();
+ res.json(await imageGen.agy.listModels({
+ agyPath: settings.imageGen?.agy?.agyPath,
+ }));
+}));
+
// SynthID-defeat regen availability (issue #912). Drives whether the lightbox
// shows the "Regenerate" action — it's hardware-gated on a local FLUX runner.
// Optional `?filename=` (issue #2036): when the caller names a source image, its
@@ -394,6 +402,12 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
// gated behind an explicit toggle each (not every Codex account has access
// to the image_gen tool, and grok spends the user's Grok quota).
if (!cloud.enabled) throw cloud.disabledError;
+ if (mode === IMAGE_GEN_MODE.AGY && (params.initImagePath || params.referenceImagePaths?.length)) {
+ throw new ServerError('Agy Imagegen supports text-to-image only', {
+ status: 400,
+ code: 'AGY_IMAGE_EDIT_UNSUPPORTED',
+ });
+ }
// `mode` inside jobParams is the queue's discriminator — laneForJob()
// routes cloud jobs to the parallel cloud lane, and runJob's image branch
// dispatches to the matching imageGen provider module when it sees it.
diff --git a/server/routes/settings.js b/server/routes/settings.js
index b94f2422fc..5c3d2dbb0e 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -10,7 +10,7 @@ import {
} from '../services/mediaJobQueue/index.js';
import { asyncHandler } from '../lib/errorHandler.js';
import { isPlainObject } from '../lib/objects.js';
-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, validateRequest } from '../lib/validation.js';
+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, validateRequest } from '../lib/validation.js';
const router = Router();
@@ -216,6 +216,9 @@ router.put('/', asyncHandler(async (req, res) => {
if (req.body?.imageGen?.grok !== undefined) {
validateRequest(imageGenGrokSettingsSchema.partial(), req.body.imageGen.grok);
}
+ if (req.body?.imageGen?.agy !== undefined) {
+ validateRequest(imageGenAgySettingsSchema.partial(), req.body.imageGen.agy);
+ }
// Install-level Layered Intelligence settings (#2515) — validate the slice when
// present so a malformed `trustShellSources` can't persist and silently unlock
// full-shell custom `cmd` sources install-wide.
diff --git a/server/routes/settings.test.js b/server/routes/settings.test.js
index 35095d9b6a..16b1f86ba0 100644
--- a/server/routes/settings.test.js
+++ b/server/routes/settings.test.js
@@ -125,3 +125,35 @@ describe('Settings routes — imageGen.grok slice (#2859)', () => {
expect(res.status).toBe(200);
});
});
+
+describe('Settings routes — imageGen.agy slice', () => {
+ beforeEach(() => {
+ store = {};
+ vi.clearAllMocks();
+ });
+
+ it('accepts a valid Agy slice and persists the selected model', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ imageGen: { agy: { enabled: true, agyPath: '/usr/local/bin/agy', model: 'gemini/image-v2' } } });
+ expect(res.status).toBe(200);
+ expect(res.body.imageGen.agy).toEqual(expect.objectContaining({
+ enabled: true,
+ model: 'gemini/image-v2',
+ }));
+ });
+
+ it('accepts empty-string UI sentinels for path and model', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ imageGen: { agy: { enabled: false, agyPath: '', model: '' } } });
+ expect(res.status).toBe(200);
+ });
+
+ it('rejects a model id containing shell syntax', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ imageGen: { agy: { model: 'gemini; rm -rf /' } } });
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/server/services/creative/tools/media.js b/server/services/creative/tools/media.js
index 33070f80de..a4b4946380 100644
--- a/server/services/creative/tools/media.js
+++ b/server/services/creative/tools/media.js
@@ -8,7 +8,7 @@ import { z } from 'zod';
import { enqueueJob } from '../../mediaJobQueue/index.js';
import { ASPECT_PRESETS, QUALITY_PRESETS, presetToRenderParams } from '../../../lib/creativeDirectorPresets.js';
import { getSettings } from '../../settings.js';
-import { IMAGE_GEN_MODE, resolveQueueImageMode } from '../../imageGen/modes.js';
+import { IMAGE_GEN_MODE, resolveQueueImageMode, resolveQueueImageEditMode } from '../../imageGen/modes.js';
import { resolveCloudProviderConfig } from '../../imageGen/cloudProviderConfig.js';
import { VIDEO_GEN_MODE, VIDEO_GEN_MODES, resolveVideoMode } from '../../videoGen/modes.js';
import { nearestGrokDuration } from '../../../lib/grokVideoClip.js';
@@ -172,7 +172,10 @@ async function enforceRenderBackendPin(kind, params, project) {
};
}
- const mode = resolveQueueImageMode(pin.mode, settings);
+ const wantsEdit = !!params?.initImagePath || params?.referenceImagePaths?.length > 0;
+ const mode = wantsEdit
+ ? resolveQueueImageEditMode(pin.mode, settings)
+ : resolveQueueImageMode(pin.mode, settings);
const cloud = resolveCloudProviderConfig(settings, mode);
if (cloud) return { ...params, ...cloud.jobParams };
return {
diff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.js
new file mode 100644
index 0000000000..34d04520d8
--- /dev/null
+++ b/server/services/imageGen/agy.js
@@ -0,0 +1,360 @@
+/**
+ * Image Gen — Antigravity (`agy`) CLI provider.
+ *
+ * Agy is an opt-in, text-to-image-only cloud CLI backend. Each request runs
+ * in a throwaway scratch directory and directs the built-in `generate_image`
+ * tool to one PortOS-owned staging path. Only signature-verified image bytes
+ * are moved into the gallery.
+ */
+
+import { spawn } from 'child_process';
+import { copyFile, mkdir, open, rename, rm, stat, unlink } from 'fs/promises';
+import { randomUUID } from 'crypto';
+import { isAbsolute, join, resolve as pathResolve, sep } from 'path';
+import { tmpdir } from 'os';
+import sharp from 'sharp';
+import {
+ ensureAntigravityPrintArgs,
+ prepareAntigravityPrompt,
+} from '../../lib/antigravity.js';
+import { bufferedSpawn, killProcessTree, prepareCliSpawn } from '../../lib/bufferedSpawn.js';
+import { atomicWrite, detectImageFormat, ensureDir, PATHS } from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
+import { killWithEscalation } from '../../lib/killWithEscalation.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { imageGenEvents } from '../imageGenEvents.js';
+import { buildNoImageReason } from './noImageReason.js';
+import { IMAGE_GEN_MODE } from './modes.js';
+
+const AGY_TIMEOUT_MS = (() => {
+ const n = Number(process.env.AGY_IMAGEGEN_TIMEOUT_MS);
+ return Number.isFinite(n) && n > 0 ? n : 20 * 60 * 1000;
+})();
+const DEFAULT_BIN = 'agy';
+const DEFAULT_HARVEST_TIMEOUT_MS = 5000;
+const MODEL_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
+let harvestTimeoutMs = DEFAULT_HARVEST_TIMEOUT_MS;
+
+const jobs = new Map();
+const activeProcs = new Map();
+const activeJobs = new Map();
+
+export const getActiveJob = () => {
+ const entries = [...activeJobs.values()];
+ return entries.length ? entries[entries.length - 1] : null;
+};
+
+export const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);
+
+const terminate = (jobId, proc) => {
+ if (process.platform === 'win32') {
+ killProcessTree(proc);
+ return;
+ }
+ killWithEscalation(proc, {
+ label: 'agy child',
+ delayMs: 5000,
+ stillRunning: () => activeProcs.get(jobId) === proc,
+ });
+};
+
+export const cancel = (jobId) => {
+ if (!jobId) throw new Error('agy.cancel requires a jobId — use agy.cancelAll() to terminate every in-flight render');
+ const proc = activeProcs.get(jobId);
+ if (!proc) return false;
+ terminate(jobId, proc);
+ return true;
+};
+
+export const cancelAll = () => {
+ const entries = [...activeProcs.entries()];
+ if (!entries.length) return false;
+ for (const [jobId, proc] of entries) terminate(jobId, proc);
+ return true;
+};
+
+export async function checkConnection({ agyPath } = {}) {
+ const bin = agyPath || DEFAULT_BIN;
+ const prepared = prepareCliSpawn(bin, ['--version']);
+ const result = await bufferedSpawn(prepared.command, prepared.args, { timeoutMs: 15_000, shell: false });
+ if (result.error) {
+ return { connected: false, mode: IMAGE_GEN_MODE.AGY, reason: `Agy CLI not found (${result.error})` };
+ }
+ if (result.timedOut) {
+ return { connected: false, mode: IMAGE_GEN_MODE.AGY, reason: 'agy --version timed out' };
+ }
+ if (result.code !== 0) {
+ return { connected: false, mode: IMAGE_GEN_MODE.AGY, reason: `agy --version exited ${result.code}` };
+ }
+ const versionMatch = `${result.stdout}${result.stderr}`.match(/(\d+\.\d+\.\d+)/);
+ return { connected: true, mode: IMAGE_GEN_MODE.AGY, model: versionMatch ? `agy ${versionMatch[1]}` : 'agy' };
+}
+
+// `agy models` waits for stdin EOF before printing its catalog, so this probe
+// intentionally owns the child instead of using bufferedSpawn.
+export function listModels({ agyPath } = {}) {
+ const bin = agyPath || DEFAULT_BIN;
+ const { command, args } = prepareCliSpawn(bin, ['models']);
+ return new Promise((resolve) => {
+ const proc = spawn(command, args, { shell: false, stdio: ['pipe', 'pipe', 'pipe'] });
+ let stdout = '';
+ let stderr = '';
+ let settled = false;
+ const finish = (result) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve(result);
+ };
+ const timer = setTimeout(() => {
+ killProcessTree(proc);
+ finish({ models: [], error: 'agy models timed out' });
+ }, 15_000);
+ proc.stdin.on('error', () => {});
+ proc.stdin.end();
+ proc.stdout.on('data', (chunk) => { stdout += chunk.toString(); });
+ proc.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
+ proc.on('error', (err) => finish({ models: [], error: `Failed to run ${bin}: ${err.message}` }));
+ proc.on('close', (code) => {
+ if (code !== 0) {
+ finish({ models: [], error: stderr.trim() || `agy models exited ${code}` });
+ return;
+ }
+ const models = [...new Set(stdout.split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter((line) => MODEL_ID_RE.test(line)))];
+ finish(models.length ? { models, error: null } : { models: [], error: 'agy models returned no model ids' });
+ });
+ });
+}
+
+const AGY_NO_IMAGE_HINT =
+ 'Agy returned no image — the selected model may not expose generate_image, or the model declined. Check Settings → Image Gen → Agy CLI.';
+
+export const noImageReason = (stdoutTail = '') => buildNoImageReason(stdoutTail, {
+ hint: AGY_NO_IMAGE_HINT,
+ describe: (said) => `Agy did not produce an image at the directed path. Agy said: "${said}"`,
+});
+
+export function buildAgyPrompt({ prompt, negativePrompt, width, height, stagingPath }) {
+ const avoid = negativePrompt?.trim() ? `\nAvoid: ${negativePrompt.trim()}` : '';
+ const dimensions = Number(width) > 0 && Number(height) > 0
+ ? `\nTarget dimensions/aspect: ${Number(width)}×${Number(height)} pixels.`
+ : '';
+ return `Use your built-in generate_image tool to generate exactly one image.
+Image prompt: ${prompt.trim()}${avoid}${dimensions}
+Save the generated image as a PNG file at exactly this path: ${stagingPath}
+Do not create any other files, do not modify any code or workspace content, and do not run unrelated tools. When the file is written, you are done.`;
+}
+
+export async function generateImage({
+ agyPath,
+ model,
+ prompt = '',
+ width,
+ height,
+ negativePrompt,
+ initImagePath,
+ referenceImagePaths,
+ jobId: providedJobId = null,
+ cleanC2PA = false,
+ denoise = false,
+}) {
+ if (initImagePath || referenceImagePaths?.length) {
+ throw new ServerError('Agy Imagegen supports text-to-image only', {
+ status: 400,
+ code: 'AGY_IMAGE_EDIT_UNSUPPORTED',
+ });
+ }
+ if (!prompt.trim()) {
+ throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (model && !MODEL_ID_RE.test(model)) {
+ throw new ServerError('Invalid Agy model id', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+
+ await ensureDir(PATHS.images);
+ const jobId = providedJobId || randomUUID();
+ const filename = `${jobId}.png`;
+ const outputPath = join(PATHS.images, filename);
+ const scratchDir = join(tmpdir(), `portos-agy-${jobId}`);
+ const stagingPath = join(scratchDir, 'output.png');
+ await mkdir(scratchDir, { recursive: true });
+
+ const fullPrompt = buildAgyPrompt({ prompt, negativePrompt, width, height, stagingPath });
+ const baseArgs = ensureAntigravityPrintArgs([], { model });
+ const { args } = prepareAntigravityPrompt(baseArgs, fullPrompt);
+ const bin = agyPath || DEFAULT_BIN;
+ const meta = {
+ id: jobId,
+ prompt: prompt.trim(),
+ negativePrompt: negativePrompt || '',
+ width: width ? Number(width) : null,
+ height: height ? Number(height) : null,
+ filename,
+ mode: IMAGE_GEN_MODE.AGY,
+ model: model || null,
+ createdAt: new Date().toISOString(),
+ };
+ const job = { ...meta, clients: [], status: 'running' };
+ jobs.set(jobId, job);
+ activeJobs.set(jobId, {
+ ...meta,
+ generationId: jobId,
+ totalSteps: 1,
+ step: 0,
+ progress: 0,
+ currentImage: null,
+ });
+ console.log(`🎨 Generating image [${jobId.slice(0, 8)}] agy: ${prompt.slice(0, 60)}…`);
+ imageGenEvents.emit('started', { generationId: jobId, totalSteps: 1 });
+ broadcastSse(job, { type: 'status', message: 'Spawning agy…' });
+
+ runAgy(job, jobId, bin, args, {
+ scratchDir,
+ stagingPath,
+ outputPath,
+ filename,
+ meta,
+ cleanC2PA,
+ denoise,
+ }).catch((err) => {
+ console.log(`❌ agy run failed [${jobId.slice(0, 8)}]: ${err?.message}`);
+ });
+
+ return {
+ jobId,
+ filename,
+ path: `/data/images/${filename}`,
+ generationId: jobId,
+ mode: IMAGE_GEN_MODE.AGY,
+ model: model || null,
+ status: 'running',
+ };
+}
+
+async function runAgy(job, jobId, bin, args, {
+ scratchDir,
+ stagingPath,
+ outputPath,
+ filename,
+ meta,
+ cleanC2PA,
+ denoise,
+}) {
+ const resolvedBin = (!isAbsolute(bin) && (bin.includes('/') || bin.includes(sep))) ? pathResolve(bin) : bin;
+ const { command, args: spawnArgs } = prepareCliSpawn(resolvedBin, args);
+ const proc = spawn(command, spawnArgs, { cwd: scratchDir, shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
+ activeProcs.set(jobId, proc);
+ const removeScratch = () => rm(scratchDir, { recursive: true, force: true }).catch(() => {});
+ let stdoutTail = '';
+ let stderrTail = '';
+ const timeoutTimer = setTimeout(() => {
+ if (activeProcs.get(jobId) === proc) {
+ console.log(`⏱️ agy timed out after ${AGY_TIMEOUT_MS}ms [${jobId.slice(0, 8)}]`);
+ terminate(jobId, proc);
+ }
+ }, AGY_TIMEOUT_MS);
+
+ proc.stdout.on('data', (chunk) => {
+ stdoutTail = `${stdoutTail}${chunk}`.slice(-8192);
+ broadcastSse(job, { type: 'status', message: 'Running…' });
+ });
+ proc.stderr.on('data', (chunk) => {
+ stderrTail = `${stderrTail}${chunk}`.slice(-32768);
+ });
+ proc.on('error', (err) => {
+ clearTimeout(timeoutTimer);
+ removeScratch();
+ finalizeError(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);
+ });
+ proc.on('close', async (code, signal) => {
+ clearTimeout(timeoutTimer);
+ try {
+ if (code !== 0) {
+ removeScratch();
+ const reason = signal ? `Killed by signal ${signal}` : `Exit code ${code}`;
+ return finalizeError(job, jobId, proc, `Agy generation failed: ${reason}\n${stderrTail.trim().split('\n').slice(-6).join('\n')}`);
+ }
+ const harvested = await harvestStagedImage(stagingPath, harvestTimeoutMs);
+ if (!harvested.found) {
+ removeScratch();
+ const prefix = harvested.invalid ? 'Agy wrote a non-image file at the directed path. ' : '';
+ return finalizeError(job, jobId, proc, `${prefix}${noImageReason(stdoutTail)}`);
+ }
+ if (harvested.format === 'png') {
+ await rename(stagingPath, outputPath).catch(async () => {
+ await copyFile(stagingPath, outputPath);
+ await unlink(stagingPath).catch(() => {});
+ });
+ } else {
+ await sharp(stagingPath).png().toFile(outputPath);
+ }
+ removeScratch();
+ const sidecar = join(PATHS.images, `${jobId}.metadata.json`);
+ await atomicWrite(sidecar, meta).catch(() => {});
+ await autoCleanGeneratedImage({
+ cleanC2PA,
+ denoise,
+ pngPath: outputPath,
+ sidecarPath: sidecar,
+ mode: IMAGE_GEN_MODE.AGY,
+ });
+ job.status = 'complete';
+ if (activeProcs.get(jobId) === proc) activeProcs.delete(jobId);
+ activeJobs.delete(jobId);
+ console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (agy)`);
+ const result = { filename, path: `/data/images/${filename}` };
+ broadcastSse(job, { type: 'complete', result });
+ imageGenEvents.emit('completed', { generationId: jobId, path: result.path, filename });
+ closeJobAfterDelay(jobs, jobId);
+ } catch (err) {
+ removeScratch();
+ finalizeError(job, jobId, proc, `Agy post-exit handler failed: ${err?.message || err}`);
+ }
+ });
+}
+
+const finalizeError = (job, jobId, proc, reason) => {
+ if (job.status === 'error' || job.status === 'complete') return;
+ if (proc == null || activeProcs.get(jobId) === proc) activeProcs.delete(jobId);
+ job.status = 'error';
+ activeJobs.delete(jobId);
+ console.log(`❌ agy 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);
+};
+
+async function harvestStagedImage(stagingPath, timeoutMs) {
+ const deadline = Date.now() + timeoutMs;
+ let sawInvalid = false;
+ while (Date.now() < deadline) {
+ const fileStat = await stat(stagingPath).catch(() => null);
+ if (fileStat?.size > 0) {
+ const head = Buffer.alloc(16);
+ const handle = await open(stagingPath, 'r').catch(() => null);
+ if (handle) {
+ const { bytesRead } = await handle.read(head, 0, 16, 0).catch(() => ({ bytesRead: 0 }));
+ await handle.close().catch(() => {});
+ const detected = detectImageFormat(head.subarray(0, bytesRead));
+ if (detected) return { found: true, invalid: false, format: detected.format };
+ sawInvalid = true;
+ }
+ }
+ const remainingMs = Math.max(1, deadline - Date.now());
+ await new Promise((resolve) => setTimeout(resolve, Math.min(250, remainingMs)));
+ }
+ return { found: false, invalid: sawInvalid };
+}
+
+export const _internals = {
+ harvestStagedImage,
+ buildAgyPrompt,
+ setHarvestTimeoutForTests: (timeoutMs = DEFAULT_HARVEST_TIMEOUT_MS) => {
+ harvestTimeoutMs = Number.isFinite(timeoutMs) && timeoutMs > 0
+ ? timeoutMs
+ : DEFAULT_HARVEST_TIMEOUT_MS;
+ },
+};
diff --git a/server/services/imageGen/agy.test.js b/server/services/imageGen/agy.test.js
new file mode 100644
index 0000000000..1730946651
--- /dev/null
+++ b/server/services/imageGen/agy.test.js
@@ -0,0 +1,157 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { mkdir, readFile, rm, writeFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { EventEmitter } from 'events';
+
+const spawnCalls = [];
+const makeFakeChild = () => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.stdin = new EventEmitter();
+ child.stdin.end = vi.fn();
+ child.kill = vi.fn();
+ child.exitCode = null;
+ child.signalCode = null;
+ return 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;
+ }),
+ };
+});
+
+const TEST_ROOT = join(tmpdir(), `portos-agy-test-${process.pid}-${Date.now()}`);
+const FAKE_IMAGES_DIR = join(TEST_ROOT, 'data-images');
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ actual.PATHS.images = FAKE_IMAGES_DIR;
+ return {
+ ...actual,
+ ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),
+ };
+});
+
+const agy = await import('./agy.js');
+const { imageGenEvents } = await import('../imageGenEvents.js');
+const flush = () => new Promise((resolve) => setImmediate(resolve));
+const stagingPathFor = (jobId) => join(tmpdir(), `portos-agy-${jobId}`, 'output.png');
+
+const closeChild = async (index = 0, code = 1) => {
+ spawnCalls[index].child.exitCode = code;
+ spawnCalls[index].child.emit('close', code, null);
+ await flush();
+};
+
+beforeEach(async () => {
+ spawnCalls.length = 0;
+ imageGenEvents.removeAllListeners();
+ agy._internals.setHarvestTimeoutForTests(10);
+ await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});
+ await mkdir(TEST_ROOT, { recursive: true });
+});
+
+afterEach(async () => {
+ agy._internals.setHarvestTimeoutForTests();
+ await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});
+});
+
+describe('agy image provider', () => {
+ it('lists installed models after closing stdin', async () => {
+ const pending = agy.listModels({ agyPath: '/opt/agy' });
+ expect(spawnCalls[0].bin).toBe('/opt/agy');
+ expect(spawnCalls[0].args).toEqual(['models']);
+ expect(spawnCalls[0].child.stdin.end).toHaveBeenCalledTimes(1);
+ spawnCalls[0].child.stdout.emit('data', 'gemini-image\ncustom/image-v2\n');
+ spawnCalls[0].child.emit('close', 0, null);
+ await expect(pending).resolves.toEqual({
+ models: ['gemini-image', 'custom/image-v2'],
+ error: null,
+ });
+ });
+
+ it('spawns headlessly with the selected model and a directed one-image prompt', async () => {
+ const job = await agy.generateImage({
+ prompt: 'a fox beneath the stars',
+ negativePrompt: 'watermark',
+ model: 'gemini-3-pro-image',
+ });
+
+ expect(job.mode).toBe('agy');
+ expect(job.model).toBe('gemini-3-pro-image');
+ expect(spawnCalls).toHaveLength(1);
+ const { bin, args } = spawnCalls[0];
+ expect(bin).toBe('agy');
+ expect(args).toContain('--dangerously-skip-permissions');
+ expect(args).toEqual(expect.arrayContaining(['--model', 'gemini-3-pro-image', '--print']));
+ const prompt = args[args.indexOf('--print') + 1];
+ expect(prompt).toContain('generate_image');
+ expect(prompt).toContain('exactly one image');
+ expect(prompt).toContain('a fox beneath the stars');
+ expect(prompt).toContain('Avoid: watermark');
+ expect(prompt).toContain(stagingPathFor(job.jobId));
+ expect(prompt).toContain('do not modify any code or workspace content');
+ await closeChild();
+ });
+
+ it('rejects image-edit inputs before spawning', async () => {
+ await expect(agy.generateImage({
+ prompt: 'edit this',
+ initImagePath: 'source.png',
+ })).rejects.toMatchObject({ code: 'AGY_IMAGE_EDIT_UNSUPPORTED', status: 400 });
+ expect(spawnCalls).toHaveLength(0);
+ });
+
+ it('rejects invalid custom model ids', async () => {
+ await expect(agy.generateImage({
+ prompt: 'a fox',
+ model: 'model; rm -rf /',
+ })).rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
+ expect(spawnCalls).toHaveLength(0);
+ });
+
+ it('imports only a signature-verified directed PNG into the gallery', async () => {
+ const completed = vi.fn();
+ imageGenEvents.on('completed', completed);
+ const job = await agy.generateImage({ prompt: 'a fox' });
+ const png = Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ Buffer.from('fakepngbody'),
+ ]);
+ await writeFile(stagingPathFor(job.jobId), png);
+ await closeChild(0, 0);
+
+ const deadline = Date.now() + 3000;
+ while (Date.now() < deadline && completed.mock.calls.length === 0) {
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ expect(completed).toHaveBeenCalledTimes(1);
+ expect(existsSync(join(FAKE_IMAGES_DIR, job.filename))).toBe(true);
+ expect(await readFile(join(FAKE_IMAGES_DIR, job.filename))).toEqual(png);
+ expect(existsSync(join(FAKE_IMAGES_DIR, `${job.jobId}.metadata.json`))).toBe(true);
+ });
+
+ it('fails closed when the directed output is not an image', async () => {
+ const failed = vi.fn();
+ imageGenEvents.on('failed', failed);
+ const job = await agy.generateImage({ prompt: 'a fox' });
+ await writeFile(stagingPathFor(job.jobId), 'not an image');
+ await closeChild(0, 0);
+
+ const deadline = Date.now() + 3000;
+ while (Date.now() < deadline && failed.mock.calls.length === 0) {
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ expect(failed).toHaveBeenCalledTimes(1);
+ expect(existsSync(join(FAKE_IMAGES_DIR, job.filename))).toBe(false);
+ });
+});
diff --git a/server/services/imageGen/cloudProviderConfig.js b/server/services/imageGen/cloudProviderConfig.js
index 04e6054478..a0f1e66c82 100644
--- a/server/services/imageGen/cloudProviderConfig.js
+++ b/server/services/imageGen/cloudProviderConfig.js
@@ -17,6 +17,7 @@
*/
import { ServerError } from '../../lib/errorHandler.js';
+import { ANTIGRAVITY_CONFIGURED_DEFAULT } from '../../lib/antigravity.js';
import {
CLOUD_IMAGE_GEN_MODES,
CODEX_IMAGEGEN_DEFAULT_MODEL,
@@ -48,6 +49,12 @@ export const CLOUD_PROVIDER_SPECS = Object.freeze({
modelId: () => 'grok-imagegen',
params: (g) => ({ grokPath: g.grokPath, aspectRatio: g.aspectRatio }),
}),
+ [IMAGE_GEN_MODE.AGY]: Object.freeze({
+ label: 'Agy Imagegen',
+ errorCode: 'AGY_IMAGEGEN_DISABLED',
+ modelId: (a) => a.model || ANTIGRAVITY_CONFIGURED_DEFAULT,
+ params: (a) => ({ agyPath: a.agyPath, model: a.model || ANTIGRAVITY_CONFIGURED_DEFAULT }),
+ }),
});
/**
diff --git a/server/services/imageGen/cloudProviderConfig.test.js b/server/services/imageGen/cloudProviderConfig.test.js
index 55fc5ed343..b8cc4ad8c9 100644
--- a/server/services/imageGen/cloudProviderConfig.test.js
+++ b/server/services/imageGen/cloudProviderConfig.test.js
@@ -4,7 +4,13 @@ import {
pickUsableMode,
resolveCloudProviderConfig,
} from './cloudProviderConfig.js';
-import { CODEX_IMAGEGEN_DEFAULT_MODEL, IMAGE_GEN_MODE } from './modes.js';
+import {
+ CODEX_IMAGEGEN_DEFAULT_MODEL,
+ IMAGE_GEN_MODE,
+ resolveQueueImageEditMode,
+ resolveQueueImageMode,
+} from './modes.js';
+import { ANTIGRAVITY_CONFIGURED_DEFAULT } from '../../lib/antigravity.js';
const settingsWith = (imageGen) => ({ imageGen });
@@ -53,6 +59,26 @@ describe('resolveCloudProviderConfig', () => {
});
});
+ it('bundles Agy path and selected model, defaulting to its configured model sentinel', () => {
+ const selected = resolveCloudProviderConfig(
+ settingsWith({ agy: { enabled: true, agyPath: '/bin/agy', model: 'gemini-image' } }),
+ IMAGE_GEN_MODE.AGY,
+ );
+ expect(selected.modelId).toBe('gemini-image');
+ expect(selected.jobParams).toEqual({
+ mode: IMAGE_GEN_MODE.AGY,
+ agyPath: '/bin/agy',
+ model: 'gemini-image',
+ });
+
+ const fallback = resolveCloudProviderConfig(
+ settingsWith({ agy: { enabled: true } }),
+ IMAGE_GEN_MODE.AGY,
+ );
+ expect(fallback.modelId).toBe(ANTIGRAVITY_CONFIGURED_DEFAULT);
+ expect(fallback.providerParams.model).toBe(ANTIGRAVITY_CONFIGURED_DEFAULT);
+ });
+
it('produces a ready-to-throw ServerError + skip reason when disabled', () => {
const cloud = resolveCloudProviderConfig(settingsWith({ grok: { enabled: false } }), IMAGE_GEN_MODE.GROK);
expect(cloud.enabled).toBe(false);
@@ -78,9 +104,10 @@ describe('resolveCloudProviderConfig', () => {
describe('isModeUsable', () => {
it('gates cloud modes on their enable toggle', () => {
- const s = settingsWith({ codex: { enabled: true }, grok: { enabled: false } });
+ const s = settingsWith({ codex: { enabled: true }, grok: { enabled: false }, agy: { enabled: true } });
expect(isModeUsable(s, IMAGE_GEN_MODE.CODEX)).toBe(true);
expect(isModeUsable(s, IMAGE_GEN_MODE.GROK)).toBe(false);
+ expect(isModeUsable(s, IMAGE_GEN_MODE.AGY)).toBe(true);
});
it('always allows local and never allows the non-queueable external backend', () => {
@@ -126,3 +153,20 @@ describe('pickUsableMode', () => {
expect(pickUsableMode(s, [IMAGE_GEN_MODE.LOCAL])).toBe(IMAGE_GEN_MODE.LOCAL);
});
});
+
+describe('queue mode resolution with Agy', () => {
+ const settings = settingsWith({
+ mode: IMAGE_GEN_MODE.AGY,
+ codex: { enabled: true },
+ grok: { enabled: false },
+ agy: { enabled: true },
+ });
+
+ it('selects enabled Agy for text-to-image work', () => {
+ expect(resolveQueueImageMode(undefined, settings)).toBe(IMAGE_GEN_MODE.AGY);
+ });
+
+ it('excludes Agy from image-edit fallback', () => {
+ expect(resolveQueueImageEditMode(IMAGE_GEN_MODE.AGY, settings)).toBe(IMAGE_GEN_MODE.CODEX);
+ });
+});
diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.js
index 7be0e22956..ec1da30e36 100644
--- a/server/services/imageGen/index.js
+++ b/server/services/imageGen/index.js
@@ -14,16 +14,22 @@
import { getSettings } from '../settings.js';
import { resolveCleanersFromConfig } from '../../lib/imageClean.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';
import * as grok from './grok.js';
+import * as agy from './agy.js';
import { IMAGE_GEN_MODE, IMAGE_GEN_MODES, CLOUD_IMAGE_GEN_MODES } from './modes.js';
import { resolveCloudProviderConfig } from './cloudProviderConfig.js';
// Cloud-CLI provider modules keyed by mode, so the shared gate in
// checkConnection/generateImage dispatches without a per-provider branch.
-const CLOUD_PROVIDERS = { [IMAGE_GEN_MODE.CODEX]: codex, [IMAGE_GEN_MODE.GROK]: grok };
+const CLOUD_PROVIDERS = {
+ [IMAGE_GEN_MODE.CODEX]: codex,
+ [IMAGE_GEN_MODE.GROK]: grok,
+ [IMAGE_GEN_MODE.AGY]: agy,
+};
// Re-export the enum + array so the existing import surface from this module
// keeps working. `IMAGE_GEN_MODE.X` is the preferred form at dispatch sites
@@ -102,13 +108,19 @@ export async function generateImage(params) {
delete normalized.cleanC2PA;
delete normalized.denoise;
delete normalized.autoClean; // legacy body field — accept-and-ignore
- // Cloud CLIs (codex, grok) share one gate + param bundle — the per-provider
+ // Cloud CLIs share one gate + param bundle — the per-provider
// knobs (codexPath/model/effort vs grokPath/aspectRatio) come from the
// resolver's spec, so a saved override always wins over the provider's own
// internal defaults.
const cloud = resolveCloudProviderConfig(s, mode);
if (cloud) {
if (!cloud.enabled) throw cloud.disabledError;
+ if (mode === IMAGE_GEN_MODE.AGY && (normalized.initImagePath || normalized.referenceImagePaths?.length)) {
+ throw new ServerError('Agy Imagegen supports text-to-image only', {
+ status: 400,
+ code: 'AGY_IMAGE_EDIT_UNSUPPORTED',
+ });
+ }
return CLOUD_PROVIDERS[mode].generateImage({ ...cloud.providerParams, cleanC2PA, denoise, ...normalized });
}
if (mode === IMAGE_GEN_MODE.LOCAL) {
@@ -152,7 +164,7 @@ export async function generateAvatar({ name, characterClass, prompt }) {
// Callers wanting all of them can read individual providers via the
// re-exports below.
export async function getActiveJob() {
- const jobs = [local.getActiveJob(), external.getActiveJob(), codex.getActiveJob(), grok.getActiveJob()].filter(Boolean);
+ const jobs = [local.getActiveJob(), external.getActiveJob(), codex.getActiveJob(), grok.getActiveJob(), agy.getActiveJob()].filter(Boolean);
if (!jobs.length) return null;
return jobs.sort((a, b) => {
const ta = a.createdAt ? Date.parse(a.createdAt) : 0;
@@ -168,23 +180,25 @@ export const attachSseClient = (jobId, res) => {
if (local.attachSseClient(jobId, res)) return true;
if (codex.attachSseClient(jobId, res)) return true;
if (grok.attachSseClient(jobId, res)) return true;
+ if (agy.attachSseClient(jobId, res)) return true;
return false;
};
export const cancel = () => {
// The "stop everything" dispatcher — invoked by routes/imageGen.js's
// `/cancel` fallback when no specific jobId or queue entry is targeted.
- // local has at most one in-flight, codex/grok can have N (parallel cloud
+ // local has at most one in-flight, cloud CLIs can have N (parallel cloud
// lane), so their bulk variants are the right ones here. Return whether
// anything was actually cancelled — short-circuiting on the first hit
// would orphan a cloud job whenever local is also active.
const localCancelled = local.cancel();
const codexCancelled = codex.cancelAll();
const grokCancelled = grok.cancelAll();
- return localCancelled || codexCancelled || grokCancelled;
+ const agyCancelled = agy.cancelAll();
+ return localCancelled || codexCancelled || grokCancelled || agyCancelled;
};
// 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, grok };
+export { local, external, codex, grok, agy };
diff --git a/server/services/imageGen/modes.js b/server/services/imageGen/modes.js
index 3ec5873fdc..aba5d61f82 100644
--- a/server/services/imageGen/modes.js
+++ b/server/services/imageGen/modes.js
@@ -15,6 +15,7 @@ export const IMAGE_GEN_MODE = Object.freeze({
LOCAL: 'local',
CODEX: 'codex',
GROK: 'grok',
+ AGY: 'agy',
});
export const IMAGE_GEN_MODES = Object.freeze(Object.values(IMAGE_GEN_MODE));
@@ -24,7 +25,11 @@ export const IMAGE_GEN_MODES = Object.freeze(Object.values(IMAGE_GEN_MODE));
// The mediaJobQueue routes these through its parallel cloud lane (they don't
// serialize on the MLX runtime) and async callers treat them like local:
// generateImage returns a job descriptor before the file lands.
-export const CLOUD_IMAGE_GEN_MODES = Object.freeze([IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]);
+export const CLOUD_IMAGE_GEN_MODES = Object.freeze([
+ IMAGE_GEN_MODE.CODEX,
+ IMAGE_GEN_MODE.GROK,
+ IMAGE_GEN_MODE.AGY,
+]);
// Modes the mediaJobQueue can run (external SD-API stays synchronous — a
// remote HTTP call with no local single-flight constraint to absorb). Single
@@ -74,14 +79,33 @@ export const LOCAL_IMAGEGEN_DEFAULT_MODEL = 'dev';
export function resolveQueueImageMode(requested, settings) {
const codexEnabled = settings?.imageGen?.codex?.enabled === true;
const grokEnabled = settings?.imageGen?.grok?.enabled === true;
+ const agyEnabled = settings?.imageGen?.agy?.enabled === true;
if (requested === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;
if (requested === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;
+ if (requested === IMAGE_GEN_MODE.AGY && agyEnabled) return IMAGE_GEN_MODE.AGY;
if (requested === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;
const settingsMode = settings?.imageGen?.mode;
if (settingsMode === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;
if (settingsMode === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;
+ if (settingsMode === IMAGE_GEN_MODE.AGY && agyEnabled) return IMAGE_GEN_MODE.AGY;
if (settingsMode === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;
if (codexEnabled) return IMAGE_GEN_MODE.CODEX;
if (grokEnabled) return IMAGE_GEN_MODE.GROK;
+ if (agyEnabled) return IMAGE_GEN_MODE.AGY;
+ return IMAGE_GEN_MODE.LOCAL;
+}
+
+export function resolveQueueImageEditMode(requested, settings) {
+ const codexEnabled = settings?.imageGen?.codex?.enabled === true;
+ const grokEnabled = settings?.imageGen?.grok?.enabled === true;
+ if (requested === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;
+ if (requested === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;
+ if (requested === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;
+ const saved = settings?.imageGen?.mode;
+ if (saved === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;
+ if (saved === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;
+ if (saved === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;
+ if (codexEnabled) return IMAGE_GEN_MODE.CODEX;
+ if (grokEnabled) return IMAGE_GEN_MODE.GROK;
return IMAGE_GEN_MODE.LOCAL;
}
diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.js
index c23425545d..983d21a4b2 100644
--- a/server/services/imageGen/prepareParams.js
+++ b/server/services/imageGen/prepareParams.js
@@ -78,6 +78,13 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
// is cheap — it's already read again below for the per-mode dispatch.)
const settings = await getSettings();
const mode = data.mode || settings.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;
+ if (mode === IMAGE_GEN_MODE.AGY && (initUpload || data.initImageFile)) {
+ cleanupReqFilesTemp();
+ throw new ServerError('Agy Imagegen supports text-to-image only', {
+ status: 400,
+ code: 'AGY_IMAGE_EDIT_UNSUPPORTED',
+ });
+ }
// Resolve cleaners ONCE at the route layer so all three dispatch paths
// (synchronous external, codex queue, local queue) see the same values.
@@ -163,12 +170,13 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
}
// Empty prompt is allowed for i2i / local / external, but cloud-CLI
- // text-to-image (codex/grok, no init image) still needs one — reject
+ // text-to-image (no init image) still needs one — reject
// synchronously here so direct API callers get a 400 instead of a
// 200-then-async-job-failure. Mirrors the guards in codex.js/grok.js and
// the client's needs-prompt gate.
if (CLOUD_IMAGE_GEN_MODES.includes(mode) && !initImagePath && !data.prompt?.trim()) {
- throw new ServerError(`Prompt is required for ${mode === IMAGE_GEN_MODE.CODEX ? 'Codex' : 'Grok'} text-to-image`, { status: 400, code: 'VALIDATION_ERROR' });
+ const label = mode === IMAGE_GEN_MODE.CODEX ? 'Codex' : mode === IMAGE_GEN_MODE.GROK ? 'Grok' : 'Agy';
+ throw new ServerError(`Prompt is required for ${label} text-to-image`, { status: 400, code: 'VALIDATION_ERROR' });
}
if (data.guidance == null && data.cfgScale != null) {
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 88706be24c..d20a638204 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -47,12 +47,12 @@ import { audioGenEvents } from '../audioGen/events.js';
import { getSettings } from '../settings.js';
import { IMAGE_GEN_MODE, CLOUD_IMAGE_GEN_MODES } from '../imageGen/modes.js';
-// Cloud-CLI jobs (codex/grok images, grok videos) share one parallel lane —
+// Cloud-CLI jobs (Codex/Grok/Agy images, Grok videos) share one parallel lane —
// each render
// shells out to its own external child spending remote quota, so they don't
// serialize on the MLX runtime the way GPU jobs do. The lane's slot count is
// `codexParallelLimit` (settings key `imageGen.codex.parallelLimit`, kept
-// under the codex name for backward compat — it now bounds codex + grok
+// under the codex name for backward compat — it now bounds every cloud CLI
// renders combined).
const isCloudImageJob = (j) =>
(j.kind === 'image' && CLOUD_IMAGE_GEN_MODES.includes(j.params?.mode))
@@ -138,6 +138,7 @@ function getGenModuleForJob(job) {
if (job.kind === 'audio') return import('../audioGen/local.js');
if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.CODEX) return import('../imageGen/codex.js');
if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.GROK) return import('../imageGen/grok.js');
+ if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.AGY) return import('../imageGen/agy.js');
if (job.kind === 'image') return import('../imageGen/local.js');
return Promise.resolve(null);
}
@@ -522,14 +523,14 @@ export function removeArchivedJob(jobId) {
return true;
}
-// "Run now" bypass — start a queued cloud-CLI (codex/grok) job immediately
+// "Run now" bypass — start a queued cloud-CLI image job immediately
// even if the lane is at its limit. GPU jobs are rejected (single MLX runtime
// would OOM). The rejection code stays 'NOT_CODEX' for client back-compat.
export function runJobNow(jobId) {
const job = queue.find((j) => j.id === jobId);
if (!job) return { ok: false, code: 'NOT_FOUND', error: 'Job not found in queue' };
if (!isCloudImageJob(job)) {
- return { ok: false, code: 'NOT_CODEX', error: 'Only cloud-CLI (Codex/Grok) image jobs can be run-now; GPU jobs serialize on the MLX runtime' };
+ return { ok: false, code: 'NOT_CODEX', error: 'Only cloud-CLI image jobs can be run now; GPU jobs serialize on the MLX runtime' };
}
startLaneJob(job, { isCloud: true });
return { ok: true, status: 'running' };
diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.js
index d1d8fa746a..24340c4fe6 100644
--- a/server/services/sprites/reference.js
+++ b/server/services/sprites/reference.js
@@ -32,10 +32,11 @@ import { ServerError } from '../../lib/errorHandler.js';
import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
import { enqueueJob } from '../mediaJobQueue/index.js';
import {
- IMAGE_GEN_MODE, resolveQueueImageMode,
+ IMAGE_GEN_MODE, resolveQueueImageMode, resolveQueueImageEditMode,
CODEX_IMAGEGEN_DEFAULT_MODEL, LOCAL_IMAGEGEN_DEFAULT_MODEL,
} from '../imageGen/modes.js';
import { resolveImageCleaners } from '../imageGen/index.js';
+import { resolveCloudProviderConfig } from '../imageGen/cloudProviderConfig.js';
import { getSettings } from '../settings.js';
import { getRecord, updateRecord, listRecords, createCharacter } from './records.js';
import { spriteDir, resolveSpriteAssetPath, listSpriteAssets } from './paths.js';
@@ -385,7 +386,7 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {
// fork subsequent renders onto a different background than the frozen set.
const genKey = manifest.chromaKey || record.chromaKey || DEFAULT_CHROMA_KEY;
const settings = await getSettings();
- const mode = resolveQueueImageMode(body.mode, settings);
+ let mode = resolveQueueImageMode(body.mode, settings);
let prompt;
let initImagePath;
@@ -532,12 +533,21 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {
// pipeline i2i renders on that platform. Cloud modes are unaffected.
}
+ if (mode === IMAGE_GEN_MODE.AGY && initImagePath) {
+ mode = resolveQueueImageEditMode(undefined, settings);
+ }
const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);
const codexModel = body.model || settings.imageGen?.codex?.model || CODEX_IMAGEGEN_DEFAULT_MODEL;
// The model the provider will ACTUALLY run, for candidate provenance —
// grok picks its model internally, so its sidecars record null.
+ const cloud = resolveCloudProviderConfig(settings, mode);
+ const cloudJobParams = mode === IMAGE_GEN_MODE.CODEX
+ ? { ...cloud?.jobParams, model: codexModel, effort: body.effort || settings.imageGen?.codex?.effort }
+ : cloud?.jobParams;
const effectiveModel = mode === IMAGE_GEN_MODE.CODEX
? codexModel
+ : mode === IMAGE_GEN_MODE.AGY
+ ? cloud.modelId
: mode === IMAGE_GEN_MODE.LOCAL
? (body.model || settings.imageGen?.local?.modelId || LOCAL_IMAGEGEN_DEFAULT_MODEL)
: null;
@@ -558,10 +568,8 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {
...(designReferencePath ? { designReferencePath } : {}),
},
};
- const params = mode === IMAGE_GEN_MODE.CODEX
- ? { mode, codexPath: settings.imageGen?.codex?.codexPath, model: codexModel, effort: body.effort || settings.imageGen?.codex?.effort, ...baseParams }
- : mode === IMAGE_GEN_MODE.GROK
- ? { mode, grokPath: settings.imageGen?.grok?.grokPath, aspectRatio: settings.imageGen?.grok?.aspectRatio, ...baseParams }
+ const params = cloud
+ ? { ...cloudJobParams, ...baseParams }
// Thread the resolved model (request override → saved local model) —
// the queue dispatches straight to local.generateImage, which does NOT
// read settings and would otherwise fall back to its own default.
diff --git a/server/services/voice/tools/media.js b/server/services/voice/tools/media.js
index b93fb1f414..03fb362ce4 100644
--- a/server/services/voice/tools/media.js
+++ b/server/services/voice/tools/media.js
@@ -16,7 +16,7 @@ export const MEDIA_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, or "grok" for the Grok Build CLI built-in image_gen tool (both subject to the user enabling them in Settings). Returns the saved file path.',
+ 'Generate an image from a text prompt and save it to the user\'s gallery. Defaults to the user\'s saved Image Gen backend. Pass `provider` to override per-call: "local", "external", "codex", "grok", or text-to-image-only "agy". Cloud CLI providers must be enabled in Settings. Returns the saved file path.',
parameters: {
type: 'object',
properties: {
@@ -59,7 +59,9 @@ export const MEDIA_TOOLS = [
if (imageGen.CLOUD_IMAGE_GEN_MODES.includes(requestedMode)) {
const s = await getSettings();
if (!s?.imageGen?.[requestedMode]?.enabled) {
- const label = requestedMode === imageGen.IMAGE_GEN_MODE.CODEX ? 'Codex' : 'Grok';
+ const label = requestedMode === imageGen.IMAGE_GEN_MODE.CODEX
+ ? 'Codex'
+ : requestedMode === imageGen.IMAGE_GEN_MODE.GROK ? 'Grok' : 'Agy';
return { ok: false, summary: `${label} Imagegen is disabled — enable it in Settings → Image Gen first.` };
}
}