Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
feat(image): synchronize BYO models and generation validation
wytb2e5ceea027e
diff --git a/src/main/features/image_auth.ts b/src/main/features/image_auth.tsindex f1c69f2e..8d032e01 100644--- a/src/main/features/image_auth.ts+++ b/src/main/features/image_auth.ts@@ -177,6 +177,8 @@ export function flattenImageProviderOptions(model: model.id,label: provider.id === 'doubao'? `DouBao · ${model.name}`+ : provider.id === 'openai' ? `OpenAI · ${model.name}`+ : provider.id === 'google' ? `Google · ${model.name}`: `${provider.label} · ${model.name}`,}));});@@ -194,7 +196,8 @@ export async function testImageProfile(id: string): Promise<TestImageProfileResuconst cap = findImageGenCapability(target.provider);if (!cap) return { ok: false, durationMs: 0, error: `provider ${target.provider} has no image-gen capability` };const model = target.model || cap.model;- if (!isImageProviderModelAllowed(target.provider, model)) {+ if (!isImageProviderModelAllowed(target.provider, model)+ && !(target.provider === 'doubao' && model === 'doubao-seedream-5-0-lite-260128')) {return { ok: false, durationMs: 0, error: `unsupported image model "${target.provider}/${model}"` };}@@ -204,7 +207,7 @@ export async function testImageProfile(id: string): Promise<TestImageProfileResuapiKey: target.apiKey,model,prompt: 'a small red dot on white background',- size: '1024x1024',+ size: cap.api === 'doubao' || cap.api === 'orkas' ? '2k' : '1024x1024',};if (cap.api === 'openai') await callOpenAIImage(req);else if (cap.api === 'gemini') await callGeminiImage(req);diff --git a/src/main/features/image_gen.ts b/src/main/features/image_gen.tsindex 9e53694f..d9dd9bd8 100644--- a/src/main/features/image_gen.ts+++ b/src/main/features/image_gen.ts@@ -1,9 +1,12 @@+import { normaliseSeedreamSize, normaliseGeminiImageSize, isSingleImageSeedream, UnsupportedImageSizeError } from './image_size';+import { logErrorSummary, logPathRef } from '../util/log-redact';+import { sanitizeLogTextForUpload } from '../util/log-sanitize';/*** Image generation — provider-agnostic dispatch on top of the existing* auth-profiles store.*- * Two-step picker:- * 1. `pickImageGenProfile()` walks the user's priority-ordered entry list,+ * Ordered API-key candidates:+ * 1. `listOpenImageGenCandidates()` walks the user's priority-ordered entry list,* filters out OAuth (none of the OAuth surfaces we ship can reach image* APIs — see auth.ts::listApiKeyEntries note), and returns the first* entry whose provider is in `IMAGE_GEN_BY_PROVIDER`.@@ -58,7 +61,8 @@ export function listOpenImageGenCandidates(): PickedImageGenProfile[] {const capability = findImageGenCapability(profile.provider);if (!capability) continue;const model = profile.model || capability.model;- if (!isImageProviderModelAllowed(profile.provider, model)) continue;+ if (!isImageProviderModelAllowed(profile.provider, model)+ && !(profile.provider === 'doubao' && model === 'doubao-seedream-5-0-lite-260128')) continue;const selectedCapability = { ...capability, model };out.push({entry: {@@ -87,9 +91,7 @@ export function listOpenImageGenCandidates(): PickedImageGenProfile[] {* 1. The user's dedicated `imageProfiles` list (from the "Image* Generation API Key" card in settings). First entry whose* provider has a capability wins.- * Multiple entries on the same provider just shadow each other —- * first wins, no rotation (image gen calls are rare; rotation isn't- * worth the surprise factor).+ * Generation tries the usable dedicated rows in their saved order.* 2. Fallback: the chat `entries` list. If the user never set up a* dedicated image key but happens to have an OpenAI/Google chat key,* reuse it. Keeps existing setups working without forcing a re-config.@@ -113,7 +115,7 @@ export interface GenerateImageInput {referenceImageUrls?: string[];referenceBindings?: ImageReferenceBinding[];negativePrompt?: string[];- /** Provider-side size hint. Default `1024x1024`. */+ /** Provider size. Defaults: Seedream/Orkas 2k, Gemini auto, OpenAI 1024x1024. */size?: string;signal?: AbortSignal;onProgress?: ImageProgressReporter;@@ -140,111 +142,136 @@ export type GenerateImageResult =| 'IO_ERROR'| 'BAD_INPUT';message: string;+ /** False only when validation prevented every provider request. */+ dispatched?: false;};export async function generateImage(input: GenerateImageInput): Promise<GenerateImageResult> {- throwIfAborted(input.signal);+ try {+ throwIfAborted(input.signal);+ } catch (error) {+ return { ok: false, errorCode: 'BAD_INPUT', message: errorMessage(error), dispatched: false };+ }if (!input.prompt || !input.prompt.trim()) {- return { ok: false, errorCode: 'BAD_INPUT', message: 'prompt is required' };+ return { ok: false, errorCode: 'BAD_INPUT', message: 'prompt is required', dispatched: false };}if (!input.outputAbsPath) {- return { ok: false, errorCode: 'BAD_INPUT', message: 'outputAbsPath is required' };+ return { ok: false, errorCode: 'BAD_INPUT', message: 'outputAbsPath is required', dispatched: false };}- const picked = pickImageGenProfile();- if (!picked) {+ const candidates = listOpenImageGenCandidates();+ if (!candidates.length) {log.warn('image gen aborted: no api-key entry maps to an image-capable provider');- return { ok: false, errorCode: 'NO_CAPABLE_MODEL', message: t('image_gen.no_capable_model') };+ return { ok: false, errorCode: 'NO_CAPABLE_MODEL', message: t('image_gen.no_capable_model'), dispatched: false };}- const { entry, capability } = picked;const refPaths = input.referenceImagePaths || [];const refUrls = input.referenceImageUrls || [];-- if ((refPaths.length || refUrls.length) && !capability.supportsEdit) {- return {- ok: false,- errorCode: 'EDIT_NOT_SUPPORTED',- message: `Image model ${capability.model} does not support reference-image editing`,- };+ const hasRefs = refPaths.length > 0 || refUrls.length > 0;+ if (hasRefs) {+ emitProgress(input.onProgress, 'prepare_references', 'Preparing image references', {+ count: refPaths.length + refUrls.length,+ });}- let referenceBuffers: Buffer[] | undefined;- if (refPaths.length || refUrls.length) {+ let adapterRes: AdapterResult | null = null;+ let picked: PickedImageGenProfile | null = null;+ let editUnsupported = '';+ let lastProviderError = '';+ let attempted = false;+ for (const candidate of candidates) {+ const { entry, capability } = candidate;+ if (hasRefs && !capability.supportsEdit) {+ editUnsupported = `Image model ${capability.model} does not support reference-image editing`;+ continue;+ }+ let size = input.size || (capability.api === 'doubao' || capability.api === 'orkas' ? '2k'+ : capability.api === 'gemini' ? 'auto' : '1024x1024');try {- referenceBuffers = await loadImageReferenceBuffersWithProgress(refUrls, refPaths, { signal: input.signal, onProgress: input.onProgress });+ if (capability.api === 'doubao') size = normaliseSeedreamSize(size, capability.model);+ if (capability.api === 'gemini') normaliseGeminiImageSize(size, capability.model);+ } catch (error) {+ if (!(error instanceof UnsupportedImageSizeError)) throw error;+ // An incompatible fallback cannot overwrite the actual primary error.+ if (attempted) continue;+ return { ok: false, errorCode: 'BAD_INPUT', message: error.message, dispatched: false };+ }+ const adapterReq: AdapterRequest = {+ apiKey: entry.apiKey,+ model: capability.model,+ prompt: input.prompt,+ size,+ signal: input.signal,+ onProgress: input.onProgress,+ usageContext: input.usageContext,+ ...(refPaths.length ? { referenceImagePaths: refPaths } : {}),+ ...(refUrls.length ? { referenceImageUrls: refUrls } : {}),+ };+ attempted = true;+ try {+ if (capability.api === 'openai') adapterRes = await callOpenAIImage(adapterReq);+ else if (capability.api === 'gemini') adapterRes = await callGeminiImage(adapterReq);+ else if (capability.api === 'doubao') adapterRes = await callDoubaoImage(adapterReq);+ else if (capability.api === 'orkas') adapterRes = await callOrkasImage(adapterReq);+ else return { ok: false, errorCode: 'BAD_INPUT', message: `Unknown image-gen api: ${capability.api}`, dispatched: false };+ picked = candidate;+ break;} catch (err) {+ if (err instanceof ImageGenerationDeliveryError) throw err;+ const msg = (err as Error).message;+ lastProviderError = msg;throwIfAborted(input.signal);- log.warn(`failed reading reference image: ${(err as Error).message}`);- return {- ok: false,- errorCode: 'IO_ERROR',- message: `Failed to read reference image: ${(err as Error).message}`,- };+ // A public async request may have been accepted despite a lost response.+ // Preserve its existing no-replay boundary rather than charging a fallback.+ if (capability.api === 'orkas') return { ok: false, errorCode: 'PROVIDER_API_ERROR', message: sanitizeLogTextForUpload(msg) };+ log.warn(`image gen API call failed (${entry.provider}/${capability.model}); trying next provider`, {+ error: logErrorSummary(err),+ });}}- const size = input.size || '1024x1024';- const adapterReq: AdapterRequest = {- apiKey: entry.apiKey,- model: capability.model,- prompt: input.prompt,- size,- onProgress: input.onProgress,- ...(input.signal ? { signal: input.signal } : {}),- ...(input.usageContext ? { usageContext: input.usageContext } : {}),- ...(referenceBuffers ? { referenceImages: referenceBuffers } : {}),- };-- let adapterRes: AdapterResult;- try {- if (capability.api === 'openai') {- adapterRes = await callOpenAIImage(adapterReq);- } else if (capability.api === 'gemini') {- adapterRes = await callGeminiImage(adapterReq);- } else if (capability.api === 'doubao') {- adapterRes = await callDoubaoImage(adapterReq);- } else if (capability.api === 'orkas') {- adapterRes = await callOrkasImage(adapterReq);- } else {+ if (!adapterRes || !picked) {+ if (lastProviderError) {return {ok: false,- errorCode: 'BAD_INPUT',- message: `Unknown image-gen api: ${(capability as ImageGenCapability).api}`,+ errorCode: 'PROVIDER_API_ERROR',+ message: sanitizeLogTextForUpload(lastProviderError),};}- } catch (err) {- if (err instanceof ImageGenerationDeliveryError) throw err;- throwIfAborted(input.signal);- const msg = (err as Error).message;- log.error(`image gen API call failed (${entry.provider}/${capability.model}): ${msg}`);- return { ok: false, errorCode: 'PROVIDER_API_ERROR', message: msg };+ return {+ ok: false,+ errorCode: 'EDIT_NOT_SUPPORTED',+ message: editUnsupported || 'No configured image model supports reference-image editing',+ ...(attempted ? {} : { dispatched: false as const }),+ };}- throwIfAborted(input.signal);- adapterRes = validateImageAdapterResult(adapterRes);- emitProgress(input.onProgress, 'save_image', 'Saving generated image');let finalPath: string;try {finalPath = ensureExtension(input.outputAbsPath, adapterRes.mimeType);+ emitProgress(input.onProgress, 'save_image', 'Saving generated image', { provider: picked.entry.provider });+ throwIfAborted(input.signal);await fs.mkdir(path.dirname(finalPath), { recursive: true });throwIfAborted(input.signal);await fs.writeFile(finalPath, adapterRes.buffer);- registerGeneratedMediaUrl(finalPath, adapterRes.sourceUrl);} catch (err) {const msg = (err as Error).message;- log.error(`image write failed (${input.outputAbsPath}): ${msg}`);+ log.error('image write failed', {+ path: logPathRef(input.outputAbsPath),+ error: logErrorSummary(err),+ });return { ok: false, errorCode: 'IO_ERROR', message: `Failed to write image: ${msg}` };}log.info('image generated', {- provider: entry.provider,- model: capability.model,- path: finalPath,+ provider: picked.entry.provider,+ model: picked.capability.model,+ path: logPathRef(finalPath),bytes: adapterRes.buffer.length,width: adapterRes.width,height: adapterRes.height,});+ registerGeneratedMediaUrl(finalPath, adapterRes.sourceUrl);return {ok: true,@@ -252,8 +279,8 @@ export async function generateImage(input: GenerateImageInput): Promise<Generatewidth: adapterRes.width,height: adapterRes.height,bytes: adapterRes.buffer.length,- provider: entry.provider,- model: capability.model,+ provider: picked.entry.provider,+ model: picked.capability.model,...(adapterRes.sourceUrl ? { sourceUrl: adapterRes.sourceUrl } : {}),};}@@ -266,6 +293,8 @@ export interface AdapterRequest {prompt: string;size: string;referenceImages?: Buffer[];+ referenceImagePaths?: string[];+ referenceImageUrls?: string[];signal?: AbortSignal;onProgress?: ImageProgressReporter;usageContext?: OrkasApiUsageContext;@@ -286,12 +315,15 @@ export const IMAGE_MODELS_BY_PROVIDER: Readonly<Record<string, Array<{ id: strin],openai: [{ id: 'gpt-image-2', name: 'GPT Image 2' },+ { id: 'gpt-image-2.5-flare', name: 'GPT Image 2.5 Flare' },+ { id: 'gpt-image-2.5-sunburst', name: 'GPT Image 2.5 Sunburst' },],google: [+ { id: 'gemini-nano-banana-2.1', name: 'Nano Banana 2.1' },{ id: 'gemini-3.1-flash-image-preview', name: 'Nano Banana 2' },],doubao: [- { id: 'doubao-seedream-5-0-lite-260128', name: 'Seedream 5.0 Lite' },+ { id: 'doubao-seedream-5-0-flash-260915', name: 'Seedream 5.0 Flash' },{ id: 'doubao-seedream-5-0-pro-260628', name: 'Seedream 5.0 Pro' },],};@@ -377,6 +409,7 @@ function sleepWithSignal(ms: number, signal: AbortSignal): Promise<void> {export async function callOrkasImage(req: AdapterRequest): Promise<AdapterResult> {throwIfAborted(req.signal);+ const referenceImages = (req.referenceImages || await loadImageReferenceBuffersWithProgress(req.referenceImageUrls, req.referenceImagePaths, { signal: req.signal, onProgress: req.onProgress }));const overall = composeAbortSignal(req.signal,ORKAS_IMAGE_TOTAL_TIMEOUT_MS,@@ -397,8 +430,8 @@ export async function callOrkasImage(req: AdapterRequest): Promise<AdapterResultsize: req.size === '1024x1024' ? '2k' : req.size,response_format: 'url',async: true,- ...(req.referenceImages?.length- ? { reference_images: req.referenceImages.map(orkasImageDataUrl) }+ ...(referenceImages.length+ ? { reference_images: referenceImages.map(orkasImageDataUrl) }: {}),}),},@@ -454,7 +487,7 @@ export async function callOrkasImage(req: AdapterRequest): Promise<AdapterResultexport async function callOpenAIImage(req: AdapterRequest): Promise<AdapterResult> {throwIfAborted(req.signal);- const referenceImages = (req.referenceImages || []);+ const referenceImages = (req.referenceImages || await loadImageReferenceBuffersWithProgress(req.referenceImageUrls, req.referenceImagePaths, { signal: req.signal, onProgress: req.onProgress }));const hasRefs = referenceImages.length > 0;const url = hasRefs? `${OPENAI_BASE}/v1/images/edits`@@ -520,9 +553,11 @@ export async function callOpenAIImage(req: AdapterRequest): Promise<AdapterResulexport async function callGeminiImage(req: AdapterRequest): Promise<AdapterResult> {throwIfAborted(req.signal);- const url = `${GEMINI_BASE}/v1beta/models/${encodeURIComponent(req.model)}:generateContent`;+ const imageConfig = normaliseGeminiImageSize(req.size, req.model);+ const upstreamModel = req.model === 'gemini-3.1-flash-image-preview' ? 'gemini-3.1-flash-image' : req.model;+ const url = `${GEMINI_BASE}/v1beta/models/${encodeURIComponent(upstreamModel)}:generateContent`;const parts: unknown[] = [{ text: req.prompt }];- const referenceImages = (req.referenceImages || []);+ const referenceImages = (req.referenceImages || await loadImageReferenceBuffersWithProgress(req.referenceImageUrls, req.referenceImagePaths, { signal: req.signal, onProgress: req.onProgress }));if (referenceImages.length) {for (const buf of referenceImages) {parts.push({@@ -535,7 +570,7 @@ export async function callGeminiImage(req: AdapterRequest): Promise<AdapterResul}const body = JSON.stringify({contents: [{ parts }],- generationConfig: { responseModalities: ['IMAGE'] },+ generationConfig: { responseModalities: ['IMAGE'], ...(imageConfig ? { imageConfig } : {}) },});emitProgress(req.onProgress, 'create_image', 'Calling Gemini image API', {provider: 'google',@@ -599,48 +634,23 @@ export async function callGeminiImage(req: AdapterRequest): Promise<AdapterResul}/**- * Volcengine Ark (Doubao) Seedream text-to-image + image-to-image (4.5+).+ * Volcengine Ark (Doubao) Seedream 5.0 text-to-image + image-to-image.* Endpoint: POST /api/v3/images/generations, OpenAI-compatible request body.- * Returns `{ data: [{ url: "..." }] }` by default (base64 also available- * on request); we use the URL mode and re-fetch the bytes ourselves so- * we don't bump into account-level base64 quotas.+ * Returns `{ data: [{ b64_json: "..." }] }` when requested. Keep this+ * adapter data-first so image generation behaves like OpenAI/Gemini.** Image-to-image: add `image: string | string[]` to the body; each entry- * is either a public HTTPS URL or a data URI- * (`data:<mime>;base64,<b64>`). Local reference images are encoded as- * data URIs uniformly.+ * is either a public HTTPS URL or a data URI (`data:<mime>;base64,<b64>`).+ * We normalise references to data URIs before sending.* Reference images + outputs total ≤ 15; the tool layer additionally* caps references to 4.*- * Size note: Seedream 4.5's `size` does NOT accept arbitrary `WxH` like- * OpenAI — the value must satisfy both:- * 1. Pixels ≥ 3,686,400 (≈ 1920×1920).- * 2. Form must be `WIDTHxHEIGHT` or one of the keywords- * `1k` / `2k` / `4k`.- * Callers default to `1024x1024` (OpenAI-style), which is under- * Seedream's lower bound, so we translate here: bump to `2k` when below- * the pixel floor; pass through anything already large enough or- * already a keyword. In image-to-image mode, when the caller hasn't- * explicitly set a non-default size, we pass `adaptive` so the model- * picks dimensions from the reference image, avoiding aspect-ratio- * conflicts when forcing 2k.+ * Ark size contracts differ by model: Lite uses 2K/3K/4K and+ * [3,686,400, 16,777,216] pixels; Pro/Flash use 1K/1.5K/2K and+ * [921,600, 4,624,220] pixels. All require aspect ratio [1/16,16].+ * Preserve explicit supported sizes; Flash/Pro reject invalid sizes before I/O.+ * Source: https://docs.volcengine.com/docs/ark/image-generation-api?lang=zh*/-const SEEDREAM_MIN_PIXELS = 3_686_400;-const SEEDREAM_DEFAULT_SIZE = '1024x1024';--function normaliseSeedreamSize(size: string): string {- const s = String(size || '').trim().toLowerCase();- if (!s) return '2k';- if (s === '1k' || s === '2k' || s === '4k' || s === 'adaptive') return s;- const m = s.match(/^(\d+)x(\d+)$/);- if (!m) return '2k';- const w = parseInt(m[1], 10);- const h = parseInt(m[2], 10);- if (!w || !h) return '2k';- if (w * h < SEEDREAM_MIN_PIXELS) return '2k';- return `${w}x${h}`;-}-function bufferToDataUri(buf: Buffer): string {const mime = detectMimeType(buf) || 'image/png';return `data:${mime};base64,${buf.toString('base64')}`;@@ -648,9 +658,9 @@ function bufferToDataUri(buf: Buffer): string {export async function callDoubaoImage(req: AdapterRequest): Promise<AdapterResult> {throwIfAborted(req.signal);- const refs = (req.referenceImages || []);+ const size = normaliseSeedreamSize(req.size, req.model);+ const refs = (req.referenceImages || await loadImageReferenceBuffersWithProgress(req.referenceImageUrls, req.referenceImagePaths, { signal: req.signal, onProgress: req.onProgress }));const isEdit = refs.length > 0;- const size = isEdit && req.size === SEEDREAM_DEFAULT_SIZE ? 'adaptive' : normaliseSeedreamSize(req.size);const bodyObj: Record<string, unknown> = {model: req.model,prompt: req.prompt,@@ -658,8 +668,8 @@ export async function callDoubaoImage(req: AdapterRequest): Promise<AdapterResulresponse_format: 'b64_json',output_format: 'jpeg',watermark: false,- sequential_image_generation: 'disabled',};+ if (!isSingleImageSeedream(req.model)) bodyObj.sequential_image_generation = 'disabled';if (isEdit) {const dataUris = refs.map(bufferToDataUri);bodyObj.image = dataUris.length === 1 ? dataUris[0] : dataUris;diff --git a/src/main/features/image_size.ts b/src/main/features/image_size.tsindex 34a577f4..688e30ad 100644--- a/src/main/features/image_size.ts+++ b/src/main/features/image_size.ts@@ -31,10 +31,6 @@ export function normaliseSeedreamSize(size: string, model: string): string {return `${w}x${h}`;}-export function normaliseManagedImageSize(size: string): string {- return normaliseSeedreamSize(size, 'doubao-seedream-5-0-flash-260915');-}-type GeminiImageConfig = { aspectRatio: string; imageSize?: '512' | '1K' | '2K' | '4K' };// Exact pixel pairs from the GenerateContent tables (not mathematical aspectdiff --git a/src/main/model/core-agent/image-gen-tool.ts b/src/main/model/core-agent/image-gen-tool.tsindex b45a794a..8ff7f625 100644--- a/src/main/model/core-agent/image-gen-tool.ts+++ b/src/main/model/core-agent/image-gen-tool.ts@@ -39,6 +39,7 @@ import { versionedChatMediaLocalUrl } from '../../util/chat-media-url';import {beginVideoProductionGeneration,finishVideoProductionGeneration,+ releaseVideoProductionGeneration,videoProductionControlStatePath,type VideoProductionGenerationTransaction,} from '../../features/video_production_control';@@ -156,7 +157,7 @@ export function createImageGenTool(opts: ImageGenToolOpts): AgentTool {size: {type: 'string',description:- 'Provider size hint. Seedream supports 2K (default after normalization), 3K, 4K, or a valid WIDTHxHEIGHT; other providers commonly use 1024x1024, 1536x1024, 1024x1536, or auto.',+ 'Flash/Pro: 1K/1.5K/2K(default) or WIDTHxHEIGHT (921600-4624220 pixels, aspect 1:16-16:1). Lite: 2K/3K/4K. Gemini: auto(default) or exact table size. OpenAI: supported size, default 1024x1024.',},production_plan_path: {type: 'string',@@ -393,17 +394,29 @@ export function createImageGenTool(opts: ImageGenToolOpts): AgentTool {}if (result.ok === false) {+ const notDispatched = result.dispatched === false;if (productionTransaction) {try {- await finishVideoProductionGeneration({- statePath: productionStatePath,- planPath: productionPlanAbs,- transactionId: productionTransaction.transaction_id,- segmentId: productionTransaction.segment_id,- kind: 'image',- ok: false,- errorCode: result.errorCode,- });+ if (notDispatched) {+ await releaseVideoProductionGeneration({+ statePath: productionStatePath,+ planPath: productionPlanAbs,+ transactionId: productionTransaction.transaction_id,+ segmentId: productionTransaction.segment_id,+ kind: 'image',+ errorCode: result.errorCode,+ });+ } else {+ await finishVideoProductionGeneration({+ statePath: productionStatePath,+ planPath: productionPlanAbs,+ transactionId: productionTransaction.transaction_id,+ segmentId: productionTransaction.segment_id,+ kind: 'image',+ ok: false,+ errorCode: result.errorCode,+ });+ }} catch (err) {return { content: `${(err as Error).message}; provider error=[${result.errorCode}] ${result.message}`, isError: true } as ToolResult;}@@ -415,6 +428,7 @@ export function createImageGenTool(opts: ImageGenToolOpts): AgentTool {transactionId: imageTransaction.transaction_id,ok: false,errorCode: result.errorCode,+ ...(notDispatched ? { countsTowardBudget: false } : {}),});} catch (err) {return { content: `${(err as Error).message}; provider error=[${result.errorCode}] ${result.message}`, isError: true } as ToolResult;diff --git a/test/main/features/image_auth.test.ts b/test/main/features/image_auth.test.tsindex 59912a84..359f6e22 100644--- a/test/main/features/image_auth.test.ts+++ b/test/main/features/image_auth.test.ts@@ -24,24 +24,24 @@ vi.mock('../../../src/main/features/auth', () => ({vi.mock('../../../src/main/model/provider_catalog', () => ({findImageGenCapability: (provider: string) => ({openai: { model: 'gpt-image-2', api: 'openai', supportsEdit: true },- google: { model: 'gemini-3.1-flash-image-preview', api: 'gemini', supportsEdit: true },- doubao: { model: 'doubao-seedream-5-0-lite-260128', api: 'doubao', supportsEdit: true },+ google: { model: 'gemini-nano-banana-2.1', api: 'gemini', supportsEdit: true },+ doubao: { model: 'doubao-seedream-5-0-flash-260915', api: 'doubao', supportsEdit: true },})[provider] || null,}));vi.mock('../../../src/main/features/image_gen', () => ({IMAGE_MODELS_BY_PROVIDER: {- openai: [{ id: 'gpt-image-2', name: 'GPT Image 2' }],- google: [{ id: 'gemini-3.1-flash-image-preview', name: 'Nano Banana 2' }],+ openai: [{ id: 'gpt-image-2', name: 'GPT Image 2' }, { id: 'gpt-image-2.5-flare', name: 'GPT Image 2.5 Flare' }, { id: 'gpt-image-2.5-sunburst', name: 'GPT Image 2.5 Sunburst' }],+ google: [{ id: 'gemini-nano-banana-2.1', name: 'Nano Banana 2.1' }, { id: 'gemini-3.1-flash-image-preview', name: 'Nano Banana 2' }],doubao: [- { id: 'doubao-seedream-5-0-lite-260128', name: 'Seedream 5.0 Lite' },+ { id: 'doubao-seedream-5-0-flash-260915', name: 'Seedream 5.0 Flash' },{ id: 'doubao-seedream-5-0-pro-260628', name: 'Seedream 5.0 Pro' },],},isImageProviderModelAllowed: (provider: string, model: string) => ({- openai: ['gpt-image-2'],- google: ['gemini-3.1-flash-image-preview'],- doubao: ['doubao-seedream-5-0-lite-260128', 'doubao-seedream-5-0-pro-260628'],+ openai: ['gpt-image-2', 'gpt-image-2.5-flare', 'gpt-image-2.5-sunburst'],+ google: ['gemini-nano-banana-2.1', 'gemini-3.1-flash-image-preview'],+ doubao: ['doubao-seedream-5-0-flash-260915', 'doubao-seedream-5-0-pro-260628'],})[provider]?.includes(model) === true,callOpenAIImage: mocks.callOpenAIImage,callGeminiImage: mocks.callGeminiImage,@@ -77,6 +77,10 @@ beforeEach(() => {describe('image auth profiles', () => {it.each([['openai', 'gpt-image-2', 'callOpenAIImage'],+ ['openai', 'gpt-image-2.5-flare', 'callOpenAIImage'],+ ['openai', 'gpt-image-2.5-sunburst', 'callOpenAIImage'],+ ['google', 'gemini-nano-banana-2.1', 'callGeminiImage'],+ ['doubao', 'doubao-seedream-5-0-flash-260915', 'callDoubaoImage'],['google', 'gemini-3.1-flash-image-preview', 'callGeminiImage'],['doubao', 'doubao-seedream-5-0-pro-260628', 'callDoubaoImage'],] as const)('dispatches a %s profile probe to its matching adapter', async (provider, model, callName) => {@@ -176,14 +180,16 @@ describe('image auth profiles', () => {{ id: 'doubao', label: 'DouBao' },])).toEqual([expect.objectContaining({- id: 'openai',+ id: 'openai:gpt-image-2',provider: 'openai',model: 'gpt-image-2',}),+ expect.objectContaining({ id: 'openai:gpt-image-2.5-flare', model: 'gpt-image-2.5-flare' }),+ expect.objectContaining({ id: 'openai:gpt-image-2.5-sunburst', model: 'gpt-image-2.5-sunburst' }),expect.objectContaining({- id: 'doubao:doubao-seedream-5-0-lite-260128',+ id: 'doubao:doubao-seedream-5-0-flash-260915',provider: 'doubao',- model: 'doubao-seedream-5-0-lite-260128',+ model: 'doubao-seedream-5-0-flash-260915',}),expect.objectContaining({id: 'doubao:doubao-seedream-5-0-pro-260628',diff --git a/test/main/features/image_gen.test.ts b/test/main/features/image_gen.test.tsindex 70cb36ac..36df8bd1 100644--- a/test/main/features/image_gen.test.ts+++ b/test/main/features/image_gen.test.ts@@ -7,12 +7,8 @@ import * as path from 'node:path';// - pickImageGenProfile's filter/match contract (the OAuth-skip + capability// lookup is the whole point of the design — easy to regress)// - adapter request construction (URL / headers / body shape) via mock fetch+// - provider fallback and the bytes-on-disk success boundary// - PNG dimension parsing (guards the bytes->dimensions math)-// We deliberately do NOT test:-// - happy-path generateImage end-to-end (would need real fs + provider) —-// covered by manual smoke verification per docs/plans/image-gen.md-// - JPEG/WebP dimension parsing — same parser pattern as PNG; one fixture-// is enough to catch a busted readUInt32BE implementationlet tmpDir: string;let prevWs: string | undefined;@@ -27,19 +23,31 @@ beforeEach(async () => {users.activateUser(TEST_UID);});-afterEach(() => {+afterEach(async () => {+ const proxy = await import('../../../src/main/util/proxy-dispatcher');+ proxy._resetProxyRoutingForTests();+ vi.unstubAllGlobals();process.env.ORKAS_WORKSPACE_ROOT = prevWs;fs.rmSync(tmpDir, { recursive: true, force: true });});// ── helpers ──────────────────────────────────────────────────────────────-function writeProfilesFile(profiles: Record<string, unknown>, entries: unknown[]): void {+function writeProfilesFile(+ profiles: Record<string, unknown>,+ entries: unknown[],+ imageProfiles?: unknown[],+): void {const dir = path.join(tmpDir, TEST_UID, 'local', 'config');fs.mkdirSync(dir, { recursive: true });fs.writeFileSync(path.join(dir, 'auth-profiles.json'),- JSON.stringify({ version: 3, profiles, entries }, null, 2),+ JSON.stringify({+ version: imageProfiles ? 4 : 3,+ profiles,+ entries,+ ...(imageProfiles ? { imageProfiles } : {}),+ }, null, 2),'utf-8',);}@@ -106,8 +114,8 @@ describe('image_gen › pickImageGenProfile', () => {it('picks first capable api-key entry, ignoring earlier non-capable entries', async () => {// Order matters: priority list says anthropic first, then openai. The// picker must skip anthropic (no image API) and land on openai (capable).- // The user's chat model on the openai entry (gpt-6-astra) is irrelevant —- // the capability map fixes the model to gpt-image-2.+ // The user's chat model on the openai entry (gpt-5.5) is irrelevant —+ // the capability map fixes the model to gpt-image-1.writeProfilesFile({'anthropic:default': apiKeyProfile('anthropic', 'sk-ant-xxx'),@@ -149,49 +157,263 @@ describe('image_gen › pickImageGenProfile', () => {});});-// ── callOrkasImage (mock fetch) ──────────────────────────────────────────+describe('image_gen › Flash and Pro service choices', () => {+ it.each(['doubao-seedream-5-0-flash-260915', 'doubao-seedream-5-0-pro-260628'])(+ 'saves and selects %s without using the managed service', async model => {+ writeProfilesFile({}, [], []);+ const auth = await import('../../../src/main/features/image_auth');+ const m = await import('../../../src/main/features/image_gen');+ const result = auth.addImageProfile({ provider: 'doubao', model, apiKey: 'fixture-key' });+ expect(result.ok).toBe(true);+ expect(m.pickImageGenProfile()?.capability).toMatchObject({ api: 'doubao', model });+ expect(auth.listImageModelOptions('doubao').map(option => option.id)).toEqual([+ 'doubao-seedream-5-0-flash-260915', 'doubao-seedream-5-0-pro-260628',+ ]);+ });-describe('image_gen › callOrkasImage', () => {- it('uses the public image contract without exposing a provider model id', async () => {- const captured: { url?: string; init?: RequestInit } = {};- vi.stubGlobal('fetch', async (url: string, init: RequestInit) => {- captured.url = url;- captured.init = init;- const b64 =- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';- return new Response(JSON.stringify({- id: 'img_public_test',- status: 'succeeded',- data: [{ b64_json: b64 }],- }), { status: 202 });+ it('uses Flash for an unversioned own-key service and keeps explicit saved Lite choices readable', async () => {+ writeProfilesFile({}, [], [{ id: 'old', provider: 'doubao', apiKey: 'fixture-key', label: 'old', createdAt: 1 }]);+ const m = await import('../../../src/main/features/image_gen');+ expect(m.pickImageGenProfile()?.capability.model).toBe('doubao-seedream-5-0-flash-260915');+ writeProfilesFile({}, [], [{ id: 'old', provider: 'doubao', model: 'doubao-seedream-5-0-lite-260128', apiKey: 'fixture-key', label: 'old', createdAt: 1 }]);+ expect(m.pickImageGenProfile()?.capability.model).toBe('doubao-seedream-5-0-lite-260128');+ });+});++describe('image_gen › generateImage', () => {+ const PNG_B64 =+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';++ it.each([+ ['gpt-image-2.5-flare', 'GPT Image 2.5 Flare'],+ ['gpt-image-2.5-sunburst', 'GPT Image 2.5 Sunburst'],+ ])('saves the selected %s profile and uses it for generation and editing', async (model, name) => {+ writeProfilesFile({}, [], [{+ id: 'legacy-openai', provider: 'openai', apiKey: 'sk-legacy', label: 'legacy', createdAt: 1,+ }]);+ const m = await import('../../../src/main/features/image_gen');+ const auth = await import('../../../src/main/features/image_auth');+ expect(m.pickImageGenProfile()?.capability.model).toBe('gpt-image-2');++ const options = auth.flattenImageProviderOptions(auth.listImageProviderOptions());+ const option = options.find((item) => item.model === model);+ expect(option).toMatchObject({+ id: `openai:${model}`, provider: 'openai', model, label: `OpenAI · ${name}`,+ });+ const added = auth.addImageProfile({+ provider: option!.provider, model: option!.model, apiKey: 'sk-selected', label: 'selected',});+ expect(added.ok).toBe(true);+ if (!added.ok) return;+ expect(auth.listImageProfiles()).toEqual([+ expect.objectContaining({ id: added.id, provider: 'openai', model }),+ expect.objectContaining({ id: 'legacy-openai' }),+ ]);++ const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => new Response(+ JSON.stringify({ data: [{ b64_json: PNG_B64 }] }), { status: 200 },+ ));+ vi.stubGlobal('fetch', fetchMock);+ const output = path.join(tmpDir, 'selected.png');+ await expect(m.generateImage({ prompt: 'a red cube', outputAbsPath: output })).resolves.toMatchObject({+ ok: true, provider: 'openai', model, path: output, width: 1, height: 1,+ });+ expect(fs.readFileSync(output)).toEqual(Buffer.from(PNG_B64, 'base64'));+ const [generationUrl, generationInit] = fetchMock.mock.calls[0];+ expect(generationUrl).toBe('https://api.openai.com/v1/images/generations');+ expect(JSON.parse(generationInit.body as string)).toMatchObject({ model, n: 1, size: '1024x1024' });+ expect(generationInit.headers).toMatchObject({ Authorization: 'Bearer sk-selected' });++ const edited = path.join(tmpDir, 'edited.png');+ await expect(m.generateImage({+ prompt: 'change the cube to blue', outputAbsPath: edited, referenceImagePaths: [output],+ })).resolves.toMatchObject({ ok: true, provider: 'openai', model, path: edited });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ const [editUrl, editInit] = fetchMock.mock.calls[1];+ expect(editUrl).toBe('https://api.openai.com/v1/images/edits');+ const form = editInit.body as FormData;+ expect(form.get('model')).toBe(model);+ const references = form.getAll('image[]') as File[];+ expect(references).toHaveLength(1);+ expect(Buffer.from(await references[0].arrayBuffer())).toEqual(fs.readFileSync(output));+ expect(fs.readFileSync(edited)).toEqual(Buffer.from(PNG_B64, 'base64'));+ });++ it('rejects the ambiguous GPT Image 2.5 family name without saving a profile', async () => {+ writeProfilesFile({}, [], []);+ const auth = await import('../../../src/main/features/image_auth');+ expect(auth.addImageProfile({ provider: 'openai', model: 'gpt-image-2.5', apiKey: 'sk-test' })).toEqual({+ ok: false, error: 'unsupported image model "openai/gpt-image-2.5"',+ });+ expect(auth.listImageProfiles()).toEqual([]);+ });++ it('rejects a provider HTTP success with invalid bytes and falls back to the next configured provider', async () => {+ writeProfilesFile({}, [], [+ {+ id: 'image-openai',+ provider: 'openai',+ model: 'gpt-image-2',+ apiKey: 'sk-openai',+ label: 'first',+ createdAt: 1,+ },+ {+ id: 'image-google',+ provider: 'google',+ model: 'gemini-3.1-flash-image-preview',+ apiKey: 'google-key',+ label: 'fallback',+ createdAt: 2,+ },+ ]);+ const attemptedUrls: string[] = [];+ vi.stubGlobal('fetch', async (url: string) => {+ attemptedUrls.push(url);+ if (url.includes('api.openai.com')) {+ const htmlAsBase64 = Buffer.from('<html>upstream error</html>').toString('base64');+ return new Response(JSON.stringify({ data: [{ b64_json: htmlAsBase64 }] }), { status: 200 });+ }+ if (url.includes('generativelanguage.googleapis.com')) {+ return new Response(JSON.stringify({+ candidates: [{ content: { parts: [{ inline_data: { mime_type: 'image/png', data: PNG_B64 } }] } }],+ }), { status: 200 });+ }+ throw new Error(`unexpected fetch ${url}`);+ });+try {const m = await import('../../../src/main/features/image_gen');- const res = await m.callOrkasImage({- apiKey: 'orkas-user-key',- model: 'orkas-image',- prompt: 'a blue circle',- size: '1024x1024',- usageContext: { conversationId: 'conv_123', turnId: 'turn-456' },+ const output = path.join(tmpDir, 'generated', 'fallback-result');+ const result = await m.generateImage({ prompt: 'a calm lake', outputAbsPath: output });++ expect(result).toMatchObject({+ ok: true,+ provider: 'google',+ path: `${output}.png`,+ width: 1,+ height: 1,});+ expect(attemptedUrls).toHaveLength(2);+ expect(fs.readFileSync(`${output}.png`)).toEqual(Buffer.from(PNG_B64, 'base64'));+ } finally {+ vi.unstubAllGlobals();+ }+ });- expect(captured.url).toBe('https://orkas.ai/v1/images/generations');- expect(captured.init?.method).toBe('POST');- expect(captured.init?.headers).toMatchObject({- Authorization: 'Bearer orkas-user-key',- 'Content-Type': 'application/json',- 'X-Orkas-Conversation-Id': 'conv_123',- 'X-Orkas-Turn-Id': 'turn-456',+ it('reports provider failure and leaves no artifact when every HTTP-success payload is invalid', async () => {+ writeProfilesFile({}, [], [{+ id: 'image-openai',+ provider: 'openai',+ model: 'gpt-image-2',+ apiKey: 'sk-openai',+ label: 'only',+ createdAt: 1,+ }]);+ vi.stubGlobal('fetch', async () => {+ const htmlAsBase64 = Buffer.from('<html>not an image</html>').toString('base64');+ return new Response(JSON.stringify({ data: [{ b64_json: htmlAsBase64 }] }), { status: 200 });+ });++ try {+ const m = await import('../../../src/main/features/image_gen');+ const output = path.join(tmpDir, 'generated', 'invalid-result');+ const result = await m.generateImage({ prompt: 'a calm lake', outputAbsPath: output });++ expect(result).toMatchObject({+ ok: false,+ errorCode: 'PROVIDER_API_ERROR',+ message: expect.stringMatching(/invalid or unsupported image bytes/i),});- const body = JSON.parse(String(captured.init?.body));- expect(body).toEqual({- prompt: 'a blue circle',- size: '2k',- response_format: 'url',- async: true,+ expect(fs.existsSync(output)).toBe(false);+ expect(fs.existsSync(`${output}.png`)).toBe(false);+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it('redacts secrets and personal data from the final provider failure returned to the model', async () => {+ writeProfilesFile({}, [], [{+ id: 'image-openai',+ provider: 'openai',+ model: 'gpt-image-2',+ apiKey: 'sk-local-secret',+ label: 'only',+ createdAt: 1,+ }]);+ vi.stubGlobal('fetch', async () => new Response(JSON.stringify({+ error: {+ message: 'denied',+ apiKey: 'sk-returned-secret-value',+ email: '[email protected]',+ },+ }), { status: 401 }));+ const output = path.join(tmpDir, 'must-not-exist.png');++ try {+ const m = await import('../../../src/main/features/image_gen');+ const result = await m.generateImage({ prompt: 'a calm lake', outputAbsPath: output });++ expect(result).toMatchObject({+ ok: false,+ errorCode: 'PROVIDER_API_ERROR',+ message: expect.stringContaining('401'),});- expect(body).not.toHaveProperty('model');- expect(res).toMatchObject({ mimeType: 'image/png', width: 1, height: 1 });+ if (result.ok) return;+ expect(result.message).not.toContain('sk-returned-secret-value');+ expect(result.message).not.toContain('[email protected]');+ expect(fs.existsSync(output)).toBe(false);+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it('does not call a second provider when generated image bytes cannot be saved locally', async () => {+ writeProfilesFile({}, [], [+ {+ id: 'image-doubao',+ provider: 'doubao',+ model: 'doubao-seedream-5-0-lite-260128',+ apiKey: 'doubao-key',+ label: 'primary',+ createdAt: 1,+ },+ {+ id: 'image-openai',+ provider: 'openai',+ model: 'gpt-image-2',+ apiKey: 'sk-openai',+ label: 'fallback',+ createdAt: 2,+ },+ ]);+ let generationCount = 0;+ let fallbackCount = 0;+ vi.stubGlobal('fetch', async (url: string) => {+ if (url === 'https://ark.cn-beijing.volces.com/api/v3/images/generations') {+ generationCount += 1;+ return new Response(JSON.stringify({ data: [{ b64_json: PNG_B64 }] }), { status: 200 });+ }+ if (url.includes('api.openai.com')) {+ fallbackCount += 1;+ throw new Error('replacement provider must not be dispatched');+ }+ throw new Error(`unexpected fetch ${url}`);+ });+ const blockedParent = path.join(tmpDir, 'parent-is-a-file');+ fs.writeFileSync(blockedParent, 'occupied');++ try {+ const m = await import('../../../src/main/features/image_gen');+ await expect(m.generateImage({+ prompt: 'one paid image',+ outputAbsPath: path.join(blockedParent, 'out.png'),+ })).resolves.toMatchObject({+ ok: false,+ errorCode: 'IO_ERROR',+ });+ expect(generationCount).toBe(1);+ expect(fallbackCount).toBe(0);} finally {vi.unstubAllGlobals();}@@ -217,11 +439,13 @@ describe('image_gen › callOpenAIImage', () => {});try {const m = await import('../../../src/main/features/image_gen');+ const progress: Array<{ phase: string; message: string }> = [];const res = await m.callOpenAIImage({apiKey: 'sk-test',model: 'gpt-image-1',prompt: 'a red cube',size: '1024x1024',+ onProgress: (event) => progress.push(event),});expect(captured.url).toBe('https://api.openai.com/v1/images/generations');expect(captured.init?.method).toBe('POST');@@ -233,6 +457,7 @@ describe('image_gen › callOpenAIImage', () => {expect(res.mimeType).toBe('image/png');expect(res.width).toBe(1);expect(res.height).toBe(1);+ expect(progress.map((e) => e.phase)).toEqual(['create_image', 'decode_image']);} finally {vi.unstubAllGlobals();}@@ -251,12 +476,16 @@ describe('image_gen › callOpenAIImage', () => {const m = await import('../../../src/main/features/image_gen');// PNG signature in a 1-byte payload so detectMimeType returns image/pngconst refBuf = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);+ const refPath = path.join(tmpDir, 'ref.png');+ fs.writeFileSync(refPath, refBuf);+ const progress: Array<{ phase: string; message: string }> = [];await m.callOpenAIImage({apiKey: 'sk-test',model: 'gpt-image-1',prompt: 'change the cube to blue',size: '1024x1024',- referenceImages: [refBuf],+ referenceImagePaths: [refPath],+ onProgress: (event) => progress.push(event),});expect(captured.url).toBe('https://api.openai.com/v1/images/edits');const headers = captured.init?.headers as Record<string, string>;@@ -266,6 +495,7 @@ describe('image_gen › callOpenAIImage', () => {// FormData round-trip is awkward to assert on directly; the URL +// header proof is enough to lock the routing decision.expect(captured.init?.body).toBeDefined();+ expect(progress.map((e) => e.phase)).toEqual(['reference_load', 'create_image', 'decode_image']);} finally {vi.unstubAllGlobals();}@@ -289,6 +519,118 @@ describe('image_gen › callOpenAIImage', () => {// ── callGeminiImage (mock fetch) ─────────────────────────────────────────describe('image_gen › callGeminiImage', () => {+ const PNG_B64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';+ // Independent pixel/ratio pairs from Google's per-model GenerateContent tables.+ it.each([+ ['gemini-nano-banana-2.1', '2752x1536', { aspectRatio: '16:9', imageSize: '2K' }],+ ['gemini-nano-banana-2.1', '1536x12288', { aspectRatio: '1:8', imageSize: '4K' }],+ ['gemini-3.1-flash-image-preview', '512x512', { aspectRatio: '1:1', imageSize: '512' }],+ ['gemini-3-pro-image', '3584x4800', { aspectRatio: '3:4', imageSize: '4K' }],+ ['gemini-2.5-flash-image', '1344x768', { aspectRatio: '16:9' }],+ ] as const)('sends the exact supported %s size %s through its image adapter', async (model, size, imageConfig) => {+ writeProfilesFile({}, [], [{ id: 'google-size', provider: 'google', model, apiKey: 'fixture-key', label: 'Images', createdAt: 1 }]);+ const fetch = vi.fn(async (_url: string, init?: RequestInit) => {+ expect(JSON.parse(String(init?.body)).generationConfig).toEqual({ responseModalities: ['IMAGE'], imageConfig });+ return new Response(JSON.stringify({ candidates: [{ content: { parts: [{ inlineData: { mimeType: 'image/png', data: PNG_B64 } }] } }] }));+ });+ vi.stubGlobal('fetch', fetch);+ const m = await import('../../../src/main/features/image_gen');+ const output = path.join(tmpDir, 'size-result.png');+ if (model === 'gemini-nano-banana-2.1' || model === 'gemini-3.1-flash-image-preview') {+ expect(await m.generateImage({ prompt: 'a lake', size, outputAbsPath: output })).toMatchObject({ ok: true, width: 1, height: 1 });+ expect(fs.readFileSync(output)).toEqual(Buffer.from(PNG_B64, 'base64'));+ } else {+ expect((await m.callGeminiImage({ apiKey: 'fixture-key', model, size, prompt: 'a lake' })).buffer).toEqual(Buffer.from(PNG_B64, 'base64'));+ }+ expect(fetch).toHaveBeenCalledOnce();+ });++ it.each([+ ['gemini-nano-banana-2.1', '1920x1080'], ['gemini-nano-banana-2.1', '512x512'],+ ['gemini-3-pro-image', '512x2048'], ['gemini-2.5-flash-image', '2048x2048'],+ ['unknown-image-model', '1024x1024'],+ ])('rejects unsupported %s size %s before reference I/O and dispatch', async (model, size) => {+ writeProfilesFile({}, [], [{ id: 'google-size', provider: 'google', model, apiKey: 'fixture-key', label: 'Images', createdAt: 1 }]);+ const fetch = vi.fn(); vi.stubGlobal('fetch', fetch);+ const m = await import('../../../src/main/features/image_gen');+ const output = path.join(tmpDir, 'rejected.png');+ const references = { referenceImagePaths: [path.join(tmpDir, 'missing.png')] };+ if (model === 'gemini-nano-banana-2.1') {+ expect(await m.generateImage({ prompt: 'a lake', size, outputAbsPath: output, ...references }))+ .toMatchObject({ ok: false, errorCode: 'BAD_INPUT', dispatched: false });+ }+ await expect(m.callGeminiImage({ apiKey: 'fixture-key', model, size, prompt: 'a lake', ...references })).rejects.toThrow(/Unsupported image size/);+ expect(fetch).not.toHaveBeenCalled();+ expect(fs.existsSync(output)).toBe(false);+ });++ it('keeps auto dimensions absent when editing and preserves a real primary failure before an incompatible fallback', async () => {+ const model = 'gemini-nano-banana-2.1';+ const google = { id: 'google-size', provider: 'google', model, apiKey: 'fixture-key', label: 'Images', createdAt: 1 };+ writeProfilesFile({}, [], [google]);+ const ref = path.join(tmpDir, 'ref.png'); fs.writeFileSync(ref, Buffer.from(PNG_B64, 'base64'));+ const fetch = vi.fn(async (_url: string, init?: RequestInit) => {+ const body = JSON.parse(String(init?.body));+ expect(body.generationConfig).toEqual({ responseModalities: ['IMAGE'] });+ expect(body.contents[0].parts).toHaveLength(2);+ return new Response(JSON.stringify({ candidates: [{ content: { parts: [{ inlineData: { mimeType: 'image/png', data: PNG_B64 } }] } }] }));+ });+ vi.stubGlobal('fetch', fetch);+ const m = await import('../../../src/main/features/image_gen');+ expect(await m.generateImage({ prompt: 'edit', size: 'auto', referenceImagePaths: [ref], outputAbsPath: path.join(tmpDir, 'auto.png') })).toMatchObject({ ok: true });+ (await import('../../../src/main/features/auth')).saveImageProfiles([+ { ...google, id: 'openai-first', provider: 'openai', model: 'gpt-image-2' }, google,+ ]);+ fetch.mockImplementation(async () => new Response('primary failed', { status: 500 }));+ const result = await m.generateImage({ prompt: 'a lake', size: '1920x1080', outputAbsPath: path.join(tmpDir, 'fallback.png') });+ expect(result).toMatchObject({ ok: false, errorCode: 'PROVIDER_API_ERROR' });+ expect(result).not.toHaveProperty('dispatched', false);+ expect(fetch).toHaveBeenCalledTimes(2);+ });+ // Google announced retirement of the3.1image preview and publishes both+ // the same-generation GA ID and Nano Banana2.1 in generateContent docs.+ // Requester approved GA mapping for old profiles and2.1 as the new default.+ it.each([+ ['gemini-3.1-flash-image-preview', 'gemini-3.1-flash-image'],+ ['gemini-nano-banana-2.1', 'gemini-nano-banana-2.1'],+ [undefined, 'gemini-nano-banana-2.1'],+ ])('generates from saved Google configuration %s using %s without rewriting it', async (savedModel, upstreamModel) => {+ let profile = { id: 'saved-google', provider: 'google', model: savedModel, apiKey: 'fixture-key', label: 'My images', createdAt: 1 };+ if (savedModel === 'gemini-nano-banana-2.1') {+ writeProfilesFile({}, []);+ const imageAuth = await import('../../../src/main/features/image_auth');+ const options = imageAuth.flattenImageProviderOptions(imageAuth.listImageProviderOptions()).filter(p => p.provider === 'google');+ expect(options.map(p => ({ model: p.model, label: p.label }))).toEqual([+ { model: savedModel, label: 'Google · Nano Banana 2.1' },+ { model: 'gemini-3.1-flash-image-preview', label: 'Google · Nano Banana 2' },+ ]);+ const added = imageAuth.addImageProfile({ provider: 'google', apiKey: profile.apiKey, label: profile.label });+ expect(added.ok).toBe(true);+ const auth = await import('../../../src/main/features/auth');+ profile = auth.loadImageProfiles().find(p => p.id === (added as { id: string }).id)! as typeof profile;+ expect(profile.model).toBe(savedModel);+ } else if (savedModel) writeProfilesFile({}, [], [profile]);+ else writeProfilesFile({ 'google:studio': apiKeyProfile('google', 'fixture-key', 'studio') }, [entry('google', 'gemini-3.8-flash', 'google:studio', 'google-main')]);+ const fetch = vi.fn(async (url: string, init?: RequestInit) => {+ expect(url).toBe(`https://generativelanguage.googleapis.com/v1beta/models/${upstreamModel}:generateContent`);+ expect(init?.headers).toMatchObject({ 'x-goog-api-key': 'fixture-key' });+ expect(JSON.parse(String(init?.body))).toEqual({ contents: [{ parts: [{ text: 'a quiet lake' }] }], generationConfig: { responseModalities: ['IMAGE'] } });+ return new Response(JSON.stringify({ candidates: [{ content: { parts: [{ inlineData: { mimeType: 'image/png', data: PNG_B64 } }] } }] }));+ });+ vi.stubGlobal('fetch', fetch);+ const m = await import('../../../src/main/features/image_gen');+ const output = path.join(tmpDir, 'google-result.png');+ expect(await m.generateImage({ prompt: 'a quiet lake', outputAbsPath: output }))+ .toMatchObject({ ok: true, provider: 'google', model: savedModel || upstreamModel, path: output });+ expect(fs.readFileSync(output)).toEqual(Buffer.from(PNG_B64, 'base64'));+ expect(fetch).toHaveBeenCalledOnce();+ if (savedModel) {+ // The normal reader migrates plaintext fixtures into encrypted storage.+ const auth = await import('../../../src/main/features/auth');+ expect(auth.loadImageProfiles().find(p => p.id === profile.id)).toEqual(profile);+ }+ });+it('hits generateContent with x-goog-api-key header and inline_data response', async () => {const captured: { url?: string; init?: RequestInit } = {};vi.stubGlobal('fetch', async (url: string, init: RequestInit) => {@@ -302,11 +644,13 @@ describe('image_gen › callGeminiImage', () => {});try {const m = await import('../../../src/main/features/image_gen');+ const progress: Array<{ phase: string; message: string }> = [];const res = await m.callGeminiImage({apiKey: 'AIza-test',model: 'gemini-2.5-flash-image-preview',prompt: 'a cat',size: '1024x1024',+ onProgress: (event) => progress.push(event),});expect(captured.url).toBe('https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image-preview:generateContent',@@ -319,6 +663,7 @@ describe('image_gen › callGeminiImage', () => {expect(body.generationConfig.responseModalities).toEqual(['IMAGE']);expect(res.mimeType).toBe('image/png');expect(res.width).toBe(1);+ expect(progress.map((e) => e.phase)).toEqual(['create_image', 'decode_image']);} finally {vi.unstubAllGlobals();}@@ -361,8 +706,236 @@ describe('image_gen › callGeminiImage', () => {});});-// Keep the body pending after headers so cancellation/deadline tests exercise-// the actual adapter's response consumption, not merely fetch dispatch.+describe('image_gen › callDoubaoImage', () => {+ // Official Flash/Pro sizes are exact requests, not hints to downgrade.+ it.each(['doubao-seedream-5-0-pro-260628', 'doubao-seedream-5-0-flash-260915'].flatMap(model => [+ [' 1K ', '1k'], ['1.5k', '1.5k'], ['2k', '2k'], ['', '2k'],+ ['960x960', '960x960'], ['1024x1024', '1024x1024'], ['2048x2048', '2048x2048'],+ ['2048x2257', '2048x2257'], ['1920x1920', '1920x1920'],+ ].map(([size, expected]) => [model, size, expected])))('preserves %s size %s as %s', async (model, size, expected) => {+ const pngB64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';+ const fetch = vi.fn(async () => new Response(JSON.stringify({ data: [{ b64_json: pngB64 }] })));+ vi.stubGlobal('fetch', fetch);+ const m = await import('../../../src/main/features/image_gen');+ await m.callDoubaoImage({ apiKey: 'fixture-key', model, size, prompt: 'a quiet lake' });+ expect(fetch).toHaveBeenCalledOnce();+ const body = JSON.parse(String((fetch.mock.calls[0] as any)[1].body));+ expect(body.size).toBe(expected);+ expect(body).not.toHaveProperty('sequential_image_generation');+ });++ it.each(['doubao-seedream-5-0-pro-260628', 'doubao-seedream-5-0-flash-260915'].flatMap(model =>+ ['3k', '4k', '4096x4096', '959x960', '2048x2258', '4097x256', 'adaptive'].map(size => [model, size])))+ ('rejects unsupported %s size %s before reading references or calling a provider', async (model, size) => {+ const fetch = vi.fn(); vi.stubGlobal('fetch', fetch);+ const m = await import('../../../src/main/features/image_gen');+ await expect(m.callDoubaoImage({ apiKey: 'fixture-key', model, size, prompt: 'a lake',+ referenceImagePaths: [path.join(tmpDir, 'does-not-exist.png')] })).rejects.toThrow(/size.*1k.*1\.5k.*2k/i);+ expect(fetch).not.toHaveBeenCalled();+ });++ it('preserves the actual legacy provider failure when an incompatible Flash fallback is skipped', async () => {+ writeProfilesFile({}, [], [+ { id: 'lite', provider: 'doubao', model: 'doubao-seedream-5-0-lite-260128', apiKey: 'fixture-key', label: 'lite', createdAt: 1 },+ { id: 'flash', provider: 'doubao', model: 'doubao-seedream-5-0-flash-260915', apiKey: 'fixture-key', label: 'flash', createdAt: 1 },+ ]);+ const fetch = vi.fn(async () => { throw new Error('fixture provider unavailable'); });+ vi.stubGlobal('fetch', fetch);+ const m = await import('../../../src/main/features/image_gen');+ const result = await m.generateImage({ prompt: 'a lake', size: '4k', outputAbsPath: path.join(tmpDir, 'none.png') });+ expect(result).toMatchObject({ ok: false, errorCode: 'PROVIDER_API_ERROR', message: 'fixture provider unavailable' });+ expect(fetch).toHaveBeenCalledOnce();+ });++ it('returns a non-dispatched input error instead of silently generating 2K or billing a fallback service', async () => {+ writeProfilesFile({}, [], [+ { id: 'flash', provider: 'doubao', model: 'doubao-seedream-5-0-flash-260915', apiKey: 'fixture-key', label: 'flash', createdAt: 1 },+ { id: 'fallback', provider: 'openai', model: 'gpt-image-2', apiKey: 'fixture-key', label: 'fallback', createdAt: 1 },+ ]);+ const fetch = vi.fn(async () => new Response(JSON.stringify({ data: [{ b64_json:+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==' }] })));+ vi.stubGlobal('fetch', fetch);+ const m = await import('../../../src/main/features/image_gen');+ const output = path.join(tmpDir, 'not-generated.png');+ const result = await m.generateImage({ prompt: 'a lake', size: '4k', outputAbsPath: output });+ expect(result).toMatchObject({ ok: false, errorCode: 'BAD_INPUT', dispatched: false });+ expect(fetch).not.toHaveBeenCalled(); expect(fs.existsSync(output)).toBe(false);+ });++ it.each([+ ['adaptive', '2k'],+ ['1k', '2k'],+ ['AUTO', '2k'],+ ['not-a-size', '2k'],+ ['1024x1024', '2k'],+ ['1920x1919', '2k'],+ ['4097x4096', '2k'],+ [' 3K ', '3k'],+ ['1920x1920', '1920x1920'],+ ['4096x4096', '4096x4096'],+ ])('normalizes Seedream size %j to %j before provider dispatch', async (inputSize, expectedSize) => {+ const pngB64 =+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';+ let sentBody: Record<string, unknown> = {};+ vi.stubGlobal('fetch', async (_url: string, init: RequestInit) => {+ sentBody = JSON.parse(String(init.body || '{}'));+ return new Response(JSON.stringify({ data: [{ b64_json: pngB64 }] }), { status: 200 });+ });++ try {+ const m = await import('../../../src/main/features/image_gen');+ await m.callDoubaoImage({+ apiKey: 'doubao-key',+ model: 'doubao-seedream-5-0-lite-260128',+ prompt: 'a calm lake',+ size: inputSize,+ });++ expect(sentBody.size).toBe(expectedSize);+ expect(sentBody.size).not.toBe('adaptive');+ expect(sentBody.size).not.toBe('1k');+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it.each([+ ['doubao-seedream-5-0-lite-260128', true],+ ['doubao-seedream-5-0-pro-260628', false],+ ['doubao-seedream-5-0-flash-260915', false],+ ['doubao-seedream-4-5-251128', true],+ ] as const)('uses the supported single-image contract for %s', async (model, supportsSequential) => {+ const pngB64 =+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';+ const referencePath = path.join(tmpDir, 'reference.png');+ fs.writeFileSync(referencePath, Buffer.from(pngB64, 'base64'));+ let sentBody: Record<string, unknown> = {};+ vi.stubGlobal('fetch', async (_url: string, init: RequestInit) => {+ sentBody = JSON.parse(String(init.body || '{}'));+ return new Response(JSON.stringify({ data: [{ b64_json: pngB64 }] }), { status: 200 });+ });++ try {+ const m = await import('../../../src/main/features/image_gen');+ const result = await m.callDoubaoImage({+ apiKey: 'doubao-key',+ model,+ prompt: 'edit this image',+ size: '1024x1024',+ referenceImagePaths: [referencePath],+ });++ expect(result.mimeType).toBe('image/png');+ expect(sentBody).toMatchObject({+ model,+ prompt: 'edit this image',+ size: supportsSequential ? '2k' : '1024x1024',+ response_format: 'b64_json',+ output_format: 'jpeg',+ watermark: false,+ });+ // Ark rejects this field for Pro/Flash even when its value is disabled.+ if (supportsSequential) expect(sentBody.sequential_image_generation).toBe('disabled');+ else expect(sentBody).not.toHaveProperty('sequential_image_generation');+ expect(sentBody.image).toMatch(/^data:image\/png;base64,/);+ expect(sentBody.n).toBeUndefined();+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it('retries a newly-published CDN 404 without replaying the Doubao generation POST', async () => {+ const png = Buffer.from(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',+ 'base64',+ );+ let generationCount = 0;+ let downloadCount = 0;+ vi.stubGlobal('fetch', async (url: string, init?: RequestInit) => {+ if (url === 'https://ark.cn-beijing.volces.com/api/v3/images/generations') {+ generationCount += 1;+ expect(init?.method).toBe('POST');+ return new Response(JSON.stringify({ data: [{ url: 'https://cdn.test/eventual.png' }] }), { status: 200 });+ }+ if (url === 'https://cdn.test/eventual.png') {+ downloadCount += 1;+ return downloadCount === 1+ ? new Response('object not propagated yet', { status: 404 })+ : new Response(png, { status: 200 });+ }+ throw new Error(`unexpected fetch ${url}`);+ });++ vi.useFakeTimers();+ try {+ const m = await import('../../../src/main/features/image_gen');+ const pending = m.callDoubaoImage({+ apiKey: 'doubao-key',+ model: 'doubao-seedream-5-0-lite-260128',+ prompt: 'a calm lake',+ size: '1024x1024',+ });+ await vi.advanceTimersByTimeAsync(600);++ await expect(pending).resolves.toMatchObject({ buffer: png, sourceUrl: 'https://cdn.test/eventual.png' });+ expect(generationCount).toBe(1);+ expect(downloadCount).toBe(2);+ } finally {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ }+ });+});++describe('image_gen › callOrkasImage', () => {+ it('uses the public image contract without exposing a provider model id', async () => {+ const captured: { url?: string; init?: RequestInit } = {};+ vi.stubGlobal('fetch', async (url: string, init: RequestInit) => {+ captured.url = url;+ captured.init = init;+ const b64 =+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';+ return new Response(JSON.stringify({+ id: 'img_public_test',+ status: 'succeeded',+ data: [{ b64_json: b64 }],+ }), { status: 202 });+ });+ try {+ const m = await import('../../../src/main/features/image_gen');+ const res = await m.callOrkasImage({+ apiKey: 'orkas-user-key',+ model: 'orkas-image',+ prompt: 'a blue circle',+ size: '1024x1024',+ usageContext: { conversationId: 'conv_123', turnId: 'turn-456' },+ });++ expect(captured.url).toBe('https://orkas.ai/v1/images/generations');+ expect(captured.init?.method).toBe('POST');+ expect(captured.init?.headers).toMatchObject({+ Authorization: 'Bearer orkas-user-key',+ 'Content-Type': 'application/json',+ 'X-Orkas-Conversation-Id': 'conv_123',+ 'X-Orkas-Turn-Id': 'turn-456',+ });+ const body = JSON.parse(String(captured.init?.body));+ expect(body).toEqual({+ prompt: 'a blue circle',+ size: '2k',+ response_format: 'url',+ async: true,+ });+ expect(body).not.toHaveProperty('model');+ expect(res).toMatchObject({ mimeType: 'image/png', width: 1, height: 1 });+ } finally {+ vi.unstubAllGlobals();+ }+ });+});++// ── callOpenAIImage (mock fetch) ─────────────────────────────────────────+describe('image generation transfer and artifact boundaries', () => {const names = ['callOpenAIImage', 'callGeminiImage', 'callDoubaoImage', 'callOrkasImage'] as const;it.each(names)('%s cancels a response body after headers have arrived', async (name) => {@@ -379,7 +952,7 @@ describe('image generation transfer and artifact boundaries', () => {return { ok: true, status: 200, text: () => { reading(); return body; }, json: () => { reading(); return body.then(JSON.parse); } };});vi.stubGlobal('fetch', fetchStub);- const result = m[name]({ apiKey: 'fixture-key', model: 'fixture', prompt: 'a circle', size: '1024x1024', signal: controller.signal })+ const result = m[name]({ apiKey: 'fixture-key', model: name === 'callGeminiImage' ? 'gemini-nano-banana-2.1' : name === 'callDoubaoImage' ? 'doubao-seedream-5-0-flash-260915' : 'fixture', prompt: 'a circle', size: '1024x1024', signal: controller.signal }).then(() => 'success', (error) => error.message);try {await bodyStarted;@@ -398,11 +971,28 @@ describe('image generation transfer and artifact boundaries', () => {? { candidates: [{ content: { parts: [{ inlineData: { mimeType: 'image/png', data: invalid } }] } }] }: { data: [{ b64_json: invalid }] }), { status: 200 }));try {- await expect(m[name]({ apiKey: 'fixture-key', model: 'fixture', prompt: 'a circle', size: '1024x1024' }))+ await expect(m[name]({ apiKey: 'fixture-key', model: name === 'callGeminiImage' ? 'gemini-nano-banana-2.1' : name === 'callDoubaoImage' ? 'doubao-seedream-5-0-flash-260915' : 'fixture', prompt: 'a circle', size: '1024x1024' })).rejects.toThrow(/invalid|unsupported|malformed/i);} finally { vi.unstubAllGlobals(); }});+ it('does not replay an uncertain public API generation through another provider', async () => {+ writeProfilesFile({}, [], [+ { id: 'public', provider: 'orkas-api', model: 'orkas-image', apiKey: 'fixture-key', label: 'public', createdAt: 1 },+ { id: 'fallback', provider: 'openai', model: 'gpt-image-2', apiKey: 'fixture-key', label: 'fallback', createdAt: 2 },+ ]);+ const requests: string[] = [];+ vi.stubGlobal('fetch', async (url: string) => {+ requests.push(url);+ throw new Error('fixture response interrupted after dispatch');+ });+ const m = await import('../../../src/main/features/image_gen');+ const output = path.join(tmpDir, 'uncertain.png');+ expect(await m.generateImage({ prompt: 'one image', outputAbsPath: output })).toMatchObject({ ok: false, errorCode: 'PROVIDER_API_ERROR' });+ expect(requests).toEqual(['https://orkas.ai/v1/images/generations']);+ expect(fs.existsSync(output)).toBe(false);+ });+it('does not submit or write an already cancelled image generation', async () => {writeProfilesFile({ 'openai:default': apiKeyProfile('openai', 'fixture-key') }, [entry('openai', 'gpt-6-astra', 'openai:default', 'e1')]);const m = await import('../../../src/main/features/image_gen');@@ -411,9 +1001,296 @@ describe('image generation transfer and artifact boundaries', () => {const controller = new AbortController(); controller.abort();try {await expect(m.generateImage({ prompt: 'a circle', outputAbsPath: path.join(tmpDir, 'cancelled.png'), signal: controller.signal }))- .rejects.toThrow(/aborted/i);+ .resolves.toMatchObject({ ok: false, errorCode: 'BAD_INPUT', dispatched: false, message: expect.stringMatching(/aborted/i) });expect(fetchStub).not.toHaveBeenCalled();expect(fs.existsSync(path.join(tmpDir, 'cancelled.png'))).toBe(false);} finally { vi.unstubAllGlobals(); }});});++describe('direct image delivery ownership', () => {+ it('does not switch providers when a direct image generation succeeds but its URL cannot be downloaded', async () => {+ writeProfilesFile({}, [], [+ {+ id: 'image-doubao',+ provider: 'doubao',+ model: 'doubao-seedream-5-0-lite-260128',+ apiKey: 'doubao-key',+ label: 'primary',+ createdAt: 1,+ },+ {+ id: 'image-openai',+ provider: 'openai',+ model: 'gpt-image-2',+ apiKey: 'sk-openai',+ label: 'fallback',+ createdAt: 2,+ },+ ]);+ let generationCount = 0;+ let downloadCount = 0;+ let fallbackCount = 0;+ vi.stubGlobal('fetch', async (url: string) => {+ if (url === 'https://ark.cn-beijing.volces.com/api/v3/images/generations') {+ generationCount += 1;+ return new Response(JSON.stringify({ data: [{ url: 'https://cdn.test/direct.png' }] }), { status: 200 });+ }+ if (url === 'https://cdn.test/direct.png') {+ downloadCount += 1;+ throw new Error('temporary CDN connection reset');+ }+ if (url.includes('api.openai.com')) {+ fallbackCount += 1;+ throw new Error('replacement provider must not be dispatched');+ }+ throw new Error(`unexpected fetch ${url}`);+ });++ vi.useFakeTimers();+ try {+ const m = await import('../../../src/main/features/image_gen');+ const output = path.join(tmpDir, 'generated', 'direct-delivery-failed');+ const generation = m.generateImage({ prompt: 'a calm lake', outputAbsPath: output });+ const assertion = expect(generation).rejects.toThrow(/Do not submit another generation task.*connection reset/i);+ await vi.advanceTimersByTimeAsync(2_100);+ await assertion;+ expect(generationCount).toBe(1);+ expect(downloadCount).toBe(3);+ expect(fallbackCount).toBe(0);+ expect(fs.existsSync(output)).toBe(false);+ expect(fs.existsSync(`${output}.png`)).toBe(false);+ } finally {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ }+ });++ it('keeps a direct generation post-dispatch when cancellation interrupts only its download backoff', async () => {+ writeProfilesFile({}, [], [+ {+ id: 'image-doubao',+ provider: 'doubao',+ model: 'doubao-seedream-5-0-lite-260128',+ apiKey: 'doubao-key',+ label: 'primary',+ createdAt: 1,+ },+ {+ id: 'image-openai',+ provider: 'openai',+ model: 'gpt-image-2',+ apiKey: 'sk-openai',+ label: 'fallback',+ createdAt: 2,+ },+ ]);+ const controller = new AbortController();+ let generationCount = 0;+ let downloadCount = 0;+ let fallbackCount = 0;+ vi.stubGlobal('fetch', async (url: string) => {+ if (url === 'https://ark.cn-beijing.volces.com/api/v3/images/generations') {+ generationCount += 1;+ return new Response(JSON.stringify({ data: [{ url: 'https://cdn.test/cancelled.png' }] }), { status: 200 });+ }+ if (url === 'https://cdn.test/cancelled.png') {+ downloadCount += 1;+ throw new Error('temporary transfer failure');+ }+ if (url.includes('api.openai.com')) {+ fallbackCount += 1;+ throw new Error('replacement provider must not be dispatched');+ }+ throw new Error(`unexpected fetch ${url}`);+ });++ vi.useFakeTimers();+ try {+ const m = await import('../../../src/main/features/image_gen');+ const output = path.join(tmpDir, 'generated', 'cancelled-delivery');+ const generation = m.generateImage({+ prompt: 'a calm lake',+ outputAbsPath: output,+ signal: controller.signal,+ });+ await vi.advanceTimersByTimeAsync(1);+ expect(downloadCount).toBe(1);+ controller.abort(new Error('user cancelled'));++ await expect(generation).rejects.toThrow(/Do not submit another generation task.*aborted/i);+ expect(generationCount).toBe(1);+ expect(downloadCount).toBe(1);+ expect(fallbackCount).toBe(0);+ expect(vi.getTimerCount()).toBe(0);+ expect(fs.existsSync(output)).toBe(false);+ expect(fs.existsSync(`${output}.png`)).toBe(false);+ } finally {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ }+ });++});++describe('public API task and legacy profile compatibility', () => {+ const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');++ it('keeps a saved Lite profile probe usable without adding it back to new choices', async () => {+ writeProfilesFile({}, [], [{ id: 'legacy', provider: 'doubao', model: 'doubao-seedream-5-0-lite-260128', apiKey: 'fixture-key', label: 'Saved', createdAt: 1 }]);+ const auth = await import('../../../src/main/features/image_auth');+ const before = auth.listImageProfiles();+ const fetch = vi.fn(async (_url: string, init?: RequestInit) => {+ expect(JSON.parse(String(init?.body))).toMatchObject({ model: 'doubao-seedream-5-0-lite-260128', size: '2k', sequential_image_generation: 'disabled' });+ return new Response(JSON.stringify({ data: [{ b64_json: png.toString('base64') }] }));+ });+ vi.stubGlobal('fetch', fetch);+ expect(await auth.testImageProfile('legacy')).toMatchObject({ ok: true, provider: 'doubao', model: 'doubao-seedream-5-0-lite-260128' });+ expect(auth.listImageProfiles()).toEqual(before);+ expect(auth.listImageModelOptions('doubao').map(item => item.id)).not.toContain('doubao-seedream-5-0-lite-260128');+ expect(fetch).toHaveBeenCalledOnce();+ });++ it('keeps unsupported model-size failures typed before any reference or provider request', async () => {+ const m = await import('../../../src/main/features/image_gen');+ const { UnsupportedImageSizeError } = await import('../../../src/main/features/image_size');+ const fetch = vi.fn(); vi.stubGlobal('fetch', fetch);+ for (const request of [+ m.callDoubaoImage({ apiKey: 'fixture-key', model: 'doubao-seedream-5-0-flash-260915', prompt: 'a circle', size: '4k', referenceImageUrls: ['https://reference.test/image.png'] }),+ m.callGeminiImage({ apiKey: 'fixture-key', model: 'gemini-nano-banana-2.1', prompt: 'a circle', size: '1920x1080', referenceImageUrls: ['https://reference.test/image.png'] }),+ ]) await expect(request).rejects.toBeInstanceOf(UnsupportedImageSizeError);+ expect(fetch).not.toHaveBeenCalled();+ });++ it('polls the public API task to completion and downloads its result without another generation', async () => {+ const calls: Array<{ url: string; method: string }> = [];+ let polls = 0;+ vi.stubGlobal('fetch', async (url: string, init?: RequestInit) => {+ calls.push({ url, method: init?.method || 'GET' });+ if (url === 'https://orkas.ai/v1/images/generations') {+ expect(JSON.parse(String(init?.body))).toMatchObject({ async: true, reference_images: [expect.stringMatching(/^data:image\/png;base64,/)] });+ expect(JSON.parse(String(init?.body))).not.toHaveProperty('model');+ return new Response(JSON.stringify({ id: 'public /task', status: 'queued' }), { status: 202 });+ }+ if (url === 'https://orkas.ai/v1/images/generations/public%20%2Ftask') {+ expect(init?.headers).toMatchObject({ Authorization: 'Bearer fixture-key' });+ return new Response(JSON.stringify(++polls === 1 ? { status: 'running' } : { status: 'succeeded', data: [{ url: 'https://cdn.test/public.png' }] }));+ }+ expect(url).toBe('https://cdn.test/public.png');+ return new Response(png);+ });+ const m = await import('../../../src/main/features/image_gen');+ vi.useFakeTimers();+ try {+ const pending = m.callOrkasImage({ apiKey: 'fixture-key', model: 'orkas-image', prompt: 'a circle', size: '2k', referenceImages: [png] }).then(value => ({ value }), error => ({ error }));+ await vi.advanceTimersByTimeAsync(6_001);+ expect(await pending).toMatchObject({ value: { buffer: png, sourceUrl: 'https://cdn.test/public.png', width: 1, height: 1 } });+ expect(calls).toEqual([+ { url: 'https://orkas.ai/v1/images/generations', method: 'POST' },+ { url: 'https://orkas.ai/v1/images/generations/public%20%2Ftask', method: 'GET' },+ { url: 'https://orkas.ai/v1/images/generations/public%20%2Ftask', method: 'GET' },+ { url: 'https://cdn.test/public.png', method: 'GET' },+ ]);+ expect(vi.getTimerCount()).toBe(0);+ } finally { vi.useRealTimers(); }+ });++ it('cancels a public task poll wait without submitting another job', async () => {+ const calls = vi.fn(async () => new Response(JSON.stringify({ id: 'queued-task', status: 'queued' }), { status: 202 }));+ vi.stubGlobal('fetch', calls);+ const m = await import('../../../src/main/features/image_gen');+ const controller = new AbortController();+ vi.useFakeTimers();+ try {+ const pending = m.callOrkasImage({ apiKey: 'fixture-key', model: 'orkas-image', prompt: 'a circle', size: '2k', signal: controller.signal }).then(() => 'success', error => error.message);+ await vi.advanceTimersByTimeAsync(1);+ controller.abort();+ expect(await pending).toMatch(/aborted/i);+ await vi.advanceTimersByTimeAsync(6_000);+ expect(calls).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ } finally { vi.useRealTimers(); }+ });++ it('retains a public terminal failure without billing another configured provider', async () => {+ writeProfilesFile({}, [], [+ { id: 'public', provider: 'orkas-api', model: 'orkas-image', apiKey: 'fixture-key', label: 'public', createdAt: 1 },+ { id: 'fallback', provider: 'openai', model: 'gpt-image-2', apiKey: 'fixture-key', label: 'fallback', createdAt: 2 },+ ]);+ const calls: string[] = [];+ vi.stubGlobal('fetch', async (url: string) => {+ calls.push(url);+ return new Response(JSON.stringify(calls.length === 1 ? { id: 'failed-task', status: 'queued' } : { status: 'failed', error: { message: 'fixture task failed' } }));+ });+ const m = await import('../../../src/main/features/image_gen');+ const output = path.join(tmpDir, 'failed-task.png');+ vi.useFakeTimers();+ try {+ const pending = m.generateImage({ prompt: 'one image', outputAbsPath: output });+ await vi.advanceTimersByTimeAsync(3_001);+ expect(await pending).toMatchObject({ ok: false, errorCode: 'PROVIDER_API_ERROR', message: expect.stringContaining('failed') });+ expect(calls).toEqual(['https://orkas.ai/v1/images/generations', 'https://orkas.ai/v1/images/generations/failed-task']);+ expect(fs.existsSync(output)).toBe(false);+ expect(vi.getTimerCount()).toBe(0);+ } finally { vi.useRealTimers(); }+ });+});++describe('mixed references across public adapters', () => {+ const PNG_B64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';+ it.each(['openai', 'gemini', 'doubao', 'orkas-api'] as const)(+ 'preserves mixed reference roles in the actual %s generation request', async (provider) => {+ const { compileImagePromptContract, normalizeImageReferenceBindings } = await import('../../../src/main/features/image_prompt_contract');+ const bindings = normalizeImageReferenceBindings([+ { index: 0, role: 'identity', preserve: ['face'] },+ { index: 1, role: 'composition', preserve: ['layout'] },+ { index: 2, role: 'style', preserve: ['palette'] },+ { index: 3, role: 'content', preserve: ['objects'] },+ ], 4);+ const prompt = compileImagePromptContract('Combine the four references.', bindings, []);+ const png = Buffer.from(PNG_B64, 'base64');+ // Distinct PNG payloads let the request oracle detect swapped identities.+ const bytes = ['identity', 'composition', 'style', 'content'].map(label => Buffer.concat([png, Buffer.from(label)]));+ const paths = [path.join(tmpDir, 'identity.png'), path.join(tmpDir, 'composition.png')];+ paths.forEach((file, i) => fs.writeFileSync(file, bytes[i]));+ const urls = ['https://cdn.example/style.png', 'https://cdn.example/content.png'];+ const requests: RequestInit[] = [];+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ const reference = urls.indexOf(String(url));+ if (reference >= 0) return new Response(bytes[reference + 2]);+ if (init?.method !== 'POST') throw new Error('unexpected request');+ requests.push(init);+ if (provider === 'gemini') return new Response(JSON.stringify({+ candidates: [{ content: { parts: [{ inline_data: { mime_type: 'image/png', data: PNG_B64 } }] } }],+ }));+ return new Response(JSON.stringify({ data: [{ b64_json: PNG_B64 }] }));+ });+ vi.stubGlobal('fetch', fetchMock);+ const m = await import('../../../src/main/features/image_gen');+ const adapter = provider === 'openai' ? m.callOpenAIImage : provider === 'gemini' ? m.callGeminiImage+ : provider === 'doubao' ? m.callDoubaoImage : m.callOrkasImage;+ const result = await adapter({ apiKey: 'fixture-key', model: provider === 'gemini' ? 'gemini-nano-banana-2.1' : 'fixture-model', prompt, size: '1024x1024',+ referenceImagePaths: paths, referenceImageUrls: urls });++ expect(result.buffer).toEqual(png);+ expect(fetchMock).toHaveBeenCalledTimes(3); // Two reference downloads, one generation.+ expect(requests).toHaveLength(1);+ let sentBytes: Buffer[];+ if (provider === 'openai') {+ const body = requests[0].body as FormData;+ expect(body.get('prompt')).toBe(prompt);+ sentBytes = await Promise.all(body.getAll('image[]').map(async item => Buffer.from(await (item as Blob).arrayBuffer())));+ } else {+ const body = JSON.parse(requests[0].body as string);+ expect(provider === 'gemini' ? body.contents[0].parts[0].text : body.prompt).toBe(prompt);+ const payloads: string[] = provider === 'gemini'+ ? body.contents[0].parts.slice(1).map((part: { inline_data: { data: string } }) => part.inline_data.data)+ : (provider === 'doubao' ? body.image : body.reference_images).map((uri: string) => uri.split(',')[1]);+ sentBytes = payloads.map(data => Buffer.from(data, 'base64'));+ }+ expect(sentBytes).toEqual(bytes);++ },+ );++});diff --git a/test/main/model/core-agent/image-production-parity.test.ts b/test/main/model/core-agent/image-production-parity.test.tsindex 6b78bed9..fbee6268 100644--- a/test/main/model/core-agent/image-production-parity.test.ts+++ b/test/main/model/core-agent/image-production-parity.test.ts@@ -49,6 +49,7 @@ vi.mock('../../../../src/main/util/chat-media-url', () => ({vi.mock('../../../../src/main/features/video_production_control', () => ({beginVideoProductionGeneration: vi.fn(),finishVideoProductionGeneration: vi.fn(),+ releaseVideoProductionGeneration: vi.fn(),videoProductionControlStatePath: () => '/ws/production-state.json',}));vi.mock('../../../../src/main/logger', () => ({@@ -368,4 +369,87 @@ describe('generate_image tool', () => {fs.rmSync(projectDir, { recursive: true, force: true });}});+ it('keeps an ImageStudio attempt that never dispatched out of the turn budget, but not a dispatched one', async () => {+ const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-image-gen-not-dispatched-'));+ try {+ const { createImageGenTool } = await import('../../../../src/main/model/core-agent/image-gen-tool');+ const tool = createImageGenTool({ userId: 'u1', cid: 'c1', agentId: '814b61b027f0' });+ const generate = () => tool.execute!({+ prompt: 'a bird',+ output_path: path.join(projectDir, 'bird.png'),+ image_project_path: projectDir,+ image_request_id: 'hero-initial',+ }, ctx());++ h.generateImage.mockResolvedValueOnce({+ ok: false,+ errorCode: 'NO_CAPABLE_MODEL',+ message: 'no image model',+ dispatched: false,+ });+ expect((await generate()).isError).toBe(true);+ expect(h.finishImageGeneration).toHaveBeenLastCalledWith(expect.objectContaining({+ ok: false,+ errorCode: 'NO_CAPABLE_MODEL',+ countsTowardBudget: false,+ }));++ h.generateImage.mockResolvedValueOnce({ ok: false, errorCode: 'PROVIDER_API_ERROR', message: 'boom' });+ expect((await generate()).isError).toBe(true);+ expect(h.finishImageGeneration.mock.lastCall?.[0]).not.toHaveProperty('countsTowardBudget');+ } finally {+ fs.rmSync(projectDir, { recursive: true, force: true });+ }+ });++ it('releases a VideoStudio still that failed before dispatch instead of demanding a new paid confirmation', async () => {+ const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-image-gen-video-release-'));+ try {+ const planPath = path.join(projectDir, 'plan.json');+ fs.writeFileSync(planPath, '{}', 'utf8');+ const control = await import('../../../../src/main/features/video_production_control');+ vi.mocked(control.releaseVideoProductionGeneration).mockReset();+ vi.mocked(control.finishVideoProductionGeneration).mockReset();+ vi.mocked(control.beginVideoProductionGeneration).mockReset().mockResolvedValue({+ status: 'started',+ transaction: { transaction_id: 'still-tx', segment_id: 'still-1' },+ } as any);+ const { createImageGenTool } = await import('../../../../src/main/model/core-agent/image-gen-tool');+ const tool = createImageGenTool({ userId: 'u1', cid: 'c1', agentId: '79df9cc89f5f' });+ const generate = () => tool.execute!({+ prompt: 'a still',+ output_path: path.join(projectDir, 'still.png'),+ production_plan_path: planPath,+ production_segment_id: 'still-1',+ }, ctx());++ h.generateImage.mockResolvedValueOnce({+ ok: false,+ errorCode: 'BAD_INPUT',+ message: 'operation aborted',+ dispatched: false,+ });+ const notSent = await generate();+ expect(String(notSent.content)).toBe('[BAD_INPUT] operation aborted');+ expect(control.releaseVideoProductionGeneration).toHaveBeenCalledWith(expect.objectContaining({+ transactionId: 'still-tx',+ segmentId: 'still-1',+ kind: 'image',+ errorCode: 'BAD_INPUT',+ }));+ expect(control.finishVideoProductionGeneration).not.toHaveBeenCalled();++ h.generateImage.mockResolvedValueOnce({ ok: false, errorCode: 'PROVIDER_API_ERROR', message: 'boom' });+ const sent = await generate();+ expect(String(sent.content)).toBe('[PROVIDER_API_ERROR] boom');+ expect(control.releaseVideoProductionGeneration).toHaveBeenCalledOnce();+ expect(control.finishVideoProductionGeneration).toHaveBeenCalledWith(expect.objectContaining({+ transactionId: 'still-tx',+ ok: false,+ errorCode: 'PROVIDER_API_ERROR',+ }));+ } finally {+ fs.rmSync(projectDir, { recursive: true, force: true });+ }+ });});