Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(editor): you can show the agent a picture

esengine65e0d50024e9
diff --git a/desktop/electron/agent/anthropic.ts b/desktop/electron/agent/anthropic.ts
index 65eefc986..7a401f79a 100644
--- a/desktop/electron/agent/anthropic.ts
+++ b/desktop/electron/agent/anthropic.ts
@@ -21,7 +21,9 @@
* sends the core format and nothing else.
*/
import Anthropic from '@anthropic-ai/sdk';
-import type { AgentProvider, AgentSession, CatalogTool, StepEvent, ToolOutcome } from './types';
+import type {
+ AgentProvider, AgentSession, CatalogTool, StepEvent, ToolOutcome, UserImage,
+} from './types';
import { DEFAULT_MODEL, DEFAULT_CONTEXT_WINDOW, COMPACT_AT, KEEP_WHOLE_RUNS } from '../../src/settings/agentIds';
/** Agentic work is what `xhigh` is for; it is also the depth Claude Code runs at. */
@@ -350,9 +352,38 @@ class AnthropicSession implements AgentSession {
this.lastInputTokens = memory.lastInputTokens ?? 0;
}
- pushUser(text: string): void {
+ pushUser(text: string, images?: readonly UserImage[]): void {
this.turnStarts.push(this.messages.length);
- this.messages.push({ role: 'user', content: text });
+ if (!images?.length) {
+ this.messages.push({ role: 'user', content: text });
+ return;
+ }
+ // An endpoint that cannot carry images is TOLD, in the turn itself, rather
+ // than quietly handed the text alone: a model that never learns a picture
+ // was attached answers confidently about something it was not shown, and
+ // the person watching has every reason to think it looked.
+ if (this.opts.dialect !== 'anthropic') {
+ const note = images.length === 1
+ ? '[the user attached an image; this endpoint cannot receive images, so you have not seen it]'
+ : `[the user attached ${images.length} images; this endpoint cannot receive images, so you have not seen them]`;
+ this.messages.push({ role: 'user', content: `${text}\n\n${note}` });
+ return;
+ }
+ // Images first: the question after them reads as being about them.
+ this.messages.push({
+ role: 'user',
+ content: [
+ ...images.map((im) => ({
+ type: 'image' as const,
+ source: {
+ type: 'base64' as const,
+ media_type: im.mediaType as 'image/png',
+ data: im.data,
+ },
+ })),
+ ...(text ? [{ type: 'text' as const, text }] : []),
+ ],
+ });
}
rewindTo(n: number): void {
diff --git a/desktop/electron/agent/host.ts b/desktop/electron/agent/host.ts
index c9fec4743..32981caae 100644
--- a/desktop/electron/agent/host.ts
+++ b/desktop/electron/agent/host.ts
@@ -24,7 +24,7 @@
import { runTurn, agentTools } from './kernel';
import { SYSTEM_PROMPT, editorContext } from './prompt';
import type {
- AgentEvent, AgentProvider, AgentSession, ConfirmAnswer, ConfirmDecision, ConfirmRequest,
+ AgentEvent, AgentProvider, AgentSession, ConfirmAnswer, ConfirmDecision, ConfirmRequest, UserImage,
} from './types';
import type { SurfaceDriver } from '../surfaceDriver';
@@ -77,9 +77,10 @@ export interface PersistedConversation {
export interface AgentHost {
status(): AgentStatus;
- /** Start a turn. Returns the resulting status — including a refusal, which is
- * an `error` on it rather than a rejection. Does not wait for the turn. */
- send(text: string): AgentStatus;
+ /** Start a turn, optionally with images the person attached. Returns the
+ * resulting status — including a refusal, which is an `error` on it rather
+ * than a rejection. Does not wait for the turn. */
+ send(text: string, images?: readonly UserImage[]): AgentStatus;
/** Abort the running turn. Idempotent, and a no-op when nothing runs. */
stop(): void;
/** Answer a pending confirmation. Unknown ids are ignored — the turn it
@@ -202,7 +203,7 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {
pushStatus();
});
- const send = (text: string, rewindTo?: number): AgentStatus => {
+ const send = (text: string, rewindTo?: number, images?: readonly UserImage[]): AgentStatus => {
if (phase !== 'idle') {
error = 'the agent is still working on the previous message';
pushStatus();
@@ -246,6 +247,7 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {
text,
context,
controller.signal,
+ images,
);
} catch (e) {
// Invariant 1: runTurn rejected, so it emitted no turn_end of its own.
@@ -275,7 +277,7 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {
return {
status,
- send: (text: string) => send(text),
+ send: (text: string, images?: readonly UserImage[]) => send(text, undefined, images),
// A retry with no session yet is just a first message — nothing to rewind to.
retry: (n, text) => send(text, session ? n : undefined),
stop: () => {
diff --git a/desktop/electron/agent/kernel.ts b/desktop/electron/agent/kernel.ts
index 499317a30..22f8b953d 100644
--- a/desktop/electron/agent/kernel.ts
+++ b/desktop/electron/agent/kernel.ts
@@ -13,7 +13,7 @@
* two would drift; there is one.
*/
import type {
- AgentEvent, CatalogTool, ConfirmReason, KernelDeps, ToolCall, ToolOutcome,
+ AgentEvent, CatalogTool, ConfirmReason, KernelDeps, ToolCall, ToolOutcome, UserImage,
} from './types';
// Plain .mjs, shared with the MCP fronts — esbuild bundles it into main.
// @ts-expect-error untyped shared module
@@ -116,6 +116,7 @@ export async function runTurn(
text: string,
context: string | null,
signal: AbortSignal,
+ images?: readonly UserImage[],
): Promise<{ mark: unknown; steps: number }> {
const { driver, session, emit, model, acceptsImages } = deps;
const mark = await driver('mark', []);
@@ -138,7 +139,7 @@ export async function runTurn(
+ 'get_diagnostics and by reading fields back instead of by looking.',
);
}
- session.pushUser(text);
+ session.pushUser(text, images);
// Bounded so a model that keeps calling tools cannot spin forever.
let round = 0;
diff --git a/desktop/electron/agent/types.ts b/desktop/electron/agent/types.ts
index 7920f0230..a24c6840d 100644
--- a/desktop/electron/agent/types.ts
+++ b/desktop/electron/agent/types.ts
@@ -82,8 +82,8 @@ export interface AgentSession {
* conversation nobody asked to end.
*/
readonly turnIndex: number;
- /** The person's turn. */
- pushUser(text: string): void;
+ /** The person's turn, and anything they attached to it. */
+ pushUser(text: string, images?: readonly UserImage[]): void;
/**
* Operator context for the turns from here on — what the editor is showing,
* what the diagnostics say. Kept OUT of the system prompt: that sits at the
@@ -117,6 +117,20 @@ export interface AgentSession {
serialize(): unknown;
}
+/**
+ * An image the person attached to their turn.
+ *
+ * Already sized down by the window that read it — the editor is where the
+ * canvas is, and a full-resolution screenshot costs the same tokens as a
+ * legible one while also having to be carried and stored.
+ */
+export interface UserImage {
+ /** `image/png`, `image/jpeg`, `image/gif` or `image/webp`. */
+ mediaType: string;
+ /** Base64, without the `data:` prefix. */
+ data: string;
+}
+
export interface AgentProvider {
readonly id: string;
/** The model this provider will run, for the transcript header. */
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index d9b790e49..a2587d74b 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -50,7 +50,7 @@ import { createAgentHost } from './agent/host';
import {
saveConversation, loadConversation, listConversations, deleteConversation,
} from './agent/store';
-import type { ConfirmAnswer } from './agent/types';
+import type { ConfirmAnswer, UserImage } from './agent/types';
import { createAnthropicProvider } from './agent/anthropic';
import {
@@ -711,7 +711,7 @@ const agentHost = createAgentHost({
});
ipcMain.handle('agent:status', () => agentHost.status());
ipcMain.handle('agent:transcript', () => agentHost.transcript());
-ipcMain.handle('agent:send', (_e, text: string) => agentHost.send(text));
+ipcMain.handle('agent:send', (_e, text: string, images?: UserImage[]) => agentHost.send(text, images));
ipcMain.handle('agent:stop', () => agentHost.stop());
ipcMain.handle(
'agent:confirm',
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index 2e579edda..363f7c0ca 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -22,7 +22,7 @@ import type { NativeTemplateEntry, InstallResult } from './nativeTemplates';
import type { McpEndpointStatus } from './mcpEndpoint';
import type { SecretStatus } from './secrets';
import type { AgentStatus, AgentMessage } from './agent/host';
-import type { AgentEvent, ConfirmAnswer } from './agent/types';
+import type { AgentEvent, ConfirmAnswer, UserImage } from './agent/types';
import type { ConversationSummary } from './agent/store';
// The privileged bridge the renderer is allowed to touch. Keep this surface small
@@ -117,8 +117,10 @@ const api = {
status: (): Promise<AgentStatus> => ipcRenderer.invoke('agent:status'),
/** The open conversation's events, for a window that was not there for them. */
transcript: (): Promise<AgentEvent[]> => ipcRenderer.invoke('agent:transcript'),
- /** Start a turn; resolves with the resulting status, refusals included. */
- send: (text: string): Promise<AgentStatus> => ipcRenderer.invoke('agent:send', text),
+ /** Start a turn, with any images the person attached; resolves with the
+ * resulting status, refusals included. */
+ send: (text: string, images?: readonly UserImage[]): Promise<AgentStatus> =>
+ ipcRenderer.invoke('agent:send', text, images),
stop: (): Promise<void> => ipcRenderer.invoke('agent:stop'),
/** Answer the pending confirmation for an irreversible tool. */
confirm: (callId: string, answer: ConfirmAnswer, declined?: readonly number[]): Promise<void> =>
diff --git a/desktop/src/agent/attachments.ts b/desktop/src/agent/attachments.ts
new file mode 100644
index 000000000..815e62ebf
--- /dev/null
+++ b/desktop/src/agent/attachments.ts
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file attachments.ts
+ * @brief Turning an image the person dropped, pasted or picked into something
+ * worth sending.
+ *
+ * The reduction happens HERE, in the window, because this is the side with a
+ * canvas and because everything downstream pays for the original otherwise: it
+ * crosses the IPC bridge, sits in the model's memory for the rest of the
+ * conversation, and is written to disk with it every turn. A 12-megapixel photo
+ * and a legible 1568px one cost the model the same to look at.
+ */
+
+/** The formats a model will look at. Anything else is refused by name. */
+const ACCEPTED = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
+
+/**
+ * The long edge an image is reduced to.
+ *
+ * Above roughly this, providers scale the image down themselves before reading
+ * it — so the extra pixels buy nothing and are paid for at every step on the way.
+ */
+const MAX_EDGE = 1568;
+
+/** Below this there is nothing to gain: re-encoding would only lose detail. */
+const REENCODE_ABOVE_BYTES = 256 * 1024;
+
+export interface Attachment {
+ /** Stable for the life of the draft, so a list can key on it. */
+ id: string;
+ name: string;
+ mediaType: string;
+ /** Base64, no `data:` prefix — what crosses the bridge. */
+ data: string;
+ /** For the thumbnail beside the composer. */
+ url: string;
+ bytes: number;
+}
+
+export class UnsupportedImage extends Error {}
+
+let nextId = 0;
+
+/**
+ * Read a file into an attachment, reduced if it is worth reducing.
+ *
+ * An animated GIF is passed through untouched: drawing one to a canvas keeps
+ * the first frame and silently throws the animation away, and a model shown one
+ * still frame of something the person sent as a sequence has been misled about
+ * what it is looking at.
+ */
+export async function readAttachment(file: File | Blob, name = ''): Promise<Attachment> {
+ const type = file.type || 'image/png';
+ if (!ACCEPTED.has(type)) throw new UnsupportedImage(type);
+
+ const label = name || (file instanceof File ? file.name : 'image');
+ // Only a GIF is passed through unseen. Byte size alone cannot decide: a flat
+ // 2400px screenshot compresses to well under any threshold you would pick,
+ // and would then be sent at a resolution the model scales down anyway.
+ const { blob, mediaType } = type === 'image/gif'
+ ? { blob: file, mediaType: type }
+ : await reduce(file, type);
+
+ const dataUrl = await asDataUrl(blob);
+ const comma = dataUrl.indexOf(',');
+ return {
+ id: `att-${++nextId}`,
+ name: label,
+ mediaType,
+ data: dataUrl.slice(comma + 1),
+ url: dataUrl,
+ bytes: blob.size,
+ };
+}
+
+/** Every image among some dropped/pasted items, in order; non-images ignored. */
+export async function readImageItems(
+ items: readonly DataTransferItem[] | DataTransferItemList,
+): Promise<Attachment[]> {
+ const files: File[] = [];
+ for (const item of Array.from(items as ArrayLike<DataTransferItem>)) {
+ if (item.kind !== 'file') continue;
+ const file = item.getAsFile();
+ if (file && file.type.startsWith('image/')) files.push(file);
+ }
+ const out: Attachment[] = [];
+ for (const file of files) {
+ try { out.push(await readAttachment(file)); } catch { /* not one a model reads */ }
+ }
+ return out;
+}
+
+/** Draw it down to {@link MAX_EDGE} on its long side. Transparency survives:
+ * a PNG stays a PNG, because a UI mock flattened onto black is a different
+ * picture from the one that was sent. */
+async function reduce(file: Blob, type: string): Promise<{ blob: Blob; mediaType: string }> {
+ const bitmap = await createImageBitmap(file);
+ try {
+ const scale = Math.min(1, MAX_EDGE / Math.max(bitmap.width, bitmap.height));
+ // Small enough to send and light enough not to bother: re-encoding here
+ // could only lose detail.
+ if (scale === 1 && file.size <= REENCODE_ABOVE_BYTES) return { blob: file, mediaType: type };
+ const w = Math.max(1, Math.round(bitmap.width * scale));
+ const h = Math.max(1, Math.round(bitmap.height * scale));
+ const canvas = document.createElement('canvas');
+ canvas.width = w;
+ canvas.height = h;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return { blob: file, mediaType: type };
+ ctx.drawImage(bitmap, 0, 0, w, h);
+
+ const out = type === 'image/png' ? 'image/png' : 'image/jpeg';
+ const encoded = await new Promise<Blob | null>((resolve) => {
+ canvas.toBlob(resolve, out, out === 'image/jpeg' ? 0.85 : undefined);
+ });
+ // Re-encoding can come out LARGER than the original (a small photo saved as
+ // PNG, say). Keeping the bigger one would be paying for the conversion.
+ if (!encoded || encoded.size >= file.size) return { blob: file, mediaType: type };
+ return { blob: encoded, mediaType: out };
+ } finally {
+ bitmap.close();
+ }
+}
+
+const asDataUrl = (blob: Blob): Promise<string> =>
+ new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(String(reader.result));
+ reader.onerror = () => reject(reader.error);
+ reader.readAsDataURL(blob);
+ });
diff --git a/desktop/src/components/AgentDrawer.tsx b/desktop/src/components/AgentDrawer.tsx
index 0f182f086..b26702b7c 100644
--- a/desktop/src/components/AgentDrawer.tsx
+++ b/desktop/src/components/AgentDrawer.tsx
@@ -34,6 +34,7 @@ import {
useAgent, sendAgentMessage, stopAgentTurn, confirmAgentCall, startNewConversation,
peekEntities, entitiesInInput, effectiveSelection, selectAgentModel, retryAgentTurn, setAgentDraft,
RESUMABLE, openAgentHistory, closeAgentHistory, resumeConversation, forgetConversation,
+ addAgentAttachments, removeAgentAttachment,
type AgentTurn, type AgentEntry, type AgentToolEntry, type AgentProseEntry,
} from '@/store/AgentStore';
import type { ConfirmAnswer } from '../../electron/agent/types';
@@ -45,6 +46,7 @@ import { useSettings } from '@/store/settingsStore';
import { MarkdownView } from '@/components/MarkdownView';
import { AgentMark } from '@/components/AgentMark';
import { OverlayDrawer } from '@/components/OverlayDrawer';
+import { readImageItems } from '@/agent/attachments';
import { dockApi } from '@/layout/dockApi';
import { EditorHistory, type HistoryMark } from '@/engine/EditorHistory';
import { useSelection } from '@/store/selectionStore';
@@ -936,6 +938,8 @@ function mentionMatches(query: string): Mention[] {
function Compose({ autoFocus }: { autoFocus?: boolean }) {
const status = useAgent((s) => s.status);
const draft = useAgent((s) => s.draft);
+ const attachments = useAgent((s) => s.attachments);
+ const [dropping, setDropping] = useState(false);
const setDraft = setAgentDraft;
const ref = useRef<HTMLTextAreaElement>(null);
const busy = status.phase !== 'idle';
@@ -978,15 +982,41 @@ function Compose({ autoFocus }: { autoFocus?: boolean }) {
el.style.height = `${Math.min(112, el.scrollHeight)}px`;
}, [draft]);
+ // An image on its own is a complete message — "what do you think of this?"
+ // does not need the words to be typed as well.
const submit = () => {
const text = draft.trim();
- if (!text) return;
+ if (!text && attachments.length === 0) return;
setDraft('');
- void sendAgentMessage(text);
+ void sendAgentMessage(text, attachments.length ? attachments : undefined);
+ for (const a of attachments) removeAgentAttachment(a.id);
+ };
+
+ const take = async (items: DataTransferItemList | null): Promise<boolean> => {
+ if (!items) return false;
+ const read = await readImageItems(items);
+ if (read.length) addAgentAttachments(read);
+ return read.length > 0;
};
return (
- <div className={`ag-compose${busy ? ' busy' : ''}`}>
+ <div
+ className={`ag-compose${busy ? ' busy' : ''}${dropping ? ' dropping' : ''}`}
+ // Anywhere in the composer, not just on the box: aiming a drag at a
+ // one-line textarea is a precision task nobody should be set.
+ onDragOver={(e) => {
+ if (!e.dataTransfer.types.includes('Files')) return;
+ e.preventDefault();
+ setDropping(true);
+ }}
+ onDragLeave={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node)) setDropping(false); }}
+ onDrop={(e) => {
+ if (!e.dataTransfer.types.includes('Files')) return;
+ e.preventDefault();
+ setDropping(false);
+ void take(e.dataTransfer.items);
+ }}
+ >
{mention && mention.items.length > 0 && (
<div className="ag-mention">
<div className="ag-mention-h">{t('agent.mention')}</div>
@@ -1018,6 +1048,25 @@ function Compose({ autoFocus }: { autoFocus?: boolean }) {
<Boxes size={12} strokeWidth={1.8} />@{selectedName}
</button>
)}
+ {/* What is going along with the message, as the picture itself: a row of
+ filenames would be a list of things you cannot check you picked. */}
+ {attachments.length > 0 && (
+ <div className="ag-atts">
+ {attachments.map((a) => (
+ <div className="ag-att" key={a.id}>
+ <img src={a.url} alt={a.name} title={`${a.name} · ${Math.round(a.bytes / 1024)}KB`} />
+ <button
+ type="button"
+ className="ag-att-x"
+ title={t('agent.attach.remove')}
+ onClick={() => removeAgentAttachment(a.id)}
+ >
+ <X size={11} strokeWidth={2.4} />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
<div className="ag-cbox">
<textarea
ref={ref}
@@ -1029,6 +1078,14 @@ function Compose({ autoFocus }: { autoFocus?: boolean }) {
autoFocus={autoFocus}
placeholder={busy ? t('agent.compose.busy') : t('agent.compose')}
aria-label={t('agent.compose')}
+ onPaste={(e) => {
+ // Only when the clipboard actually carries one — otherwise this is
+ // an ordinary paste and the field should do what it always does.
+ if (![...e.clipboardData.items].some((i) => i.kind === 'file'
+ && i.type.startsWith('image/'))) return;
+ e.preventDefault();
+ void take(e.clipboardData.items);
+ }}
onChange={(e) => {
setDraft(e.target.value);
openMention(e.target.value, e.target.selectionStart ?? 0);
@@ -1173,8 +1230,8 @@ export function AgentPanel({ docked }: { docked?: boolean }) {
))}
{/* Held until the run ends. Shown rather than merely promised: a message
that vanished into a queue nobody can see is one you retype. */}
- {queued.map((text, i) => (
- <div className="ag-sys" key={i}>{t('agent.queued.msg', { text })}</div>
+ {queued.map((q, i) => (
+ <div className="ag-sys" key={i}>{t('agent.queued.msg', { text: q.text })}</div>
))}
</div>
diff --git a/desktop/src/i18n/messages/agent.ts b/desktop/src/i18n/messages/agent.ts
index 63ccad5d5..87fd7e011 100644
--- a/desktop/src/i18n/messages/agent.ts
+++ b/desktop/src/i18n/messages/agent.ts
@@ -29,6 +29,10 @@ export const agentMessages = defineMessages({
'agent.hint.mention': { en: 'reference', zh: '引用' },
'agent.mention': { en: 'Reference', zh: '引用' },
+ // — Images the person attaches —
+ 'agent.attach.remove': { en: 'Remove', zh: '移除' },
+ 'agent.attach.hint': { en: 'drop or paste an image', zh: '拖入或粘贴图片' },
+
// — Conversations this project has had —
'agent.history.open': { en: 'Earlier conversations', zh: '历史对话' },
'agent.history.title': { en: 'Earlier conversations', zh: '历史对话' },
diff --git a/desktop/src/store/AgentStore.ts b/desktop/src/store/AgentStore.ts
index 845409578..b76178b4d 100644
--- a/desktop/src/store/AgentStore.ts
+++ b/desktop/src/store/AgentStore.ts
@@ -24,6 +24,7 @@ import {
} from '@/agent/providers';
import { refreshSecret, secretStatus, subscribeSecrets } from '@/store/SecretStore';
import { useSettings } from '@/store/settingsStore';
+import type { Attachment } from '@/agent/attachments';
import { confirm } from '@/components/confirm';
import { t } from '@/i18n';
@@ -128,7 +129,7 @@ interface AgentState {
*/
peeked: readonly number[];
/** Typed while a turn was running, waiting for it to end. See sendAgentMessage. */
- queued: readonly string[];
+ queued: readonly { text: string; images?: readonly Attachment[] }[];
/**
* What is typed and not yet sent.
*
@@ -138,6 +139,12 @@ interface AgentState {
* should not disagree about what you were writing.
*/
draft: string;
+ /**
+ * Images attached to the draft. Beside it rather than in it for the same
+ * reason: the drawer's composer unmounts every time it closes, and a picture
+ * you dragged in is worse to lose than a sentence you typed.
+ */
+ attachments: readonly Attachment[];
/** The turn whose checkpoint bar has been answered — see AgentCheckpoint. */
checkpointDone: number | null;
/** What the user picked, or null for "whichever provider has a key". */
@@ -163,7 +170,7 @@ export interface ConversationSummary {
export const useAgent = create<AgentState>(() => ({
status: IDLE, turns: [], driving: false, peeked: [], queued: [], checkpointDone: null,
- draft: '', selection: loadSelection(), conversations: [], historyOpen: false,
+ draft: '', attachments: [], selection: loadSelection(), conversations: [], historyOpen: false,
}));
// ── Conversations kept with the project ─────────────────────────────────────
@@ -202,6 +209,12 @@ export const peekEntities = (ids: readonly number[]): void => useAgent.setState(
export const setAgentDraft = (draft: string): void => useAgent.setState({ draft });
+export const addAgentAttachments = (added: readonly Attachment[]): void =>
+ useAgent.setState((s) => ({ attachments: [...s.attachments, ...added] }));
+
+export const removeAgentAttachment = (id: string): void =>
+ useAgent.setState((s) => ({ attachments: s.attachments.filter((a) => a.id !== id) }));
+
// ── Which provider and model the next conversation runs on ──────────────────
// Persisted here rather than as a registered setting: it is picked from the
// composer, and a settings row for it would be a second control for one choice.
@@ -539,13 +552,16 @@ export function attachAgentBridge(): () => void {
return () => { off(); offSecrets(); };
}
-export async function sendAgentMessage(text: string): Promise<void> {
+export async function sendAgentMessage(
+ text: string,
+ images?: readonly Attachment[],
+): Promise<void> {
// The host REFUSES a send while a turn runs, so holding the message is this
// side's job. Without it the composer's own promise ("this will be the next
// message") was a lie that cost the person what they had typed: the box was
// already cleared, and all they got back was a red banner.
if (useAgent.getState().status.phase !== 'idle') {
- useAgent.setState((s) => ({ queued: [...s.queued, text] }));
+ useAgent.setState((s) => ({ queued: [...s.queued, { text, images }] }));
return;
}
// Before the IPC, not after: main drives this window through
@@ -554,7 +570,12 @@ export async function sendAgentMessage(text: string): Promise<void> {
// built-in agent. Waiting for main's status to come back would race the first
// tool call of the turn we are starting.
useAgent.setState({ driving: true });
- const status = await window.estella?.agent?.send(text);
+ // Only what the model needs crosses the bridge: the thumbnail url and the
+ // file's name are this side's business.
+ const payload = images?.length
+ ? images.map((a) => ({ mediaType: a.mediaType, data: a.data }))
+ : undefined;
+ const status = await window.estella?.agent?.send(text, payload);
if (status) adoptStatus(status);
}
@@ -563,7 +584,7 @@ function drainQueue(): void {
const [next, ...rest] = useAgent.getState().queued;
if (next === undefined) return;
useAgent.setState({ queued: rest });
- void sendAgentMessage(next);
+ void sendAgentMessage(next.text, next.images);
}
/** Nothing queued survives the turn being stopped: stopping means stop. */
diff --git a/desktop/src/theme/agent.css b/desktop/src/theme/agent.css
index 3fd9a182e..cdd2d5c14 100644
--- a/desktop/src/theme/agent.css
+++ b/desktop/src/theme/agent.css
@@ -930,6 +930,33 @@
.ag-mention-i.on { background: var(--hover); color: var(--text-hi); }
.ag-mention-id { margin-left: auto; font: var(--fs-2xs) var(--font-mono); color: var(--text-faint); }
+/* What is going along with the message. Shown as the pictures themselves —
+ a row of filenames is a list of things you cannot check you picked. */
+.ag-atts { display: flex; flex-wrap: wrap; gap: 6px; margin: 0 0 7px; }
+.ag-att { position: relative; width: 56px; height: 56px; flex: none; }
+.ag-att img {
+ width: 100%; height: 100%;
+ object-fit: cover;
+ border-radius: var(--r-sm);
+ border: 1px solid var(--line);
+ background: var(--inset);
+}
+.ag-att-x {
+ position: absolute;
+ top: -5px; right: -5px;
+ width: 17px; height: 17px;
+ display: grid; place-items: center;
+ border-radius: 50%;
+ background: var(--raised);
+ border: 1px solid var(--line-strong);
+ color: var(--text-dim);
+ transition: color var(--t-fast), background var(--t-fast);
+}
+.ag-att-x:hover { color: var(--text-hi); background: var(--pressed); }
+/* A drag is over the composer: the whole box says so, since the whole box takes
+ it — aiming at a one-line textarea is a precision task nobody should be set. */
+.ag-compose.dropping .ag-cbox { border-color: var(--acc); background: var(--hover); }
+
.ag-selchip {
display: flex; align-items: center; gap: 6px;
margin: 0 0 7px;
diff --git a/desktop/tests/agent-dialect.test.ts b/desktop/tests/agent-dialect.test.ts
index fdbb7fc40..539ad7688 100644
--- a/desktop/tests/agent-dialect.test.ts
+++ b/desktop/tests/agent-dialect.test.ts
@@ -212,3 +212,56 @@ describe('what a failed request says', () => {
expect(describeApiError(err(400, 'max_tokens too large'))).toContain('max_tokens too large');
});
});
+
+/**
+ * An image the person attached, on its way to the model.
+ *
+ * The judgement worth testing is what happens where it CANNOT go: a model handed
+ * the text alone answers confidently about a picture it was never shown, and the
+ * person watching has every reason to think it looked.
+ */
+describe('an image on the person\'s turn', () => {
+ const shot = [{ mediaType: 'image/png', data: 'AAAA' }];
+ /** The session's messages — what the request would carry. */
+ const messagesOf = (baseURL?: string, images = shot, text = 'like this') => {
+ const provider = createAnthropicProvider({ apiKey: 'k', baseURL });
+ const session = provider.createSession({ system: 's', tools: TOOLS });
+ session.pushUser(text, images);
+ return (session.serialize() as { messages: Array<{ role: string; content: unknown }> }).messages;
+ };
+
+ it('rides the turn as an image block, ahead of the question about it', () => {
+ const [msg] = messagesOf();
+ expect(Array.isArray(msg.content)).toBe(true);
+ const blocks = msg.content as Array<{ type: string }>;
+ expect(blocks.map((b) => b.type)).toEqual(['image', 'text']);
+ expect(blocks[0]).toMatchObject({
+ type: 'image',
+ source: { type: 'base64', media_type: 'image/png', data: 'AAAA' },
+ });
+ });
+
+ it('is a complete message on its own — an image needs no caption', () => {
+ const blocks = messagesOf(undefined, shot, '')[0].content as Array<{ type: string }>;
+ expect(blocks.map((b) => b.type)).toEqual(['image']);
+ });
+
+ // The gateway dialect speaks the core format and may refuse image blocks.
+ it('an endpoint that cannot carry it says so IN the turn', () => {
+ const [msg] = messagesOf('https://gateway.example/anthropic');
+ expect(typeof msg.content).toBe('string');
+ expect(msg.content as string).toContain('like this');
+ expect(msg.content as string).toMatch(/cannot receive images|have not seen/);
+ });
+
+ it('counts them when there are several', () => {
+ const two = [shot[0], { mediaType: 'image/jpeg', data: 'BBBB' }];
+ const [msg] = messagesOf('https://gateway.example/anthropic', two);
+ expect(msg.content as string).toContain('2 images');
+ });
+
+ it('a turn with no image is still a plain string', () => {
+ const [msg] = messagesOf(undefined, []);
+ expect(msg.content).toBe('like this');
+ });
+});
diff --git a/desktop/tests/agent-queue.test.ts b/desktop/tests/agent-queue.test.ts
index 0e8e27ac0..edb7cc703 100644
--- a/desktop/tests/agent-queue.test.ts
+++ b/desktop/tests/agent-queue.test.ts
@@ -13,7 +13,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { useAgent, sendAgentMessage, stopAgentTurn, applyAgentMessage } from '@/store/AgentStore';
import type { AgentStatus } from '../electron/agent/host';
-const send = vi.fn(async (_text: string) => undefined);
+const send = vi.fn(async (_text: string, _images?: unknown) => undefined);
const stop = vi.fn();
const status = (phase: AgentStatus['phase']): AgentStatus =>
@@ -34,7 +34,7 @@ afterEach(() => { delete (globalThis as { window?: unknown }).window; });
describe('messages typed while a turn runs', () => {
it('sends straight through when nothing is running', async () => {
await sendAgentMessage('add a pause menu');
- expect(send).toHaveBeenCalledWith('add a pause menu');
+ expect(send).toHaveBeenCalledWith('add a pause menu', undefined);
expect(useAgent.getState().queued).toEqual([]);
});
@@ -42,14 +42,27 @@ describe('messages typed while a turn runs', () => {
useAgent.setState({ status: status('running') });
await sendAgentMessage('and make the buttons bigger');
expect(send).not.toHaveBeenCalled();
- expect(useAgent.getState().queued).toEqual(['and make the buttons bigger']);
+ expect(useAgent.getState().queued.map((q) => q.text)).toEqual(['and make the buttons bigger']);
});
it('holds one per message, in the order they were typed', async () => {
useAgent.setState({ status: status('running') });
await sendAgentMessage('first');
await sendAgentMessage('second');
- expect(useAgent.getState().queued).toEqual(['first', 'second']);
+ expect(useAgent.getState().queued.map((q) => q.text)).toEqual(['first', 'second']);
+ });
+
+ // Attachments are part of the message, so they wait with it — losing the
+ // picture you dragged in would be worse than losing the sentence.
+ it('holds what was attached along with the message', async () => {
+ useAgent.setState({ status: status('running') });
+ const shot = [{ id: 'a1', name: 'mock.png', mediaType: 'image/png', data: 'AAA', url: 'data:,', bytes: 3 }];
+ await sendAgentMessage('like this', shot);
+ expect(useAgent.getState().queued[0]?.images).toEqual(shot);
+
+ pushStatus('idle');
+ await Promise.resolve();
+ expect(send).toHaveBeenCalledWith('like this', [{ mediaType: 'image/png', data: 'AAA' }]);
});
// A confirmation is not the turn ending — the run still owns the session.
@@ -57,7 +70,7 @@ describe('messages typed while a turn runs', () => {
useAgent.setState({ status: status('awaiting_confirm') });
await sendAgentMessage('meanwhile, rename it');
expect(send).not.toHaveBeenCalled();
- expect(useAgent.getState().queued).toEqual(['meanwhile, rename it']);
+ expect(useAgent.getState().queued.map((q) => q.text)).toEqual(['meanwhile, rename it']);
});
it('releases the oldest one when the turn ends', async () => {
@@ -68,8 +81,8 @@ describe('messages typed while a turn runs', () => {
pushStatus('idle');
await Promise.resolve();
expect(send).toHaveBeenCalledTimes(1);
- expect(send).toHaveBeenCalledWith('first');
- expect(useAgent.getState().queued).toEqual(['second']);
+ expect(send).toHaveBeenCalledWith('first', undefined);
+ expect(useAgent.getState().queued.map((q) => q.text)).toEqual(['second']);
});
// Stopping means stop: a queue that drained itself afterwards would start a