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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(editor): let the agent actually see what it drew
esengine731e80e7d31e
diff --git a/desktop/electron/agent/anthropic.ts b/desktop/electron/agent/anthropic.tsindex c176a7b1c..8ea1e4d4a 100644--- a/desktop/electron/agent/anthropic.ts+++ b/desktop/electron/agent/anthropic.ts@@ -109,6 +109,39 @@ export function buildStepRequest(opts: {return request;}+/**+ * What a tool result looks like on the wire.+ *+ * A screenshot reaches the model only where the endpoint takes images, and+ * whether it does is a property of the ENDPOINT, not of the editor — so the+ * substitution belongs to the provider rather than the kernel. It also SAYS what+ * happened: a model handed a silently dropped screenshot concludes the editor is+ * broken, while one told the endpoint cannot carry it asks a different way.+ *+ * Exported because the native branch cannot be exercised against a local+ * stand-in gateway — pointing at one is exactly what selects the other dialect.+ */+export function toolResultContent(+ outcome: ToolOutcome,+ dialect: Dialect,+): Anthropic.Beta.BetaToolResultBlockParam['content'] {+ if (!outcome.image) return outcome.content;+ if (dialect !== 'anthropic') {+ return `${outcome.content}\n[the screenshot could not be sent: this endpoint does not accept images]`;+ }+ return [+ {+ type: 'image',+ source: {+ type: 'base64',+ media_type: outcome.image.mediaType as 'image/png',+ data: outcome.image.data,+ },+ },+ ...(outcome.content ? [{ type: 'text' as const, text: outcome.content }] : []),+ ];+}+class AnthropicSession implements AgentSession {private readonly messages: Message[] = [];/** Context waiting for a legal spot — see {@link flushContext}. */@@ -137,7 +170,7 @@ class AnthropicSession implements AgentSession {content: outcomes.map((o) => ({type: 'tool_result' as const,tool_use_id: o.id,- content: o.content,+ content: toolResultContent(o, this.opts.dialect),is_error: o.isError,})),});diff --git a/desktop/electron/agent/kernel.ts b/desktop/electron/agent/kernel.tsindex ad575b6fe..432b88e8f 100644--- a/desktop/electron/agent/kernel.ts+++ b/desktop/electron/agent/kernel.ts@@ -42,16 +42,22 @@ function summarize(text: string): string {}/**- * MCP wraps a result as content blocks because that is its wire format. The- * provider wants text, and an image block wants to stay an image — flatten,- * keeping the distinction the model actually acts on.+ * MCP wraps a result as content blocks because that is its wire format. Text+ * flattens; an image stays an image — a tool whose whole purpose is letting the+ * model SEE is not served by being handed the word "[image]".*/function toOutcome(id: string, result: {- content: Array<{ type: string; text?: string; data?: string }>;+ content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;isError?: boolean;}): ToolOutcome {- const parts = result.content.map((c) => (c.type === 'image' ? '[image]' : c.text ?? ''));- return { id, content: parts.join('\n') || 'ok', isError: result.isError === true };+ const image = result.content.find((c) => c.type === 'image' && c.data);+ const text = result.content.filter((c) => c.type !== 'image').map((c) => c.text ?? '').join('\n');+ return {+ id,+ content: text || (image ? 'screenshot attached' : 'ok'),+ isError: result.isError === true,+ ...(image ? { image: { data: image.data!, mediaType: image.mimeType ?? 'image/png' } } : {}),+ };}/**@@ -166,7 +172,13 @@ async function execute(isError?: boolean;};const outcome = toOutcome(call.id, result);- emit({ type: 'tool_end', id: call.id, ok: !outcome.isError, summary: summarize(outcome.content) });+ emit({+ type: 'tool_end',+ id: call.id,+ ok: !outcome.isError,+ summary: summarize(outcome.content),+ ...(outcome.image ? { image: `data:${outcome.image.mediaType};base64,${outcome.image.data}` } : {}),+ });// A failed call changed nothing worth re-verifying.return { outcome, mutated: mutates(tool) && !outcome.isError };}diff --git a/desktop/electron/agent/types.ts b/desktop/electron/agent/types.tsindex f35315fed..9bc6d1ede 100644--- a/desktop/electron/agent/types.ts+++ b/desktop/electron/agent/types.ts@@ -33,9 +33,17 @@ export interface ToolCall {/** Its outcome, in the shape a provider appends to its history. */export interface ToolOutcome {id: string;- /** Text or an image the model reads back. */content: string;isError: boolean;+ /**+ * A rendered frame the model is meant to LOOK at (capture_viewport,+ * screenshot). Kept as data rather than flattened to "[image]": a tool whose+ * entire purpose is sight is not served by being told it happened.+ *+ * The PROVIDER decides what becomes of it, because whether images cross the+ * wire is a property of the endpoint, not of the editor.+ */+ image?: { data: string; mediaType: string };}/** What a provider emits while ONE model call runs. */@@ -106,7 +114,7 @@ export type AgentEvent =| StepEvent| { type: 'turn_start'; prompt: string }| { type: 'tool_start'; call: ToolCall; effect: NonNullable<CatalogTool['effect']> }- | { type: 'tool_end'; id: string; ok: boolean; summary: string }+ | { type: 'tool_end'; id: string; ok: boolean; summary: string; image?: string }| { type: 'awaiting_confirm'; request: ConfirmRequest }/** The turn is over. `steps` is what a single Undo would take back — 0 is the* signal not to offer one — and `mark` is where it would take it back to. */diff --git a/desktop/src/components/AgentDrawer.tsx b/desktop/src/components/AgentDrawer.tsxindex 1c3df7aa8..dd30289bc 100644--- a/desktop/src/components/AgentDrawer.tsx+++ b/desktop/src/components/AgentDrawer.tsx@@ -74,6 +74,9 @@ function ToolRow({ entry, onConfirm }: { entry: AgentToolEntry; onConfirm: (allo{(entry.state === 'ok' || entry.state === 'error') && entry.summary}</span></button>+ {/* What the agent looked at, shown without asking: a screenshot row that+ hides its screenshot is a row you have to click to learn anything from. */}+ {entry.image && <img className="ag-shot" src={entry.image} alt={entry.name} />}{open && entry.summary && <div className="ag-call-detail">{entry.summary}</div>}</div>{entry.state === 'awaiting' && <ConfirmPassage entry={entry} onConfirm={onConfirm} />}diff --git a/desktop/src/store/AgentStore.ts b/desktop/src/store/AgentStore.tsindex c0eb921f3..16c6cc5d9 100644--- a/desktop/src/store/AgentStore.ts+++ b/desktop/src/store/AgentStore.ts@@ -49,6 +49,8 @@ export interface AgentToolEntry {state: ToolState;/** The result, shortened for one row. */summary: string | null;+ /** A frame the call rendered — the transcript shows what the agent looked at. */+ image: string | null;/** Why it needs saying out loud, while it is awaiting an answer. */reason: ConfirmReason | null;}@@ -263,6 +265,7 @@ export function applyAgentEvent(turns: readonly AgentTurn[], event: AgentEvent):effect: null,state: 'queued',summary: null,+ image: null,reason: null,}]);@@ -283,7 +286,7 @@ export function applyAgentEvent(turns: readonly AgentTurn[], event: AgentEvent):// decline as an ordinary failed call, and painting it as an error would// blame the tool for the user's answer.const state: ToolState = e.state === 'declined' ? 'declined' : event.ok ? 'ok' : 'error';- return { ...e, state, summary: event.summary };+ return { ...e, state, summary: event.summary, image: event.image ?? null };}));case 'usage':diff --git a/desktop/src/theme/agent.css b/desktop/src/theme/agent.cssindex 7ef51cb1e..226112652 100644--- a/desktop/src/theme/agent.css+++ b/desktop/src/theme/agent.css@@ -551,3 +551,16 @@.ag-drawer .ag-panel { height: 100%; }/* Docked, the dock tab carries the title, so the head is just its actions. */.ag-head.docked { height: 30px; border-bottom: 1px solid var(--line-soft); }++/* A frame the agent looked at. Shown expanded rather than behind a disclosure:+ a screenshot row that hides its screenshot is a row you must click to learn+ anything from, and the whole point of the tool is seeing. */+.ag-shot {+ display: block;+ width: 100%;+ margin: 2px 0 9px 25px;+ max-width: calc(100% - 25px);+ border-radius: var(--r-sm);+ border: 1px solid var(--line);+ background: var(--inset);+}diff --git a/desktop/tests/agent-dialect.test.ts b/desktop/tests/agent-dialect.test.tsindex bfc0075e7..d0067d9d3 100644--- a/desktop/tests/agent-dialect.test.ts+++ b/desktop/tests/agent-dialect.test.ts@@ -13,7 +13,7 @@* rejected or silently dropped, taking the editor's context with it.*/import { describe, it, expect } from 'vitest';-import { buildStepRequest, createAnthropicProvider } from '../electron/agent/anthropic';+import { buildStepRequest, createAnthropicProvider, toolResultContent } from '../electron/agent/anthropic';import { DEFAULT_MODEL } from '../src/settings/agentIds';import type { CatalogTool } from '../electron/agent/types';@@ -128,3 +128,36 @@ describe('where per-turn editor context lands', () => {expect((session as unknown as { messages: unknown[] }).messages).toHaveLength(0);});});++// capture_viewport exists so the model can SEE. Where the endpoint cannot carry+// an image the substitution has to SAY so — a model handed a silently dropped+// screenshot concludes the editor is broken.+describe('a tool result carrying a rendered frame', () => {+ const shot = {+ id: 'c1',+ content: 'screenshot attached',+ isError: false,+ image: { data: 'BASE64PNG', mediaType: 'image/png' },+ };++ it('sends the image itself to Anthropic', () => {+ const content = toolResultContent(shot, 'anthropic');+ expect(Array.isArray(content)).toBe(true);+ expect((content as { type: string }[])[0]).toMatchObject({+ type: 'image',+ source: { type: 'base64', media_type: 'image/png', data: 'BASE64PNG' },+ });+ });++ it('tells a gateway why there is no image rather than dropping it in silence', () => {+ const content = toolResultContent(shot, 'compatible');+ expect(typeof content).toBe('string');+ expect(content).toContain('does not accept images');+ });++ it('leaves an ordinary result a plain string on both', () => {+ const plain = { id: 'c2', content: '7 created', isError: false };+ expect(toolResultContent(plain, 'anthropic')).toBe('7 created');+ expect(toolResultContent(plain, 'compatible')).toBe('7 created');+ });+});diff --git a/desktop/tests/agent-kernel.test.ts b/desktop/tests/agent-kernel.test.tsindex 8d8c66d23..cbdf61259 100644--- a/desktop/tests/agent-kernel.test.ts+++ b/desktop/tests/agent-kernel.test.ts@@ -171,4 +171,19 @@ describe('the agent turn', () => {expect(s.context[0]).toContain('main.esscene');expect(s.user).toEqual(['hi']);});++ // The tool exists so the model can SEE. Handing it the word "[image]" is a+ // capability quietly removed — and the provider, not the kernel, is the side+ // that knows whether the endpoint can carry one.+ it('passes a rendered frame through instead of flattening it to text', async () => {+ (driver as { op: unknown }).op = vi.fn(async () => 'BASE64PNG');+ const s = fakeSession([asks(call('screenshot')), ends()]);+ await runTurn(deps(s), 'show me', null, new AbortController().signal);++ const outcome = s.results[0][0];+ expect(outcome.image).toEqual({ data: 'BASE64PNG', mediaType: 'image/png' });+ expect(outcome.content).not.toContain('[image]');+ const ended = events.find((e) => e.type === 'tool_end');+ expect(ended).toMatchObject({ image: 'data:image/png;base64,BASE64PNG' });+ });});diff --git a/desktop/tests/agent-transcript.test.ts b/desktop/tests/agent-transcript.test.tsindex bb27a9591..fd847f920 100644--- a/desktop/tests/agent-transcript.test.ts+++ b/desktop/tests/agent-transcript.test.ts@@ -60,6 +60,17 @@ describe('the transcript projection', () => {expect(tools(running[0])[0]).toMatchObject({ state: 'running', effect: 'undoable' });});+ // A screenshot is the point of the tool that produced it, so it rides the row+ // rather than being something the reader has to expand to find.+ it('keeps a rendered frame on the row that produced it', () => {+ const [turn] = fold(+ started(),+ { type: 'tool_call', call: call('capture_viewport') },+ { type: 'tool_end', id: 'c-capture_viewport', ok: true, summary: 'ok', image: 'data:image/png;base64,AAA' },+ );+ expect(tools(turn)[0].image).toBe('data:image/png;base64,AAA');+ });+it('carries a call through to its result', () => {const [turn] = fold(started(),@@ -159,7 +170,7 @@ describe('the transcript projection', () => {describe('which entities a turn touched', () => {const toolEntry = (over: Partial<AgentToolEntry>): AgentToolEntry => ({kind: 'tool', id: 'c1', name: 'set_field', input: {}, effect: 'undoable',- state: 'ok', summary: 'ok', reason: null, ...over,+ state: 'ok', summary: 'ok', image: null, reason: null, ...over,});const turn = (entries: AgentToolEntry[], id = 0): AgentTurn => ({id, prompt: 'p', entries, inputTokens: 0, outputTokens: 0, steps: 1, mark: { seq: 1 }, reason: 'end_turn',