Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<id>` or `group:<id>` 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.
Expand Down
3 changes: 3 additions & 0 deletions apps/docs/content/concepts/chats.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
40 changes: 36 additions & 4 deletions apps/server/src/bots/bots-submissions.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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,
Expand All @@ -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 ??
Expand Down
12 changes: 11 additions & 1 deletion apps/server/src/bots/chat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 4 additions & 3 deletions apps/server/src/bots/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,9 @@ async function ensureModel(

type ModelBlocks = ReturnType<typeof modelBlocks>;

export const unreadableImages = (agent: Pick<Agent, "name" | "model">) =>
`${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(
Expand All @@ -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) {
Expand Down
4 changes: 4 additions & 0 deletions apps/server/src/contract/api-responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/providers/providers-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -107,6 +108,7 @@ const registerProviderStatusRoutes = (options: ProviderRoutesOptions) => {
contextWindow: model.contextWindow,
reasoning: model.reasoning,
thinkingLevels: getSupportedThinkingLevels(model),
images: readsImages(model),
})),
200,
);
Expand Down
2 changes: 2 additions & 0 deletions apps/web/features/bot-chat/chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -322,6 +323,7 @@ function ChatComposer({
onCancelReply={() => setReplyTo(null)}
mentionable={mentionableBots(bot, bots)}
actions={<BotReasoning bot={bot} />}
notice={(uploads) => <ImageWarning bot={bot} uploads={uploads} />}
onSend={(content, uploads) => sendMessage(content, uploads)}
onStop={onStop}
/>
Expand Down
135 changes: 135 additions & 0 deletions apps/web/features/bot-chat/image-warning.dom.test.tsx
Original file line number Diff line number Diff line change
@@ -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(
<QueryClientProvider client={client}>
<RouterContextProvider router={router}>
<ImageWarning bot={bot} uploads={uploads} />
</RouterContextProvider>
</QueryClientProvider>,
);
});
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();
}
});
59 changes: 59 additions & 0 deletions apps/web/features/bot-chat/image-warning.tsx
Original file line number Diff line number Diff line change
@@ -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<Bot, "id" | "name" | "provider" | "model">;

/** 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 (
<p role="alert" className="text-xs text-destructive">
{bot.name}'s model ({bot.model}) can't read images. Choose a model that
accepts images in{" "}
<Link
to="/bots/$botId/edit"
params={{ botId: bot.id }}
className="underline"
>
{bot.name}'s profile
</Link>
, or set a{" "}
<Link to="/settings/vision-model" className="underline">
vision model
</Link>{" "}
to describe images for it.
</p>
);
}
Loading
Loading