diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index e6dcdc81fa..18b1516e9f 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -45192bb9f511422c8a2baf80ac36c4f63ff43fa5 +2a59a3b336ae88f9314dfb25e0e7d4552b40b867 diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 6a6e43152a..f456adcdd8 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -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: diff --git a/backend/windmill-api/src/ai_session_tools/chat.rs b/backend/windmill-api/src/ai_session_tools/chat.rs index cbd099a33f..73724604b2 100644 --- a/backend/windmill-api/src/ai_session_tools/chat.rs +++ b/backend/windmill-api/src/ai_session_tools/chat.rs @@ -36,6 +36,8 @@ struct ToolResponse { #[serde(flatten)] outcome: ToolOutcome, effects: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] + images: Vec, } 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, + /// 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)] diff --git a/backend/windmill-api/src/ai_session_tools/images.rs b/backend/windmill-api/src/ai_session_tools/images.rs index ac892b2a1d..6364b2d68e 100644 --- a/backend/windmill-api/src/ai_session_tools/images.rs +++ b/backend/windmill-api/src/ai_session_tools/images.rs @@ -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, _slot: Option, ) -> Result { Err(unreadable( - "images are read only for MCP clients".to_string(), + "this server was built without image support".to_string(), )) } diff --git a/backend/windmill-api/src/ai_session_tools/mod.rs b/backend/windmill-api/src/ai_session_tools/mod.rs index e0e93a44c9..3f926d2074 100644 --- a/backend/windmill-api/src/ai_session_tools/mod.rs +++ b/backend/windmill-api/src/ai_session_tools/mod.rs @@ -255,7 +255,9 @@ pub(crate) fn session_tools(access: SessionAccess) -> impl Iterator; -/// 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>, - /// 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>, } @@ -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. diff --git a/backend/windmill-api/src/ai_session_tools/runs.rs b/backend/windmill-api/src/ai_session_tools/runs.rs index 6dc2ab97b0..7955d12506 100644 --- a/backend/windmill-api/src/ai_session_tools/runs.rs +++ b/backend/windmill-api/src/ai_session_tools/runs.rs @@ -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(); diff --git a/docs/feature-telemetry.md b/docs/feature-telemetry.md index 497f82f83e..bb6a3fa86a 100644 --- a/docs/feature-telemetry.md +++ b/docs/feature-telemetry.md @@ -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`, diff --git a/frontend/src/lib/components/copilot/chat/global/backendSessionTools.ts b/frontend/src/lib/components/copilot/chat/global/backendSessionTools.ts index 32e46f8a9d..7f89e0bc2d 100644 --- a/frontend/src/lib/components/copilot/chat/global/backendSessionTools.ts +++ b/frontend/src/lib/components/copilot/chat/global/backendSessionTools.ts @@ -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 diff --git a/frontend/src/lib/components/copilot/chat/global/core.test.ts b/frontend/src/lib/components/copilot/chat/global/core.test.ts index c7d3fbe9ad..2f0538010e 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.test.ts @@ -357,6 +357,12 @@ vi.mock('$lib/components/secretArgUtils', () => ({ processSecretArgs: vi.fn(async (args: Record) => args) })) +// jsdom has no canvas to decode an image on. +vi.mock('../imageUtils', async (importOriginal) => ({ + ...(await importOriginal()), + 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) diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index 53ff9adf6c..ff4f870b1d 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -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, { diff --git a/frontend/src/lib/components/copilot/chat/global/mcpTools.ts b/frontend/src/lib/components/copilot/chat/global/mcpTools.ts index 3dcc0126ed..49a49f8869 100644 --- a/frontend/src/lib/components/copilot/chat/global/mcpTools.ts +++ b/frontend/src/lib/components/copilot/chat/global/mcpTools.ts @@ -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, diff --git a/frontend/src/lib/components/copilot/chat/global/sessionModel.ts b/frontend/src/lib/components/copilot/chat/global/sessionModel.ts new file mode 100644 index 0000000000..705edfa7df --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/global/sessionModel.ts @@ -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() +}