Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(images): add configured batch generation and editing

Jackc91db60504e8
diff --git a/apps/desktop/electron/main/builtin-skills.ts b/apps/desktop/electron/main/builtin-skills.ts
index 9e7d5d71f..3dcb12005 100644
--- a/apps/desktop/electron/main/builtin-skills.ts
+++ b/apps/desktop/electron/main/builtin-skills.ts
@@ -15,13 +15,16 @@ import type { PluginSkillDef } from "@pi-desktop/agent-runtime";
/** Bundled skill teaching the plugin-development loop. */
export const PLUGIN_DEV_SKILL_FILE = "plugin-development.md";
export const PLUGIN_DEV_SKILL_ID = "pi-desktop/plugin-development";
+export const IMAGE_GENERATION_SKILL_ID = "pi-desktop/imagegen";
+const IMAGE_GENERATION_SKILL_FILE = "image-generation.md";
/** electron-builder copies `resources/skills` to `<resources>/skills`. */
function resolveBuiltinSkillPath(fileName: string): string | null {
+ const moduleDir = typeof __dirname === "string" ? __dirname : import.meta.dirname;
const candidates = [
join(process.resourcesPath || "", "skills", fileName),
- join(__dirname, "../../resources/skills", fileName),
- join(__dirname, "../../../resources/skills", fileName),
+ join(moduleDir, "../../resources/skills", fileName),
+ join(moduleDir, "../../../resources/skills", fileName),
];
for (const candidate of candidates) {
if (candidate && existsSync(candidate)) return candidate;
@@ -85,18 +88,15 @@ export type BuiltinSkillInput = {
* fresh so a packaged update takes effect without a restart.
*/
export function builtinSkills(input: BuiltinSkillInput): PluginSkillDef[] {
- if (!isPluginWorkspace(input.workspacePath, input.pluginPaths)) return [];
- const raw = readBuiltinSkill(PLUGIN_DEV_SKILL_FILE);
- if (!raw?.trim()) return [];
- const parsed = parseSkillFrontmatter(raw);
- if (!parsed.body) return [];
- return [
- {
- id: PLUGIN_DEV_SKILL_ID,
- name: parsed.name ?? "PI-Desktop plugin development",
- description: parsed.description,
- },
- ];
+ const ids = [IMAGE_GENERATION_SKILL_ID];
+ if (isPluginWorkspace(input.workspacePath, input.pluginPaths)) ids.push(PLUGIN_DEV_SKILL_ID);
+ return ids.flatMap((id) => {
+ const file = id === IMAGE_GENERATION_SKILL_ID ? IMAGE_GENERATION_SKILL_FILE : PLUGIN_DEV_SKILL_FILE;
+ const raw = readBuiltinSkill(file);
+ if (!raw?.trim()) return [];
+ const parsed = parseSkillFrontmatter(raw);
+ return parsed.body ? [{ id, name: parsed.name ?? id, description: parsed.description }] : [];
+ });
}
/**
@@ -106,14 +106,14 @@ export function builtinSkills(input: BuiltinSkillInput): PluginSkillDef[] {
export function loadBuiltinSkillBody(
id: string,
): { id: string; name: string; body: string } | null {
- if (id !== PLUGIN_DEV_SKILL_ID) return null;
- const raw = readBuiltinSkill(PLUGIN_DEV_SKILL_FILE);
+ if (id !== PLUGIN_DEV_SKILL_ID && id !== IMAGE_GENERATION_SKILL_ID) return null;
+ const raw = readBuiltinSkill(id === IMAGE_GENERATION_SKILL_ID ? IMAGE_GENERATION_SKILL_FILE : PLUGIN_DEV_SKILL_FILE);
if (!raw?.trim()) return null;
const parsed = parseSkillFrontmatter(raw);
if (!parsed.body) return null;
return {
- id: PLUGIN_DEV_SKILL_ID,
- name: parsed.name ?? "PI-Desktop plugin development",
+ id,
+ name: parsed.name ?? id,
body: parsed.body,
};
}
diff --git a/apps/desktop/electron/main/runtime/sidecar.ts b/apps/desktop/electron/main/runtime/sidecar.ts
index 685734af0..fcd68d044 100644
--- a/apps/desktop/electron/main/runtime/sidecar.ts
+++ b/apps/desktop/electron/main/runtime/sidecar.ts
@@ -7,6 +7,7 @@ import {
subagentProviderLookupError,
} from "@pi-desktop/agent-runtime";
import { loadBuiltinSkillBody } from "../builtin-skills";
+import { createImageGenerationTool } from "../services/image-generation-service";
import { registerPluginDevTools } from "../plugin-dev-tools";
import { resolveLocalFile } from "../browser-view";
import { modelConfigFromModelsDev } from "../models-dev-catalog";
@@ -469,6 +470,7 @@ export function createSidecarRuntime({
});
// Agent-driven work panel preview (D100): open a workspace HTML file in
// the embedded browser; live reload keeps it current through later edits.
+ s.setLocalTool("GenerateImages", createImageGenerationTool({ dataDir, getHost: () => runtimeState.host }));
s.setLocalTool("BrowserPreview", async ({ args, sessionId }) => {
const raw = String((args as { path?: unknown })?.path ?? "").trim();
if (!raw) {
diff --git a/apps/desktop/electron/main/services/image-generation-service.ts b/apps/desktop/electron/main/services/image-generation-service.ts
new file mode 100644
index 000000000..99da58cc4
--- /dev/null
+++ b/apps/desktop/electron/main/services/image-generation-service.ts
@@ -0,0 +1,114 @@
+import { randomUUID } from "node:crypto";
+import { mkdir, realpath, writeFile } from "node:fs/promises";
+import { isAbsolute, join, relative, resolve } from "node:path";
+import { generateImageBatch } from "@pi-desktop/agent-runtime";
+import {
+ imageGenerationPrompts,
+ parseImageGenerationBinding,
+ type AppSettings,
+ type ProviderPublic,
+} from "@pi-desktop/shared";
+import type { HostProcess } from "../host-process";
+import type { LocalToolHandler } from "../agent-sidecar";
+import { imageInputLoader } from "./image-inputs";
+
+function failure(errorCode: string, content: string) {
+ return {
+ ok: false,
+ isError: true,
+ errorCode,
+ content: { kind: "image-generation-error", errorCode, message: content },
+ };
+}
+
+export function createImageGenerationTool(options: {
+ dataDir: string;
+ getHost: () => Pick<HostProcess, "call"> | null;
+ fetchImpl?: typeof fetch;
+}): LocalToolHandler {
+ return async ({ sessionId, args, signal }) => {
+ imageGenerationPrompts(args);
+ const host = options.getHost();
+ if (!host) return failure("HOST_UNAVAILABLE", "Host unavailable.");
+ const settings = await host.call<AppSettings>("settings.get");
+ const binding = parseImageGenerationBinding(settings.imageGeneration);
+ if (!binding)
+ return failure(
+ "IMAGE_NOT_CONFIGURED",
+ "Configure an image generation model in Settings > AI > Image generation model before generating images. Do not substitute another model.",
+ );
+ const { provider } = await host.call<{ provider?: ProviderPublic }>("providers.get", {
+ id: binding.providerId,
+ });
+ if (
+ !provider?.enabled ||
+ !provider.baseUrl ||
+ !provider.models.some((model) => model.id === binding.modelId)
+ ) {
+ return failure(
+ "IMAGE_MODEL_UNAVAILABLE",
+ "The configured image model is unavailable. Update Settings > AI > Image generation model.",
+ );
+ }
+ if (provider.authKind === "oauth")
+ return failure(
+ "IMAGE_AUTH_UNSUPPORTED",
+ "Image generation requires an API-key or no-auth service.",
+ );
+ const { value } = await host.call<{ value?: string }>("providers.getSecret", {
+ id: provider.id,
+ });
+ if (provider.authKind !== "none" && !value)
+ return failure("IMAGE_AUTH_FAILED", "The image provider needs an API key.");
+ const { path } = await host.call<{ path: string }>("session.getScratchPath", { sessionId });
+ const root = resolve(options.dataDir, "scratch");
+ const within = (base: string, target: string) => {
+ const rel = relative(base, target);
+ return !!rel && !rel.startsWith("..") && !isAbsolute(rel);
+ };
+ if (typeof path !== "string" || !within(root, resolve(path)))
+ return failure("INVALID_ARGUMENT", "Invalid image output directory.");
+ await mkdir(path, { recursive: true });
+ const realRoot = await realpath(root);
+ const realDir = await realpath(path);
+ if (!within(realRoot, realDir))
+ return failure("INVALID_ARGUMENT", "Invalid image output directory.");
+ signal.throwIfAborted();
+ const { session } = await host.call<{ session?: { projectPath?: string } }>("session.get", {
+ id: sessionId,
+ });
+ if (!session) return failure("SESSION_NOT_FOUND", "The image session no longer exists.");
+ const results = await generateImageBatch({
+ input: args,
+ endpoint: {
+ baseUrl: provider.baseUrl,
+ modelId: binding.modelId,
+ apiKey: value,
+ headers: provider.headers,
+ },
+ signal,
+ fetchImpl: options.fetchImpl,
+ loadImages: imageInputLoader({
+ dataDir: options.dataDir,
+ scratchPath: realDir,
+ projectPath: session?.projectPath,
+ }),
+ save: async (image) => {
+ const target = join(realDir, `generated-${randomUUID()}.${image.extension}`);
+ await writeFile(target, image.bytes, { flag: "wx" });
+ return target;
+ },
+ });
+ const ok = results.some((result) => result.status === "succeeded");
+ return {
+ ok,
+ isError: !ok,
+ content: {
+ kind: "generated-images",
+ providerId: binding.providerId,
+ modelId: binding.modelId,
+ results,
+ },
+ };
+ };
+}
diff --git a/apps/desktop/electron/main/services/image-inputs.ts b/apps/desktop/electron/main/services/image-inputs.ts
new file mode 100644
index 000000000..6a9fbfb6a
--- /dev/null
+++ b/apps/desktop/electron/main/services/image-inputs.ts
@@ -0,0 +1,88 @@
+import { open, realpath } from "node:fs/promises";
+import { isAbsolute, relative, resolve } from "node:path";
+import { generatedImageType, MAX_IMAGE_BYTES } from "@pi-desktop/agent-runtime";
+
+/** Session/project roots are captured by the host, never supplied by the model. */
+export function imageInputLoader(options: {
+ projectPath?: string;
+ scratchPath: string;
+ dataDir: string;
+}) {
+ let loadedBytes = 0;
+ const cache = new Map<
+ string,
+ Promise<{ bytes: Uint8Array; mimeType: string; extension: string }>
+ >();
+ const read = async (ref: string) => {
+ const candidate = /^attachments[\\/][a-f0-9]{64}$/.test(ref)
+ ? resolve(options.dataDir, ref)
+ : isAbsolute(ref)
+ ? ref
+ : options.projectPath
+ ? resolve(options.projectPath, ref)
+ : resolve(options.scratchPath, ref);
+ const path = await realpath(candidate);
+ const roots = await Promise.all(
+ [options.projectPath, options.scratchPath, resolve(options.dataDir, "attachments")]
+ .filter((root): root is string => !!root)
+ .map((root) =>
+ realpath(root).catch((error: NodeJS.ErrnoException) => {
+ if (error.code === "ENOENT") return null;
+ throw error;
+ }),
+ ),
+ );
+ if (
+ !roots.some((root) => {
+ if (!root) return false;
+ const rel = relative(root, path);
+ return !!rel && !rel.startsWith("..") && !isAbsolute(rel);
+ })
+ )
+ throw Object.assign(new Error("Image input is outside the session and project roots"), {
+ errorCode: "IMAGE_INPUT_OUTSIDE_ROOT",
+ });
+ const file = await open(path, "r");
+ try {
+ const stat = await file.stat();
+ if (!stat.isFile() || stat.size > MAX_IMAGE_BYTES)
+ throw Object.assign(new Error("Image input is too large"), {
+ errorCode: "IMAGE_INPUT_INVALID",
+ });
+ // A bounded read still holds if another process grows the file after stat.
+ const bytes = Buffer.alloc(Math.min(stat.size + 1, MAX_IMAGE_BYTES + 1));
+ let size = 0;
+ while (size < bytes.length) {
+ const read = await file.read(bytes, size, bytes.length - size, null);
+ if (!read.bytesRead) break;
+ size += read.bytesRead;
+ }
+ const data = bytes.subarray(0, size);
+ if (loadedBytes + size > 64 * 1024 * 1024)
+ throw Object.assign(new Error("Batch image inputs exceed 64 MB"), {
+ errorCode: "IMAGE_INPUT_TOO_LARGE",
+ });
+ loadedBytes += size;
+ return { bytes: data, ...generatedImageType(data) };
+ } finally {
+ await file.close();
+ }
+ };
+ return async (refs: string[]) => {
+ const images = await Promise.all(
+ refs.map((ref) => {
+ let image = cache.get(ref);
+ if (!image) {
+ image = read(ref);
+ cache.set(ref, image);
+ }
+ return image;
+ }),
+ );
+ if (images.reduce((size, image) => size + image.bytes.length, 0) > 32 * 1024 * 1024)
+ throw Object.assign(new Error("Image inputs exceed 32 MB"), {
+ errorCode: "IMAGE_INPUT_TOO_LARGE",
+ });
+ return images;
+ };
+}
diff --git a/apps/desktop/resources/skills/image-generation.md b/apps/desktop/resources/skills/image-generation.md
new file mode 100644
index 000000000..31590959c
--- /dev/null
+++ b/apps/desktop/resources/skills/image-generation.md
@@ -0,0 +1,59 @@
+---
+name: imagegen
+description: Generate or edit raster images, illustrations, photos, banners, and project assets with the configured image model. Supports reference images, edits of earlier results, variants, and batches. Prefer existing code-native tools for SVG/CSS edits.
+---
+
+# Image generation
+
+Use the desktop `GenerateImages` tool. The user selects its provider and model
+under Settings → AI → Image generation model; this is independent of the chat
+model. If ToolSearch is available and GenerateImages is not loaded, discover it
+there first. Do not install an SDK, run an API script, ask for a key in chat, or
+substitute the conversation model.
+
+## Prepare the request
+
+- Preserve the requested subject, composition, style, exact text, and constraints.
+ Add useful detail to a vague prompt without inventing additional deliverables.
+- For a project asset, include its intended use and required framing. Prefer the
+ existing SVG/CSS asset system for changes to code-native icons or diagrams.
+- For an edit, pass the source file paths as `images` (one to four per item).
+ Specify what changes and what must stay unchanged. For a follow-up edit, use
+ the previous result path. Inputs must be under the current project, session
+ scratch directory, or attachment store. Do not use remote URLs.
+- Editing uses OpenAI Images multipart requests and depends on the selected
+ model supporting that endpoint. Do not silently replace an edit with a fresh
+ generation if it fails. Mask painting is not a desktop UI feature.
+
+## Generate one image or a batch
+
+Call `GenerateImages` with `items`, where each item has `prompt` and optional
+`count` (default 1), plus optional `images` for edits. Use one item with `count` for variants of the same prompt;
+use separate items for different assets. A batch permits at most 10 images
+total. For a larger explicitly requested set, split it into bounded batches.
+Generate only the quantity the user asked for; do not add unrequested variants.
+
+Example: two cover variants and one distinct icon:
+
+```json
+{"items":[{"prompt":"Editorial cover: a ceramic cup on a quiet desk, warm daylight, no text","count":2},{"prompt":"A small raster illustration of a green leaf on a white background","count":1}]}
+```
+
+Generation may incur cost. Do not retry failed or timed-out items automatically,
+including after cancellation: the provider may already have processed them.
+Report partial success and wait for a user request before retrying. If no image
+model is configured, direct the user to Settings → AI; do not select one silently.
+
+## Deliver the result
+
+Results are ordered and contain a status and, for successes, a local image path.
+Show the successful images with Markdown image links and report failed items.
+The desktop also renders their previews directly from the tool result.
+
+Use available image inspection tools to check the result when possible. Do not
+claim to have visually inspected an image if you only received its file path.
+For project deliverables, copy the selected image into the requested project
+location using existing file/shell tools and update the consuming reference.
+Use a new filename unless replacement was requested. Preview-only images may
+remain in session storage. Report the final project paths, the prompt used,
+and any requested images that did not complete.
diff --git a/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx b/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx
new file mode 100644
index 000000000..a245f1e68
--- /dev/null
+++ b/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx
@@ -0,0 +1,125 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { AppSettings, ImageGenerationBinding, ProviderPublic } from "@pi-desktop/shared";
+import { api } from "../../lib/api";
+import { useAppStore } from "../../stores/app-store";
+import { Button, Input } from "../ui";
+import { AnchoredMenu } from "./AnchoredMenu";
+
+export function ImageGenerationModelRow({
+ settings,
+ providers,
+}: {
+ settings: AppSettings;
+ providers: ProviderPublic[];
+}) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const binding = settings.imageGeneration;
+ const provider = providers.find((entry) => entry.id === binding?.providerId);
+ const eligible = (entry: ProviderPublic) =>
+ entry.enabled &&
+ entry.authKind !== "oauth" &&
+ !!entry.baseUrl &&
+ (entry.hasSecret || entry.authKind === "none");
+ const valid =
+ provider &&
+ eligible(provider) &&
+ provider.models.some((model) => model.id === binding?.modelId);
+ const options = providers
+ .filter(eligible)
+ .flatMap((entry) => entry.models.map((model) => ({ provider: entry, model })))
+ .filter(({ provider: entry, model }) =>
+ `${entry.name} ${model.id} ${model.alias ?? ""}`
+ .toLowerCase()
+ .includes(query.trim().toLowerCase()),
+ );
+ const save = async (next: ImageGenerationBinding | null) => {
+ setBusy(true);
+ setError("");
+ try {
+ await api.setSettings({ ...(await api.getSettings()), imageGeneration: next });
+ useAppStore.setState({ settings: await api.getSettings() });
+ setOpen(false);
+ } catch {
+ setError(t("settings.imageModelSaveFailed"));
+ } finally {
+ setBusy(false);
+ }
+ };
+ return (
+ <div className="settings-panel">
+ <div className="settings-row">
+ <div className="settings-row-copy">
+ <div className="settings-row-title">{t("settings.imageModel")}</div>
+ <div className="settings-row-detail">
+ {binding
+ ? `${provider?.name ?? binding.providerId} / ${binding.modelId}`
+ : t("settings.imageModelUnset")}
+ </div>
+ {binding && !valid ? (
+ <div role="status">{t("settings.imageModelUnavailable")}</div>
+ ) : null}
+ {error ? <div role="alert">{error}</div> : null}
+ </div>
+ <AnchoredMenu
+ open={open}
+ onClose={() => setOpen(false)}
+ label={t("settings.imageModel")}
+ align="end"
+ menuClassName="model-default-menu"
+ trigger={(ref) => (
+ <Button
+ ref={ref}
+ variant="ghost"
+ disabled={busy}
+ aria-haspopup="listbox"
+ aria-expanded={open}
+ onClick={() => {
+ setQuery("");
+ setOpen(!open);
+ }}
+ >
+ {t("settings.changeDefaultModel")}
+ </Button>
+ )}
+ >
+ <Input
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder={t("settings.defaultModelSearch")}
+ aria-label={t("settings.defaultModelSearch")}
+ autoFocus
+ />
+ <ul className="model-default-list">
+ {options.map(({ provider: entry, model }) => (
+ <li key={`${entry.id}:${model.id}`}>
+ <button
+ type="button"
+ role="option"
+ className="model-default-option"
+ aria-selected={binding?.providerId === entry.id && binding.modelId === model.id}
+ disabled={busy}
+ onClick={() => void save({ providerId: entry.id, modelId: model.id })}
+ >
+ {entry.name} / {model.alias || model.id}
+ </button>
+ </li>
+ ))}
+ </ul>
+ {!options.length ? (
+ <div className="model-default-no-results">{t("settings.noModelMatches")}</div>
+ ) : null}
+ </AnchoredMenu>
+ {binding ? (
+ <Button variant="ghost" disabled={busy} onClick={() => void save(null)}>
+ {t("settings.clearImageModel")}
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/components/settings/ModelConfigPage.tsx b/apps/desktop/src/components/settings/ModelConfigPage.tsx
index dc9a342ca..8e98b7606 100644
--- a/apps/desktop/src/components/settings/ModelConfigPage.tsx
+++ b/apps/desktop/src/components/settings/ModelConfigPage.tsx
@@ -37,6 +37,7 @@ import {
displayedDefaultModelId,
} from "./default-model";
import { copyProviderConfiguration, type ProviderCopyDraft } from "./provider-copy";
+import { ImageGenerationModelRow } from "./ImageGenerationModelRow";
import { ProviderSetupDialog } from "./ProviderSetupDialog";
import { useProviderReorder } from "./useProviderReorder";
import { VendorAccountsSection } from "./VendorAccountsSection";
@@ -161,10 +162,14 @@ export function ModelConfigPage() {
/**
* Preserve the selected app default unless it was removed from the provider.
*/
- const afterSaved = async (saved: ProviderPublic, models: ModelBinding[]) => {
+ const afterSaved = async (saved: ProviderPublic, models: ModelBinding[], imageModelId?: string) => {
const firstModelId = models[0]?.id;
try {
- if (copyDraft) {
+ if (imageModelId) {
+ await api.setSettings({ ...(await api.getSettings()), imageGeneration: { providerId: saved.id, modelId: imageModelId } });
+ useAppStore.setState({ settings: await api.getSettings() });
+ showToast(t("settings.providerSaved"), { variant: "success" });
+ } else if (copyDraft) {
showToast(t("settings.providerSaved"), { variant: "success" });
} else if (!editingProvider) {
await api.setSettings({
@@ -421,6 +426,8 @@ export function ModelConfigPage() {
</div>
</section>
+ <ImageGenerationModelRow settings={settings} providers={providers} />
+
<section className="settings-card-block">
<div className="model-config-section-head">
<div className="settings-card-heading-line">
@@ -722,7 +729,8 @@ export function ModelConfigPage() {
provider={editingProvider}
initialDraft={copyDraft}
onClose={() => { setSetupFor(null); setCopyDraft(null); }}
- onSaved={(saved, models) => void afterSaved(saved, models)}
+ imageModelId={settings.imageGeneration?.providerId === editingProvider?.id ? settings.imageGeneration?.modelId : undefined}
+ onSaved={afterSaved}
/>
) : null}
</div>
diff --git a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx b/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
index b4a8872d8..33cf11ed4 100644
--- a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
+++ b/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
@@ -179,6 +179,8 @@ export function applyVisibleModelSelection(
}
export type ModelSelectionPanesProps = {
+ imageModelId?: string;
+ onImageModelChange?: (id: string) => void;
discovery: ProviderModelsState & { canReload?: boolean };
selection: ModelSelection;
/** Heading of the discovered list: a service's models, or an account's. */
@@ -207,6 +209,8 @@ export function ModelSelectionPanes({
busy = false,
onReload,
apiStyle,
+ imageModelId,
+ onImageModelChange,
}: ModelSelectionPanesProps) {
const { t } = useTranslation();
const { rows, models, publishedLevelsById, setModels } = selection;
@@ -598,6 +602,7 @@ export function ModelSelectionPanes({
id={advancedId}
hidden={!expanded}
>
+ {onImageModelChange ? <button type="button" className="provider-chosen-advanced-toggle" disabled={busy || imageModelId === binding.id} onClick={() => onImageModelChange(binding.id)}>{t(imageModelId === binding.id ? "settings.imageModelSelected" : "settings.setImageModel")}</button> : null}
<label className="provider-chosen-field">
<span className="provider-chosen-field-label">
{t("settings.modelAlias")}
diff --git a/apps/desktop/src/components/settings/ProviderSetupDialog.tsx b/apps/desktop/src/components/settings/ProviderSetupDialog.tsx
index e4ab383bf..dc1611a5d 100644
--- a/apps/desktop/src/components/settings/ProviderSetupDialog.tsx
+++ b/apps/desktop/src/components/settings/ProviderSetupDialog.tsx
@@ -120,7 +120,8 @@ export type ProviderSetupDialogProps = {
provider?: ProviderPublic | null;
initialDraft?: ProviderCopyDraft | null;
onClose: () => void;
- onSaved: (provider: ProviderPublic, models: ModelBinding[]) => void;
+ imageModelId?: string;
+ onSaved: (provider: ProviderPublic, models: ModelBinding[], imageModelId?: string) => void | Promise<void>;
};
export function ProviderSetupDialog({
@@ -128,8 +129,10 @@ export function ProviderSetupDialog({
initialDraft,
onClose,
onSaved,
+ imageModelId,
}: ProviderSetupDialogProps) {
const { t } = useTranslation();
+ const [imageModelDraft, setImageModelDraft] = useState<string | undefined>();
const editing = !!provider;
const apiKeyRef = useRef<HTMLInputElement>(null);
const [service, setService] = useState(() => initialDraft
@@ -284,7 +287,7 @@ export function ProviderSetupDialog({
headers,
...(apiKey ? { secretValue: apiKey } : {}),
});
- onSaved(result.provider ?? provider, persisted);
+ await onSaved(result.provider ?? provider, persisted, persisted.some((model) => model.id === imageModelDraft) ? imageModelDraft : undefined);
} else {
const result = await api.createProvider({
name: providerName,
@@ -299,7 +302,7 @@ export function ProviderSetupDialog({
apiStyle: resolvedApiStyle,
headers,
});
- onSaved(result.provider, persisted);
+ await onSaved(result.provider, persisted, persisted.some((model) => model.id === imageModelDraft) ? imageModelDraft : undefined);
}
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
@@ -529,6 +532,8 @@ export function ProviderSetupDialog({
busy={saving}
onReload={discovery.reload}
apiStyle={resolvedApiStyle}
+ imageModelId={imageModelDraft ?? imageModelId}
+ onImageModelChange={setImageModelDraft}
/>
</div>
</div>
diff --git a/apps/desktop/src/features/chat/transcript/GeneratedImages.tsx b/apps/desktop/src/features/chat/transcript/GeneratedImages.tsx
new file mode 100644
index 000000000..99a50e5e5
--- /dev/null
+++ b/apps/desktop/src/features/chat/transcript/GeneratedImages.tsx
@@ -0,0 +1,92 @@
+import { useTranslation } from "react-i18next";
+import type { UiMessage } from "@pi-desktop/shared";
+import { useReferencedImageDataUrl } from "../../../lib/use-referenced-image-data-url";
+import { toolResultPayload } from "../../../lib/tool-presentation";
+import { useOpenChatFileRef } from "../../../hooks/use-preview-target";
+import { useAppStore } from "../../../stores/app-store";
+import { Button } from "../../../components/ui";
+
+function ImageResult({
+ path,
+ index,
+ mimeType,
+}: {
+ path: string;
+ index: number;
+ mimeType?: string;
+}) {
+ const { t } = useTranslation();
+ const dataUrl = useReferencedImageDataUrl(path, mimeType);
+ const open = useOpenChatFileRef();
+ return (
+ <figure>
+ <button
+ type="button"
+ className="generated-image-preview"
+ onClick={() => void open(path)}
+ aria-label={t("settings.generatedImage", { index: index + 1 })}
+ >
+ {dataUrl ? (
+ <img src={dataUrl} alt={t("settings.generatedImage", { index: index + 1 })} />
+ ) : (
+ <span>{t("settings.imagePreviewUnavailable")}</span>
+ )}
+ </button>
+ </figure>
+ );
+}
+
+export function GeneratedImages({ message }: { message: UiMessage }) {
+ const { t } = useTranslation();
+ if (message.toolName !== "GenerateImages") return null;
+ const payload = toolResultPayload(message);
+ const record =
+ payload && typeof payload === "object" ? (payload as Record<string, unknown>) : null;
+ const results =
+ record?.kind === "generated-images" && Array.isArray(record.results) ? record.results : [];
+ const needsSetup =
+ record?.kind === "image-generation-error" &&
+ [
+ "IMAGE_NOT_CONFIGURED",
+ "IMAGE_MODEL_UNAVAILABLE",
+ "IMAGE_AUTH_FAILED",
+ "IMAGE_AUTH_UNSUPPORTED",
+ ].includes(String(record.errorCode));
+ return (
+ <div className="generated-images" aria-label={t("settings.imageModel")}>
+ {needsSetup ? (
+ <div>
+ <p>{t("settings.imageModelSetupHint")}</p>
+ <Button
+ variant="ghost"
+ onClick={() => {
+ const state = useAppStore.getState();
+ state.setSettingsTab("ai");
+ state.setSettingsAnchor("settings.imageModel");
+ state.setPage("settings");
+ }}
+ >
+ {t("settings.configureImageModel")}
+ </Button>
+ </div>
+ ) : null}
+ {results.map((raw, index) => {
+ if (!raw || typeof raw !== "object") return null;
+ const item = raw as Record<string, unknown>;
+ return item.status === "succeeded" && typeof item.path === "string" ? (
+ <ImageResult
+ key={index}
+ path={item.path}
+ index={index}
+ mimeType={typeof item.mimeType === "string" ? item.mimeType : undefined}
+ />
+ ) : (
+ <p key={index} role="status">
+ {t("settings.imageGenerationFailed", { index: index + 1 })}{" "}
+ {typeof item.errorCode === "string" ? item.errorCode : ""}
+ </p>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/features/chat/transcript/ToolRow.tsx b/apps/desktop/src/features/chat/transcript/ToolRow.tsx
index de940394d..e483d038d 100644
--- a/apps/desktop/src/features/chat/transcript/ToolRow.tsx
+++ b/apps/desktop/src/features/chat/transcript/ToolRow.tsx
@@ -1,3 +1,5 @@
+import { GeneratedImages } from "./GeneratedImages";
+import "../../../styles/generated-images.css";
import {
Fragment,
memo,
@@ -523,6 +525,7 @@ export const ToolRow = memo(function ToolRow({
<ToolDetailBlocks blocks={blocks} plain={runHead} />
</div>
) : null}
+ <GeneratedImages message={message} />
{inlineOpen && delegate ? (
<SubagentRunRows
run={delegate}
diff --git a/apps/desktop/src/lib/settings-search.ts b/apps/desktop/src/lib/settings-search.ts
index 808ceeaa4..948cd9cef 100644
--- a/apps/desktop/src/lib/settings-search.ts
+++ b/apps/desktop/src/lib/settings-search.ts
@@ -85,6 +85,7 @@ export const SETTINGS_NAV: SettingsNavEntry[] = [
"settings.permissionModeAcceptEdits",
"settings.permissionModeAuto",
"settings.defaultsTitle",
+ "settings.imageModel",
"settings.mode",
"settings.commandShell",
"settings.linkOpenTarget",
diff --git a/apps/desktop/src/styles/generated-images.css b/apps/desktop/src/styles/generated-images.css
new file mode 100644
index 000000000..e3393020d
--- /dev/null
+++ b/apps/desktop/src/styles/generated-images.css
@@ -0,0 +1,23 @@
+.generated-images {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-3);
+ max-width: 100%;
+}
+.generated-images figure { margin: 0; max-width: 100%; }
+.generated-image-preview {
+ display: block;
+ max-width: 100%;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ cursor: pointer;
+}
+.generated-image-preview img {
+ display: block;
+ width: auto;
+ height: auto;
+ max-width: min(100%, 320px);
+ max-height: 320px;
+ object-fit: contain;
+}
diff --git a/apps/desktop/test/image-generation.test.mjs b/apps/desktop/test/image-generation.test.mjs
new file mode 100644
index 000000000..66e2d3acd
--- /dev/null
+++ b/apps/desktop/test/image-generation.test.mjs
@@ -0,0 +1,126 @@
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { createServer } from "node:http";
+import { register } from "node:module";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import test from "node:test";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { createImageGenerationTool } = await import(
+ "../electron/main/services/image-generation-service.ts"
+);
+const { imageInputLoader } = await import("../electron/main/services/image-inputs.ts");
+const png = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9mQAAAAASUVORK5CYII=",
+ "base64",
+);
+
+test("configure, batch generate, edit a result, replace binding, clear; files survive service recreation", async (t) => {
+ const dataDir = await mkdtemp(join(tmpdir(), "pi-images-test-"));
+ t.after(() => rm(dataDir, { recursive: true, force: true }));
+ const requests = [];
+ const server = createServer(async (request, response) => {
+ let body = "";
+ for await (const chunk of request) body += chunk.toString("latin1");
+ requests.push({ url: request.url, body, authorization: request.headers.authorization });
+ response.setHeader("Content-Type", "application/json");
+ response.end(JSON.stringify({ data: [{ b64_json: png.toString("base64") }] }));
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ t.after(() => new Promise((resolve) => server.close(resolve)));
+ let settings = {
+ defaultModelId: "chat",
+ defaultProviderId: "chat-provider",
+ imageGeneration: { providerId: "image-provider", modelId: "image-one" },
+ };
+ const host = {
+ call: async (method) => {
+ if (method === "settings.get") return structuredClone(settings);
+ if (method === "providers.get")
+ return {
+ provider: {
+ id: "image-provider",
+ enabled: true,
+ authKind: "api_key_and_base_url",
+ models: [{ id: "image-one" }, { id: "image-two" }],
+ baseUrl: `http://127.0.0.1:${server.address().port}`,
+ },
+ };
+ if (method === "providers.getSecret") return { value: "fixture-key" };
+ if (method === "session.getScratchPath") return { path: join(dataDir, "scratch", "session") };
+ if (method === "session.get") return { session: {} };
+ throw new Error(method);
+ },
+ };
+ const options = { dataDir, getHost: () => host };
+ const call = (args) =>
+ createImageGenerationTool(options)({
+ sessionId: "session",
+ toolCallId: "call",
+ args,
+ signal: new AbortController().signal,
+ });
+ const batch = await call({ items: [{ prompt: "cover", count: 2 }, { prompt: "icon" }] });
+ assert.equal(batch.ok, true);
+ assert.equal(batch.content.results.length, 3);
+ for (const image of batch.content.results) assert.deepEqual(await readFile(image.path), png);
+ assert.ok(
+ requests.every(
+ (request) =>
+ request.url === "/v1/images/generations" && request.authorization === "Bearer fixture-key",
+ ),
+ );
+ const original = batch.content.results[0].path;
+ const edited = await call({ items: [{ prompt: "make it green", images: [original], count: 2 }] });
+ assert.equal(edited.content.results.length, 2);
+ assert.ok(
+ requests
+ .slice(3)
+ .every(
+ (request) => request.url === "/v1/images/edits" && request.body.includes('name="image"'),
+ ),
+ );
+ assert.notEqual(edited.content.results[0].path, original);
+ assert.deepEqual(await readFile(original), png);
+ settings.imageGeneration = { providerId: "image-provider", modelId: "image-two" };
+ await call({ items: [{ prompt: "replacement" }] });
+ assert.equal(JSON.parse(requests.at(-1).body).model, "image-two");
+ settings.imageGeneration = null;
+ assert.equal((await call({ items: [{ prompt: "unset" }] })).errorCode, "IMAGE_NOT_CONFIGURED");
+ assert.equal(requests.length, 6);
+ assert.equal(settings.defaultModelId, "chat");
+});
+
+test("edit inputs reject outside paths, traversal and non-image files", async (t) => {
+ const dataDir = await mkdtemp(join(tmpdir(), "pi-image-input-"));
+ t.after(() => rm(dataDir, { recursive: true, force: true }));
+ const scratchPath = join(dataDir, "scratch", "s");
+ await mkdir(scratchPath, { recursive: true });
+ await writeFile(join(dataDir, "outside.png"), png);
+ await writeFile(join(scratchPath, "fake.png"), "not an image");
+ const load = imageInputLoader({ dataDir, scratchPath });
+ await assert.rejects(load([join(dataDir, "outside.png")]), /outside/);
+ await assert.rejects(load(["../../outside.png"]), /outside/);
+ await assert.rejects(load(["fake.png"]), /IMAGE_INVALID_CONTENT/);
+});
+
+test("the default imagegen skill is discoverable and loads in an ordinary session", async () => {
+ const previous = globalThis.__dirname;
+ globalThis.__dirname = fileURLToPath(new URL("../electron/main/", import.meta.url));
+ try {
+ const { builtinSkills, loadBuiltinSkillBody } = await import(
+ "../electron/main/builtin-skills.ts"
+ );
+ const skills = builtinSkills({});
+ assert.equal(skills.find((skill) => skill.id === "pi-desktop/imagegen")?.name, "imagegen");
+ assert.ok(!skills.some((skill) => skill.id === "pi-desktop/plugin-development"));
+ const body = loadBuiltinSkillBody("pi-desktop/imagegen").body;
+ assert.match(body, /GenerateImages/);
+ assert.match(body, /previous result path/);
+ assert.match(body, /Do not retry/);
+ assert.equal(loadBuiltinSkillBody("../../outside"), null);
+ } finally {
+ globalThis.__dirname = previous;
+ }
+});
diff --git a/apps/desktop/test/plugin-skills.test.mjs b/apps/desktop/test/plugin-skills.test.mjs
index 0b5ac0166..bbd50a64d 100644
--- a/apps/desktop/test/plugin-skills.test.mjs
+++ b/apps/desktop/test/plugin-skills.test.mjs
@@ -105,7 +105,7 @@ test("the built-in plugin skill only activates for plugin workspaces", () => {
assert.match(builtinSrc, /isPluginWorkspace/);
assert.match(builtinSrc, /schemaVersion.*number/s);
assert.match(builtinSrc, /pluginPaths\.some/);
- assert.match(builtinSrc, /if \(!isPluginWorkspace\(input\.workspacePath, input\.pluginPaths\)\) return \[\]/);
+ assert.match(builtinSrc, /if \(isPluginWorkspace\(input\.workspacePath, input\.pluginPaths\)\) ids\.push\(PLUGIN_DEV_SKILL_ID\)/);
assert.match(mainSrc, /builtinSkills\(\{/);
});
diff --git a/crates/host-core/src/permissions.rs b/crates/host-core/src/permissions.rs
index 87506e595..475b9387f 100644
--- a/crates/host-core/src/permissions.rs
+++ b/crates/host-core/src/permissions.rs
@@ -127,7 +127,7 @@ impl PermissionManager {
pub fn tool_risk_with_declared(tool_name: &str, declared: Option<&str>) -> Risk {
match tool_name {
"Read" | "Glob" | "Grep" | "ScheduledTaskList" => Risk::Low,
- "Write" | "Edit" | "Bash" => Risk::High,
+ "Write" | "Edit" | "Bash" | "GenerateImages" => Risk::High,
name if name.starts_with("plugin_") => match declared {
Some("low") => Risk::Low,
Some("high") => Risk::High,
@@ -736,3 +736,43 @@ mod tests {
);
}
}
+
+#[cfg(test)]
+mod image_generation_tests {
+ use super::*;
+
+ #[test]
+ fn image_generation_requires_approval_and_is_not_plan_safe() {
+ assert!(matches!(
+ PermissionManager::tool_risk_with_declared("GenerateImages", None),
+ Risk::High
+ ));
+ let manager = PermissionManager::default();
+ let grants = HashMap::new();
+ for mode in ["ask", "accept-edits"] {
+ assert!(manager
+ .evaluate_auto_with_permission_mode("s", "GenerateImages", "agent", mode, &grants)
+ .is_none());
+ }
+ assert_eq!(
+ manager.evaluate_auto_with_permission_mode(
+ "s",
+ "GenerateImages",
+ "plan",
+ "auto",
+ &grants
+ ),
+ Some(PermissionDecision::Deny)
+ );
+ assert_eq!(
+ manager.evaluate_auto_with_permission_mode(
+ "s",
+ "GenerateImages",
+ "goal",
+ "auto",
+ &grants
+ ),
+ Some(PermissionDecision::Deny)
+ );
+ }
+}
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index ef448b811..837ef9ab9 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -685,6 +685,21 @@ fn validate_settings_value(value: &Value) -> Result<(), JsonRpcError> {
let Some(object) = value.as_object() else {
return Ok(());
};
+ if let Some(binding) = object.get("imageGeneration").filter(|v| !v.is_null()) {
+ for (key, max) in [("providerId", 128), ("modelId", 256)] {
+ if !binding
+ .get(key)
+ .and_then(Value::as_str)
+ .is_some_and(|s| !s.trim().is_empty() && s.len() <= max)
+ {
+ return Err(rpc_err(
+ 1002,
+ "invalid image generation binding",
+ "INVALID_PARAMS",
+ ));
+ }
+ }
+ }
if let Some(template_value) = object.get("promptEnhancementUserTemplate") {
if let Some(message) =
prompt_enhancement_template_error("promptEnhancementUserTemplate", template_value)
@@ -1096,7 +1111,7 @@ fn bash_cancellation_requested(receiver: &Option<tokio::sync::watch::Receiver<bo
}
async fn clear_bash_cancellation(state: &Arc<Mutex<AppState>>, p: &ToolsExecuteParams) {
- if p.tool_name != "Bash" {
+ if !matches!(p.tool_name.as_str(), "Bash" | "GenerateImages") {
return;
}
let mut st = state.lock().await;
@@ -3204,7 +3219,8 @@ async fn handle_request(
// Register before permission evaluation so tools.abort can cancel
// an approval wait as well as an already-spawned process.
- let cancellation_receiver = if p.tool_name == "Bash" {
+ let cancellation_receiver = if matches!(p.tool_name.as_str(), "Bash" | "GenerateImages")
+ {
let mut st = state.lock().await;
match st.register_bash_cancellation(&p.session_id, &p.tool_call_id) {
Ok(receiver) => Some(receiver),
@@ -8606,3 +8622,25 @@ mod tests {
assert_eq!(st.plugins.locale(), "en-US");
}
}
+
+#[cfg(test)]
+mod image_generation_settings_tests {
+ use super::*;
+ #[test]
+ fn validates_optional_image_binding() {
+ for value in [
+ json!({}),
+ json!({"imageGeneration": null}),
+ json!({"imageGeneration": {"providerId": "p", "modelId": "image"}}),
+ ] {
+ assert!(validate_settings_value(&value).is_ok());
+ }
+ for value in [
+ json!(false),
+ json!({}),
+ json!({"providerId": "p", "modelId": " "}),
+ ] {
+ assert!(validate_settings_value(&json!({"imageGeneration": value})).is_err());
+ }
+ }
+}
diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rs
index 58211d47c..0479585e2 100644
--- a/crates/host-core/src/tools/mod.rs
+++ b/crates/host-core/src/tools/mod.rs
@@ -1068,6 +1068,9 @@ pub async fn execute_tool_with_path_access(
}
}
let result: Result<Value, hashline::ToolError> = match tool_name {
+ // Authorize the desktop-owned image request through the normal host gate.
+ // Only the trusted desktop runner performs the external call.
+ "GenerateImages" => Ok(serde_json::json!({ "authorized": true })),
"Read" => tool_read(
workspace,
scratch,
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 917bd6cb0..ac6398788 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -331,3 +331,4 @@ Each ADR includes:
| turn-process-and-thinking-display | [Turn process and thinking presentation](turn-process-and-thinking-display.md) | Accepted |
| provider-display-order | [Provider display order](provider-display-order.md) | Accepted |
| provider-system-certificates | [Desktop sidecar uses OS-trusted certificates](provider-system-certificates.md) | Accepted |
+| image-generation-capability | [Image generation as a configured Agent capability](image-generation-capability.md) | Accepted |
diff --git a/docs/adr/image-generation-capability.md b/docs/adr/image-generation-capability.md
new file mode 100644
index 000000000..ba33fd25f
--- /dev/null
+++ b/docs/adr/image-generation-capability.md
@@ -0,0 +1,41 @@
+# ADR: Image generation as a configured Agent capability
+
+- Status: Accepted
+- Date: 2026-09-21
+- Related: ADR 0281, ADR 0101, ADR 0172; [image generation spec](../spec/03-runtime/21-image-generation.md)
+
+## Context
+
+The desktop understands image input and previews but has no image production
+path. Users need one selectable image model, conversational generation/editing,
+and batches without changing their default chat model. A Skill alone cannot
+execute image requests. Pure image endpoints cannot be treated as chat adapters.
+
+## Decision
+
+Keep a separate optional settings binding referencing existing provider credentials.
+Expose one Agent tool plus a bundled, lazily loaded imagegen skill. Use an independent
+OpenAI Images adapter and batch scheduler in agent-runtime; the desktop service
+coordinates host-owned settings/credentials, contained source files and saved output.
+Renderer code handles configuration, previews and navigation only.
+
+The existing local-tool shortcut does not perform host permission checks. For this
+billable tool, the bridge must obtain host-core authorization through `tools.execute`
+before invoking the local service. Host-core never performs the HTTP call; its
+result is authorization, while the sidecar result records actual generated files.
+Local tools gain an abort signal so this path can stop requests on cancellation,
+timeout and process loss. Existing tools retain their deadlines and behavior.
+
+## Alternatives and consequences
+
+- An independent image workspace would duplicate conversation/history ownership;
+ use existing chat and previews first.
+- A shell/API-only skill would bypass model settings and require scripts to handle
+ credentials, files and retries. The skill instead calls the bounded host tool.
+- A broad multi-protocol framework is unnecessary for the requested single Images
+ protocol. Generation and multipart editing share its adapter and scheduler.
+- Optional settings preserve existing stored data and conversation defaults. No
+ schema migration, plugin API change or direct renderer credential access occurs.
+- Partial results remain useful; no automatic retry avoids duplicate paid work.
+ Upstream model support and billing remain provider responsibilities.
+- Headless hosts without the desktop image runner do not perform image requests.
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index 2af8ccf0e..91c7c7b33 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -614,3 +614,10 @@ Naming:
- command allowlist / denylist
- dry-run mode
- apply patches after preview
+
+## Image generation and editing
+
+`GenerateImages` is a high-risk Agent-only capability, authorized by host-core
+before the trusted desktop executes the request. Plan/Goal remain denied even
+under Auto. See [image generation](21-image-generation.md) for cancellation,
+limits and result semantics.
diff --git a/docs/spec/03-runtime/13-model-catalog-and-selection.md b/docs/spec/03-runtime/13-model-catalog-and-selection.md
index 540176f35..f05863ab9 100644
--- a/docs/spec/03-runtime/13-model-catalog-and-selection.md
+++ b/docs/spec/03-runtime/13-model-catalog-and-selection.md
@@ -538,3 +538,10 @@ same model to the check mark, the toggle and the duplicate guard.
- [ ] compact limit text never reads above the published value, keeps the
neighbouring 1M-line windows apart (`1M` / `1.05M` / `1.1M`), and never
renders a `K` mantissa at or above 1000
+
+## Image model binding
+
+The default conversation model has a separate **Image generation model** row below
+it. Model Advanced can select that unique binding; provider form Save commits it,
+Cancel discards it, and replacing it leaves the conversation default unchanged.
+See [image generation and editing](21-image-generation.md) for the tool and batch contract.
diff --git a/docs/spec/03-runtime/21-image-generation.md b/docs/spec/03-runtime/21-image-generation.md
new file mode 100644
index 000000000..00ae77215
--- /dev/null
+++ b/docs/spec/03-runtime/21-image-generation.md
@@ -0,0 +1,77 @@
+# Image generation and editing
+
+The desktop exposes one optional `AppSettings.imageGeneration` binding with
+`providerId` and `modelId`. `null` clears it; absent means unconfigured. Host-core
+validates and persists it through the existing settings store. No schema bump
+is needed. The binding is independent of the conversation default and references
+an existing enabled API-key or no-auth provider and one of its configured models.
+
+## Configuration
+
+Model Advanced offers **Set as image model**. A draft selection only takes effect
+when the provider form saves; Cancel leaves settings unchanged. Saving a provider
+as an image model does not replace the default conversation model. Below the
+default model row, **Image generation model** displays the binding and offers
+searchable replacement and Clear. OAuth accounts are not eligible. Missing,
+disabled or removed bindings remain visible as unavailable; there is no fallback.
+
+## Agent contract
+
+`GenerateImages({items: [{prompt, count?, images?}]})` is an Agent-mode tool.
+`count` defaults to 1. Both distinct prompts and same-prompt variants are supported,
+with 1–10 output images total. An optional `images` array supplies 1–4 local source
+files per item for editing; a previous generated path supports iterative edits.
+Prompt length is bounded at 32,000 characters. Unsupported or excessive input is
+rejected rather than truncated. Plan and Goal cannot execute the tool.
+
+The bundled `pi-desktop/imagegen` skill is discoverable in ordinary sessions and
+loads through the existing Skill tool. It teaches prompting, batches, reference
+edits, preserving originals, partial-failure handling and project asset delivery.
+It does not grant permission or carry credentials.
+
+The trusted desktop bridge first calls host-core `tools.execute` with the same
+identity, arguments and permission scope. Host-core applies the existing high-risk
+tool policy and returns authorization only. The bridge executes the image service
+only after approval. The host authorization audit is distinct from the actual
+sidecar tool result. Runtime cancellation reaches both pending approval and the
+network request; host loss or sidecar disposal aborts local work.
+
+## OpenAI Images adapter
+
+Only OpenAI-compatible Images is supported. A root base URL acquires `/v1`; an
+explicit path prefix is retained. Generation uses `POST images/generations` with
+`model`, `prompt`, `n: 1`. Editing uses `POST images/edits`, multipart image files,
+the prompt, model and `n: 1`. No browser mask editor is included. A configured
+service may implement generation without editing; its error is reported without
+silently switching to generation or another model.
+
+Each batch snapshots the binding and provider before dispatch, uses two workers,
+and returns results in input order. Each output has a 180-second request budget.
+Requests are never automatically retried. Authentication failure stops queued
+work. Cancellation stops queued work and aborts active HTTP; it cannot promise the
+upstream provider stopped processing or billing. Completed output files survive.
+
+Responses accept exactly one Base64 image or HTTPS image URL per request. JSON and
+download bodies are bounded; image files are capped at 16 MiB and restricted to
+PNG, JPEG and WebP signatures. Downloads use checked, pinned public DNS addresses,
+reject redirects and private destinations, and never receive provider headers.
+Input edits accept the session project, that session's scratch directory and the
+attachment store after realpath containment. Each edit input set is capped at
+32 MiB, with a 64 MiB input cache budget for the batch. Credentials remain outside the renderer and tool results.
+
+## Results and recovery
+
+Each result records index, status (`succeeded`, `failed`, `cancelled`), successful
+path/MIME type or a safe error code. New files get unique names in session scratch;
+editing never overwrites its source. The tool result and transcript retain file
+references, not Base64. Existing bounded image reads and file viewers serve previews.
+Successful images and per-item failures render even when only part of a batch
+completed. Missing configuration returns a structured error and a Settings → AI
+navigation action. The same references render after session reload/restart.
+
+Validation: `node scripts/e2e-image-generation.mjs` covers host/stdio/HTTP/storage;
+`node scripts/e2e-image-generation-ui.mjs` covers real React/Chromium interactions
+with an API-boundary fixture. Unit/service tests cover limits, cancellation,
+partial failures, authentication, timeout, unsafe paths, and bounded downloads.
+Live verification is opt-in via `scripts/test-image-generation-live.mjs`, limited
+to one generation plus one edit and never a default test command.
diff --git a/docs/spec/03-runtime/README.md b/docs/spec/03-runtime/README.md
index 3b2ded8df..e8b945e50 100644
--- a/docs/spec/03-runtime/README.md
+++ b/docs/spec/03-runtime/README.md
@@ -22,3 +22,5 @@
| [18-line-anchored-edit-contract.md](18-line-anchored-edit-contract.md) | Line-anchored Edit contract |
| [19-remote-agent-control-protocol.md](19-remote-agent-control-protocol.md) | Remote Agent Control Protocol |
| [20-speech.md](20-speech.md) | Host speech (ASR/TTS) |
+
+- [Image generation and editing](21-image-generation.md)
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 010f2ee41..4057bb062 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -58,8 +58,8 @@
- Document every user-visible and protocol-visible behavior that MVP must verify.
- Provide a scenario catalog that maps to acceptance criteria (A–H) and milestones (M1–M6).
- Serve as the traceability backbone: scenario ID ↔ acceptance criterion ↔ spec.
-- Define the required E2E gate for code-bearing changes on the integrated
- `main` that precedes the pull request.
+- Define the required E2E gate for code-bearing task candidates containing the
+ latest `origin/main`, before the pull request; do not merge into local `main`.
- Keep validation evidence tied to the commit the gate ran on, plus any later
commit that changes the landed executable content.
@@ -14163,3 +14163,25 @@ the latest destination. These assertions measure work counts, not device FPS.
- **Milestone**: Maintenance.
- **Status**: Covered by the existing HTTP client integration fixture and a
focused component-render validation; no live IDA process required.
+
+### E2E-IMAGE-generation-and-editing
+
+- **Preconditions:** Built task candidate containing latest origin/main; isolated
+ host data directory, local image HTTP fixture, no production credentials.
+- **Steps:** Choose a model in Advanced, cancel and verify no change; save, replace
+ and clear it through Settings. Generate same-prompt variants and distinct images,
+ edit a generated image, inspect partial failures, then restart the host/session.
+ Attempt the tool in a durable Plan session and verify no HTTP request occurs.
+- **Expected:** One image binding persists without changing the chat default;
+ generated files, edit sources and transcript references survive restart.
+ Images render in chat; unconfigured errors navigate to AI settings.
+- **Specs:** 03-runtime/21-image-generation; 03-runtime/13-model-catalog-and-selection.
+- **Acceptance:** Configured image generation/editing, safe cancellation and persistence.
+- **Milestone:** Post-MVP.
+- **Status:** Automated by `scripts/e2e-image-generation.mjs` and
+ `scripts/e2e-image-generation-ui.mjs`; backend test uses real Rust/stdio/HTTP/files,
+ UI test uses real Chromium and production components with API-boundary fixtures.
+
+| Scenario | Acceptance | Specification | Automation |
+| --- | --- | --- | --- |
+| E2E-IMAGE-generation-and-editing | Image capability and recovery | 03-runtime/21-image-generation | Host and UI suites above |
diff --git a/package.json b/package.json
index cea4a8a9e..3b2d1ab2e 100644
--- a/package.json
+++ b/package.json
@@ -31,6 +31,7 @@
"test:e2e:composer-paste": "node scripts/e2e-composer-paste.mjs",
"test:e2e:transcript": "node scripts/e2e-transcript-render.mjs",
"test:e2e:transcript-disclosure": "node scripts/e2e-transcript-disclosure-anchor.mjs",
+ "test:e2e:images": "node scripts/e2e-image-generation.mjs && node scripts/e2e-image-generation-ui.mjs",
"test:e2e:provider-order": "node scripts/e2e-provider-order.mjs",
"test:e2e:provider-api-style": "node scripts/e2e-provider-api-style.mjs",
"test:e2e:oauth-retry": "node --test apps/desktop/test/anthropic-oauth-retry.test.mjs",
diff --git a/packages/agent-runtime/src/image-generation/download.ts b/packages/agent-runtime/src/image-generation/download.ts
new file mode 100644
index 000000000..523fce36e
--- /dev/null
+++ b/packages/agent-runtime/src/image-generation/download.ts
@@ -0,0 +1,130 @@
+import { lookup } from "node:dns/promises";
+import { isIP } from "node:net";
+import { Agent, fetch as fetchPinned } from "undici";
+
+export const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
+export function imageError(code: string): Error & { errorCode: string } {
+ return Object.assign(new Error(code), { errorCode: code });
+}
+
+export async function boundedBytes(
+ response: Pick<Response, "headers" | "body">,
+ max: number,
+): Promise<Uint8Array> {
+ if (Number(response.headers.get("content-length")) > max) {
+ await response.body?.cancel();
+ throw imageError("IMAGE_TOO_LARGE");
+ }
+ if (!response.body) throw imageError("IMAGE_EMPTY_RESPONSE");
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ try {
+ while (true) {
+ const part = await reader.read();
+ if (part.done) break;
+ size += part.value.length;
+ if (size > max) throw imageError("IMAGE_TOO_LARGE");
+ chunks.push(part.value);
+ }
+ return Buffer.concat(chunks);
+ } finally {
+ await reader.cancel();
+ reader.releaseLock();
+ }
+}
+
+/** Deny non-public destinations, including mapped IPv6 and cloud metadata. */
+export function publicImageAddress(address: string): boolean {
+ if (isIP(address) === 4) {
+ const [a, b, c] = address.split(".").map(Number);
+ return !(
+ a === 0 ||
+ a === 10 ||
+ a === 127 ||
+ a >= 224 ||
+ (a === 100 && b >= 64 && b <= 127) ||
+ (a === 169 && b === 254) ||
+ (a === 172 && b >= 16 && b <= 31) ||
+ (a === 192 && (b === 168 || b === 0 || (b === 88 && c === 99))) ||
+ (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100))) ||
+ (a === 203 && b === 0 && c === 113)
+ );
+ }
+ if (isIP(address) === 6) {
+ const lower = address.toLowerCase();
+ return (
+ /^[23][0-9a-f]{3}:/.test(lower) && !lower.startsWith("2001:") && !lower.startsWith("2002:")
+ );
+ }
+ return false;
+}
+
+/** Pin the checked DNS answer to the connection; never forward provider headers. */
+export async function downloadGeneratedImage(
+ raw: string,
+ signal: AbortSignal,
+): Promise<Uint8Array> {
+ let url: URL;
+ try {
+ url = new URL(raw);
+ } catch {
+ throw imageError("IMAGE_INVALID_URL");
+ }
+ if (
+ url.protocol !== "https:" ||
+ url.username ||
+ url.password ||
+ (url.port && url.port !== "443")
+ ) {
+ throw imageError("IMAGE_INVALID_URL");
+ }
+ const hostname = url.hostname.replace(/^\[|\]$/g, "");
+ const answers = await lookup(hostname, { all: true });
+ signal.throwIfAborted();
+ if (!answers.length || answers.some((answer) => !publicImageAddress(answer.address)))
+ throw imageError("IMAGE_UNSAFE_URL");
+ const address = answers[0];
+ const dispatcher = new Agent({
+ connect: {
+ lookup: (_name, options, callback) => {
+ if (options.all) callback(null, [address]);
+ else callback(null, address.address, address.family);
+ },
+ },
+ });
+ try {
+ const response = await fetchPinned(url, { signal, redirect: "error", dispatcher });
+ if (!response.ok) throw imageError("IMAGE_DOWNLOAD_FAILED");
+ return await boundedBytes(response as unknown as Response, MAX_IMAGE_BYTES);
+ } finally {
+ await dispatcher.destroy();
+ }
+}
+
+export function generatedImageType(bytes: Uint8Array): { mimeType: string; extension: string } {
+ const data = Buffer.from(bytes);
+ if (data.length > MAX_IMAGE_BYTES) throw imageError("IMAGE_TOO_LARGE");
+ if (
+ data.length >= 24 &&
+ data.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) &&
+ data.toString("ascii", 12, 16) === "IHDR"
+ )
+ return { mimeType: "image/png", extension: "png" };
+ if (
+ data.length > 4 &&
+ data[0] === 255 &&
+ data[1] === 216 &&
+ data[2] === 255 &&
+ data[data.length - 2] === 255 &&
+ data[data.length - 1] === 217
+ )
+ return { mimeType: "image/jpeg", extension: "jpg" };
+ if (
+ data.length >= 16 &&
+ data.toString("ascii", 0, 4) === "RIFF" &&
+ data.toString("ascii", 8, 12) === "WEBP"
+ )
+ return { mimeType: "image/webp", extension: "webp" };
+ throw imageError("IMAGE_INVALID_CONTENT");
+}
diff --git a/packages/agent-runtime/src/image-generation/image-generation.test.ts b/packages/agent-runtime/src/image-generation/image-generation.test.ts
new file mode 100644
index 000000000..127c5865d
--- /dev/null
+++ b/packages/agent-runtime/src/image-generation/image-generation.test.ts
@@ -0,0 +1,171 @@
+import { describe, expect, it, vi } from "vitest";
+import { generateImageBatch, generateOneImage, imageGenerationUrl } from "./index.js";
+import { publicImageAddress, generatedImageType, boundedBytes } from "./download.js";
+import { imageGenerationPrompts, parseImageGenerationBinding } from "@pi-desktop/shared";
+
+const png =
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9mQAAAAASUVORK5CYII=";
+const endpoint = { baseUrl: "https://example.com", modelId: "image-model", apiKey: "test-only" };
+const response = () => Response.json({ data: [{ b64_json: png }] });
+const save = async (_image: unknown, index: number) => `/scratch/image-${index}.png`;
+
+describe("image generation", () => {
+ it("normalizes root/versioned base URLs without doubling the version", () => {
+ expect(imageGenerationUrl(endpoint.baseUrl)).toBe("https://example.com/v1/images/generations");
+ expect(imageGenerationUrl("https://example.com/gateway/v1/")).toBe(
+ "https://example.com/gateway/v1/images/generations",
+ );
+ expect(() => imageGenerationUrl("https://user:[email protected]")).toThrow();
+ });
+ it("validates binding and both batch forms without truncation", () => {
+ expect(parseImageGenerationBinding(null)).toBeNull();
+ expect(
+ imageGenerationPrompts({
+ items: [
+ { prompt: "a", images: [] },
+ { prompt: "b", images: null },
+ ],
+ }),
+ ).toEqual(["a", "b"]);
+ expect(() => parseImageGenerationBinding({ modelId: "m" })).toThrow();
+ expect(imageGenerationPrompts({ items: [{ prompt: "a", count: 2 }, { prompt: "b" }] })).toEqual(
+ ["a", "a", "b"],
+ );
+ for (const count of [0, 1.5, 11, "2"])
+ expect(() => imageGenerationPrompts({ items: [{ prompt: "a", count }] })).toThrow();
+ expect(() =>
+ imageGenerationPrompts({
+ items: [
+ { prompt: "a", count: 6 },
+ { prompt: "b", count: 5 },
+ ],
+ }),
+ ).toThrow();
+ });
+ it("uses the configured model, key and headers without chat protocol fields", async () => {
+ const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(response());
+ const image = await generateOneImage(
+ { ...endpoint, headers: { "X-Test": "custom" } },
+ "draw",
+ new AbortController().signal,
+ fetchImpl,
+ );
+ const [url, init] = fetchImpl.mock.calls[0];
+ expect(url).toBe("https://example.com/v1/images/generations");
+ expect(JSON.parse(String(init?.body))).toEqual({ model: "image-model", prompt: "draw", n: 1 });
+ expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer test-only");
+ expect(new Headers(init?.headers).get("X-Test")).toBe("custom");
+ expect(init?.redirect).toBe("error");
+ expect(image.mimeType).toBe("image/png");
+ });
+ it("limits concurrency to two and preserves input order through partial failure", async () => {
+ const releases: Array<() => void> = [];
+ let inFlight = 0;
+ let peak = 0;
+ let calls = 0;
+ const fetchImpl: typeof fetch = async () => {
+ const call = calls++;
+ peak = Math.max(peak, ++inFlight);
+ await new Promise<void>((resolve) => releases.push(resolve));
+ inFlight--;
+ return call === 1 ? new Response("failure", { status: 500 }) : response();
+ };
+ const batch = generateImageBatch({
+ input: { items: [{ prompt: "a", count: 3 }] },
+ endpoint,
+ signal: new AbortController().signal,
+ save,
+ fetchImpl,
+ });
+ await vi.waitFor(() => expect(releases.length).toBe(2));
+ releases[1]();
+ await vi.waitFor(() => expect(releases.length).toBe(3));
+ releases[2]();
+ releases[0]();
+ expect((await batch).map((result) => result.status)).toEqual([
+ "succeeded",
+ "failed",
+ "succeeded",
+ ]);
+ expect(peak).toBe(2);
+ expect(calls).toBe(3);
+ });
+ it("cancels in-flight requests and never starts queued images", async () => {
+ const controller = new AbortController();
+ const fetchImpl = vi.fn<typeof fetch>().mockImplementation(
+ async (_url, init) =>
+ new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () => reject(new Error("aborted")), {
+ once: true,
+ });
+ }),
+ );
+ const batch = generateImageBatch({
+ input: { items: [{ prompt: "a", count: 5 }] },
+ endpoint,
+ signal: controller.signal,
+ save,
+ fetchImpl,
+ });
+ controller.abort();
+ expect((await batch).every((item) => item.status === "cancelled")).toBe(true);
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ });
+ it("stops queued work on authentication failure and does not disclose provider bodies", async () => {
+ const fetchImpl = vi
+ .fn<typeof fetch>()
+ .mockResolvedValue(new Response("secret provider payload", { status: 401 }));
+ const result = await generateImageBatch({
+ input: { items: [{ prompt: "a", count: 5 }] },
+ endpoint,
+ signal: new AbortController().signal,
+ save,
+ fetchImpl,
+ });
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ expect(JSON.stringify(result)).not.toContain("secret");
+ expect(result[4].status).toBe("cancelled");
+ });
+ it("times out each image without retry", async () => {
+ vi.useFakeTimers();
+ try {
+ const fetchImpl = vi.fn<typeof fetch>().mockImplementation(
+ async (_url, init) =>
+ new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () => reject(new Error("timeout")), {
+ once: true,
+ });
+ }),
+ );
+ const batch = generateImageBatch({
+ input: { items: [{ prompt: "a" }] },
+ endpoint,
+ signal: new AbortController().signal,
+ save,
+ fetchImpl,
+ });
+ await vi.advanceTimersByTimeAsync(180_000);
+ expect((await batch)[0].errorCode).toBe("IMAGE_TIMEOUT");
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+ it("rejects unsafe image addresses, forged images and oversized bodies", async () => {
+ for (const address of [
+ "127.0.0.1",
+ "10.0.0.1",
+ "169.254.169.254",
+ "172.16.0.1",
+ "192.168.0.1",
+ "::1",
+ "::ffff:127.0.0.1",
+ "fc00::1",
+ "2002:7f00:1::",
+ ])
+ expect(publicImageAddress(address)).toBe(false);
+ expect(publicImageAddress("8.8.8.8")).toBe(true);
+ expect(() => generatedImageType(Buffer.from("<svg>"))).toThrow("IMAGE_INVALID_CONTENT");
+ await expect(boundedBytes(new Response("oversized"), 2)).rejects.toThrow("IMAGE_TOO_LARGE");
+ });
+});
diff --git a/packages/agent-runtime/src/image-generation/index.ts b/packages/agent-runtime/src/image-generation/index.ts
new file mode 100644
index 000000000..bf1ffb694
--- /dev/null
+++ b/packages/agent-runtime/src/image-generation/index.ts
@@ -0,0 +1,169 @@
+import {
+ IMAGE_GENERATION_TIMEOUT_MS,
+ imageGenerationItems,
+ type GeneratedImageResult,
+} from "@pi-desktop/shared";
+import {
+ boundedBytes,
+ downloadGeneratedImage,
+ generatedImageType,
+ imageError,
+ MAX_IMAGE_BYTES,
+} from "./download.js";
+export { generatedImageType, MAX_IMAGE_BYTES } from "./download.js";
+
+export type ImageEndpoint = {
+ baseUrl: string;
+ modelId: string;
+ apiKey?: string;
+ headers?: Record<string, string>;
+};
+
+export function imageGenerationUrl(baseUrl: string, edit = false): string {
+ const url = new URL(baseUrl);
+ if (
+ !["http:", "https:"].includes(url.protocol) ||
+ url.username ||
+ url.password ||
+ url.search ||
+ url.hash
+ )
+ throw imageError("IMAGE_INVALID_ENDPOINT");
+ const path = url.pathname.replace(/\/+$/, "");
+ url.pathname = `${path || "/v1"}/images/${edit ? "edits" : "generations"}`;
+ return url.href;
+}
+
+export type ImageEditInput = { bytes: Uint8Array; mimeType: string; extension: string };
+
+export async function generateOneImage(
+ endpoint: ImageEndpoint,
+ prompt: string,
+ signal: AbortSignal,
+ fetchImpl: typeof fetch = fetch,
+ images: ImageEditInput[] = [],
+) {
+ const headers = new Headers(endpoint.headers);
+ headers.set("Content-Type", "application/json");
+ if (endpoint.apiKey) headers.set("Authorization", `Bearer ${endpoint.apiKey}`);
+ let body: BodyInit = JSON.stringify({ model: endpoint.modelId, prompt, n: 1 });
+ if (images.length) {
+ const form = new FormData();
+ form.set("model", endpoint.modelId);
+ form.set("prompt", prompt);
+ form.set("n", "1");
+ images.forEach((image, index) =>
+ form.append(
+ images.length === 1 ? "image" : "image[]",
+ new Blob([new Uint8Array(image.bytes)], { type: image.mimeType }),
+ `input-${index}.${image.extension}`,
+ ),
+ );
+ headers.delete("Content-Type");
+ body = form;
+ }
+ const response = await fetchImpl(imageGenerationUrl(endpoint.baseUrl, images.length > 0), {
+ method: "POST",
+ headers,
+ redirect: "error",
+ signal,
+ body,
+ });
+ if (!response.ok) {
+ await response.body?.cancel();
+ throw imageError(
+ response.status === 401 || response.status === 403
+ ? "IMAGE_AUTH_FAILED"
+ : `IMAGE_HTTP_${response.status}`,
+ );
+ }
+ const raw = await boundedBytes(response, Math.ceil((MAX_IMAGE_BYTES * 4) / 3) + 65536);
+ let payload: unknown;
+ try {
+ payload = JSON.parse(Buffer.from(raw).toString("utf8"));
+ } catch {
+ throw imageError("IMAGE_INVALID_RESPONSE");
+ }
+ const data = (payload as { data?: unknown })?.data;
+ if (!Array.isArray(data) || data.length !== 1 || !data[0] || typeof data[0] !== "object")
+ throw imageError("IMAGE_INVALID_RESPONSE");
+ const item = data[0] as Record<string, unknown>;
+ let bytes: Uint8Array;
+ if (
+ typeof item.b64_json === "string" &&
+ item.b64_json.length &&
+ /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(item.b64_json)
+ ) {
+ bytes = Buffer.from(item.b64_json, "base64");
+ } else if (typeof item.url === "string") {
+ bytes = await downloadGeneratedImage(item.url, signal);
+ } else throw imageError("IMAGE_INVALID_RESPONSE");
+ return { bytes, ...generatedImageType(bytes) };
+}
+
+/** Two workers, stable result ordering, no automatic retry of billable requests. */
+export async function generateImageBatch(options: {
+ input: unknown;
+ endpoint: ImageEndpoint;
+ signal: AbortSignal;
+ save: (image: Awaited<ReturnType<typeof generateOneImage>>, index: number) => Promise<string>;
+ fetchImpl?: typeof fetch;
+ loadImages?: (paths: string[]) => Promise<ImageEditInput[]>;
+}): Promise<GeneratedImageResult[]> {
+ const prompts = imageGenerationItems(options.input);
+ const results: GeneratedImageResult[] = new Array(prompts.length);
+ let next = 0;
+ let authFailed = false;
+ const worker = async () => {
+ while (next < prompts.length) {
+ const index = next++;
+ if (options.signal.aborted || authFailed) {
+ results[index] = {
+ index,
+ status: "cancelled",
+ errorCode: authFailed ? "IMAGE_AUTH_FAILED" : "IMAGE_CANCELLED",
+ };
+ continue;
+ }
+ const controller = new AbortController();
+ const signal = AbortSignal.any([options.signal, controller.signal]);
+ const timer = setTimeout(() => controller.abort(), IMAGE_GENERATION_TIMEOUT_MS);
+ try {
+ const item = prompts[index];
+ if (item.images && !options.loadImages) throw imageError("IMAGE_EDIT_UNAVAILABLE");
+ const images = item.images ? await options.loadImages!(item.images) : [];
+ signal.throwIfAborted();
+ const image = await generateOneImage(
+ options.endpoint,
+ item.prompt,
+ signal,
+ options.fetchImpl,
+ images,
+ );
+ const path = await options.save(image, index);
+ results[index] = { index, status: "succeeded", path, mimeType: image.mimeType };
+ } catch (error) {
+ const code = options.signal.aborted
+ ? "IMAGE_CANCELLED"
+ : controller.signal.aborted
+ ? "IMAGE_TIMEOUT"
+ : error &&
+ typeof error === "object" &&
+ "errorCode" in error &&
+ typeof error.errorCode === "string"
+ ? error.errorCode
+ : "IMAGE_REQUEST_FAILED";
+ if (code === "IMAGE_AUTH_FAILED") authFailed = true;
+ results[index] = {
+ index,
+ status: options.signal.aborted ? "cancelled" : "failed",
+ errorCode: code,
+ };
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+ };
+ await Promise.all([worker(), worker()]);
+ return results;
+}
diff --git a/packages/agent-runtime/src/image-generation/tool.ts b/packages/agent-runtime/src/image-generation/tool.ts
new file mode 100644
index 000000000..e7d877926
--- /dev/null
+++ b/packages/agent-runtime/src/image-generation/tool.ts
@@ -0,0 +1,19 @@
+import { Type } from "@earendil-works/pi-ai";
+
+export const imageGenerationDescription =
+ "Generate raster images using the image model configured in Settings > AI. items supports distinct prompts and count variants; at most 10 images total. Each image may incur a charge. Generate only the requested number, report partial failures, and do not retry without the user's request. Results contain local image paths: display successful images with Markdown image links. For edits, provide images as local paths from the session, attachments, or project. Use previous result paths to refine generated images; preserve originals.";
+export const imageGenerationParameters = {
+ items: Type.Array(
+ Type.Object({
+ prompt: Type.String({ minLength: 1, maxLength: 32000 }),
+ images: Type.Optional(
+ Type.Union([
+ Type.Array(Type.String({ minLength: 1, maxLength: 4096 }), { maxItems: 4 }),
+ Type.Null(),
+ ]),
+ ),
+ count: Type.Optional(Type.Integer({ minimum: 1, maximum: 10 })),
+ }),
+ { minItems: 1, maxItems: 10 },
+ ),
+};
diff --git a/packages/agent-runtime/src/index.ts b/packages/agent-runtime/src/index.ts
index 5546ac24b..2834f0aa6 100644
--- a/packages/agent-runtime/src/index.ts
+++ b/packages/agent-runtime/src/index.ts
@@ -23,3 +23,4 @@ export { startAuthenticatedProxyRelay } from "./authenticated-proxy-relay.js";
export type { AuthenticatedProxyRelay } from "./authenticated-proxy-relay.js";
export * from "./speech/index.js";
+export * from "./image-generation/index.js";
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 60f6a8014..948a1997d 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -1,3 +1,4 @@
+import { imageGenerationDescription, imageGenerationParameters } from "./image-generation/tool.js";
import { scheduledToolParameters, scheduledToolDescriptions } from "./scheduled-tools.js";
import { randomUUID } from "node:crypto";
import {
@@ -2749,6 +2750,7 @@ Delegation rules:
const externalPathHint =
" An explicit path outside the workspace and session scratch roots requires permission unless the effective mode is Auto.";
const describe = (toolName: string): string => {
+ if (toolName === "GenerateImages") return imageGenerationDescription;
if (scheduledToolDescriptions[toolName]) return scheduledToolDescriptions[toolName];
switch (toolName) {
case "BrowserPreview":
@@ -2801,6 +2803,7 @@ Delegation rules:
// One entry per tool: the shapes diverge enough that a chain of ternaries
// stopped being readable.
const parameters: Record<string, Parameters<typeof Type.Object>[0]> = {
+ GenerateImages: imageGenerationParameters,
Read: {
path: pathParam(
"Existing regular file only, never a directory; workspace-relative or explicitly approved.",
@@ -2947,7 +2950,7 @@ Delegation rules:
})
: undefined;
const abort = () => {
- if (!isBash || abortRequested || settled) return;
+ if ((!isBash && toolName !== "GenerateImages") || abortRequested || settled) return;
abortRequested = true;
abortPromise = this.host
.call("tools.abort", {
@@ -3260,7 +3263,7 @@ Delegation rules:
]
: ["Read", "Glob", "Grep", "BrowserPreview", "Bash"];
if (this.mode === "agent") {
- tools.push("PluginScaffold", "PluginPack", ...Object.keys(scheduledToolParameters));
+ tools.push("PluginScaffold", "PluginPack", "GenerateImages", ...Object.keys(scheduledToolParameters));
}
const builtins = tools.map(exec);
diff --git a/packages/host-runtime/src/agent-sidecar.ts b/packages/host-runtime/src/agent-sidecar.ts
index b89741ae8..3b35323ef 100644
--- a/packages/host-runtime/src/agent-sidecar.ts
+++ b/packages/host-runtime/src/agent-sidecar.ts
@@ -1,6 +1,6 @@
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { randomUUID } from "node:crypto";
-import { DEFAULT_RPC_TIMEOUT_MS, readNdjsonLines, rpcTimeoutMs } from "@pi-desktop/shared";
+import { DEFAULT_RPC_TIMEOUT_MS, IMAGE_BATCH_TIMEOUT_MS, imageGenerationPrompts, readNdjsonLines, rpcTimeoutMs } from "@pi-desktop/shared";
import type { ProcessExitHandler, StderrHandler } from "./host-process.js";
// stderr lines kept per sidecar so an unexpected exit can be reported with the
@@ -21,6 +21,7 @@ export type LocalToolHandler = (input: {
sessionId: string;
toolCallId: string;
args: unknown;
+ signal: AbortSignal;
}) => Promise<LocalToolResult>;
export type ProjectInstructionResolver = (input: {
@@ -142,6 +143,7 @@ export class AgentSidecar {
private stdoutReader?: ReturnType<typeof readNdjsonLines>;
// Tools served by the embedding host itself (e.g. BrowserPreview drives the
// work panel's WebContentsView) — host-core never sees these.
+ private localToolControllers = new Map<string, AbortController>();
private localTools = new Map<string, LocalToolHandler>();
private localToolTimers = new Set<ReturnType<typeof setTimeout>>();
private projectInstructionResolver: ProjectInstructionResolver | null = null;
@@ -210,6 +212,8 @@ export class AgentSidecar {
this.pending.clear();
for (const timer of this.localToolTimers) clearTimeout(timer);
this.localToolTimers.clear();
+ for (const controller of this.localToolControllers.values()) controller.abort();
+ this.localToolControllers.clear();
this.handlers.clear();
this.stdoutReader?.close();
this.stdoutReader = undefined;
@@ -258,24 +262,39 @@ export class AgentSidecar {
private async runLocalTool(
handler: LocalToolHandler,
- input: Parameters<LocalToolHandler>[0],
+ input: Omit<Parameters<LocalToolHandler>[0], "signal">,
+ params: Record<string, unknown>,
): Promise<LocalToolResult> {
+ const key = `${input.sessionId}:${input.toolCallId}`;
+ if (this.localToolControllers.has(key)) throw new Error("duplicate local tool call");
+ const controller = new AbortController();
+ this.localToolControllers.set(key, controller);
+ const imageGeneration = params.toolName === "GenerateImages";
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
- handler(input),
+ (async () => {
+ if (imageGeneration) {
+ imageGenerationPrompts(input.args);
+ if (!this.host) throw new Error("host unavailable");
+ const gate = await this.host.call<LocalToolResult>("tools.execute", params);
+ if (!gate.ok) return gate;
+ controller.signal.throwIfAborted();
+ }
+ return handler({ ...input, signal: controller.signal });
+ })(),
new Promise<LocalToolResult>((_, reject) => {
timer = setTimeout(() => {
+ controller.abort();
reject(new Error("host-local tool timeout"));
- }, DEFAULT_RPC_TIMEOUT_MS);
+ }, imageGeneration ? IMAGE_BATCH_TIMEOUT_MS + 130_000 : DEFAULT_RPC_TIMEOUT_MS);
this.localToolTimers.add(timer);
}),
]);
} finally {
- if (timer) {
- clearTimeout(timer);
- this.localToolTimers.delete(timer);
- }
+ controller.abort();
+ this.localToolControllers.delete(key);
+ if (timer) { clearTimeout(timer); this.localToolTimers.delete(timer); }
}
}
@@ -340,6 +359,9 @@ export class AgentSidecar {
setHost(host: SidecarHostLink) {
if (this.closed) return;
+ if (this.host && this.host !== host) {
+ for (const controller of this.localToolControllers.values()) controller.abort();
+ }
this.host = host;
this.unsubscribeHost?.();
this.unsubscribeHostExit?.();
@@ -358,6 +380,7 @@ export class AgentSidecar {
this.writeToChild(payload);
});
this.unsubscribeHostExit = host.onExit(() => {
+ for (const controller of this.localToolControllers.values()) controller.abort();
this.unsubscribeHost?.();
this.unsubscribeHost = null;
this.unsubscribeHostExit = null;
@@ -462,6 +485,9 @@ export class AgentSidecar {
{ code: -32000, data: { errorCode: "TOOL_DISABLED_IN_PLAN" } },
);
}
+ if (method === "tools.abort") {
+ this.localToolControllers.get(`${params.sessionId}:${params.toolCallId}`)?.abort();
+ }
if (method === "project.instructions.resolve") {
if (!this.projectInstructionResolver) {
throw new Error("project instruction resolver unavailable");
@@ -530,7 +556,7 @@ export class AgentSidecar {
sessionId: String(params.sessionId ?? ""),
toolCallId: String(params.toolCallId ?? ""),
args: params.args,
- });
+ }, params);
this.writeToChild(
JSON.stringify({ jsonrpc: "2.0", id: msg.id, result }) + "\n",
);
diff --git a/packages/host-runtime/src/image-generation-bridge.test.ts b/packages/host-runtime/src/image-generation-bridge.test.ts
new file mode 100644
index 000000000..d35ac2b58
--- /dev/null
+++ b/packages/host-runtime/src/image-generation-bridge.test.ts
@@ -0,0 +1,83 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { AgentSidecar, type SidecarHostLink } from "./agent-sidecar.js";
+
+// A real stdio child forwards requested calls over the production reverse RPC.
+const child = `const rl=require('node:readline').createInterface({input:process.stdin});
+const pending=new Map(); rl.on('line',line=>{const m=JSON.parse(line);
+if(m.method==='probe'){pending.set('r'+m.id,m.id);console.log(JSON.stringify({id:'r'+m.id,method:'host.proxy',params:m.params}));}
+else if(pending.has(m.id)){console.log(JSON.stringify({...m,id:pending.get(m.id)}));pending.delete(m.id);}});`;
+const sidecars: AgentSidecar[] = [];
+afterEach(async () => {
+ await Promise.all(sidecars.splice(0).map((sidecar) => sidecar.dispose()));
+});
+function harness(allowed = true) {
+ const sidecar = new AgentSidecar({
+ launch: { command: process.execPath, args: ["-e", child] },
+ onStderr: () => {},
+ });
+ sidecars.push(sidecar);
+ const calls: string[] = [];
+ const host: SidecarHostLink = {
+ async call<T>(method: string): Promise<T> {
+ calls.push(method);
+ return { ok: allowed, content: allowed ? { authorized: true } : "denied" } as T;
+ },
+ onNotification: () => () => {},
+ onExit: () => () => {},
+ };
+ sidecar.setHost(host);
+ const execute = (mode = "agent", toolCallId = "i") =>
+ sidecar.call<{ ok: boolean }>("probe", {
+ method: "tools.execute",
+ params: {
+ sessionId: "s",
+ toolCallId,
+ mode,
+ toolName: "GenerateImages",
+ args: { items: [{ prompt: "image" }] },
+ },
+ });
+ return { sidecar, calls, execute };
+}
+
+it("authorizes image calls through the host before executing the local handler", async () => {
+ const { sidecar, calls, execute } = harness();
+ sidecar.setLocalTool("GenerateImages", async () => {
+ calls.push("generated");
+ return { ok: true, content: "image" };
+ });
+ expect((await execute()).ok).toBe(true);
+ expect(calls).toEqual(["tools.execute", "generated"]);
+});
+
+it("denied and Plan calls never reach the image service", async () => {
+ const { sidecar, execute } = harness(false);
+ const generate = vi.fn().mockResolvedValue({ ok: true, content: "image" });
+ sidecar.setLocalTool("GenerateImages", generate);
+ expect((await execute()).ok).toBe(false);
+ expect((await execute("plan")).ok).toBe(false);
+ expect(generate).not.toHaveBeenCalled();
+});
+
+it("tools.abort reaches the in-flight request and still forwards host cancellation", async () => {
+ const { sidecar, calls, execute } = harness();
+ let started!: () => void;
+ const ready = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ sidecar.setLocalTool("GenerateImages", async ({ signal }) => {
+ started();
+ await new Promise<void>((resolve) =>
+ signal.addEventListener("abort", () => resolve(), { once: true }),
+ );
+ return { ok: false, content: "cancelled" };
+ });
+ const pending = execute();
+ await ready;
+ await sidecar.call("probe", {
+ method: "tools.abort",
+ params: { sessionId: "s", toolCallId: "i" },
+ });
+ expect((await pending).ok).toBe(false);
+ expect(calls).toEqual(["tools.execute", "tools.abort"]);
+});
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 4c4fba2d2..7d1d8aeaf 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -550,6 +550,19 @@ export const de = {
"dismiss": "Verwerfen"
},
"settings": {
+ "imageModel": "Bildgenerierungsmodell",
+ "imageModelUnset": "Nicht konfiguriert",
+ "imageModelUnavailable": "Dieses Bildmodell ist nicht verfügbar. Wählen Sie ein anderes.",
+ "imageModelSaveFailed": "Bildmodell konnte nicht gespeichert werden.",
+ "clearImageModel": "Löschen",
+ "setImageModel": "Als Bildmodell festlegen",
+ "imageModelSelected": "Ausgewähltes Bildmodell",
+ "generatedImage": "Generiertes Bild {{index}}",
+ "imagePreviewUnavailable": "Vorschau nicht verfügbar; Datei öffnen",
+ "imageGenerationFailed": "Bild {{index}} wurde nicht fertiggestellt.",
+ "imageModelSetupHint": "Konfigurieren Sie ein Bildmodell unter Einstellungen → AI.",
+ "configureImageModel": "Bildmodell konfigurieren",
+
sklm: {
browse: "Markt",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index e3b69ebcc..546d27a1c 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -557,6 +557,19 @@ export const en = {
dismiss: "Dismiss",
},
settings: {
+ imageModel: "Image generation model",
+ imageModelUnset: "Not configured",
+ imageModelUnavailable: "This image model is unavailable. Choose another model.",
+ imageModelSaveFailed: "Could not save the image model.",
+ clearImageModel: "Clear",
+ setImageModel: "Set as image model",
+ imageModelSelected: "Selected image model",
+ generatedImage: "Generated image {{index}}",
+ imagePreviewUnavailable: "Preview unavailable; open file",
+ imageGenerationFailed: "Image {{index}} did not complete.",
+ imageModelSetupHint: "Configure an image model in Settings → AI before generating images.",
+ configureImageModel: "Configure image model",
+
sklm: {
browse: "Market",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 667a54c07..04311bd85 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -550,6 +550,19 @@ export const es = {
"dismiss": "Descartar"
},
"settings": {
+ "imageModel": "Modelo de imágenes",
+ "imageModelUnset": "Sin configurar",
+ "imageModelUnavailable": "Este modelo no está disponible. Elige otro.",
+ "imageModelSaveFailed": "No se pudo guardar el modelo.",
+ "clearImageModel": "Borrar",
+ "setImageModel": "Usar para generar imágenes",
+ "imageModelSelected": "Modelo de imágenes seleccionado",
+ "generatedImage": "Imagen generada {{index}}",
+ "imagePreviewUnavailable": "Vista previa no disponible; abrir archivo",
+ "imageGenerationFailed": "La imagen {{index}} no se completó.",
+ "imageModelSetupHint": "Configura un modelo de imágenes en Ajustes → AI.",
+ "configureImageModel": "Configurar modelo de imágenes",
+
sklm: {
browse: "Mercado",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index d69c1f39a..b3cae75a3 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -550,6 +550,19 @@ export const fr = {
"dismiss": "Ignorer"
},
"settings": {
+ "imageModel": "Modèle de génération d’images",
+ "imageModelUnset": "Non configuré",
+ "imageModelUnavailable": "Ce modèle est indisponible. Choisissez-en un autre.",
+ "imageModelSaveFailed": "Impossible d’enregistrer le modèle.",
+ "clearImageModel": "Effacer",
+ "setImageModel": "Définir comme modèle d’images",
+ "imageModelSelected": "Modèle d’images sélectionné",
+ "generatedImage": "Image générée {{index}}",
+ "imagePreviewUnavailable": "Aperçu indisponible ; ouvrir le fichier",
+ "imageGenerationFailed": "L’image {{index}} n’a pas été terminée.",
+ "imageModelSetupHint": "Configurez un modèle d’images dans Paramètres → AI.",
+ "configureImageModel": "Configurer le modèle d’images",
+
sklm: {
browse: "Marché",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 9c9cb78c7..1396300aa 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -559,6 +559,19 @@ export const ko = {
dismiss: "닫기",
},
settings: {
+ "imageModel": "이미지 생성 모델",
+ "imageModelUnset": "설정되지 않음",
+ "imageModelUnavailable": "이 이미지 모델을 사용할 수 없습니다. 다른 모델을 선택하세요.",
+ "imageModelSaveFailed": "이미지 모델을 저장할 수 없습니다.",
+ "clearImageModel": "지우기",
+ "setImageModel": "이미지 모델로 설정",
+ "imageModelSelected": "선택된 이미지 모델",
+ "generatedImage": "생성된 이미지 {{index}}",
+ "imagePreviewUnavailable": "미리보기 불가; 파일 열기",
+ "imageGenerationFailed": "이미지 {{index}} 생성이 완료되지 않았습니다.",
+ "imageModelSetupHint": "설정 → AI에서 이미지 모델을 설정하세요.",
+ "configureImageModel": "이미지 모델 설정",
+
sklm: {
browse: "마켓",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index a3e57db14..e7d3a1a60 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -559,6 +559,19 @@ export const tr = {
dismiss: "Kapat",
},
settings: {
+ "imageModel": "Görsel oluşturma modeli",
+ "imageModelUnset": "Yapılandırılmadı",
+ "imageModelUnavailable": "Bu görsel modeli kullanılamıyor. Başka bir model seçin.",
+ "imageModelSaveFailed": "Görsel modeli kaydedilemedi.",
+ "clearImageModel": "Temizle",
+ "setImageModel": "Görsel modeli olarak ayarla",
+ "imageModelSelected": "Seçili görsel modeli",
+ "generatedImage": "Oluşturulan görsel {{index}}",
+ "imagePreviewUnavailable": "Önizleme yok; dosyayı aç",
+ "imageGenerationFailed": "Görsel {{index}} tamamlanmadı.",
+ "imageModelSetupHint": "Ayarlar → AI bölümünde bir görsel modeli yapılandırın.",
+ "configureImageModel": "Görsel modelini yapılandır",
+
sklm: {
browse: "Market",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 6e6020c2d..172be5da8 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -554,6 +554,19 @@ export const zhCN = {
dismiss: "关闭",
},
settings: {
+ imageModel: "生图模型",
+ imageModelUnset: "未配置",
+ imageModelUnavailable: "当前生图模型不可用,请选择其他模型。",
+ imageModelSaveFailed: "无法保存生图模型。",
+ clearImageModel: "清除",
+ setImageModel: "设为生图模型",
+ imageModelSelected: "已设为生图模型",
+ generatedImage: "生成图片 {{index}}",
+ imagePreviewUnavailable: "预览不可用,打开文件",
+ imageGenerationFailed: "图片 {{index}} 未完成。",
+ imageModelSetupHint: "请前往 设置 → AI → 生图模型 完成配置。",
+ configureImageModel: "配置生图模型",
+
sklm: {
browse: "市场",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 6bd827035..0184c917c 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -554,6 +554,19 @@ export const zhTW = {
dismiss: "關閉",
},
settings: {
+ imageModel: "生圖模型",
+ imageModelUnset: "未設定",
+ imageModelUnavailable: "目前生圖模型無法使用,請選擇其他模型。",
+ imageModelSaveFailed: "無法儲存生圖模型。",
+ clearImageModel: "清除",
+ setImageModel: "設為生圖模型",
+ imageModelSelected: "已設為生圖模型",
+ generatedImage: "生成圖片 {{index}}",
+ imagePreviewUnavailable: "無法預覽,開啟檔案",
+ imageGenerationFailed: "圖片 {{index}} 未完成。",
+ imageModelSetupHint: "請前往 設定 → AI → 生圖模型 完成設定。",
+ configureImageModel: "設定生圖模型",
+
sklm: {
browse: "市場",
diff --git a/packages/shared/src/changelog-de.ts b/packages/shared/src/changelog-de.ts
index 7931ce40b..e6425a2ff 100644
--- a/packages/shared/src/changelog-de.ts
+++ b/packages/shared/src/changelog-de.ts
@@ -5,6 +5,7 @@ export const deEntries: ChangelogEntry[] = [
"version": "0.15.2",
"date": "2026-09-21",
"highlights": [
+ "Bilder im Chat generieren und bearbeiten, ein Bildmodell wählen und mit dem integrierten imagegen-Skill Stapel erstellen.",
"Werkzeugaktivitäten folgen der Gesprächsbreite; lange Aktivitätsnamen werden sauber begrenzt.",
"Dateianhänge aus dem Einfügen bleiben erhalten, auch wenn der Vorgang nach einem Sitzungswechsel endet.",
"Das ausgewählte Standardmodell bleibt beim Bearbeiten von Anbietern erhalten und fällt sicher zurück, wenn es entfernt wird.",
diff --git a/packages/shared/src/changelog-es.ts b/packages/shared/src/changelog-es.ts
index c5fc55490..03dc25905 100644
--- a/packages/shared/src/changelog-es.ts
+++ b/packages/shared/src/changelog-es.ts
@@ -5,6 +5,7 @@ export const esEntries: ChangelogEntry[] = [
"version": "0.15.2",
"date": "2026-09-21",
"highlights": [
+ "Genera y edita imágenes en el chat, elige un modelo y crea lotes con la habilidad integrada imagegen.",
"La actividad de herramientas sigue el ancho de la conversación y contiene correctamente las etiquetas largas.",
"Los archivos adjuntos pegados se conservan aunque el pegado termine después de cambiar de sesión.",
"El modelo predeterminado seleccionado se conserva al editar proveedores y se aplica un respaldo seguro si se elimina.",
diff --git a/packages/shared/src/changelog-fr.ts b/packages/shared/src/changelog-fr.ts
index aa9aaf9fa..d2b6c77c9 100644
--- a/packages/shared/src/changelog-fr.ts
+++ b/packages/shared/src/changelog-fr.ts
@@ -5,6 +5,7 @@ export const frEntries: ChangelogEntry[] = [
"version": "0.15.2",
"date": "2026-09-21",
"highlights": [
+ "Générez et modifiez des images dans le chat, choisissez un modèle et créez des lots avec la compétence intégrée imagegen.",
"L'activité des outils suit la largeur de la conversation et contient proprement les libellés longs.",
"Les pièces jointes collées sont conservées même si le collage se termine après un changement de session.",
"Le modèle par défaut sélectionné est conservé lors de la modification des fournisseurs, avec un repli sûr s'il est supprimé.",
diff --git a/packages/shared/src/changelog-ko.ts b/packages/shared/src/changelog-ko.ts
index 8d53800e3..ec5ecf31e 100644
--- a/packages/shared/src/changelog-ko.ts
+++ b/packages/shared/src/changelog-ko.ts
@@ -5,6 +5,7 @@ export const koEntries: ChangelogEntry[] = [
version: "0.15.2",
date: "2026-09-21",
highlights: [
+ "채팅에서 이미지를 생성하고 편집하며, 이미지 모델과 내장 imagegen 스킬로 일괄 생성할 수 있습니다.",
"도구 활동이 대화 너비를 따라 정렬되고 긴 활동 이름도 깔끔하게 표시됩니다.",
"세션을 전환한 뒤 붙여넣기가 완료되어도 붙여넣은 파일 첨부가 유지됩니다.",
"제공자를 편집할 때 선택한 기본 모델을 유지하며, 모델이 삭제되면 안전하게 대체 모델로 전환합니다.",
diff --git a/packages/shared/src/changelog-tr.ts b/packages/shared/src/changelog-tr.ts
index 18ee14192..12986cec8 100644
--- a/packages/shared/src/changelog-tr.ts
+++ b/packages/shared/src/changelog-tr.ts
@@ -5,6 +5,7 @@ export const trEntries: ChangelogEntry[] = [
"version": "0.15.2",
"date": "2026-09-21",
"highlights": [
+ "Sohbette görsel oluşturun ve düzenleyin; tek bir görsel modeli ve yerleşik imagegen becerisiyle toplu üretim yapın.",
"Araç etkinlikleri konuşma genişliğini izler ve uzun etkinlik etiketleri düzgünce sığdırılır.",
"Oturum değiştirdikten sonra yapıştırma tamamlansa bile yapıştırılan dosya ekleri korunur.",
"Sağlayıcıları düzenlerken seçili varsayılan model korunur; model kaldırılırsa güvenli bir yedek kullanılır.",
diff --git a/packages/shared/src/changelog.ts b/packages/shared/src/changelog.ts
index 828aa0386..299f1afd9 100644
--- a/packages/shared/src/changelog.ts
+++ b/packages/shared/src/changelog.ts
@@ -32,6 +32,7 @@ const enEntries: ChangelogEntry[] = [
version: "0.15.2",
date: "2026-09-21",
highlights: [
+ "Generate and edit images in chat, choose one image model, and create batches with the built-in imagegen skill.",
"Keep tool activity aligned with the conversation width and contain long activity labels cleanly.",
"Preserve pasted file attachments when a paste finishes after switching sessions.",
"Keep the selected default model when editing providers, and fall back safely when it is removed.",
@@ -827,6 +828,7 @@ const zhCNEntries: ChangelogEntry[] = [
version: "0.15.2",
date: "2026-09-21",
highlights: [
+ "支持聊天生图与图片编辑,可设置唯一生图模型,并通过内置 imagegen 技能批量生成。",
"让工具活动跟随对话宽度排列,并妥善收纳过长的活动名称。",
"切换会话后,如果粘贴操作稍后完成,文件附件也会保留。",
"编辑提供商时保留已选的默认模型;模型被移除后安全回退。",
@@ -1622,6 +1624,7 @@ const zhTWEntries: ChangelogEntry[] = [
version: "0.15.2",
date: "2026-09-21",
highlights: [
+ "支援聊天生圖與圖片編輯,可設定唯一生圖模型,並透過內建 imagegen 技能批次生成。",
"讓工具活動跟隨對話寬度排列,並妥善收納過長的活動名稱。",
"切換工作階段後,即使貼上操作稍後完成,檔案附件也會保留。",
"編輯提供商時保留已選的預設模型;模型被移除後安全回退。",
diff --git a/packages/shared/src/image-generation.ts b/packages/shared/src/image-generation.ts
new file mode 100644
index 000000000..8a8898021
--- /dev/null
+++ b/packages/shared/src/image-generation.ts
@@ -0,0 +1,75 @@
+/** A single host-owned binding, independent of the default conversation model. */
+export type ImageGenerationBinding = { providerId: string; modelId: string };
+export const MAX_GENERATED_IMAGES = 10;
+export const IMAGE_GENERATION_TIMEOUT_MS = 180_000;
+export const IMAGE_BATCH_TIMEOUT_MS = 950_000;
+export type ImageGenerationItem = { prompt: string; count?: number; images?: string[] };
+export type ImageGenerationInput = { items: ImageGenerationItem[] };
+export type GeneratedImageResult = {
+ index: number;
+ status: "succeeded" | "failed" | "cancelled";
+ path?: string;
+ mimeType?: string;
+ errorCode?: string;
+};
+
+function invalid(message: string): never {
+ throw Object.assign(new Error(message), { errorCode: "INVALID_ARGUMENT" });
+}
+
+export function parseImageGenerationBinding(value: unknown): ImageGenerationBinding | null {
+ if (value == null) return null;
+ if (typeof value !== "object" || Array.isArray(value))
+ invalid("imageGeneration must be an object");
+ const record = value as Record<string, unknown>;
+ const field = (name: string, max: number) => {
+ const raw = record[name];
+ if (typeof raw !== "string" || !raw.trim() || raw.length > max)
+ invalid(`imageGeneration.${name} is invalid`);
+ return raw.trim();
+ };
+ return { providerId: field("providerId", 128), modelId: field("modelId", 256) };
+}
+
+/** Expand variants into individually accountable requests; never silently truncate. */
+export function imageGenerationItems(value: unknown): ImageGenerationItem[] {
+ if (!value || typeof value !== "object" || Array.isArray(value)) invalid("items are required");
+ const items = (value as Record<string, unknown>).items;
+ if (!Array.isArray(items) || !items.length || items.length > MAX_GENERATED_IMAGES)
+ invalid("items must contain 1–10 entries");
+ const prompts: ImageGenerationItem[] = [];
+ for (const item of items) {
+ if (!item || typeof item !== "object" || Array.isArray(item)) invalid("invalid image item");
+ const { prompt, count = 1, images } = item as Record<string, unknown>;
+ if (typeof prompt !== "string" || !prompt.trim() || prompt.length > 32_000)
+ invalid("prompt must contain 1–32000 characters");
+ if (
+ typeof count !== "number" ||
+ !Number.isInteger(count) ||
+ count < 1 ||
+ count > MAX_GENERATED_IMAGES
+ )
+ invalid("count must be an integer from 1 to 10");
+ if (
+ images != null &&
+ (!Array.isArray(images) ||
+ images.length > 4 ||
+ images.some((path) => typeof path !== "string" || !path.trim() || path.length > 4096))
+ )
+ invalid("images must contain at most 4 local image paths");
+ for (let i = 0; i < count; i++)
+ prompts.push({
+ prompt: prompt.trim(),
+ ...(Array.isArray(images) && images.length
+ ? { images: (images as string[]).map((path) => path.trim()) }
+ : {}),
+ });
+ if (prompts.length > MAX_GENERATED_IMAGES)
+ invalid("at most 10 images may be generated per batch");
+ }
+ return prompts;
+}
+
+export function imageGenerationPrompts(value: unknown): string[] {
+ return imageGenerationItems(value).map((item) => item.prompt);
+}
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index c310ecbac..bf6fc44b9 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -49,6 +49,7 @@ export * from "./github-feedback.js";
export * from "./network-proxy.js";
export * from "./attachment-limits.js";
export * from "./speech.js";
+export * from "./image-generation.js";
export * from "./font-size.js";
export * from "./chat-content-width.js";
export * from "./racp.js";
diff --git a/packages/shared/src/rpc-timeouts.ts b/packages/shared/src/rpc-timeouts.ts
index 57a69f682..e84b754f6 100644
--- a/packages/shared/src/rpc-timeouts.ts
+++ b/packages/shared/src/rpc-timeouts.ts
@@ -1,3 +1,5 @@
+import { IMAGE_BATCH_TIMEOUT_MS } from "./image-generation.js";
+
export const DEFAULT_RPC_TIMEOUT_MS = 130_000;
export const PERMISSION_TIMEOUT_MS = 120_000;
export const DEFAULT_COMMAND_TIMEOUT_MS = 60_000;
@@ -53,6 +55,7 @@ export function rpcTimeoutMs(
if (method !== "tools.execute") return DEFAULT_RPC_TIMEOUT_MS;
const input = isRecord(params) ? params : undefined;
+ if (input?.toolName === "GenerateImages") return IMAGE_BATCH_TIMEOUT_MS + PERMISSION_TIMEOUT_MS + TOOL_QUEUE_WAIT_MS + COMMAND_RPC_BUFFER_MS;
if (isDesktopDispatchedTool(input?.toolName)) {
return executionRpcTimeoutMs(
input?.timeoutMs,
diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.ts
index b351f1ef3..f65060c47 100644
--- a/packages/shared/src/types/settings.ts
+++ b/packages/shared/src/types/settings.ts
@@ -22,6 +22,7 @@ export type ThemePreference = "system" | "light" | "dark" | `plugin:${string}`;
export type CloseBehavior = "ask" | "tray" | "quit";
export type AppSettings = {
+ imageGeneration?: import("../image-generation.js").ImageGenerationBinding | null;
defaultProviderId?: string;
defaultModelId?: string;
/** Host speech bindings. Absent means voice actions stay disabled. */
diff --git a/scripts/e2e-image-generation-ui.mjs b/scripts/e2e-image-generation-ui.mjs
new file mode 100644
index 000000000..1c5609e45
--- /dev/null
+++ b/scripts/e2e-image-generation-ui.mjs
@@ -0,0 +1,90 @@
+#!/usr/bin/env node
+/** Real React/Chromium coverage for the custom-provider API-format boundary. */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const require = createRequire(join(root, "packages/agent-runtime/package.json"));
+const { build } = require("esbuild");
+const { electronBinary } = resolveElectronBinary(root);
+const temp = await mkdtemp(join(tmpdir(), "pi-image-generation-ui-"));
+try {
+ await build({
+ entryPoints: [join(root, "scripts/e2e/image-generation-ui.tsx")],
+ outfile: join(temp, "renderer.js"),
+ bundle: true,
+ platform: "browser",
+ format: "iife",
+ jsx: "automatic",
+ define: { "process.env.NODE_ENV": '"production"' },
+ // Exercise API-format interactions with real components/hooks, not visual layout.
+ loader: { ".css": "empty" },
+ alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),
+ // The fixture lives outside the desktop package; use its React instance.
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ });
+ await writeFile(
+ join(temp, "index.html"),
+ '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; style-src \'self\' \'unsafe-inline\'"><title>Image generation interactions</title><body><script src="renderer.js"></script>',
+ );
+ await writeFile(
+ join(temp, "main.cjs"),
+ `
+const { app, BrowserWindow } = require("electron");
+const path = require("node:path");
+app.setPath("userData", path.join(__dirname, "profile"));
+app.whenReady().then(async () => {
+ const window = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false } });
+ window.webContents.on("console-message", (event) => console.error(event.message));
+ try {
+ await window.loadFile(path.join(__dirname, "index.html"));
+ const result = await window.webContents.executeJavaScript("globalThis.imageGenerationProbe()");
+ console.log("IMAGE_GENERATION_UI_PROBE " + JSON.stringify(result));
+ app.quit();
+ } catch (error) {
+ console.error("IMAGE_GENERATION_UI_PROBE " + JSON.stringify({ ok: false, error: String(error) }));
+ app.exit(1);
+ }
+});
+`,
+ );
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(electronBinary, [join(temp, "main.cjs")], {
+ env,
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr])
+ stream.on("data", (data) => {
+ output += data;
+ });
+ const timeout = setTimeout(() => child.kill("SIGKILL"), 45_000);
+ let code;
+ try {
+ code = await new Promise((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", resolve);
+ });
+ } finally {
+ clearTimeout(timeout);
+ }
+ const line = output.split(/\r?\n/).find((line) => line.startsWith("IMAGE_GENERATION_UI_PROBE "));
+ assert(line, `renderer returned no probe result (exit=${code}): ${output.slice(-2000)}`);
+ const result = JSON.parse(line.slice("IMAGE_GENERATION_UI_PROBE ".length));
+ console.log("IMAGE_GENERATION_UI_PROBE " + JSON.stringify(result));
+ assert.equal(code, 0, output.slice(-6000));
+ assert.equal(result.ok, true);
+} finally {
+ await rm(temp, { recursive: true, force: true });
+}
diff --git a/scripts/e2e-image-generation.mjs b/scripts/e2e-image-generation.mjs
new file mode 100644
index 000000000..efaf9d1bc
--- /dev/null
+++ b/scripts/e2e-image-generation.mjs
@@ -0,0 +1,139 @@
+/** Isolated host/stdio/HTTP/filesystem candidate gate; no paid providers. */
+import assert from "node:assert/strict";
+import { createServer } from "node:http";
+import { register } from "node:module";
+import { mkdtemp, mkdir, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { randomUUID } from "node:crypto";
+import { Host, resolveHostBinary } from "./e2e/host.mjs";
+import { AgentSidecar } from "../packages/host-runtime/dist/agent-sidecar.js";
+register(new URL("../apps/desktop/test/helpers/ts-import-hooks.mjs", import.meta.url));
+const { createImageGenerationTool } = await import(
+ "../apps/desktop/electron/main/services/image-generation-service.ts"
+);
+const dataDir = await mkdtemp(join(tmpdir(), "pi-image-e2e-"));
+const host = new Host(resolveHostBinary(), dataDir);
+const png = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9mQAAAAASUVORK5CYII=",
+ "base64",
+);
+let requests = 0;
+const server = createServer(async (request, response) => {
+ for await (const _chunk of request) {
+ /* Drain the bounded fixture request. */
+ }
+ requests++;
+ response.setHeader("Content-Type", "application/json");
+ response.end(JSON.stringify({ data: [{ b64_json: png.toString("base64") }] }));
+});
+await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+// Only the LLM edge is simulated; reverse RPC, authorization and execution are real.
+const child = `const rl=require('node:readline').createInterface({input:process.stdin});const p=new Map();rl.on('line',line=>{const m=JSON.parse(line);if(m.method==='probe'){p.set('r'+m.id,m.id);console.log(JSON.stringify({id:'r'+m.id,method:'host.proxy',params:m.params}));}else if(p.has(m.id)){console.log(JSON.stringify({...m,id:p.get(m.id)}));p.delete(m.id);}});`;
+const sidecar = new AgentSidecar({
+ launch: { command: process.execPath, args: ["-e", child] },
+ onStderr: (text) => process.stderr.write(text),
+});
+sidecar.setHost({
+ call: (method, params) => host.call(method, params),
+ onNotification: () => () => {},
+ onExit: () => () => {},
+});
+sidecar.setLocalTool("GenerateImages", createImageGenerationTool({ dataDir, getHost: () => host }));
+try {
+ await host.start();
+ const project = join(dataDir, "project");
+ await mkdir(project);
+ await host.call("workspace.set", { path: project });
+ const { provider } = await host.call("providers.create", {
+ name: "Image fixture",
+ type: "openai_compatible",
+ protocol: "openai_compatible",
+ authKind: "none",
+ baseUrl: `http://127.0.0.1:${server.address().port}/v1`,
+ defaultModelId: "image-fixture",
+ apiStyle: "chat_completions",
+ });
+ const binding = { providerId: provider.id, modelId: "image-fixture" };
+ await host.call("settings.set", {
+ defaultPermissionMode: "auto",
+ imageGeneration: binding,
+ defaultModelId: "chat-fixture",
+ });
+ const { session } = await host.call("session.create", {
+ title: "Image test",
+ mode: "agent",
+ projectPath: project,
+ providerId: provider.id,
+ modelId: "chat-fixture",
+ });
+ const execute = (id, items) =>
+ sidecar.call("probe", {
+ method: "tools.execute",
+ params: {
+ sessionId: id,
+ toolCallId: randomUUID(),
+ toolName: "GenerateImages",
+ mode: "agent",
+ args: { items },
+ },
+ });
+ const generated = await execute(session.id, [{ prompt: "cover", count: 2 }, { prompt: "icon" }]);
+ assert.equal(generated.ok, true, JSON.stringify(generated));
+ assert.equal(generated.content.results.length, 3);
+ const source = generated.content.results[0].path;
+ const edited = await execute(session.id, [{ prompt: "green background", images: [source] }]);
+ assert.equal(edited.ok, true, JSON.stringify(edited));
+ assert.notEqual(edited.content.results[0].path, source);
+ await host.call("session.appendMessage", {
+ sessionId: session.id,
+ message: {
+ id: randomUUID(),
+ role: "tool",
+ content: "",
+ toolName: "GenerateImages",
+ toolResult: { details: generated.content },
+ createdAt: new Date().toISOString(),
+ status: "complete",
+ },
+ });
+ const { session: plan } = await host.call("session.create", {
+ title: "Plan",
+ mode: "plan",
+ projectPath: project,
+ });
+ const denied = await execute(plan.id, [{ prompt: "must not run" }]);
+ assert.equal(denied.ok, false);
+ assert.equal(requests, 4);
+ await host.restart();
+ const restored = await host.call("settings.get");
+ assert.deepEqual(restored.imageGeneration, binding);
+ assert.equal(restored.defaultModelId, "chat-fixture");
+ const recovered = await host.call("session.get", { id: session.id });
+ assert.deepEqual(recovered.session.messages[0].toolResult.details, generated.content);
+ assert.deepEqual(await readFile(source), png);
+ await host.call("settings.set", { imageGeneration: null });
+ assert.equal(
+ (await execute(session.id, [{ prompt: "unset" }])).errorCode,
+ "IMAGE_NOT_CONFIGURED",
+ );
+ assert.equal(requests, 4);
+ console.log(
+ JSON.stringify({
+ ok: true,
+ fixtureRequests: requests,
+ scenarios: [
+ "batch-generation",
+ "edit-result",
+ "host-plan-denial",
+ "settings-and-transcript-restart",
+ "clear-binding",
+ ],
+ }),
+ );
+} finally {
+ await sidecar.dispose();
+ await host.stop();
+ await new Promise((resolve) => server.close(resolve));
+ await rm(dataDir, { recursive: true, force: true });
+}
diff --git a/scripts/e2e/image-generation-ui.tsx b/scripts/e2e/image-generation-ui.tsx
new file mode 100644
index 000000000..5bf1bb2c8
--- /dev/null
+++ b/scripts/e2e/image-generation-ui.tsx
@@ -0,0 +1,201 @@
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import { createInstance } from "i18next";
+import { I18nextProvider } from "react-i18next";
+import { catalogs } from "@pi-desktop/i18n";
+import type { AppSettings, ProviderPublic, UiMessage } from "@pi-desktop/shared";
+import { ModelConfigPage } from "../../apps/desktop/src/components/settings/ModelConfigPage";
+import { GeneratedImages } from "../../apps/desktop/src/features/chat/transcript/GeneratedImages";
+import { api } from "../../apps/desktop/src/lib/api";
+import { useAppStore } from "../../apps/desktop/src/stores/app-store";
+
+declare global {
+ var imageGenerationProbe: () => Promise<unknown>;
+}
+const assert = (condition: unknown, message: string) => {
+ if (!condition) throw new Error(message);
+};
+const painted = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+async function until(condition: () => boolean, message: string) {
+ const deadline = performance.now() + 6000;
+ while (!condition() && performance.now() < deadline) await painted();
+ assert(condition(), message);
+}
+
+globalThis.imageGenerationProbe = async () => {
+ const i18n = createInstance();
+ await i18n.init({
+ lng: "en",
+ resources: { en: { translation: catalogs.en }, "zh-CN": { translation: catalogs["zh-CN"] } },
+ });
+ let settings = {
+ defaultMode: "agent",
+ defaultProviderId: "chat",
+ defaultModelId: "chat-model",
+ language: "en",
+ } as AppSettings;
+ const provider: ProviderPublic = {
+ id: "p",
+ name: "Images",
+ baseUrl: "https://example.com/v1",
+ vendorKey: "custom",
+ type: "openai_compatible",
+ protocol: "openai_compatible",
+ apiStyle: "chat_completions",
+ authKind: "api_key_and_base_url",
+ enabled: true,
+ hasSecret: true,
+ supportsReasoning: false,
+ supportedThinkingLevels: [],
+ createdAt: "",
+ updatedAt: "",
+ models: ["image-one", "image-two"].map((id) => ({
+ id,
+ contextWindow: 32000,
+ maxTokens: 4096,
+ thinkingLevels: [],
+ defaultThinkingLevel: null,
+ })),
+ };
+ api.getSettings = async () => structuredClone(settings);
+ api.setSettings = async (next) => {
+ settings = structuredClone(next);
+ return { ok: true };
+ };
+ api.listProviders = async () => ({ providers: [provider] });
+ api.listSessions = async () => ({ sessions: [] });
+ api.getOnboarding = async () => ({ dismissed: true });
+ api.listProviderModels = async () => ({ models: [], source: "remote" });
+ api.modelCatalogStatus = async () => ({
+ loaded: true,
+ source: "bundled",
+ catalogPath: "",
+ providerCount: 1,
+ modelCount: 2,
+ });
+ api.updateProvider = async () => ({ provider });
+ api.fsReadImageDataUrl = async () => ({
+ kind: "image",
+ dataUrl:
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9mQAAAAASUVORK5CYII=",
+ });
+ useAppStore.setState({ settings, providers: [provider] });
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ const render = (message?: UiMessage) =>
+ flushSync(() =>
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ {message ? <GeneratedImages message={message} /> : <ModelConfigPage />}
+ </I18nextProvider>,
+ ),
+ );
+ const click = (element: HTMLElement | undefined | null) => {
+ assert(element, "missing click target");
+ flushSync(() => element!.click());
+ };
+ const button = (text: string) =>
+ [...document.querySelectorAll<HTMLButtonElement>("button")].find(
+ (element) => element.textContent?.trim() === text,
+ );
+ try {
+ for (const locale of ["en", "zh-CN"]) {
+ await i18n.changeLanguage(locale);
+ render();
+ const edit =
+ container.querySelector<HTMLButtonElement>(
+ 'button[aria-label="' + i18n.t("settings.editProvider") + '"]',
+ ) ??
+ container.querySelector<HTMLButtonElement>(
+ ".model-provider-row button[aria-label*='Edit']",
+ );
+ // Enter from the real model settings page, not the advanced pane alone.
+ click(edit);
+ await until(
+ () => !!button(i18n.t("settings.setImageModel")),
+ "advanced image-model action missing",
+ );
+ click(button(i18n.t("settings.setImageModel")));
+ assert(!settings.imageGeneration, "draft selection persisted before Save");
+ click(button(i18n.t("settings.cancel")));
+ assert(!settings.imageGeneration, "cancel changed binding");
+ click(
+ container.querySelector<HTMLButtonElement>(
+ 'button[aria-label="' + i18n.t("settings.editProvider") + '"]',
+ ),
+ );
+ await until(() => !!button(i18n.t("settings.setImageModel")), "second edit did not mount");
+ click(button(i18n.t("settings.setImageModel")));
+ click(button(i18n.t("settings.saveProvider")));
+ await until(
+ () =>
+ settings.imageGeneration?.modelId === "image-one" &&
+ !document.querySelector(".provider-setup"),
+ "saved image model missing",
+ );
+ assert(settings.defaultModelId === "chat-model", "image model changed default chat model");
+ const row = [...container.querySelectorAll<HTMLElement>(".settings-row")].find((element) =>
+ element.textContent?.includes(i18n.t("settings.imageModel")),
+ )!;
+ click(
+ [...row.querySelectorAll<HTMLButtonElement>("button")].find(
+ (element) => element.textContent === i18n.t("settings.changeDefaultModel"),
+ ),
+ );
+ await until(() => !!button("Images / image-two"), "replacement picker missing");
+ click(button("Images / image-two"));
+ await until(
+ () => settings.imageGeneration?.modelId === "image-two",
+ "replacement did not persist",
+ );
+ click(button(i18n.t("settings.clearImageModel")));
+ await until(() => settings.imageGeneration === null, "clear did not persist");
+ }
+ const message = {
+ id: "image",
+ role: "tool",
+ content: "",
+ createdAt: "",
+ toolName: "GenerateImages",
+ toolResult: {
+ details: {
+ kind: "generated-images",
+ results: [
+ { index: 0, status: "succeeded", path: "/scratch/result.png", mimeType: "image/png" },
+ { index: 1, status: "failed", errorCode: "IMAGE_TIMEOUT" },
+ ],
+ },
+ },
+ } as UiMessage;
+ render(message);
+ await until(() => !!container.querySelector("img"), "generated preview missing");
+ assert(container.textContent?.includes("IMAGE_TIMEOUT"), "partial failure missing");
+ render({
+ ...message,
+ toolResult: {
+ details: { kind: "image-generation-error", errorCode: "IMAGE_NOT_CONFIGURED" },
+ },
+ });
+ click(button(i18n.t("settings.configureImageModel")));
+ assert(
+ useAppStore.getState().settingsTab === "ai" && useAppStore.getState().page === "settings",
+ "setup action did not navigate",
+ );
+ return {
+ ok: true,
+ locales: ["en", "zh-CN"],
+ scenarios: [
+ "advanced-save-cancel",
+ "replace-clear",
+ "chat-default-preserved",
+ "image-preview-partial-failure",
+ "setup-navigation",
+ ],
+ apiBoundary: "fixture",
+ };
+ } finally {
+ flushSync(() => root.unmount());
+ container.remove();
+ }
+};
diff --git a/scripts/test-image-generation-live.mjs b/scripts/test-image-generation-live.mjs
new file mode 100644
index 000000000..082adfc18
--- /dev/null
+++ b/scripts/test-image-generation-live.mjs
@@ -0,0 +1,167 @@
+/** Explicitly authorized opt-in smoke: at most one generation and one edit. */
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+register(new URL("../apps/desktop/test/helpers/ts-import-hooks.mjs", import.meta.url));
+const { createImageGenerationTool } = await import(
+ "../apps/desktop/electron/main/services/image-generation-service.ts"
+);
+const { imageGenerationParameters, imageGenerationDescription } = await import(
+ "../packages/agent-runtime/src/image-generation/tool.ts"
+);
+const { imageGenerationItems } = await import("../packages/shared/dist/image-generation.js");
+
+let inputConfig = {};
+if (process.argv.includes("--stdin")) {
+ const { createInterface } = await import("node:readline");
+ if (process.stdin.isTTY) process.stdin.setRawMode(true);
+ const reader = createInterface({ input: process.stdin, terminal: false });
+ const line = await new Promise((resolve) => reader.once("line", resolve));
+ reader.close();
+ inputConfig = JSON.parse(line);
+}
+const base = inputConfig.baseUrl || process.env.PI_IMAGE_TEST_BASE_URL;
+const chatKey = inputConfig.chatKey || process.env.PI_IMAGE_TEST_CHAT_KEY;
+const imageKey = inputConfig.imageKey || process.env.PI_IMAGE_TEST_IMAGE_KEY;
+const imageModel = inputConfig.imageModel || process.env.PI_IMAGE_TEST_MODEL;
+assert(base && chatKey && imageKey && imageModel, "Set the opt-in image test environment first.");
+const apiBase = new URL(base);
+if (!apiBase.pathname.replace(/\/+$/, "")) apiBase.pathname = "/v1";
+const url = (path) => `${apiBase.href.replace(/\/+$/, "")}/${path}`;
+const chatHeaders = { Authorization: `Bearer ${chatKey}`, "Content-Type": "application/json" };
+const directory = await mkdtemp(join(tmpdir(), "pi-image-live-"));
+let attempts = 0;
+try {
+ const list = await fetch(url("models"), {
+ headers: chatHeaders,
+ redirect: "error",
+ signal: AbortSignal.timeout(30_000),
+ });
+ assert(list.ok, `Model discovery HTTP ${list.status}`);
+ const ids = ((await list.json()).data ?? [])
+ .map((row) => row.id)
+ .filter((id) => typeof id === "string");
+ const chatModel =
+ process.env.PI_IMAGE_TEST_CHAT_MODEL ||
+ ["deepseek", "deepseek-chat", "deepseek-v3"].find((id) => ids.includes(id)) ||
+ ids.find((id) => /deepseek/i.test(id));
+ assert(chatModel, "No DeepSeek model was advertised by the supplied endpoint.");
+ const chat = await fetch(url("chat/completions"), {
+ method: "POST",
+ headers: chatHeaders,
+ redirect: "error",
+ signal: AbortSignal.timeout(90_000),
+ body: JSON.stringify({
+ model: chatModel,
+ messages: [
+ {
+ role: "user",
+ content:
+ "Use GenerateImages exactly once to generate ONE simple raster illustration of a blue ceramic cup on a plain white background. No text, no variants, no input images. Return a tool call.",
+ },
+ ],
+ tools: [
+ {
+ type: "function",
+ function: {
+ name: "GenerateImages",
+ description: imageGenerationDescription,
+ parameters: {
+ type: "object",
+ properties: imageGenerationParameters,
+ required: ["items"],
+ },
+ },
+ },
+ ],
+ tool_choice: "auto",
+ max_tokens: 1200,
+ }),
+ });
+ assert(chat.ok, `DeepSeek HTTP ${chat.status}`);
+ const call = (await chat.json()).choices?.[0]?.message?.tool_calls?.[0];
+ assert.equal(
+ call?.function?.name,
+ "GenerateImages",
+ "DeepSeek did not return the expected tool call.",
+ );
+ const input = JSON.parse(call.function.arguments);
+ const jobs = imageGenerationItems(input);
+ assert(jobs.length === 1 && !jobs[0].images, "Live test refuses more than one initial image.");
+ const host = {
+ call: async (method) => {
+ if (method === "settings.get")
+ return { imageGeneration: { providerId: "live-image", modelId: imageModel } };
+ if (method === "providers.get")
+ return {
+ provider: {
+ id: "live-image",
+ enabled: true,
+ authKind: "api_key_and_base_url",
+ baseUrl: apiBase.href,
+ models: [{ id: imageModel }],
+ },
+ };
+ if (method === "providers.getSecret") return { value: imageKey };
+ if (method === "session.getScratchPath") return { path: join(directory, "scratch", "live") };
+ if (method === "session.get") return { session: {} };
+ throw new Error("Unexpected host method");
+ },
+ };
+ const tool = createImageGenerationTool({
+ dataDir: directory,
+ getHost: () => host,
+ fetchImpl: async (...args) => {
+ assert(++attempts <= 2, "Live image request budget exhausted");
+ return fetch(...args);
+ },
+ });
+ const run = (args) =>
+ tool({
+ sessionId: "live",
+ toolCallId: String(attempts),
+ args,
+ signal: new AbortController().signal,
+ });
+ const generated = await run(input);
+ console.log(
+ JSON.stringify({
+ stage: "generation",
+ chatModel,
+ imageModel,
+ toolCalled: true,
+ results: generated.content.results?.map(({ status, errorCode, mimeType }) => ({
+ status,
+ errorCode,
+ mimeType,
+ })),
+ }),
+ );
+ assert(generated.ok, "Live generation failed; no retry was attempted.");
+ const edited = await run({
+ items: [
+ {
+ prompt:
+ "Change only the blue ceramic cup to green. Preserve the plain white background and the composition.",
+ images: [generated.content.results[0].path],
+ },
+ ],
+ });
+ console.log(
+ JSON.stringify({
+ stage: "edit",
+ imageModel,
+ results: edited.content.results?.map(({ status, errorCode, mimeType }) => ({
+ status,
+ errorCode,
+ mimeType,
+ })),
+ attempts,
+ }),
+ );
+ assert(edited.ok, "Live edit failed; no retry was attempted.");
+} finally {
+ await rm(directory, { recursive: true, force: true });
+}