Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(images): refine settings and keep generated previews visible
Jackf5c19739ec23
diff --git a/apps/desktop/electron/main/services/image-generation-service.ts b/apps/desktop/electron/main/services/image-generation-service.tsindex 99da58cc4..b85bf7ac5 100644--- a/apps/desktop/electron/main/services/image-generation-service.ts+++ b/apps/desktop/electron/main/services/image-generation-service.ts@@ -35,7 +35,7 @@ export function createImageGenerationTool(options: {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.",+ "Configure an image generation model in Settings > Models > Image generation model before generating images. Do not substitute another model.",);const { provider } = await host.call<{ provider?: ProviderPublic }>("providers.get", {id: binding.providerId,@@ -47,7 +47,7 @@ export function createImageGenerationTool(options: {) {return failure("IMAGE_MODEL_UNAVAILABLE",- "The configured image model is unavailable. Update Settings > AI > Image generation model.",+ "The configured image model is unavailable. Update Settings > Models > Image generation model.",);}if (provider.authKind === "oauth")diff --git a/apps/desktop/resources/skills/image-generation.md b/apps/desktop/resources/skills/image-generation.mdindex 31590959c..7e4178b48 100644--- a/apps/desktop/resources/skills/image-generation.md+++ b/apps/desktop/resources/skills/image-generation.md@@ -6,7 +6,7 @@ description: Generate or edit raster images, illustrations, photos, banners, and# Image generationUse the desktop `GenerateImages` tool. The user selects its provider and model-under Settings → AI → Image generation model; this is independent of the chat+under Settings → Models → Image generation model; this is independent of the chatmodel. If ToolSearch is available and GenerateImages is not loaded, discover itthere first. Do not install an SDK, run an API script, ask for a key in chat, orsubstitute the conversation model.@@ -42,7 +42,7 @@ Example: two cover variants and one distinct icon: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.+model is configured, direct the user to Settings → Models; do not select one silently.## Deliver the resultdiff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsxindex 9a03b7799..253829c8c 100644--- a/apps/desktop/src/components/Markdown.tsx+++ b/apps/desktop/src/components/Markdown.tsx@@ -51,6 +51,7 @@ import {} from "../lib/latex-math";import { useAppStore } from "../stores/app-store";import { useReferencedImageDataUrl } from "../lib/use-referenced-image-data-url";+import { absoluteImagePath, remarkLocalImagePaths } from "../lib/markdown-image-paths";import { useOpenChatFileRef } from "../hooks/use-preview-target";import {remarkChatFileLinks,@@ -621,7 +622,7 @@ function MarkdownImage({!isRemote && /^attachments\/[0-9a-f]{64}$/i.test(decoded.replace(/\\/g, "/"))? decoded.replace(/\\/g, "/"): null;- const localRef = rel ?? attachmentRef;+ const localRef = (isRemote ? null : absoluteImagePath(source)) ?? rel ?? attachmentRef;// Always run the hook before any branch so hook order stays stable when a// streaming src flips between remote and local. Remote images pass null.const dataUrl = useReferencedImageDataUrl(isRemote ? null : localRef);@@ -716,7 +717,7 @@ const markdownComponents: Components = {table: Table,};-const staticRemarkPlugins = [remarkGfm, remarkMath];+const staticRemarkPlugins = [remarkGfm, remarkMath, remarkLocalImagePaths];// Extend the default schema only for the media elements rendered above, plus// `remark-math`'s math classes on `<code>`: the default `language-*` allow listdiff --git a/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx b/apps/desktop/src/components/settings/ImageGenerationModelRow.tsxindex a245f1e68..0f829985f 100644--- a/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx+++ b/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx@@ -1,124 +1,32 @@-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";+import type { AppSettings, ProviderPublic } from "@pi-desktop/shared";-export function ImageGenerationModelRow({- settings,- providers,-}: {+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) &&+ const valid = provider?.enabled && provider.authKind !== "oauth" &&+ !!provider.baseUrl && (provider.hasSecret || provider.authKind === "none") &&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>+ <div className="settings-row model-default-row model-image-row">+ <div className="settings-row-copy model-default-copy">+ <div className="settings-row-title model-default-label">{t("settings.imageModel")}</div>+ <div className="settings-row-detail model-default-value">+ {valid && binding ? (+ <>+ <span className="model-default-provider">{provider.name}</span>+ <span className="model-default-sep" aria-hidden>·</span>+ <span className="model-default-model font-mono">{binding.modelId}</span>+ </>+ ) : (+ <span className="model-default-empty" role="status">{t("settings.imageModelUnavailable")}</span>)}- >- <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></div>);diff --git a/apps/desktop/src/components/settings/ModelConfigPage.tsx b/apps/desktop/src/components/settings/ModelConfigPage.tsxindex 8e98b7606..8b0d3f8d1 100644--- a/apps/desktop/src/components/settings/ModelConfigPage.tsx+++ b/apps/desktop/src/components/settings/ModelConfigPage.tsx@@ -423,11 +423,10 @@ export function ModelConfigPage() {</div></AnchoredMenu></div>+ <ImageGenerationModelRow settings={settings} providers={providers} /></div></section>- <ImageGenerationModelRow settings={settings} providers={providers} />-<section className="settings-card-block"><div className="model-config-section-head"><div className="settings-card-heading-line">diff --git a/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx b/apps/desktop/src/features/chat/transcript/ActivityGroup.tsxindex 9b95b5442..18c1718c1 100644--- a/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx+++ b/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx@@ -359,6 +359,7 @@ export const ActivityGroup = memo(function ActivityGroup({return (<Fragment key={item.message.id}><ToolRow+ imagesInTurnmessage={item.message}autoOpen={autoOpenLatest}onUserInteraction={claimDisclosure}diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsxindex 9ce21de86..5a474c701 100644--- a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx+++ b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx@@ -42,6 +42,7 @@ import {MessageMeta,} from "./shared";import { activityItemsEqual, ActivityGroup } from "./ActivityGroup";+import { GeneratedImages } from "./GeneratedImages";import { MessageRow } from "./MessageRow";import { assistantTurnMenuItems } from "./menu-items";import {@@ -378,6 +379,9 @@ export const AssistantTurn = memo(function AssistantTurn({) : (entry.parts.map(renderPart))}+ {turnAllActivityItems.filter((item) => item.kind === "tool" && item.message.toolName === "GenerateImages").map((item) => (+ <GeneratedImages key={item.message.id} message={item.message} />+ ))}{!isActive && metaMessage ? (<MessageMetamodelId={modelId}diff --git a/apps/desktop/src/features/chat/transcript/GeneratedImages.tsx b/apps/desktop/src/features/chat/transcript/GeneratedImages.tsxindex 99a50e5e5..34cab3353 100644--- a/apps/desktop/src/features/chat/transcript/GeneratedImages.tsx+++ b/apps/desktop/src/features/chat/transcript/GeneratedImages.tsx@@ -61,7 +61,7 @@ export function GeneratedImages({ message }: { message: UiMessage }) {variant="ghost"onClick={() => {const state = useAppStore.getState();- state.setSettingsTab("ai");+ state.setSettingsTab("agent");state.setSettingsAnchor("settings.imageModel");state.setPage("settings");}}diff --git a/apps/desktop/src/features/chat/transcript/ToolRow.tsx b/apps/desktop/src/features/chat/transcript/ToolRow.tsxindex e483d038d..37640f490 100644--- a/apps/desktop/src/features/chat/transcript/ToolRow.tsx+++ b/apps/desktop/src/features/chat/transcript/ToolRow.tsx@@ -87,6 +87,8 @@ type ToolRowProps = {variant?: "default" | "topology";/** Open the latest detailed-mode tool unless the user took over. */autoOpen?: boolean;+ /** The containing turn renders image results outside its process disclosure. */+ imagesInTurn?: boolean;/** Claims the containing activity group when this row is manually used. */onUserInteraction?: () => void;/** Live delegation statuses read from the turn's lifecycle-tool rows. */@@ -117,6 +119,7 @@ function toolRowPropsEqual(previous.message !== next.message ||previous.variant !== next.variant ||previous.autoOpen !== next.autoOpen ||+ previous.imagesInTurn !== next.imagesInTurn ||previous.onUserInteraction !== next.onUserInteraction ||!subagentRunsEqual(previous.delegate, next.delegate)) {@@ -142,6 +145,7 @@ export const ToolRow = memo(function ToolRow({delegate,variant = "default",autoOpen = false,+ imagesInTurn = false,onUserInteraction,delegationStatuses,delegationTimings,@@ -525,7 +529,7 @@ export const ToolRow = memo(function ToolRow({<ToolDetailBlocks blocks={blocks} plain={runHead} /></div>) : null}- <GeneratedImages message={message} />+ {!imagesInTurn && <GeneratedImages message={message} />}{inlineOpen && delegate ? (<SubagentRunRowsrun={delegate}diff --git a/apps/desktop/src/lib/markdown-image-paths.ts b/apps/desktop/src/lib/markdown-image-paths.tsnew file mode 100644index 000000000..5333f9cce--- /dev/null+++ b/apps/desktop/src/lib/markdown-image-paths.ts@@ -0,0 +1,31 @@+interface ImagePathNode {+ type: string;+ url?: string;+ children?: ImagePathNode[];+}++/** Recognition only: the host image reader remains responsible for containment. */+export function absoluteImagePath(source: string): string | null {+ let decoded: string;+ try {+ decoded = decodeURIComponent(source);+ } catch {+ return null;+ }+ if (decoded.includes("\0")) return null;+ return /^(?:[a-z]:[\\/]|\/(?!\/))[^\r\n]+$/i.test(decoded) ? decoded : null;+}++/** Encode drive letters before URL sanitization without allowing new protocols. */+export function remarkLocalImagePaths() {+ return (tree: ImagePathNode) => {+ const visit = (node: ImagePathNode) => {+ if (node.type === "image" && typeof node.url === "string") {+ const path = absoluteImagePath(node.url);+ if (path) node.url = encodeURIComponent(path);+ }+ node.children?.forEach(visit);+ };+ visit(tree);+ };+}diff --git a/apps/desktop/src/styles/model-config.css b/apps/desktop/src/styles/model-config.cssindex 0f16dd36c..c98e4b6f7 100644--- a/apps/desktop/src/styles/model-config.css+++ b/apps/desktop/src/styles/model-config.css@@ -10,6 +10,10 @@/* ------------------------------------------------- catalog status footer */+.model-config-page .model-default-panel {+ gap: 12px;+}+/* models.dev is the enrichment source, so the page only reports its snapshot. */.model-catalog-status {display: flex;diff --git a/apps/desktop/test/markdown-image-paths.test.mjs b/apps/desktop/test/markdown-image-paths.test.mjsnew file mode 100644index 000000000..f867f92ef--- /dev/null+++ b/apps/desktop/test/markdown-image-paths.test.mjs@@ -0,0 +1,30 @@+import assert from "node:assert/strict";+import test from "node:test";+import { absoluteImagePath, remarkLocalImagePaths } from "../src/lib/markdown-image-paths.ts";++test("absolute image paths survive URL encoding without enabling URL protocols", () => {+ for (const path of [String.raw`C:\scratch\cup.png`, "D:/work/cup image.png", "/tmp/scratch/杯子.png"]) {+ assert.equal(absoluteImagePath(path), path);+ assert.equal(absoluteImagePath(encodeURIComponent(path)), path);+ const tree = { type: "root", children: [{ type: "image", url: path }] };+ remarkLocalImagePaths()(tree);+ assert.equal(tree.children[0].url, encodeURIComponent(path));+ }+});++test("remote, executable, network and malformed paths are not local image refs", () => {+ for (const source of ["https://example.com/image.png", "javascript:alert(1)", "data:image/png;base64,AA", "//server/share.png", String.raw`\\server\share.png`, "file://server/share.png", "C:relative.png", "../image.png", "%ZZ", "C:/image%00.png", "C:/image\n.png"]) {+ assert.equal(absoluteImagePath(source), null, source);+ }+});++test("the image transformer preserves ordinary links, relative and remote images", () => {+ const tree = { type: "root", children: [+ { type: "link", url: "C:/file.md" },+ { type: "image", url: "relative.png" },+ { type: "image", url: "https://example.com/image.png" },+ ] };+ const original = structuredClone(tree);+ remarkLocalImagePaths()(tree);+ assert.deepEqual(tree, original);+});diff --git a/docs/spec/03-runtime/21-image-generation.md b/docs/spec/03-runtime/21-image-generation.mdindex 00ae77215..89bbe1be6 100644--- a/docs/spec/03-runtime/21-image-generation.md+++ b/docs/spec/03-runtime/21-image-generation.md@@ -11,9 +11,11 @@ an existing enabled API-key or no-auth provider and one of its configured modelsModel Advanced offers **Set as image model**. A draft selection only takes effectwhen the provider form saves; Cancel leaves settings unchanged. Saving a provideras 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.+default model row in the same defaults panel, **Image generation model** is a+read-only summary with the same provider/model typography and a 12px row gap.+It has no Change or Clear actions; replacement uses the provider's Advanced+settings. Missing, disabled, credential-less or removed bindings display only+**Currently unavailable**. OAuth accounts are not eligible; there is no fallback.## Agent contract@@ -66,12 +68,20 @@ path/MIME type or a safe error code. New files get unique names in session scratediting never overwrites its source. The tool result and transcript retain filereferences, 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+completed. Missing configuration returns a structured error and a Settings → Modelsnavigation action. The same references render after session reload/restart.+Image results and setup actions remain visible outside the turn's collapsible+process details; opening tool details does not duplicate the image gallery.+Markdown image references to generated absolute paths, including Windows drive+paths, use the existing bounded host image reader. URL sanitization stays enabled;+the host still rejects files outside its permitted workspace/scratch/attachment roots.Validation: `node scripts/e2e-image-generation.mjs` covers host/stdio/HTTP/storage;`node scripts/e2e-image-generation-ui.mjs` covers real React/Chromium interactionswith an API-boundary fixture. Unit/service tests cover limits, cancellation,partial failures, authentication, timeout, unsafe paths, and bounded downloads.+`node scripts/e2e-image-chat.mjs` exercises the full isolated desktop with local+model/image HTTP fixtures: adjacent default settings, composer submission, batch+previews, editing a generated file, collapsed results, and setup navigation.Live verification is opt-in via `scripts/test-image-generation-live.mjs`, limitedto one generation plus one edit and never a default test command.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 4057bb062..98f387892 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -8,6 +8,26 @@## 1. Goals+### E2E-IMAGES-desktop-conversation++- **Preconditions:** Isolated desktop profile and workspace, built image feature,+ local chat and OpenAI Images HTTP fixtures; no live provider credentials.+- **Steps:** Open Models settings; verify the conversation and image defaults+ share a compact panel. Submit a two-image request through the composer, then+ edit the first output through a follow-up message. Collapse tool details.+ Clear the binding and follow the visible configuration action back to Models.+- **Expected:** A 12px default-row gap, decoded image previews outside collapsed+ process details, multipart source upload for editing, preserved originals,+ and no image HTTP request while unconfigured.+- **Settings interactions:** The image summary has no Change/Clear buttons and+ matches the default model's provider/model text styles. Select another+ provider's image model in Advanced and save; the summary changes while the+ chat default stays unchanged. Missing/disabled bindings show only Currently+ unavailable. Covered in `scripts/e2e-image-generation-ui.mjs`.+- **Status:** Automated in `node scripts/e2e-image-chat.mjs`; optional screenshots+ use `PI_IMAGE_CHAT_EVIDENCE_DIR`. The images are deterministic raster fixtures,+ not evidence of real-model quality or provider compatibility.+### E2E-SCHEDULED-desktop-automation-lifecycle- **Preconditions:** Isolated desktop profile, built task candidate, local SSEdiff --git a/package.json b/package.jsonindex 3b2d1ab2e..3a211d5fa 100644--- a/package.json+++ b/package.json@@ -31,7 +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:images": "node scripts/e2e-image-generation.mjs && node scripts/e2e-image-generation-ui.mjs && node scripts/e2e-image-chat.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/tool.ts b/packages/agent-runtime/src/image-generation/tool.tsindex e7d877926..07b36d6bd 100644--- a/packages/agent-runtime/src/image-generation/tool.ts+++ b/packages/agent-runtime/src/image-generation/tool.ts@@ -1,7 +1,7 @@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.";+ "Generate raster images using the image model configured in Settings > Models. 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({diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 7d1d8aeaf..dcfb173e6 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -552,7 +552,7 @@ export const de = {"settings": {"imageModel": "Bildgenerierungsmodell","imageModelUnset": "Nicht konfiguriert",- "imageModelUnavailable": "Dieses Bildmodell ist nicht verfügbar. Wählen Sie ein anderes.",+ "imageModelUnavailable": "Derzeit nicht verfügbar","imageModelSaveFailed": "Bildmodell konnte nicht gespeichert werden.","clearImageModel": "Löschen","setImageModel": "Als Bildmodell festlegen",@@ -560,7 +560,7 @@ export const de = {"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.",+ "imageModelSetupHint": "Konfigurieren Sie ein Bildmodell unter Einstellungen → Modelle.","configureImageModel": "Bildmodell konfigurieren",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 546d27a1c..05e14dfa0 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -559,7 +559,7 @@ export const en = {settings: {imageModel: "Image generation model",imageModelUnset: "Not configured",- imageModelUnavailable: "This image model is unavailable. Choose another model.",+ imageModelUnavailable: "Currently unavailable",imageModelSaveFailed: "Could not save the image model.",clearImageModel: "Clear",setImageModel: "Set as image model",@@ -567,7 +567,7 @@ export const en = {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.",+ imageModelSetupHint: "Configure an image model in Settings → Models before generating images.",configureImageModel: "Configure image model",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 04311bd85..ad5afaf0c 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -552,7 +552,7 @@ export const es = {"settings": {"imageModel": "Modelo de imágenes","imageModelUnset": "Sin configurar",- "imageModelUnavailable": "Este modelo no está disponible. Elige otro.",+ "imageModelUnavailable": "No disponible por ahora","imageModelSaveFailed": "No se pudo guardar el modelo.","clearImageModel": "Borrar","setImageModel": "Usar para generar imágenes",@@ -560,7 +560,7 @@ export const es = {"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.",+ "imageModelSetupHint": "Configura un modelo de imágenes en Ajustes → Modelos.","configureImageModel": "Configurar modelo de imágenes",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex b3cae75a3..9dfb10575 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -552,7 +552,7 @@ export const fr = {"settings": {"imageModel": "Modèle de génération d’images","imageModelUnset": "Non configuré",- "imageModelUnavailable": "Ce modèle est indisponible. Choisissez-en un autre.",+ "imageModelUnavailable": "Indisponible pour le moment","imageModelSaveFailed": "Impossible d’enregistrer le modèle.","clearImageModel": "Effacer","setImageModel": "Définir comme modèle d’images",@@ -560,7 +560,7 @@ export const fr = {"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.",+ "imageModelSetupHint": "Configurez un modèle d’images dans Paramètres → Modèles.","configureImageModel": "Configurer le modèle d’images",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 1396300aa..586504577 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -561,7 +561,7 @@ export const ko = {settings: {"imageModel": "이미지 생성 모델","imageModelUnset": "설정되지 않음",- "imageModelUnavailable": "이 이미지 모델을 사용할 수 없습니다. 다른 모델을 선택하세요.",+ "imageModelUnavailable": "현재 사용 불가","imageModelSaveFailed": "이미지 모델을 저장할 수 없습니다.","clearImageModel": "지우기","setImageModel": "이미지 모델로 설정",@@ -569,7 +569,7 @@ export const ko = {"generatedImage": "생성된 이미지 {{index}}","imagePreviewUnavailable": "미리보기 불가; 파일 열기","imageGenerationFailed": "이미지 {{index}} 생성이 완료되지 않았습니다.",- "imageModelSetupHint": "설정 → AI에서 이미지 모델을 설정하세요.",+ "imageModelSetupHint": "설정 → 모델에서 이미지 모델을 설정하세요.","configureImageModel": "이미지 모델 설정",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex e7d3a1a60..d2036d327 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -561,7 +561,7 @@ export const tr = {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.",+ "imageModelUnavailable": "Şu anda kullanılamıyor","imageModelSaveFailed": "Görsel modeli kaydedilemedi.","clearImageModel": "Temizle","setImageModel": "Görsel modeli olarak ayarla",@@ -569,7 +569,7 @@ export const tr = {"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.",+ "imageModelSetupHint": "Ayarlar → Modeller bölümünde bir görsel modeli yapılandırın.","configureImageModel": "Görsel modelini yapılandır",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 172be5da8..4b321c26b 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -556,7 +556,7 @@ export const zhCN = {settings: {imageModel: "生图模型",imageModelUnset: "未配置",- imageModelUnavailable: "当前生图模型不可用,请选择其他模型。",+ imageModelUnavailable: "暂不可用",imageModelSaveFailed: "无法保存生图模型。",clearImageModel: "清除",setImageModel: "设为生图模型",@@ -564,7 +564,7 @@ export const zhCN = {generatedImage: "生成图片 {{index}}",imagePreviewUnavailable: "预览不可用,打开文件",imageGenerationFailed: "图片 {{index}} 未完成。",- imageModelSetupHint: "请前往 设置 → AI → 生图模型 完成配置。",+ imageModelSetupHint: "请前往 设置 → 模型 → 生图模型 完成配置。",configureImageModel: "配置生图模型",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 0184c917c..a4de10a8e 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -556,7 +556,7 @@ export const zhTW = {settings: {imageModel: "生圖模型",imageModelUnset: "未設定",- imageModelUnavailable: "目前生圖模型無法使用,請選擇其他模型。",+ imageModelUnavailable: "暫不可用",imageModelSaveFailed: "無法儲存生圖模型。",clearImageModel: "清除",setImageModel: "設為生圖模型",@@ -564,7 +564,7 @@ export const zhTW = {generatedImage: "生成圖片 {{index}}",imagePreviewUnavailable: "無法預覽,開啟檔案",imageGenerationFailed: "圖片 {{index}} 未完成。",- imageModelSetupHint: "請前往 設定 → AI → 生圖模型 完成設定。",+ imageModelSetupHint: "請前往 設定 → 模型 → 生圖模型 完成設定。",configureImageModel: "設定生圖模型",diff --git a/scripts/e2e-image-chat.mjs b/scripts/e2e-image-chat.mjsnew file mode 100644index 000000000..fdb613442--- /dev/null+++ b/scripts/e2e-image-chat.mjs@@ -0,0 +1,222 @@+#!/usr/bin/env node+// Real desktop, preload, Host SQLite and agent sidecar; only the model is local SSE.+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createServer } from "node:http";+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { once } from "node:events";+import { Host, resolveHostBinary } from "./e2e/host.mjs";+import { resolveElectronBinary } from "./e2e/boot.mjs";+import { waitFor } from "./e2e/wait.mjs";+import { imageChatModel } from "./e2e/image-chat-model.mjs";++const root = mkdtempSync(join(tmpdir(), "pi-image-chat-e2e-"));+const dataDir = join(root, "data"),+ project = join(root, "project");+mkdirSync(project);+const evidence = process.env.PI_IMAGE_CHAT_EVIDENCE_DIR;+if (evidence) mkdirSync(evidence, { recursive: true });+const model = imageChatModel();+const server = createServer(model.handler);+await new Promise((done) => server.listen(0, "127.0.0.1", done));+const host = new Host(resolveHostBinary(), dataDir);+await host.start();+await host.call("workspace.set", { path: project });+const { provider } = await host.call("providers.create", {+ name: "本地测试服务",+ vendorKey: "custom",+ type: "openai_compatible",+ protocol: "openai_compatible",+ baseUrl: `http://127.0.0.1:${server.address().port}/v1`,+ authKind: "none",+ defaultModelId: "fixture",+ apiStyle: "chat_completions",+});+await host.call("settings.set", {+ language: "zh-CN",+ defaultProviderId: provider.id,+ defaultModelId: "fixture",+ defaultMode: "agent",+ defaultPermissionMode: "auto",+});+const { provider: imageProvider } = await host.call("providers.create", {+ name: "Image-only fixture", vendorKey: "custom", type: "openai_compatible",+ protocol: "openai_compatible", baseUrl: `http://127.0.0.1:${server.address().port}/v1`,+ authKind: "none", defaultModelId: "fixture", apiStyle: "chat_completions",+});+await host.call("settings.set", { imageGeneration: { providerId: imageProvider.id, modelId: "fixture" } });+await host.stop();++const { appDir, electronBinary } = resolveElectronBinary();+const port = Number(process.env.PI_IMAGE_CHAT_CDP_PORT || 9386);+const env = {+ ...process.env,+ PI_DESKTOP_DATA_DIR: dataDir,+ PI_DESKTOP_START_MAXIMIZED: "0",+ ELECTRON_RENDERER_URL: "",+};+delete env.ELECTRON_RUN_AS_NODE;+const child = spawn(+ electronBinary,+ [`--remote-debugging-port=${port}`, `--user-data-dir=${join(root, "profile")}`, "."],+ { cwd: appDir, env, stdio: ["ignore", "pipe", "pipe"] },+);+let output = "";+child.stdout.on("data", (data) => {+ output += data;+});+child.stderr.on("data", (data) => {+ output += data;+});+let ws;+try {+ let target;+ await waitFor(+ async () => {+ try {+ target = (await (await fetch(`http://127.0.0.1:${port}/json/list`)).json()).find(+ (entry) =>+ entry.type === "page" &&+ entry.url.includes("index.html") &&+ !entry.url.includes("plugin-launcher"),+ );+ return !!target;+ } catch {+ return false;+ }+ },+ 30_000,+ "desktop CDP target",+ );+ ws = new WebSocket(target.webSocketDebuggerUrl);+ console.log("Desktop target", target.url);+ await once(ws, "open");+ let sequence = 0;+ const pending = new Map();+ ws.onmessage = ({ data }) => {+ const message = JSON.parse(data),+ entry = pending.get(message.id);+ if (!entry) return;+ pending.delete(message.id);+ if (message.error) entry.reject(new Error(JSON.stringify(message.error)));+ else entry.resolve(message.result);+ };+ const send = (method, params = {}) =>+ new Promise((resolveCall, reject) => {+ const id = ++sequence;+ pending.set(id, { resolve: resolveCall, reject });+ ws.send(JSON.stringify({ id, method, params }));+ });+ const evaluate = async (expression) => {+ const result = await send("Runtime.evaluate", {+ expression,+ awaitPromise: true,+ returnByValue: true,+ });+ if (result.exceptionDetails)+ throw new Error(+ result.exceptionDetails.exception?.description ?? JSON.stringify(result.exceptionDetails),+ );+ return result.result.value;+ };+ const invoke = (name, ...args) =>+ evaluate(+ `(async () => { const r = await window.piDesktop.invoke(window.piDesktop.channels.invoke[${JSON.stringify(name)}], ...${JSON.stringify(args)}); if (!r.ok) throw new Error(JSON.stringify(r.error)); return r.data; })()`,+ );+ await send("Page.enable");+ const click = async (text, selector = "button", byLabel = false) => {+ await waitFor(+ () =>+ evaluate(+ `(() => { const e = [...document.querySelectorAll(${JSON.stringify(selector)})].find(e => (${byLabel} ? e.getAttribute('aria-label') : e.textContent.trim()) === ${JSON.stringify(text)}); return !!e && !e.disabled; })()`,+ ),+ 5000,+ `enabled ${text}`,+ );+ const point = await evaluate(+ `(() => { const button = [...document.querySelectorAll(${JSON.stringify(selector)})].find(e => (${byLabel} ? e.getAttribute('aria-label') : e.textContent.trim()) === ${JSON.stringify(text)}); if (!button || button.disabled) return null; button.scrollIntoView({block:'nearest'}); const r=button.getBoundingClientRect(), x=r.x+r.width/2, y=r.y+r.height/2; return button.contains(document.elementFromPoint(x,y)) ? {x,y} : null; })()`,+ );+ assert.ok(point, `button hit target: ${text}`);+ await send("Input.dispatchMouseEvent", {+ type: "mousePressed",+ ...point,+ button: "left",+ clickCount: 1,+ });+ await send("Input.dispatchMouseEvent", {+ type: "mouseReleased",+ ...point,+ button: "left",+ clickCount: 1,+ });+ };+ const key = async (name, code) => {+ await send("Input.dispatchKeyEvent", { type: "keyDown", key: name, code: name, windowsVirtualKeyCode: code, ...(name === "Enter" ? { text: "\r" } : {}) });+ await send("Input.dispatchKeyEvent", { type: "keyUp", key: name, code: name, windowsVirtualKeyCode: code });+ };+ const screenshot = async (name) => {+ if (evidence) {+ const result = await send("Page.captureScreenshot", { format: "png" });+ writeFileSync(join(evidence, name), Buffer.from(result.data, "base64"));+ }+ };+ await send("Emulation.setDeviceMetricsOverride", {width:1280,height:900,deviceScaleFactor:1,mobile:false});+ await waitFor(() => evaluate(`!!document.querySelector('[data-nav="settings"]') && !document.querySelector('.startup-splash')`),30000,"desktop ready");+ await evaluate(`document.querySelector('[data-nav="settings"]').click()`);+ await waitFor(() => evaluate(`!![...document.querySelectorAll('button')].find(e=>e.textContent.trim()==='AI')`),10000,"AI settings");+ await click("AI");+ await click("模型");+ await waitFor(() => evaluate(`!!document.querySelector('.model-default-row')`),10000,"model defaults");+ const gap = await evaluate(`(() => {const rows=[...document.querySelectorAll('.settings-row')];const image=rows.find(e=>e.innerText.includes('生图模型'));return image.getBoundingClientRect().top-document.querySelector('.model-default-row').getBoundingClientRect().bottom})()`);+ await screenshot("settings.png");+ assert.ok(gap>=11 && gap<=13, `defaults gap ${gap}px`);+ await click("返回应用");+ const prompt = async (content) => {+ await waitFor(() => evaluate(`!!document.querySelector('.composer-input[contenteditable="true"]')`),10000,"composer ready");+ await evaluate(`document.querySelector('.composer-input').focus()`);+ await send("Input.insertText",{text:content});+ await key("Enter",13);+ };+ await prompt("请生成两张橙色球体、蓝色背景的图片。");+ await waitFor(() => evaluate(`document.querySelectorAll('.generated-image-preview img').length===2 && [...document.querySelectorAll('.generated-image-preview img')].every(e=>e.naturalWidth===480) && document.body.innerText.includes('已生成两张图片')`),60000,"batch images decoded in chat");+ assert.ok(await evaluate(`[...document.querySelectorAll('.generated-image-preview img')].every(e=>e.checkVisibility() && !e.closest('[inert]'))`), "generated images remain visible outside collapsed tool details");+ await screenshot("chat-batch.png");+ const source = model.results[0].value.results[0].path;+ const sourceBytes = readFileSync(source);+ assert.equal(model.imageRequests.length,2);+ model.setScenario("edit");+ await prompt("把第一张图片背景改成绿色,保留橙色球体和原图。");+ await waitFor(() => evaluate(`document.querySelectorAll('.generated-image-preview img').length===3 && [...document.querySelectorAll('.generated-image-preview img')].every(e=>e.naturalWidth===480) && document.body.innerText.includes('已将第一张图的背景改为绿色')`),60000,"edited image decoded in chat");+ await waitFor(() => evaluate(`!document.querySelector('.assistant-turn.streaming')`),10000,"turn completed");+ await evaluate(`document.querySelectorAll('.turn-process > button[aria-expanded="true"]').forEach(e=>e.click())`);+ await evaluate(`Promise.all(document.getAnimations().filter(a=>a.effect?.getTiming().iterations!==Infinity).map(a=>a.finished.catch(()=>{})))`);+ assert.ok(await evaluate(`[...document.querySelectorAll('.generated-image-preview img')].every(e=>e.checkVisibility() && !e.closest('[inert]'))`), "collapse preserves generated and edited previews");+ await evaluate(`[...document.querySelectorAll('.message-row.user')].at(-1)?.scrollIntoView({block:'start'})`);+ await screenshot("chat-edit.png");+ assert.equal(model.imageRequests.length,3);+ assert.ok(model.imageRequests[2].edited);+ assert.deepEqual(readFileSync(source),sourceBytes,"editing preserves the original file");+ assert.notEqual(model.results[1].value.results[0].path,source,"editing creates a new file");+ await invoke("settingsSet", {...await invoke("settingsGet"),imageGeneration:null});+ model.setScenario("unset");+ await prompt("再生成一张图片。");+ await waitFor(() => evaluate(`!![...document.querySelectorAll('button')].find(e=>e.textContent.trim()==='配置生图模型' && e.checkVisibility())`),60000,"visible setup action");+ await waitFor(() => evaluate(`!document.querySelector('.stop-btn') && document.body.innerText.includes('请先到模型设置选择生图模型,再重试。')`),10000,"configuration error turn completed");+ await evaluate(`new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))`);+ await screenshot("chat-unconfigured.png");+ await click("配置生图模型");+ await waitFor(() => evaluate(`!!document.querySelector('.model-default-row')`),10000,"setup action opens model settings");+ assert.equal(model.imageRequests.length,3,"unconfigured generation makes no image request");+ assert.deepEqual(model.failures,[]);+ console.log(JSON.stringify({ok:true,gap,scenarios:["settings-spacing","composer-batch-generation","composer-edit-generated-image","collapsed-previews","unconfigured-setup-navigation"],imageRequests:model.imageRequests,evidence}));+} catch (error) {+ console.error("MODEL_FIXTURE_ERRORS",JSON.stringify(model.failures));+ console.error(output.slice(-4000));+ throw error;+} finally {+ ws?.close();+ child.kill();+ server.close();+}diff --git a/scripts/e2e-image-generation-ui.mjs b/scripts/e2e-image-generation-ui.mjsindex 6ac9a6ded..eb2a3f149 100644--- a/scripts/e2e-image-generation-ui.mjs+++ b/scripts/e2e-image-generation-ui.mjs@@ -22,9 +22,8 @@ try {platform: "browser",format: "iife",jsx: "automatic",+ loader: { ".woff": "file", ".woff2": "file", ".ttf": "file" },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.@@ -35,7 +34,7 @@ try {});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\'; img-src \'self\' data:"><title>Image generation interactions</title><body><script src="renderer.js"></script>',+ '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; style-src \'self\' \'unsafe-inline\'; img-src \'self\' data:"><link rel="stylesheet" href="renderer.css"><title>Image generation interactions</title><body><script src="renderer.js"></script>',);await writeFile(join(temp, "main.cjs"),diff --git a/scripts/e2e/image-chat-model.mjs b/scripts/e2e/image-chat-model.mjsnew file mode 100644index 000000000..836acf00a--- /dev/null+++ b/scripts/e2e/image-chat-model.mjs@@ -0,0 +1,98 @@+import assert from "node:assert/strict";+import { deflateSync } from "node:zlib";++// Deterministic raster fixtures, not AI artwork. Only the HTTP provider is mocked.+function png(edited, variant) {+ const width = 480, height = 320;+ const pixels = Buffer.alloc((width * 4 + 1) * height);+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ const offset = y * (width * 4 + 1) + 1 + x * 4;+ const circle = (x - 240) ** 2 + (y - 145) ** 2 < 82 ** 2;+ const floor = y > 250;+ const color = circle ? [245, 169 + variant * 15, 85] : floor ? [40, 56, 66] : edited ? [49, 105 + Math.floor(y / 8), 92] : [42 + Math.floor(y / 12), 70, 119 + variant * 15];+ pixels.set([...color, 255], offset);+ }+ }+ const chunk = (type, data) => {+ const payload = Buffer.concat([Buffer.from(type), data]);+ let crc = 0xffffffff;+ for (const byte of payload) {+ crc ^= byte;+ for (let i = 0; i < 8; i++) crc = (crc >>> 1) ^ ((crc & 1) ? 0xedb88320 : 0);+ }+ const result = Buffer.alloc(data.length + 12);+ result.writeUInt32BE(data.length); payload.copy(result, 4);+ result.writeUInt32BE((crc ^ 0xffffffff) >>> 0, result.length - 4);+ return result;+ };+ const header = Buffer.alloc(13);+ header.writeUInt32BE(width); header.writeUInt32BE(height, 4); header[8] = 8; header[9] = 6;+ return Buffer.concat([Buffer.from("89504e470d0a1a0a", "hex"), chunk("IHDR", header), chunk("IDAT", deflateSync(pixels)), chunk("IEND", Buffer.alloc(0))]);+}++export function imageChatModel() {+ let scenario = "batch", pending, done = false, calls = 0;+ const results = [], imageRequests = [], failures = [];+ const handler = async (req, res) => {+ try {+ if (req.method === "GET" && req.url.endsWith("/models")) {+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ data: [{ id: "fixture", object: "model" }] }));+ return;+ }+ const chunks = [];+ for await (const chunk of req) chunks.push(chunk);+ const raw = Buffer.concat(chunks);+ if (req.url.includes("/images/")) {+ const edited = req.url.endsWith("/edits");+ if (edited) {+ assert.match(req.headers["content-type"], /multipart\/form-data/);+ assert.ok(raw.includes(Buffer.from("image/png")));+ assert.ok(raw.includes(Buffer.from("89504e470d0a1a0a", "hex")), "edit uploads source PNG");+ }+ imageRequests.push({ edited, bytes: raw.length });+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ data: [{ b64_json: png(edited, imageRequests.length % 2).toString("base64") }] }));+ return;+ }+ const request = JSON.parse(raw.toString());+ if (pending) {+ const result = request.messages.find((item) => item.role === "tool" && item.tool_call_id === pending.id);+ assert.ok(result, "tool result returns to model");+ if (pending.name === "GenerateImages") {+ const text = typeof result.content === "string" ? result.content : result.content.map((item) => item.text ?? "").join("");+ const value = JSON.parse(text);+ results.push({ scenario, value });+ done = true;+ }+ pending = undefined;+ }+ res.writeHead(200, { "content-type": "text/event-stream" });+ const base = { id: `image-chat-${++calls}`, object: "chat.completion.chunk", created: 1, model: request.model };+ const emit = (delta, finish_reason = null) => res.write(`data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta, finish_reason }] })}\n\n`);+ if (!done) {+ const available = request.tools?.some((tool) => tool.function?.name === "GenerateImages");+ const name = available ? "GenerateImages" : "ToolSearch";+ let args = { query: "GenerateImages" };+ if (available) {+ const source = results.find((result) => result.scenario === "batch")?.value.results?.[0]?.path;+ if (scenario === "edit") assert.ok(source, "generation returns an editable path");+ args = { items: [{ prompt: scenario === "edit" ? "Keep the orange sphere and change the background to green." : "An orange sphere on a blue background.", count: scenario === "batch" ? 2 : 1, ...(scenario === "edit" ? { images: [source] } : {}) }] };+ }+ pending = { id: `image-call-${calls}`, name };+ emit({ role: "assistant", tool_calls: [{ index: 0, id: pending.id, type: "function", function: { name, arguments: JSON.stringify(args) } }] });+ emit({}, "tool_calls");+ } else {+ const text = scenario === "batch" ? "已生成两张图片,可在对话中查看。" : scenario === "edit" ? "已将第一张图的背景改为绿色,原图保留。" : "请先到模型设置选择生图模型,再重试。";+ emit({ role: "assistant", content: text }); emit({}, "stop");+ }+ res.end("data: [DONE]\n\n");+ } catch (error) {+ failures.push(String(error));+ if (!res.headersSent) res.writeHead(500);+ res.end();+ }+ };+ return { handler, results, imageRequests, failures, setScenario(value) { scenario = value; pending = undefined; done = false; } };+}diff --git a/scripts/e2e/image-generation-ui.tsx b/scripts/e2e/image-generation-ui.tsxindex dae3435b6..a62aa76c9 100644--- a/scripts/e2e/image-generation-ui.tsx+++ b/scripts/e2e/image-generation-ui.tsx@@ -6,8 +6,12 @@ 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 { Markdown } from "../../apps/desktop/src/components/Markdown";import { api } from "../../apps/desktop/src/lib/api";import { useAppStore } from "../../apps/desktop/src/stores/app-store";+import "../../apps/desktop/src/styles/tokens.css";+import "../../apps/desktop/src/styles/settings.css";+import "../../apps/desktop/src/styles/model-config.css";declare global {var imageGenerationProbe: () => Promise<unknown>;@@ -57,12 +61,15 @@ globalThis.imageGenerationProbe = async () => {defaultThinkingLevel: null,})),};+ const alternate = { ...provider, id: "q", name: "Images B" };+ const chatProvider = { ...provider, id: "chat", name: "Chat", models: [{ ...provider.models[0], id: "chat-model" }] };+ const providers = [provider, alternate, chatProvider];api.getSettings = async () => structuredClone(settings);api.setSettings = async (next) => {settings = structuredClone(next);return { ok: true };};- api.listProviders = async () => ({ providers: [provider] });+ api.listProviders = async () => ({ providers });api.listSessions = async () => ({ sessions: [] });api.getOnboarding = async () => ({ dismissed: true });api.listProviderModels = async () => ({ models: [], source: "remote" });@@ -73,13 +80,13 @@ globalThis.imageGenerationProbe = async () => {providerCount: 1,modelCount: 2,});- api.updateProvider = async () => ({ provider });+ api.updateProvider = async (input) => ({ provider: providers.find((entry) => entry.id === input.id)! });api.fsReadImageDataUrl = async () => ({kind: "image",dataUrl:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9mQAAAAASUVORK5CYII=",});- useAppStore.setState({ settings, providers: [provider] });+ useAppStore.setState({ settings, providers });const container = document.createElement("div");document.body.append(container);const root = createRoot(container);@@ -103,6 +110,12 @@ globalThis.imageGenerationProbe = async () => {for (const locale of ["en", "zh-CN"]) {await i18n.changeLanguage(locale);render();+ const defaultRow = container.querySelector<HTMLElement>(".model-default-row")!;+ const imageRow = [...container.querySelectorAll<HTMLElement>(".settings-row")].find(+ (element) => element.textContent?.includes(i18n.t("settings.imageModel")),+ )!;+ const gap = imageRow.getBoundingClientRect().top - defaultRow.getBoundingClientRect().bottom;+ assert(gap >= 11 && gap <= 13, `model defaults should be adjacent rows, got ${gap}px`);const edit =container.querySelector<HTMLButtonElement>('button[aria-label="' + i18n.t("settings.editProvider") + '"]',@@ -138,19 +151,35 @@ globalThis.imageGenerationProbe = async () => {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");+ assert(row.querySelectorAll("button").length === 0, "image summary still offers change or clear");+ const textStyle = (element: Element | null) => {+ assert(element, "missing model text");+ const style = getComputedStyle(element!);+ return [style.fontSize, style.fontWeight, style.fontFamily].join("|");+ };+ assert(textStyle(row.querySelector(".model-default-provider")) === textStyle(defaultRow.querySelector(".model-default-provider")), "provider typography differs from default model");+ assert(textStyle(row.querySelector(".model-default-model")) === textStyle(defaultRow.querySelector(".model-default-model")), "model typography differs from default model");+ const alternateRow = [...container.querySelectorAll<HTMLElement>(".model-provider-row")].find((element) => element.textContent?.includes("Images B"));+ click(alternateRow?.querySelector<HTMLButtonElement>('button[aria-label="' + i18n.t("settings.editProvider") + '"]'));+ await until(() => !!button(i18n.t("settings.setImageModel")), "alternate provider edit missing");+ click(button(i18n.t("settings.setImageModel")));+ click(button(i18n.t("settings.saveProvider")));+ await until(() => settings.imageGeneration?.providerId === "q" && !document.querySelector(".provider-setup"), "advanced provider switch did not persist");+ assert(settings.defaultProviderId === "chat" && settings.defaultModelId === "chat-model", "image switch changed chat default");+ assert(row.textContent?.includes("Images B"), "new provider name missing");+ for (const invalid of [+ { ...alternate, enabled: false },+ { ...alternate, hasSecret: false },+ { ...alternate, models: [] },+ ]) {+ flushSync(() => useAppStore.setState({ providers: [provider, invalid, chatProvider] }));+ assert(row.querySelector('[role="status"]')?.textContent === i18n.t("settings.imageModelUnavailable"), "unavailable state missing");+ assert(!row.querySelector(".model-default-provider"), "unavailable binding still displays provider");+ }+ settings = { ...settings, imageGeneration: null };+ flushSync(() => useAppStore.setState({ settings, providers }));+ assert(row.querySelector('[role="status"]')?.textContent === i18n.t("settings.imageModelUnavailable"), "unset state missing");+}const message = {id: "image",@@ -179,18 +208,34 @@ globalThis.imageGenerationProbe = async () => {});click(button(i18n.t("settings.configureImageModel")));assert(- useAppStore.getState().settingsTab === "ai" && useAppStore.getState().page === "settings",+ useAppStore.getState().settingsTab === "agent" && useAppStore.getState().page === "settings","setup action did not navigate",);+ const imageReads: string[] = [];+ const readImage = api.fsReadImageDataUrl;+ api.fsReadImageDataUrl = async (ref, mimeType) => {+ imageReads.push(ref);+ return readImage(ref, mimeType);+ };+ for (const ref of [String.raw`C:\scratch\cup.png`, "/tmp/scratch/cup.png"]) {+ flushSync(() => root.render(+ <I18nextProvider i18n={i18n}><Markdown source={``} /></I18nextProvider>,+ ));+ await until(() => (container.querySelector("img")?.naturalWidth ?? 0) > 0, "absolute generated image Markdown did not decode");+ await until(() => imageReads.includes(ref), `Markdown image did not use the contained host reader: ${JSON.stringify(imageReads)}`);+ }return {ok: true,locales: ["en", "zh-CN"],scenarios: ["advanced-save-cancel",- "replace-clear",+ "advanced-provider-switch",+ "read-only-summary-typography",+ "unavailable-summary","chat-default-preserved","image-preview-partial-failure","setup-navigation",+ "absolute-image-markdown",],apiBoundary: "fixture",};