From d9ffd5054caedd30ca07df391b041e29a08f6d6c Mon Sep 17 00:00:00 2001 From: Laura Thiel Date: Mon, 16 Nov 2026 13:18:25 +0100 Subject: [PATCH] fix(web): warn before sending images a bot's model can't read The server refuses an unreadable image before recording a turn, so the error shows once and names the bot. The composer warns as soon as such an image is attached and links to the bot's profile and the vision model setting. GET /v1/models returns images for each model. Closes #80 --- CHANGELOG.md | 1 + apps/docs/content/concepts/chats.mdx | 3 + apps/server/src/bots/bots-submissions.ts | 40 +++++- apps/server/src/bots/chat.test.ts | 12 +- apps/server/src/bots/runtime.ts | 7 +- apps/server/src/contract/api-responses.ts | 4 + apps/server/src/providers/providers-api.ts | 2 + apps/web/features/bot-chat/chat.tsx | 2 + .../bot-chat/image-warning.dom.test.tsx | 135 ++++++++++++++++++ apps/web/features/bot-chat/image-warning.tsx | 59 ++++++++ apps/web/features/chat/composer.tsx | 6 + openapi/openapi.json | 7 +- 12 files changed, 269 insertions(+), 9 deletions(-) create mode 100644 apps/web/features/bot-chat/image-warning.dom.test.tsx create mode 100644 apps/web/features/bot-chat/image-warning.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 80e3bae6..db67e412 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- When a bot's model can't read images and no vision model is set, the web chat warns as soon as an image is attached and links to the bot's profile and the vision model setting. The server refuses such a message before recording a turn, so the error shows once, names the bot, and the message goes back to the composer. `GET /v1/models` returns `images` for each model. - Pinned conversations are saved on the account, so every app shows the same pins in the same order. The session returns them as `pinnedConversations`, `update-user` saves the whole list (up to nine `agent:` or `group:` keys), and `/v1/events` sends a `pins` event to the account's open apps when they change. On the web, pin or unpin a bot chat or group chat from its **More** menu in the sidebar, and drag pins in the **Pinned** section to reorder them. - Bots may stay quiet after automations. A scheduled or event automation, and a succeeded script automation's result, tell the bot it can react with 👍 instead of replying when the run found nothing the owner needs, unless the automation asks for a message every time. A reaction sends no notification. Results of failed, timed-out, and interrupted script runs don't carry the note. - Push notifications wait at least three seconds after enqueue and are suppressed on every device when the reply was seen or its bot or group chat is active in a focused web tab. Request cards count as seen only after their content loads and appears in the viewport. Browser notifications and unread counters are unchanged. diff --git a/apps/docs/content/concepts/chats.mdx b/apps/docs/content/concepts/chats.mdx index 503c3a00..797dd6e4 100644 --- a/apps/docs/content/concepts/chats.mdx +++ b/apps/docs/content/concepts/chats.mdx @@ -79,6 +79,9 @@ PNG, JPEG, GIF, and WebP images up to 5 MB reach the model as images; larger images arrive as references. A bot whose model reads images sees them as they are. A bot whose model can't read images refuses a message with an inline image, unless the account has a [vision model](/getting-started/providers#vision-model). +The web chat warns you as soon as you attach such an image, with links to the +bot's profile and the vision model setting. A refused message goes back to the +composer so you can remove the image or send it again after changing the model. With a vision model set, the vision model reads each image and describes it, including any visible text. The bot works from the description, and the diff --git a/apps/server/src/bots/bots-submissions.ts b/apps/server/src/bots/bots-submissions.ts index 687bd2a7..ba416bfd 100644 --- a/apps/server/src/bots/bots-submissions.ts +++ b/apps/server/src/bots/bots-submissions.ts @@ -1,15 +1,23 @@ import { Effect } from "effect"; +import type { Agent } from "../contract/agents"; +import { pi } from "../shared/app-errors"; +import { MAX_IMAGE_BYTES, attachmentKind } from "../shared/attachment-rules"; import { fileIdDigest } from "../shared/attachments"; import { groupTurnScope } from "../shared/request-ids"; import { validTimezone } from "../contract/cron"; import type { Execution } from "../shared/domain"; -import { Conflict, REQUEST_ID_REUSED, type AppError } from "../shared/errors"; +import { + Conflict, + InvalidInput, + REQUEST_ID_REUSED, + type AppError, +} from "../shared/errors"; import type { BotsAnnouncements } from "./bots-announcements"; import type { BotsChat } from "./bots-chat"; import { isChatTurn, type BotsContext } from "./bots-context"; import type { BotsLookup } from "./bots-lookup"; import type { BotsNotifications } from "./bots-notifications"; -import { OWNER_TIMEZONE } from "./runtime"; +import { OWNER_TIMEZONE, unreadableImages } from "./runtime"; export type SendOptions = { scheduleId?: string; @@ -45,12 +53,34 @@ const differsFrom = ( (existing.attachmentsDigest ?? null) !== attachmentsDigest; export const botsSubmissions = (context: BotsContext, deps: SubmissionDeps) => { - const { executions, runtime, settings } = context; + const { executions, runtime, settings, library } = context; const { conversation, withAgent } = deps.lookup; const { changed } = deps.notifications; const { forkPreview } = deps.announcements; const { admit, chat } = deps; + // Refuses before the turn is recorded, so the owner sees one error and the message goes back to the composer. + const refuseUnreadableImages = Effect.fnUntraced(function* ( + owner: Agent, + files: readonly string[], + ) { + const entries = yield* library.entries( + { kind: "bot", agentId: owner.id }, + files, + ); + + const images = [...entries.values()].some( + (entry) => + attachmentKind(entry.mimeType) === "image" && + entry.size <= MAX_IMAGE_BYTES, + ); + + if (images && !(yield* pi(() => runtime.acceptsImages(owner)))) + return yield* Effect.fail( + new InvalidInput({ message: unreadableImages(owner) }), + ); + }); + const send = Effect.fn("Bots.send")(function* ( conversationId: string, content: string, @@ -70,8 +100,10 @@ export const botsSubmissions = (context: BotsContext, deps: SubmissionDeps) => { if (existing && differsFrom(existing, content, replyTo, attachmentsDigest)) return yield* conflict(REQUEST_ID_REUSED); - if (!existing && files.length && !groupTurnScope(requestId, owner.id)) + if (!existing && files.length && !groupTurnScope(requestId, owner.id)) { yield* runtime.validateFiles(owner.id, files); + yield* refuseUnreadableImages(owner, files); + } const execution = existing ?? diff --git a/apps/server/src/bots/chat.test.ts b/apps/server/src/bots/chat.test.ts index 2fee48b1..c0aa2b5d 100644 --- a/apps/server/src/bots/chat.test.ts +++ b/apps/server/src/bots/chat.test.ts @@ -970,7 +970,17 @@ describe("library files", () => { await expect( service.sendChat(agent.id, "look", uuid(11), undefined, [small.file.id]), - ).rejects.toThrow("can't read images"); + ).rejects.toThrow( + "Chat's model (chat) can't read images. Choose a model that accepts images in Chat's profile", + ); + + // Refused before a turn is recorded, so the chat shows no failed turn beside the send error. + const refused = await service.chatSnapshot(agent.id); + + expect(refused.error).toBeNull(); + expect(refused.messages.some((message) => message.role === "user")).toBe( + false, + ); const accepted = await service.sendChat( agent.id, diff --git a/apps/server/src/bots/runtime.ts b/apps/server/src/bots/runtime.ts index 39c7bda9..a1363dc2 100644 --- a/apps/server/src/bots/runtime.ts +++ b/apps/server/src/bots/runtime.ts @@ -318,6 +318,9 @@ async function ensureModel( type ModelBlocks = ReturnType; +export const unreadableImages = (agent: Pick) => + `${agent.name}'s model (${agent.model}) can't read images. Choose a model that accepts images in ${agent.name}'s profile, or set a vision model in Settings to describe images for it.`; + // Catalogs that list no modalities are trusted; the provider reports anything it refuses. With a vision model set, // the vision extension describes images for a model that can't read them. function assertImageSupport( @@ -331,9 +334,7 @@ function assertImageSupport( !readsImages(model) && !vision ) - throw new InvalidInput({ - message: `${agent.model} can't read images. Choose a model that accepts images in the bot's profile, or set a vision model in Settings to describe images for it.`, - }); + throw new InvalidInput({ message: unreadableImages(agent) }); } function inputContent(text: string, blocks: ModelBlocks) { diff --git a/apps/server/src/contract/api-responses.ts b/apps/server/src/contract/api-responses.ts index 95b74822..a06df473 100644 --- a/apps/server/src/contract/api-responses.ts +++ b/apps/server/src/contract/api-responses.ts @@ -1102,6 +1102,10 @@ export const modelResponse = z description: "The thinking levels this model takes, from lowest to highest. A bot's level outside them runs at the nearest one.", }), + images: z.boolean().openapi({ + description: + "Whether this model reads images. True when the provider's catalog lists no input types.", + }), }) .openapi("Model"); diff --git a/apps/server/src/providers/providers-api.ts b/apps/server/src/providers/providers-api.ts index 5f5b6fa8..e0fe714a 100644 --- a/apps/server/src/providers/providers-api.ts +++ b/apps/server/src/providers/providers-api.ts @@ -17,6 +17,7 @@ import { NotFound, Unavailable, } from "../shared/errors"; +import { readsImages } from "../vision/vision"; import { loginMethods, type ProviderSignInsAccess } from "./provider-auth"; export function previewReasoning( @@ -107,6 +108,7 @@ const registerProviderStatusRoutes = (options: ProviderRoutesOptions) => { contextWindow: model.contextWindow, reasoning: model.reasoning, thinkingLevels: getSupportedThinkingLevels(model), + images: readsImages(model), })), 200, ); diff --git a/apps/web/features/bot-chat/chat.tsx b/apps/web/features/bot-chat/chat.tsx index f1f42868..86c957ee 100644 --- a/apps/web/features/bot-chat/chat.tsx +++ b/apps/web/features/bot-chat/chat.tsx @@ -32,6 +32,7 @@ import { } from "@/features/chat/conversation"; import type { ConversationTarget } from "@/features/chat/conversation-target"; import { DetailsPanel, DetailsSheet } from "./details"; +import { ImageWarning } from "./image-warning"; import { JobPanel } from "@/features/jobs/jobs"; import { CallPanel } from "@/features/call-requests/call-panel"; import { CallNotice } from "@/features/call-requests/call-request-card"; @@ -322,6 +323,7 @@ function ChatComposer({ onCancelReply={() => setReplyTo(null)} mentionable={mentionableBots(bot, bots)} actions={} + notice={(uploads) => } onSend={(content, uploads) => sendMessage(content, uploads)} onStop={onStop} /> diff --git a/apps/web/features/bot-chat/image-warning.dom.test.tsx b/apps/web/features/bot-chat/image-warning.dom.test.tsx new file mode 100644 index 00000000..59ba66de --- /dev/null +++ b/apps/web/features/bot-chat/image-warning.dom.test.tsx @@ -0,0 +1,135 @@ +import { expect, spyOn, test } from "bun:test"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { Window } from "happy-dom"; +import { + createRootRoute, + createRouter, + RouterContextProvider, +} from "@tanstack/react-router"; +import { act } from "react"; +import { z } from "zod"; +import { settle, waitFor, waitForIdle } from "@/test/wait-for"; +import type { Upload } from "@/features/chat/composer"; +import { ImageWarning } from "./image-warning"; + +const bot = { id: "b1", name: "Atlas", provider: "p", model: "flash" }; + +const image: Upload = { + name: "photo.png", + mimeType: "image/png", + size: 1024, + status: "ready", + id: "f1", +}; + +const largeImage: Upload = { ...image, size: 6 * 1024 * 1024 }; + +const text: Upload = { ...image, name: "notes.txt", mimeType: "text/plain" }; + +async function render( + uploads: Upload[], + { images = false, vision = false } = {}, +) { + const window = new Window({ url: "http://localhost" }); + const globals = Object.getOwnPropertyDescriptors(globalThis); + Object.defineProperties(globalThis, { + window: { configurable: true, value: window }, + document: { configurable: true, value: window.document }, + HTMLElement: { configurable: true, value: window.HTMLElement }, + IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true }, + }); + + const fetch = spyOn(globalThis, "fetch").mockImplementation( + Object.assign( + async (input: RequestInfo | URL) => { + const url = z.string().parse(input); + + if (url.startsWith("/v1/models")) + return Response.json([ + { + provider: "p", + id: "flash", + name: "Flash", + contextWindow: 1000, + reasoning: false, + thinkingLevels: [], + images, + }, + ]); + + return Response.json({ + visionModel: vision ? { provider: "p", model: "eyes" } : null, + choices: [], + }); + }, + { preconnect: globalThis.fetch.preconnect }, + ), + ); + + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + + const router = createRouter({ routeTree: createRootRoute() }); + const { createRoot } = await import("react-dom/client"); + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + + await act(async () => { + root.render( + + + + + , + ); + }); + await waitForIdle(client); + await settle(); + + return { + container, + cleanup: async () => { + await act(async () => root.unmount()); + client.clear(); + fetch.mockRestore(); + await window.happyDOM.abort(); + Object.defineProperties(globalThis, globals); + }, + }; +} + +test("warns about an attached image the bot's model can't read, naming the bot", async () => { + const { container, cleanup } = await render([text, image]); + + try { + await waitFor(() => container.querySelector("[role=alert]") !== null); + expect(container.textContent).toContain( + "Atlas's model (flash) can't read images.", + ); + expect( + [...container.querySelectorAll("a")].map((link) => + link.getAttribute("href"), + ), + ).toEqual(["/bots/b1/edit", "/settings/vision-model"]); + } finally { + await cleanup(); + } +}); + +for (const [name, uploads, options] of [ + ["the model reads images", [image], { images: true }], + ["a vision model describes images", [image], { vision: true }], + ["no image is attached", [text], {}], + ["the image is sent as a file reference", [largeImage], {}], +] as const) + test(`stays quiet when ${name}`, async () => { + const { container, cleanup } = await render([...uploads], options); + + try { + expect(container.querySelector("[role=alert]")).toBeNull(); + } finally { + await cleanup(); + } + }); diff --git a/apps/web/features/bot-chat/image-warning.tsx b/apps/web/features/bot-chat/image-warning.tsx new file mode 100644 index 00000000..a010e82e --- /dev/null +++ b/apps/web/features/bot-chat/image-warning.tsx @@ -0,0 +1,59 @@ +import { useQuery } from "@tanstack/react-query"; +import { Link } from "@tanstack/react-router"; +import { + MAX_IMAGE_BYTES, + attachmentKind, +} from "@crumble/server/contract/limits"; +import type { Bot } from "@/features/bots/api"; +import type { Upload } from "@/features/chat/composer"; +import { modelsQuery, visionModelQuery } from "@/features/providers/api"; + +type ImageBot = Pick; + +/** Images the bot's model gets as images; larger ones arrive as file references. */ +const sentAsImage = (upload: Upload) => + attachmentKind(upload.mimeType) === "image" && + (upload.size ?? 0) <= MAX_IMAGE_BYTES; + +/** False only when the catalog says the model can't read images and no vision model describes them. */ +function useReadsImages(bot: ImageBot) { + const models = useQuery(modelsQuery(bot.provider)); + const vision = useQuery(visionModelQuery); + const model = models.data?.find((each) => each.id === bot.model); + + if (!model || !vision.data) return true; + + return model.images || vision.data.visionModel !== null; +} + +/** Warns before sending an image the bot can't read; the server refuses the message. */ +export function ImageWarning({ + bot, + uploads, +}: { + bot: ImageBot; + uploads: Upload[]; +}) { + const reads = useReadsImages(bot); + + if (reads || !uploads.some(sentAsImage)) return null; + + return ( +

+ {bot.name}'s model ({bot.model}) can't read images. Choose a model that + accepts images in{" "} + + {bot.name}'s profile + + , or set a{" "} + + vision model + {" "} + to describe images for it. +

+ ); +} diff --git a/apps/web/features/chat/composer.tsx b/apps/web/features/chat/composer.tsx index a33da573..514ae6c8 100644 --- a/apps/web/features/chat/composer.tsx +++ b/apps/web/features/chat/composer.tsx @@ -40,6 +40,7 @@ import { uploadFile } from "@/features/library/api"; export type Upload = { name: string; mimeType: string; + size?: number; id?: string; status: "pending" | "ready" | "error"; existed?: boolean; @@ -82,6 +83,7 @@ function useAttachments(path: string) { const upload: Upload = { name: file.name, mimeType: file.type, + size: file.size, status: file.size > MAX_FILE_BYTES ? "error" : "pending", ...(file.size > MAX_FILE_BYTES && { error: "Larger than 100 MB" }), }; @@ -584,6 +586,8 @@ type ComposerProps = { onCancelReply?: () => void; mentionable?: Mentionable[]; actions?: ReactNode; + /** Shown above the composer for the files attached so far. */ + notice?: (uploads: Upload[]) => ReactNode; onSend: (content: string, uploads: Upload[]) => Promise; onStop: () => void; }; @@ -716,6 +720,7 @@ export function Composer({ onCancelReply, mentionable = [], actions, + notice, onSend, onStop, }: ComposerProps) { @@ -745,6 +750,7 @@ export function Composer({ > + {notice?.(uploads)}