feat: show run image results to the in-app AI chat's model (#12789)

* feat: let MCP clients see the images a run returns

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: bump ee-repo-ref for the result_image usage kind

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: allow the unread image MIME type in builds without mcp

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: leave out images wider or taller than 8000 px in get_run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: attach a scaled JPEG copy of images past get_run's limits

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: limit what get_run's image decoders allocate for metadata

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: cap WebP EXIF reads and read listed images one at a time

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: move image decoding to images.rs, build it with mcp and bound image reads

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: show run image results to the in-app AI chat's model

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: keep waitSecondsToDetachMs's doc on its function

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: share the session-model lookup with call_mcp_tool

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: name the build that leaves out image support

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: update ee-repo-ref to 2a59a3b336ae88f9314dfb25e0e7d4552b40b867

This commit updates the EE repository reference after PR #1036 was merged in windmill-ee-private.

Previous ee-repo-ref: 92ab06951981817e3e3b615e62d64ad43e28437e

New ee-repo-ref: 2a59a3b336ae88f9314dfb25e0e7d4552b40b867

Automated by sync-ee-ref workflow.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
This commit is contained in:
Guilhem
2026-12-02 22:38:31 +01:00
committed by GitHub
co-authored by Claude Opus 5.5 windmill-internal-app[bot]
parent 37062260a8
commit 1dedda79ca
12 changed files with 139 additions and 26 deletions
+1 -1
View File
@@ -1 +1 @@
45192bb9f511422c8a2baf80ac36c4f63ff43fa5
2a59a3b336ae88f9314dfb25e0e7d4552b40b867
+14
View File
@@ -16081,6 +16081,20 @@ paths:
items:
type: object
additionalProperties: true
images:
type: array
description: images the model reads after the tool results, sent only when the context's reads_images is set
items:
type: object
required:
- data
- mime_type
properties:
data:
type: string
description: standard base64
mime_type:
type: string
/w/{workspace}/ai_session_tools/secret_request/open:
post:
@@ -36,6 +36,8 @@ struct ToolResponse {
#[serde(flatten)]
outcome: ToolOutcome,
effects: Vec<Effect>,
#[serde(skip_serializing_if = "Vec::is_empty")]
images: Vec<super::ToolImage>,
}
async fn call_tool(
@@ -63,7 +65,11 @@ async fn call_tool(
| CallRefused::NotAvailable(message) => Error::BadRequest(message),
})?;
let effects = ctx.effects.into_inner().unwrap();
Ok(Json(ToolResponse { outcome, effects }))
let images = match outcome.is_error {
true => Vec::new(),
false => ctx.images.into_inner().unwrap(),
};
Ok(Json(ToolResponse { outcome, effects, images }))
}
/// Browser-held state a tool needs and the server cannot see.
@@ -98,6 +104,10 @@ pub(crate) struct ChatContext {
/// resolves what will run, `start` queues it with the arguments the form settled on.
#[serde(default)]
pub run: Option<RunPhase>,
/// The session's model reads images, which the chat hands it in a message after the
/// tool results. A text-only model would fail the turn on that message.
#[serde(default)]
pub reads_images: bool,
}
#[derive(Deserialize)]
@@ -1,4 +1,4 @@
//! Image files handed to an MCP client's model: a file within the limits as it is, a file past
//! Image files handed to the model, over MCP or the chat: a file within the limits as it is, a file past
//! them as a JPEG copy, and why an image is left out. Which results are images is `runs.rs`'s.
use std::time::Duration;
@@ -105,14 +105,15 @@ pub(super) async fn image_from_bytes(
.await
}
/// Only an MCP client is handed images, and the image crates are built only with it.
/// The image crates are built only with `windmill-api/mcp`, which the Windows build
/// (`ee_windows`) leaves out.
#[cfg(not(feature = "mcp"))]
pub(super) async fn image_from_bytes(
_bytes: Vec<u8>,
_slot: Option<ReadSlot>,
) -> Result<Attachment, Unattached> {
Err(unreadable(
"images are read only for MCP clients".to_string(),
"this server was built without image support".to_string(),
))
}
@@ -255,7 +255,9 @@ pub(crate) fn session_tools(access: SessionAccess) -> impl Iterator<Item = ToolI
/// What a tool hands back: the text the model reads, or the message of a failed call.
pub(super) type ToolResult = Result<String, String>;
/// An image the model reads beside a tool's text: an MCP `image` content block.
/// An image the model reads beside a tool's text: an MCP `image` content block, or for the
/// chat, an image of the message that follows the tool results.
#[derive(serde::Serialize)]
#[cfg_attr(not(feature = "mcp"), allow(dead_code))]
pub(crate) struct ToolImage {
/// Standard base64.
@@ -282,7 +284,7 @@ pub(crate) struct Ctx<'a> {
/// What the card draws of this call, as `(key, value)`: returned in the result's
/// `_meta`, which the model never reads.
pub view: std::sync::Mutex<Option<(&'static str, Value)>>,
/// The images the model reads beside the text, returned as MCP content blocks.
/// The images the model reads beside the text.
pub images: std::sync::Mutex<Vec<ToolImage>>,
}
@@ -308,11 +310,22 @@ impl<'a> Ctx<'a> {
}
}
/// Whether the model reads images beside the text. The chat's providers take a tool
/// result as text only (OpenAI's tool messages cannot carry an image), so only an MCP
/// client is handed any.
/// Whether the model reads images beside the text. The chat's tool results are text
/// only (OpenAI's tool messages cannot carry an image), so the chat hands them over in
/// a message of their own, and only when its model reads images.
pub(super) fn reads_images(&self) -> bool {
self.surface == Surface::Mcp
match self.surface {
Surface::Mcp => true,
Surface::Chat => self.chat.is_some_and(|chat| chat.reads_images),
}
}
/// The `feature_usage` feature this surface's tool calls count under.
pub(super) fn usage_feature(&self) -> &'static str {
match self.surface {
Surface::Mcp => "mcp_workspace",
Surface::Chat => "ai_chat",
}
}
/// Hand the chat something to apply. A no-op for MCP, which has no editor.
@@ -2495,7 +2495,7 @@ fn jsonb_text_len(value: &Value) -> u64 {
// ============================================================================
// Images the model reads: a result Windmill draws as an image, attached to
// `get_run`'s answer for an MCP client.
// `get_run`'s answer when `Ctx::reads_images`.
// ============================================================================
/// The images one answer carries at most, and their bytes together.
@@ -2654,7 +2654,11 @@ async fn attach_result_images(
Ok(None) => source,
Err(skip) => skip.key,
};
windmill_common::feature_usage::log_feature_usage("mcp_workspace", "result_image", key);
windmill_common::feature_usage::log_feature_usage(
ctx.usage_feature(),
"result_image",
key,
);
(name, outcome.map_err(|skip| skip.why))
})
.collect();
+1 -1
View File
@@ -4,7 +4,7 @@
anonymous usage-stats payload. It answers "does anyone use this, and which variant do they pick"
without any identifying data leaving the instance.
It currently carries 117 registered actions across forty-four features (`access_view`, `ai_session`, `ai_chat`,
It currently carries 118 registered actions across forty-four features (`access_view`, `ai_session`, `ai_chat`,
`autoscaling_diagnostics`, `code_mode`,
`ai_fix`, `ai_agent`, `ai_decision`, `ai_agent_eval`, `app_sandbox`, `datatable`, `db_manager`, `flow_editor`,
`flow_run`, `flow_step`, `home`, `header_nav`, `run_form`, `sharing`, `debugger`, `trigger`,
@@ -49,6 +49,8 @@ export type SessionToolResponse = {
text: string
is_error: boolean
effects: SessionToolEffect[]
/** Sent only when the call's context set `reads_images`. */
images?: { data: string; mime_type: string }[]
}
/** What the browser holds that a tool reads: the editor open on each draft kind, and
@@ -357,6 +357,12 @@ vi.mock('$lib/components/secretArgUtils', () => ({
processSecretArgs: vi.fn(async (args: Record<string, any>) => args)
}))
// jsdom has no canvas to decode an image on.
vi.mock('../imageUtils', async (importOriginal) => ({
...(await importOriginal<typeof import('../imageUtils')>()),
normalizeImageDataUrl: vi.fn(async (dataUrl: string) => ({ dataUrl, mediaType: 'image/png' }))
}))
vi.mock('./rawAppBundlerBridge', () => ({
bundleRawAppDraft: vi.fn(async () => ({
js: 'bundled js',
@@ -589,6 +595,44 @@ describe('global AI tools', () => {
expect(names).toContain('list_runs')
})
it("hands get_run's result images to a model that reads them, and asks none for one that cannot", async () => {
const contexts: any[] = []
stubSessionTools(({ context }) => {
contexts.push(context)
return {
text: '{"result": "PNG image", "result_image": "attached"}',
is_error: false,
effects: [],
images: context.reads_images ? [{ data: 'iVBORw0KGgo=', mime_type: 'image/png' }] : []
}
})
const attachToolImage = vi.fn()
const model = (name: string) => ({
sessionAi: () => ({ model: { provider: 'openai', model: name } })
})
await callGlobalTool(
'get_run',
{ id: 'j' },
{ ...toolCallbacks, attachToolImage },
model('gpt-4o')
)
expect(contexts[0].reads_images).toBe(true)
expect(attachToolImage).toHaveBeenCalledExactlyOnceWith('test-get_run', {
image: { dataUrl: 'data:image/png;base64,iVBORw0KGgo=', mediaType: 'image/png' },
caption: 'Image(s) from run j:'
})
await callGlobalTool(
'get_run',
{ id: 'j' },
{ ...toolCallbacks, attachToolImage },
model('o1-mini')
)
expect(contexts[1].reads_images).toBe(false)
expect(attachToolImage).toHaveBeenCalledOnce()
})
it('keeps the trigger config schemas out of the tool definitions', async () => {
const def = JSON.stringify(getGlobalTool('write_trigger').def)
expect(def.length).toBeLessThan(2000)
@@ -68,7 +68,8 @@ import type { RawAppDomQuery } from '$lib/components/raw_apps/rawAppDom'
import { dataUrlToImagePart, normalizeImageDataUrl, type AttachedImage } from '../imageUtils'
import { sanitizeAttachmentName, textLineCount, type AttachedTextFile } from '../textFileUtils'
import { modelSupportsVision } from '../../modelConfig'
import { tryGetCurrentModel, type SessionAi } from '$lib/aiStore'
import { type SessionAi } from '$lib/aiStore'
import { sessionModel } from './sessionModel'
import { isChromiumBrowser } from '$lib/utils'
import { isCloudHosted } from '$lib/cloud'
import { BROWSER } from 'esm-env'
@@ -4142,26 +4143,45 @@ export const globalTools: SessionTool<{}>[] = [
planModeSafe: true,
lookup: true,
showDetails: true,
fn: async ({ args, workspace, toolId, toolCallbacks }) => {
fn: async ({ args, workspace, toolId, toolCallbacks, helpers }) => {
const parsed = getRunSchema.parse(args)
toolCallbacks.setToolStatus(toolId, {
content: parsed.step
? `Fetching result of step ${parsed.step} in run ${parsed.id}...`
: `Inspecting run ${parsed.id}...`
})
const { text, effects } = await runOnServer('get_run', workspace, args)
const model = sessionModel(helpers)
const { text, effects, images } = await runOnServer('get_run', workspace, args, {
reads_images: !model || modelSupportsVision(model.provider, model.model)
})
const jobId = effects.flatMap((e) => (e.type === 'inspected_run' ? [e.job_id] : []))[0]
const caption = parsed.step
? `Image(s) from step ${parsed.step} of run ${parsed.id}:`
: `Image(s) from run ${parsed.id}:`
const decoded = await Promise.all(
(images ?? []).map(({ data, mime_type }) =>
normalizeImageDataUrl(`data:${mime_type};base64,${data}`).catch(() => undefined)
)
)
const attached = decoded.filter((image): image is AttachedImage => image !== undefined)
for (const image of attached) toolCallbacks.attachToolImage?.(toolId, { image, caption })
// The server's note counts these as attached; the model must not look for them.
const lost = (images?.length ?? 0) - attached.length
const result =
lost > 0
? `${text}\n\n${lost} of the attached images could not be decoded and are not in the following message.`
: text
toolCallbacks.setToolStatus(toolId, {
content: parsed.step
? `Fetched result of step ${parsed.step} in run ${parsed.id}`
: `Inspected run ${parsed.id}`,
result: text,
result,
// The card reads the run itself from here; the model only ever gets `text`.
...(jobId
? { inspectedRun: { jobId, workspace, runId: parsed.id, step: parsed.step } }
: {})
})
return text
return result
}
},
{
@@ -4818,8 +4838,7 @@ export const globalTools: SessionTool<{}>[] = [
// A known text-only model would reject the follow-up image message and fail
// the turn, so refuse before capturing rather than buffer an image it can
// never read. The model is re-read here because it can change between turns.
const sessionAi = (ctx.helpers as GlobalToolHelpers | undefined)?.sessionAi
const model = sessionAi ? sessionAi().model : tryGetCurrentModel()
const model = sessionModel(ctx.helpers)
if (model && !modelSupportsVision(model.provider, model.model)) {
const cannotSee = `${model.model} cannot read images, so a screenshot would be discarded. Ask the user to describe what looks wrong, or to switch to a model that supports images.`
ctx.toolCallbacks.setToolStatus(ctx.toolId, {
@@ -7,8 +7,7 @@ import { listVisibleMcpServers } from '$lib/components/mcp/ownServers'
import { mcpUnavailableMessage } from './mcpUnavailable'
import { MAX_ATTACHED_IMAGES, normalizeImageDataUrl, type AttachedImage } from '../imageUtils'
import { modelSupportsVision } from '../../modelConfig'
import { tryGetCurrentModel } from '$lib/aiStore'
import type { GlobalToolHelpers } from './core'
import { sessionModel } from './sessionModel'
/**
* Access to the MCP servers the user has connected (resources of type `mcp`)
@@ -471,9 +470,7 @@ function createCallTool(servers: McpServer[], mode: 'read' | 'write'): SessionTo
return bounded({ success: false, error })
}
toolCallbacks.setToolStatus(toolId, { content: `Calling ${parsed.tool}...` })
// Re-read per call: the session's model can change between turns.
const sessionAi = (helpers as GlobalToolHelpers | undefined)?.sessionAi
const model = sessionAi ? sessionAi().model : tryGetCurrentModel()
const model = sessionModel(helpers)
const { result, images } = await executeTool(
workspace,
resolved.server,
@@ -0,0 +1,9 @@
import { tryGetCurrentModel } from '$lib/aiStore'
import type { GlobalToolHelpers } from './core'
/** The session's model, re-read per call because it can change between turns. A known
* text-only model fails the turn on the message that hands it a tool's images. */
export function sessionModel(helpers: unknown) {
const sessionAi = (helpers as GlobalToolHelpers | undefined)?.sessionAi
return sessionAi ? sessionAi().model : tryGetCurrentModel()
}