Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Composer: a message takes up to 10 images (#4366)
Aditya Umale051dd75bb72f
diff --git a/server/turn-images.test.ts b/server/turn-images.test.tsindex 01f7b0d5dc..c95427f3dd 100644--- a/server/turn-images.test.ts+++ b/server/turn-images.test.ts@@ -103,6 +103,18 @@ describe("turn image admission", () => {);});+ it("takes up to ten images in one message by default and refuses the eleventh", () => {+ const root = store();+ const tags = Array.from({ length: 11 }, (_, index) => {+ const path = join(root, `123e4567-e89b-42d3-a456-4266141741${String(index).padStart(2, "0")}.png`);+ writeFileSync(path, Buffer.alloc(4, index + 1));+ return `<attached-image path="${path}" />`;+ });++ expect(extractTurnImages(tags.slice(0, 10).join("\n\n"), { attachmentsDir: root }).images).toHaveLength(10);+ expect(() => extractTurnImages(tags.join("\n\n"), { attachmentsDir: root })).toThrow("Send no more than 10 images");+ });+it("does not admit a symlink carrying an attachment-shaped name", () => {const root = store();const outside = store("-target");diff --git a/server/turn-images.ts b/server/turn-images.tsindex e06328cecd..82f199f86a 100644--- a/server/turn-images.ts+++ b/server/turn-images.ts@@ -7,8 +7,9 @@ import { ATTACHMENTS_DIR, IMAGE_MAX_BYTES } from "./attachments.ts";import type { TurnImageInput } from "./contracts.ts";import { decodeAttachmentAttribute } from "./message-file.ts";-export const TURN_IMAGE_MAX_COUNT = 4;-export const TURN_IMAGE_MAX_BYTES = TURN_IMAGE_MAX_COUNT * IMAGE_MAX_BYTES;+export const TURN_IMAGE_MAX_COUNT = 10;+/** Total image bytes one turn may carry: the 40 MB it was when a turn took four images, so engine requests don't grow. */+export const TURN_IMAGE_MAX_BYTES = 4 * IMAGE_MAX_BYTES;type MarkdownNode = {type: string;diff --git a/src/components/Composer.tsx b/src/components/Composer.tsxindex 6ebdf38a25..713b0c72e6 100644--- a/src/components/Composer.tsx+++ b/src/components/Composer.tsx@@ -53,6 +53,7 @@ import {composerShouldRefocus,composerTakesFocusOnOpen,imageAttachmentFromFile,+ imageBytesLeft,imageSlotsLeft,imagesThatFit,replyTargetTakesFocus,@@ -511,6 +512,7 @@ export function Composer({getPath: pathForFile,uploadImage,imageSlots: imageSlotsLeft(attachments),+ imageBytes: imageBytesLeft(attachments),});if (added.length) addAttachments(added);if (notice) setAttachmentNotice(notice);@@ -631,7 +633,7 @@ export function Composer({dispatch({ type: "error", message: t("composer.error.clipboardImage") });return;}- const kept = imagesThatFit(imageFiles, imageSlotsLeft(attachments), setAttachmentNotice);+ const kept = imagesThatFit(imageFiles, imageSlotsLeft(attachments), setAttachmentNotice, imageBytesLeft(attachments));changeDraftAttachmentPending(draftId, true);void (async () => {try {diff --git a/src/components/ComposerAttachments.tsx b/src/components/ComposerAttachments.tsxindex 60d8747e38..8bf1f53d5f 100644--- a/src/components/ComposerAttachments.tsx+++ b/src/components/ComposerAttachments.tsx@@ -5,6 +5,7 @@ import {attachmentImageUrl,intakeFiles,formatSize,+ imageBytesLeft,imageSlotsLeft,pasteSummary,type Attachment,@@ -48,8 +49,9 @@ export function ComposerAttachments({const depth = useRef(0);// A drop past the images the message can still take is left out with a notice.const imageSlots = imageSlotsLeft(items);- const callbacks = useRef({ onAdd, onNotice, onPendingChange, allowImages, imageSlots, uploadImage });- callbacks.current = { onAdd, onNotice, onPendingChange, allowImages, imageSlots, uploadImage };+ const imageBytes = imageBytesLeft(items);+ const callbacks = useRef({ onAdd, onNotice, onPendingChange, allowImages, imageSlots, imageBytes, uploadImage });+ callbacks.current = { onAdd, onNotice, onPendingChange, allowImages, imageSlots, imageBytes, uploadImage };const pendingDrops = useRef(new Set<symbol>());useEffect(() => {@@ -84,6 +86,7 @@ export function ComposerAttachments({getPath: pathForFile,uploadImage: callbacks.current.uploadImage,imageSlots: callbacks.current.imageSlots,+ imageBytes: callbacks.current.imageBytes,});if (attachments.length) callbacks.current.onAdd(attachments);if (message) callbacks.current.onNotice(message);diff --git a/src/lib/composer-attachments.ts b/src/lib/composer-attachments.tsindex b7c042bf0c..ff765b348e 100644--- a/src/lib/composer-attachments.ts+++ b/src/lib/composer-attachments.ts@@ -93,21 +93,26 @@ export function fileAttachment(name: string, path: string, size: number): FileAtexport const IMAGE_MAX_BYTES = 10 * 1024 * 1024;export const FILE_MAX_BYTES = 25 * 1024 * 1024;/** Must match the server's TURN_IMAGE_MAX_COUNT: a message carrying more images is refused at send. */-export const TURN_IMAGE_MAX_COUNT = 4;+export const TURN_IMAGE_MAX_COUNT = 10;++/** Must match the server's TURN_IMAGE_MAX_BYTES: a message whose images total more is refused at send. */+export const TURN_IMAGE_MAX_BYTES = 4 * IMAGE_MAX_BYTES;export function imageLimitNotice(leftOut: readonly string[]): string {- return `A message takes up to ${TURN_IMAGE_MAX_COUNT} images. ${leftOut.join(", ")} ${leftOut.length === 1 ? "wasn't" : "weren't"} attached.`;+ return `A message takes up to ${TURN_IMAGE_MAX_COUNT} images, ${TURN_IMAGE_MAX_BYTES / (1024 * 1024)} MB in all. ${leftOut.join(", ")} ${leftOut.length === 1 ? "wasn't" : "weren't"} attached.`;}-/** Splits images by the slots left: an image over IMAGE_MAX_BYTES is kept to fail with its own size error but takes no slot. */-export function fitImagesToSlots<T extends { size: number }>(images: readonly T[], slots: number): { kept: T[]; leftOut: T[] } {+/** Splits images by the slots and bytes left: an image over IMAGE_MAX_BYTES is kept to fail with its own size error but takes no room. */+export function fitImagesToSlots<T extends { size: number }>(images: readonly T[], slots: number, bytes = Infinity): { kept: T[]; leftOut: T[] } {const kept: T[] = [];const leftOut: T[] = [];let room = slots;+ let bytesRoom = bytes;for (const image of images) {if (image.size > IMAGE_MAX_BYTES) kept.push(image);- else if (room > 0) {+ else if (room > 0 && image.size <= bytesRoom) {room -= 1;+ bytesRoom -= image.size;kept.push(image);} else leftOut.push(image);}@@ -119,9 +124,14 @@ export function imageSlotsLeft(attachments: readonly Attachment[]): number {return Math.max(0, TURN_IMAGE_MAX_COUNT - attachments.filter((attachment) => attachment.kind === "image").length);}-/** The images that fit the slots left; the rest are named in one notice. */-export function imagesThatFit<T extends { name: string; size: number }>(images: readonly T[], slots: number, onNotice: (notice: string) => void): T[] {- const { kept, leftOut } = fitImagesToSlots(images, slots);+/** Image bytes a draft holding these attachments can still take. */+export function imageBytesLeft(attachments: readonly Attachment[]): number {+ return Math.max(0, TURN_IMAGE_MAX_BYTES - attachments.reduce((total, attachment) => total + (attachment.kind === "image" ? attachment.size : 0), 0));+}++/** The images that fit the slots and bytes left; the rest are named in one notice. */+export function imagesThatFit<T extends { name: string; size: number }>(images: readonly T[], slots: number, onNotice: (notice: string) => void, bytes = Infinity): T[] {+ const { kept, leftOut } = fitImagesToSlots(images, slots, bytes);if (leftOut.length) onNotice(imageLimitNotice(leftOut.map((image) => image.name)));return kept;}@@ -739,11 +749,13 @@ export async function intakeFiles<T extends DroppedFile & { type: string }>(uploadFile?: (file: T) => Promise<FileAttachment | null>;/** Images the message can still take; the rest are left out and named in the notice. */imageSlots?: number;+ /** Image bytes the message can still take; images past it are left out the same way. */+ imageBytes?: number;},): Promise<{ attachments: Attachment[]; notice: string | null }> {const { allowImages, getPath, uploadImage } = _opts;const images = allowImages ? _files.filter((file) => isImageFile(file)) : [];- const overflow = new Set(fitImagesToSlots(images, _opts.imageSlots ?? Infinity).leftOut);+ const overflow = new Set(fitImagesToSlots(images, _opts.imageSlots ?? Infinity, _opts.imageBytes).leftOut);const leftOut = [...overflow].map((file) => file.name);const files = _files.filter((file) => !overflow.has(file));const uploadFile = _opts.uploadFile ?? (async (file: T) => {diff --git a/src/lib/intake-files.test.ts b/src/lib/intake-files.test.tsindex 3fb3fb2e71..2ad840e41e 100644--- a/src/lib/intake-files.test.ts+++ b/src/lib/intake-files.test.ts@@ -1,7 +1,7 @@import { describe, expect, it, vi } from "vitest";-import { TURN_IMAGE_MAX_COUNT as SERVER_TURN_IMAGE_MAX_COUNT } from "../../server/turn-images";-import { fitImagesToSlots, IMAGE_MAX_BYTES, imageSlotsLeft, imagesThatFit, intakeFiles, TURN_IMAGE_MAX_COUNT, type Attachment } from "./composer-attachments";+import { TURN_IMAGE_MAX_BYTES as SERVER_TURN_IMAGE_MAX_BYTES, TURN_IMAGE_MAX_COUNT as SERVER_TURN_IMAGE_MAX_COUNT } from "../../server/turn-images";+import { fitImagesToSlots, IMAGE_MAX_BYTES, imageBytesLeft, imageSlotsLeft, imagesThatFit, intakeFiles, TURN_IMAGE_MAX_BYTES, TURN_IMAGE_MAX_COUNT, type Attachment } from "./composer-attachments";type Fake = { name: string; size: number; type: string; text: () => Promise<string> };const file = (name: string, type: string, size = 10): Fake => ({@@ -128,7 +128,7 @@ describe("intakeFiles", () => {);expect(out.attachments.map((a) => "name" in a ? a.name : "")).toEqual(["1.png", "notes.txt"]);expect(uploadImage).toHaveBeenCalledTimes(1);- expect(out.notice).toBe(`A message takes up to ${TURN_IMAGE_MAX_COUNT} images. 2.png, 3.png weren't attached.`);+ expect(out.notice).toBe(`A message takes up to ${TURN_IMAGE_MAX_COUNT} images, 40 MB in all. 2.png, 3.png weren't attached.`);});it("lets an oversized image fail on its own without taking the last slot", async () => {@@ -176,12 +176,35 @@ describe("intakeFiles", () => {const notices: string[] = [];const pasted = [file("a.png", "image/png"), file("b.png", "image/png"), file("c.png", "image/png")];expect(imagesThatFit(pasted, 2, (notice) => notices.push(notice)).map((image) => image.name)).toEqual(["a.png", "b.png"]);- expect(notices).toEqual([`A message takes up to ${TURN_IMAGE_MAX_COUNT} images. c.png wasn't attached.`]);+ expect(notices).toEqual([`A message takes up to ${TURN_IMAGE_MAX_COUNT} images, 40 MB in all. c.png wasn't attached.`]);expect(imagesThatFit(pasted, 3, (notice) => notices.push(notice))).toHaveLength(3);expect(notices).toHaveLength(1);});- it("keeps the image cap in step with the server", () => {+ it("keeps the image caps in step with the server", () => {expect(TURN_IMAGE_MAX_COUNT).toBe(SERVER_TURN_IMAGE_MAX_COUNT);+ expect(TURN_IMAGE_MAX_BYTES).toBe(SERVER_TURN_IMAGE_MAX_BYTES);+ });++ it("stops at the image bytes a message can still take, so large images are never refused at send", async () => {+ const big = IMAGE_MAX_BYTES - 1;+ const draft = [{ kind: "image", size: big }, { kind: "file", size: big }] as unknown as Attachment[];+ expect(imageBytesLeft(draft)).toBe(TURN_IMAGE_MAX_BYTES - big);+ const out = await intakeFiles(Array.from({ length: 5 }, (_, index) => file(`${index + 1}.png`, "image/png", big)), {+ allowImages: true, getPath: onDisk, uploadImage: upload, imageSlots: imageSlotsLeft(draft), imageBytes: imageBytesLeft(draft),+ });+ expect(out.attachments.map((a) => "name" in a ? a.name : "")).toEqual(["1.png", "2.png", "3.png"]);+ expect(out.notice).toBe("A message takes up to 10 images, 40 MB in all. 4.png, 5.png weren't attached.");+ const notices: string[] = [];+ expect(imagesThatFit([file("a.png", "image/png", big)], 9, (notice) => notices.push(notice), big - 1)).toEqual([]);+ expect(notices).toEqual(["A message takes up to 10 images, 40 MB in all. a.png wasn't attached."]);+ });++ it("lets an empty draft take ten images and names the eleventh", () => {+ expect(imageSlotsLeft([])).toBe(10);+ const notices: string[] = [];+ const pasted = Array.from({ length: 11 }, (_, index) => file(`${index + 1}.png`, "image/png"));+ expect(imagesThatFit(pasted, imageSlotsLeft([]), (notice) => notices.push(notice))).toHaveLength(10);+ expect(notices).toEqual(["A message takes up to 10 images, 40 MB in all. 11.png wasn't attached."]);});});