Files
windmill/frontend/src/lib/components/copilot/chat/imageUtils.ts
T
hugocasaandClaude Opus 4.8 7a139ab23e feat(ai-chat): image attachments and agent raw-app screenshots (#10130)
* feat(ai-chat): add image attachments and agent raw-app screenshots

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

* docs(ai-chat): generalise take_screenshot fidelity caveat

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

* fix(ai-chat): keep compaction boundary on a displayed user message

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

* fix(raw-apps): count line boxes by vertical overlap, not rect count

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

* fix(ai-chat): enforce vision gating and bound image attachments

Refuse images on known text-only models instead of warning and sending them
anyway; cap input bytes before decode; keep clipboard text when it accompanies
a bitmap; don't queue a message whose images can't ride the plain-text queue.

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

* perf(ai-chat): trim take_screenshot schema and shrink the card's copy

Move the fidelity caveat from the tool def onto the tool result: the def is
re-sent every global iteration (~258 tok), while the caveat only matters once a
capture exists. Keep a downscaled copy in displayMessages when it is actually
smaller — those are never compacted and are re-cloned on every saveChat.

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

* fix(ai-chat): carry attached images through the message queue

Enter during a streaming turn queued the text and silently dropped the images,
so the auto-send was not the message the user submitted. The queue now holds
both, moved together via takeQueue/clearQueue/restoreQueue so none of the three
flush sites, the dequeue-to-composer path, or the two conversation-switch drops
can leak one without the other.

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

* fix(ai-chat): gate screenshots on vision, narrow when the tool fires

take_screenshot buffered an image unconditionally, so a text-only model got an
image_url and rejected the turn; the attach-time check never covered it, nor a
model switched after attaching. Gate before capture and again at send.

Only reach for the tool when the user raises how the app looks, rather than
after every UI edit.

A collapsed preview keeps the iframe mounted at zero width, passing the ready
checks and then failing inside the rasteriser as '[object Event]'. Name it.

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

* fix(ai-chat): hold sending while attachments decode

addImages read the free-slot count before its await and appended after it, so a
send during the ~50-800ms decode cleared images while the closure still wrote to
them, landing the picture on the following message; two drops also claimed the
same slots and could pass the cap. Reserve slots up front, block sending until
they resolve, and show a placeholder so the held send is explained.

Keep only a bounded copy in the transcript: displayMessages are never compacted
and are re-cloned on every save. Measured 6.1x smaller per attachment.

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

* fix(ai-chat): route screenshots to the visible tab, resend full-res on retry

Every mounted raw-app editor claimed the runtime's single screenshot slot, so
take_screenshot could capture a background tab's app; ownership now follows the
visible tab and only the owner releases it.

restartGeneration resent displayMessages' images, which became a 384px thumbnail
when the transcript copy was bounded — retries downgraded the model's own input.
Recover the sent parts from the API message instead.

Move modelSupportsVision to modelConfig: it was untestable behind lib.ts's monaco
import chain, and the denylist missed bundled text-only defaults (Groq/Together
Llama 3.3, Foundry Phi-4 and Mistral-Large). Llama 3.2 and Phi-4 split by variant,
so both are matched narrowly. Pinned against the shipped defaultModels.

Decode attachments one at a time and derive the preview from the bounded copy: a
12MP bitmap is ~48MB and the batch was held live at once, decoded twice each.

The attach tooltip claimed nothing is uploaded, which is untrue for images.

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

* fix(ai-chat): keep images out of text-only turns and bound the queue

The vision gate only dropped the current turn's images, so history's image parts
still went out after a switch to a text-only model and failed the request; strip
the outbound copy instead, leaving history intact for a switch back.

queueMessage had no cap, and each queued send clears the composer for another
eight, so repeated sends stacked an unbounded batch into one message.

Editing a message resent displayMessages' bounded copy, downgrading the model's
own input; retries recovered the full-size one but then re-persisted it at full
resolution. storedImages pairs the API message with its transcript entry so both
paths resend the original and re-persist the bounded copy.

Reserve image slots before awaiting text attachments: the gap left sending
enabled with an image pending, measured ~90ms for a 40-file drop, now ~8ms
regardless of batch size.

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

* fix(ai-chat): treat deepseek-v4 as text-only

deepseek-v4-pro ships as a bundled default and the gate let images through to
it, so an attachment would fail the turn. DeepSeek's vision line is deepseek-vl.

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

* fix(ai-chat): drop a rejected image instead of wedging the conversation

A provider that refuses an image leaves it in history, so every later turn
resends it and fails identically: the chat is stuck until the user edits the
message or starts over, and Retry re-sends the same image. The vision gate only
knows the models we ship, so this is the net for the rest. Strip the parts on an
image-related rejection and say so; unrelated failures keep the image.

Verified at the wire that no provider rejects a base64 data URL: anthropic
(source.base64), openai/gpt-4o (input_image), googleai and aws_bedrock/claude
(image_url passthrough) all 200 and read the image.

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

* fix(ai-chat): match text-only models exactly, from provider API docs

The gate guessed by substring over model names, which answers the wrong
question. What matters is whether a provider's API accepts image parts, not
whether the model can see: DeepSeek V4 ships vision in its chat product that its
API has no content type for, and o3-mini gained vision in ChatGPT the API never
exposed. Neither is inferable from a name.

Substrings also block working models. 'mistral-large' matches Mistral Large 3,
which takes images; 'phi-4' matches Phi-4-multimodal, which does too. A wrong
entry blocks with no override, while a missing one costs a turn and recovers via
the rejection path, so the list is now exact ids only, each backed by a provider
doc.

Verdicts verified against provider API docs rather than recall. Live-checked
where a doc was contradicted: Bedrock's compatibility matrix claims no Anthropic
model is served over chat completions, but it serves images fine.

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

* fix(ai-chat): stop retry resurrecting a rejected image

The rejection fallback strips the image from history but leaves the bubble's
thumbnail so the user can still see what they sent. storedImages fell back to
that thumbnail when the API message had no parts, so Retry re-attached the very
image the provider had just refused and failed identically — the conversation
stayed wedged through the one control offered to escape it.

Found by retrying in the UI; unit tests, wire tests and four review passes all
missed it, since it only exists between two separate fixes.

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

* fix(ai-chat): harden image rejection recovery and drop-path attachment

* fix(ai-chat): fix image drop race, mid-turn vision gate, retry aliasing

* fix(ai-chat): key vision denylist by provider, flatten alpha before jpeg

* feat(ai-chat): offer take_screenshot on chromium only, ask for one elsewhere

* feat(ai-chat): image-only sends and click-to-expand image previews

* fix(ai-chat): capture screenshots at 2x and expand tool images full-res

* feat(frontend): expandable image previews in composer and result views

* fix(ai-chat): image-only send edge cases from review round

* fix(ai-chat): keep image-only drafts on rollback, track failing model id

* fix(ai-chat): gate rejection recovery on the failing iteration's model

* refactor(ai-chat): record iteration model via onBeforeIteration, trim tests

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): restore composer draft when beforeSend preflight fails

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): bound cumulative outbound image bytes per request

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): make the image byte bound part-granular so over-cap turns keep a subset

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): evict newest-first within a message in the image byte bound

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): prune over-cap images from stored history, not just requests

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): bound history at every save boundary, keep thumbnail pairing across eviction

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): slot-align storedImages so the bubble expands the right image after eviction

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): match rejection keywords as whole words so provisioning errors keep images

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): match input_image rejections, restore images refused by non-GLOBAL modes

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): defer non-GLOBAL image refusal restore past the composer clear

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): persist full tool screenshots for post-reload expansion

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(ai-chat): persist chat images out-of-band via blob-store refs

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): scope image blobs per chat and stop cap-eviction rotation

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): keep blob-cap chronology across drop-oldest compaction

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(ai-chat): derive blob eviction from the saved record, not write times

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): serialize chat history DB writes per manager

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): pin queued history writes to the enqueue-time user database

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): delete stale image blobs only after the chat record commits

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): don't double-restore a queued image-only draft on vision refusal

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): label image-only chats and evicted image-only bubbles

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): keep the in-memory chat mirror hydrated for DB-less sessions

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): converge the chat mirror to refs after a successful DB commit

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): guard mirror convergence against rewinding newer saves

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): invalidate pending convergences on identity re-init, keep retry image names

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ai-chat): bound the screenshot raster before rasterization

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(ai-chat): drop the no-IndexedDB in-memory image fallback

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 19:36:51 +02:00

274 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Image handling shared by the two multimodal chat features: user-attached images
* (drag/drop/paste, GLOBAL mode) and the app agent's `take_screenshot` tool.
*
* Every image the model sees passes through here first so it is bounded in BOTH
* dimensions (≤ MAX_EDGE longest side — beyond this the provider downscales anyway
* and just bills more tokens) and bytes. Bounding bytes matters because the data URL
* rides every request (stateless APIs resend the whole history) and is persisted in
* the chat history's blob store. Everything is rasterised to PNG/JPEG so exotic
* inputs (SVG, WebP, HEIC where the browser can decode it) become a media type all
* providers accept.
*/
import type {
ChatCompletionContentPartImage,
ChatCompletionMessageParam
} from 'openai/resources/index.mjs'
/** Longest-edge cap. Matches the point past which vision models downscale server-side. */
export const MAX_IMAGE_EDGE = 1568
/** Above this many bytes a PNG re-encodes to JPEG to keep history/storage bounded. */
const PNG_SIZE_CAP = 700_000
/**
* Refuse a file this large before reading it. Decoding allocates ~4 bytes per pixel
* — a 12MP photo is ~48MB of bitmap — and the downscale below can only run once that
* bitmap exists, so the cap has to bite before the read, not after.
*/
export const MAX_IMAGE_BYTES = 20_000_000
/** Decoded-pixel ceiling, in case a small file expands to an absurd bitmap. */
const MAX_IMAGE_PIXELS = 40_000_000
/**
* Images one message may carry. Enforced wherever a message is assembled, not just
* at the composer: queuing clears the composer, so its own count would reset and let
* repeated sends stack an unbounded batch into a single message.
*/
export const MAX_ATTACHED_IMAGES = 8
export type ImageMediaType = 'image/png' | 'image/jpeg'
/** A model-ready image: a normalised (bounded, png/jpeg) data URL plus its media type. */
export type AttachedImage = {
dataUrl: string
mediaType: ImageMediaType
/** Original filename when it came from a user file; absent for screenshots. */
name?: string
}
/** Stands in for a stripped or evicted image part in message content. */
export const IMAGE_OMITTED_PLACEHOLDER = '[image omitted]'
/**
* Recover the model's own images from an API message's content parts. Anything
* resending a turn (retry, edit) must read images from here, never from the
* transcript bubble: a provider rejection strips them from history while the
* bubble keeps its copy so the user can still see what they sent — resending
* that copy would re-attach the image the provider just refused.
*/
export function imagesFromContent(content: unknown): AttachedImage[] | undefined {
if (!Array.isArray(content)) return undefined
const images = (content as any[]).flatMap((part): AttachedImage[] => {
if (part?.type !== 'image_url' || typeof part?.image_url?.url !== 'string') return []
const dataUrl = part.image_url.url as string
return [
{
dataUrl,
mediaType:
parseImageDataUrl(dataUrl).mediaType === 'image/jpeg' ? 'image/jpeg' : 'image/png'
}
]
})
return images.length > 0 ? images : undefined
}
/**
* Raster scale for a DOM screenshot of a target whose longest CSS edge is
* `cssEdge`. Above CSS resolution (up to 2×) for small targets — the SVG
* re-render is vector, so the extra scale is real detail, not interpolation —
* but never a raster larger than MAX_IMAGE_EDGE: normalize would downscale the
* excess away, and rasterising an oversized body (a tall scrolling app) at ≥1×
* first can allocate a tab-freezing canvas. Sub-1× output is deliberate.
*/
export function captureScale(cssEdge: number): number {
return Math.min(2, MAX_IMAGE_EDGE / Math.max(1, cssEdge))
}
export function isImageFile(file: File | Blob): boolean {
return typeof file.type === 'string' && file.type.startsWith('image/')
}
/** Byte size of a base64 data URL's payload (4 base64 chars → 3 bytes). */
function base64Bytes(dataUrl: string): number {
const comma = dataUrl.indexOf(',')
const b64 = comma >= 0 ? dataUrl.slice(comma + 1) : dataUrl
const padding = b64.endsWith('==') ? 2 : b64.endsWith('=') ? 1 : 0
return Math.max(0, Math.floor((b64.length * 3) / 4) - padding)
}
function loadImage(src: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const img = new Image()
img.onload = () => resolve(img)
img.onerror = () => reject(new Error('Could not decode image'))
img.src = src
})
}
function blobToDataUrl(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(reader.result as string)
reader.onerror = () => reject(reader.error ?? new Error('Could not read file'))
reader.readAsDataURL(blob)
})
}
/** PNG by default (lossless — crisp for the common UI-screenshot/diagram case); fall
* back to JPEG only when the PNG would blow the size cap (photographic content). */
function encodeCanvas(canvas: HTMLCanvasElement): { dataUrl: string; mediaType: ImageMediaType } {
const png = canvas.toDataURL('image/png')
if (base64Bytes(png) <= PNG_SIZE_CAP) {
return { dataUrl: png, mediaType: 'image/png' }
}
// JPEG has no alpha channel and canvas encoders composite transparent pixels
// onto black, which hides dark strokes in a transparent diagram. Flatten onto
// white before encoding.
const flat = document.createElement('canvas')
flat.width = canvas.width
flat.height = canvas.height
const ctx = flat.getContext('2d')
if (ctx) {
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, flat.width, flat.height)
ctx.drawImage(canvas, 0, 0)
}
return {
dataUrl: (ctx ? flat : canvas).toDataURL('image/jpeg', 0.82),
mediaType: 'image/jpeg'
}
}
/**
* Downscale a data URL to ≤ MAX_IMAGE_EDGE on its longest side and re-encode to
* png/jpeg. Used by both the file-attach path and the screenshot tool.
*/
export async function normalizeImageDataUrl(
dataUrl: string,
name?: string,
maxEdge: number = MAX_IMAGE_EDGE
): Promise<AttachedImage> {
const img = await loadImage(dataUrl)
const srcW = img.naturalWidth || img.width
const srcH = img.naturalHeight || img.height
if (!srcW || !srcH) throw new Error('Image has no dimensions')
if (srcW * srcH > MAX_IMAGE_PIXELS) throw new Error('Image resolution is too large')
const scale = Math.min(1, maxEdge / Math.max(srcW, srcH))
const w = Math.max(1, Math.round(srcW * scale))
const h = Math.max(1, Math.round(srcH * scale))
const canvas = document.createElement('canvas')
canvas.width = w
canvas.height = h
const ctx = canvas.getContext('2d')
if (!ctx) throw new Error('Canvas 2D context unavailable')
ctx.drawImage(img, 0, 0, w, h)
return { ...encodeCanvas(canvas), name }
}
/** Read a user-provided image file and produce a bounded, model-ready AttachedImage. */
export async function fileToAttachedImage(file: File | Blob): Promise<AttachedImage> {
if (file.size > MAX_IMAGE_BYTES) throw new Error('Image file is too large')
const name = file instanceof File ? file.name : undefined
const dataUrl = await blobToDataUrl(file)
return await normalizeImageDataUrl(dataUrl, name)
}
/** Split a data URL into its media type and base64 payload (for the Anthropic converter). */
export function parseImageDataUrl(url: string): { mediaType: string; base64: string } {
const match = /^data:([^;,]+)?(;base64)?,(.*)$/s.exec(url)
if (!match) return { mediaType: 'image/png', base64: '' }
return { mediaType: match[1] || 'image/png', base64: match[2] ? match[3] : '' }
}
/** Build the OpenAI-format image content part that all three provider paths convert from. */
export function dataUrlToImagePart(dataUrl: string): ChatCompletionContentPartImage {
return { type: 'image_url', image_url: { url: dataUrl } }
}
/** Whether any message still carries an image_url content part. */
export function messagesHaveImageParts(messages: ChatCompletionMessageParam[]): boolean {
return messages.some(
(message) =>
Array.isArray(message.content) &&
(message.content as any[]).some((part) => part?.type === 'image_url')
)
}
/**
* Total decoded image bytes one request may carry. Providers reject the whole
* request body over a size limit (20MB on Bedrock, 32MB direct Anthropic), and
* that 413 never mentions images, so the vision-rejection fallback cannot
* recover it — each request must stay under the limit in the first place.
* Compaction cannot be relied on for this: it triggers on estimated tokens,
* and images are cheap in tokens relative to their bytes. 12MB decoded is
* ~16MB of base64 on the wire, safely under the tightest limit with text.
*/
export const MAX_TOTAL_IMAGE_BYTES = 12_000_000
/**
* Keep the request's cumulative image bytes under the cap by stripping the
* OLDEST image parts first (the newest images are the ones the conversation
* is about). Part-granular so a single over-cap batch keeps the subset that
* fits — the newest message never silently loses all its images (one bounded
* image alone cannot exceed the cap). Returns the input array unchanged when
* everything fits.
*/
export function boundImagePartBytes(
messages: ChatCompletionMessageParam[],
cap: number = MAX_TOTAL_IMAGE_BYTES
): ChatCompletionMessageParam[] {
let total = 0
const drops = new Map<number, Set<number>>()
for (let i = messages.length - 1; i >= 0; i--) {
const content = messages[i].content
if (!Array.isArray(content)) continue
// Parts walk in reverse too: within a message they are in attachment order,
// and for screenshot follow-ups the last one is the app's current state.
for (let j = (content as any[]).length - 1; j >= 0; j--) {
const part = (content as any[])[j]
if (part?.type !== 'image_url' || typeof part?.image_url?.url !== 'string') continue
total += base64Bytes(part.image_url.url)
if (total > cap) {
if (!drops.has(i)) drops.set(i, new Set())
drops.get(i)!.add(j)
}
}
}
if (drops.size === 0) return messages
return messages.map((message, i) => {
const drop = drops.get(i)
if (!drop) return message
return {
...message,
content: (message.content as any[]).map((part, j) =>
drop.has(j) ? { type: 'text', text: IMAGE_OMITTED_PLACEHOLDER } : part
)
} as ChatCompletionMessageParam
})
}
/**
* Replace image_url content parts with a short text placeholder, collapsing the
* remaining parts back to a plain string. Used to keep base64 blobs out of the
* summarizer request during compaction (the summary text then stands in for them).
*/
export function stripImagePartsFromMessages(
messages: ChatCompletionMessageParam[]
): ChatCompletionMessageParam[] {
return messages.map((message) => {
if (!Array.isArray(message.content)) return message
let hadImage = false
const text = (message.content as any[])
.map((part) => {
if (part?.type === 'text') return part.text ?? ''
if (part?.type === 'image_url') {
hadImage = true
return IMAGE_OMITTED_PLACEHOLDER
}
return ''
})
.filter(Boolean)
.join('\n')
if (!hadImage) return message
return { ...message, content: text } as ChatCompletionMessageParam
})
}