Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Composer: stop at 4 images and say which ones weren't attached (#4032)

Suhani1f1e8f452aef
diff --git a/src/components/Composer.tsx b/src/components/Composer.tsx
index ee8a2fe893..23b699dbcf 100644
--- a/src/components/Composer.tsx
+++ b/src/components/Composer.tsx
@@ -52,6 +52,8 @@ import {
composerShouldRefocus,
composerTakesFocusOnOpen,
imageAttachmentFromFile,
+ imageSlotsLeft,
+ imagesThatFit,
replyTargetTakesFocus,
intakeFiles,
isLongPaste,
@@ -62,7 +64,7 @@ import {
type PasteAttachment,
} from "@/lib/composer-attachments";
import { goalCoordinatorForComposer, jevRoomRoutingOn, openTaskWorking, roomRespondersForComposer } from "@/lib/group-routing";
-import { composerPlaceholder, sendLabels, SIMPLE_CONTROL, slotColors } from "./composer-simple";
+import { composerPlaceholder, sendLabels, SIMPLE_COMPOSER, SIMPLE_CONTROL, slotColors } from "./composer-simple";
import { PendingApprovalActions, PendingApprovalPanel, pendingApprovals } from "./PendingApproval";
import { CallButton } from "./CallView";
import { GroupCallButton } from "./GroupCallView";
@@ -93,8 +95,6 @@ import {
} from "@/lib/composer-commands";
import { useSlashSkills } from "@/lib/use-slash-skills";
-const SIMPLE_COMPOSER = "bg-composer p-2 ring-[0.5px] ring-ink/10 hover:ring-ink/[0.22] focus-within:ring-ink/[0.22] shadow-[0_2px_8px_-1px_rgb(0_0_0/0.05),0_1px_2px_rgb(0_0_0/0.03),0_0_0_1px_rgb(228_228_228/0.04)] [transition:border-radius_300ms,box-shadow_150ms]";
-
const supportsAgents = (instances: InstanceInfo[], candidate?: Bot) =>
Boolean(candidate && instances.find((instance) => instance.instanceId === candidate.modelSelection.instanceId)?.capabilities?.agentsMcp);
@@ -511,6 +511,7 @@ export function Composer({
allowImages: engineSupportsImages,
getPath: pathForFile,
uploadImage,
+ imageSlots: imageSlotsLeft(attachments),
});
if (added.length) addAttachments(added);
if (notice) setAttachmentNotice(notice);
@@ -628,25 +629,24 @@ export function Composer({
dispatch({ type: "error", message: t("composer.error.clipboardImage") });
return;
}
- if (imageFiles.length > 0) {
- changeDraftAttachmentPending(draftId, true);
- void (async () => {
- try {
- const results = await Promise.allSettled(imageFiles.map(uploadImage));
- for (const result of results) {
- if (result.status === "rejected") {
- dispatch({
- type: "error",
- message: result.reason instanceof Error ? result.reason.message : "image upload failed",
- });
- }
+ const kept = imagesThatFit(imageFiles, imageSlotsLeft(attachments), setAttachmentNotice);
+ changeDraftAttachmentPending(draftId, true);
+ void (async () => {
+ try {
+ const results = await Promise.allSettled(kept.map(uploadImage));
+ for (const result of results) {
+ if (result.status === "rejected") {
+ dispatch({
+ type: "error",
+ message: result.reason instanceof Error ? result.reason.message : "image upload failed",
+ });
}
- } finally {
- changeDraftAttachmentPending(draftId, false);
}
- })();
- return;
- }
+ } finally {
+ changeDraftAttachmentPending(draftId, false);
+ }
+ })();
+ return;
}
const pasted = e.clipboardData.getData("text/plain");
const reference = threadTokenFromPaste(pasted, threads, currentBotId);
diff --git a/src/components/ComposerAttachments.tsx b/src/components/ComposerAttachments.tsx
index 1f3c4c1ae1..60d8747e38 100644
--- a/src/components/ComposerAttachments.tsx
+++ b/src/components/ComposerAttachments.tsx
@@ -5,6 +5,7 @@ import {
attachmentImageUrl,
intakeFiles,
formatSize,
+ imageSlotsLeft,
pasteSummary,
type Attachment,
type PasteAttachment,
@@ -45,8 +46,10 @@ export function ComposerAttachments({
const [preview, setPreview] = useState<PreviewImage | null>(null);
// dragenter/dragleave fire once per element crossed, so the overlay tracks depth.
const depth = useRef(0);
- const callbacks = useRef({ onAdd, onNotice, onPendingChange, allowImages, uploadImage });
- callbacks.current = { onAdd, onNotice, onPendingChange, allowImages, uploadImage };
+ // 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 pendingDrops = useRef(new Set<symbol>());
useEffect(() => {
@@ -80,6 +83,7 @@ export function ComposerAttachments({
allowImages: callbacks.current.allowImages,
getPath: pathForFile,
uploadImage: callbacks.current.uploadImage,
+ imageSlots: callbacks.current.imageSlots,
});
if (attachments.length) callbacks.current.onAdd(attachments);
if (message) callbacks.current.onNotice(message);
diff --git a/src/components/composer-simple.ts b/src/components/composer-simple.ts
index ec21c176bb..f9468ae1c6 100644
--- a/src/components/composer-simple.ts
+++ b/src/components/composer-simple.ts
@@ -3,6 +3,9 @@ import { effectiveDefaultResponder, groupComposerHint } from "@/lib/group-routin
import { t } from "@/lib/i18n";
import { BOT_BUTTON, botButtonStyle, botButtonTone, type BotButton } from "@/lib/bot-button";
+/** Simple mode's composer pill on a wider screen: the field, the mic and the round button in one shell. */
+export const SIMPLE_COMPOSER = "bg-composer p-2 ring-[0.5px] ring-ink/10 hover:ring-ink/[0.22] focus-within:ring-ink/[0.22] shadow-[0_2px_8px_-1px_rgb(0_0_0/0.05),0_1px_2px_rgb(0_0_0/0.03),0_0_0_1px_rgb(228_228_228/0.04)] [transition:border-radius_300ms,box-shadow_150ms]";
+
/** Simple mode's small round controls in the composer: the +, the mic and Stop beside the round button. */
export const SIMPLE_CONTROL = "size-7 rounded-full bg-ink/[0.05] ring-[0.5px] ring-inset ring-ink/[0.07] text-ink-tertiary hover:bg-ink/[0.09] hover:text-ink";
diff --git a/src/lib/composer-attachments.ts b/src/lib/composer-attachments.ts
index a44cae26c1..d82dbde39c 100644
--- a/src/lib/composer-attachments.ts
+++ b/src/lib/composer-attachments.ts
@@ -105,6 +105,41 @@ export function fileAttachment(name: string, path: string, size: number): FileAt
/** Must match the server's IMAGE_MAX_BYTES. */
export 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 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.`;
+}
+
+/** 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[] } {
+ const kept: T[] = [];
+ const leftOut: T[] = [];
+ let room = slots;
+ for (const image of images) {
+ if (image.size > IMAGE_MAX_BYTES) kept.push(image);
+ else if (room > 0) {
+ room -= 1;
+ kept.push(image);
+ } else leftOut.push(image);
+ }
+ return { kept, leftOut };
+}
+
+/** Images a draft holding these attachments can still take. */
+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);
+ if (leftOut.length) onNotice(imageLimitNotice(leftOut.map((image) => image.name)));
+ return kept;
+}
+
+const ARCHIVE_NAME = /\.(?:zip|rar|7z|tar|gz|tgz|bz2|xz)$/i;
const DOCUMENT_MIMES: Readonly<Record<string, string>> = {
txt: "text/plain",
@@ -715,10 +750,15 @@ export async function intakeFiles<T extends DroppedFile & { type: string }>(
getPath: (file: T) => string;
uploadImage: (file: T) => Promise<Attachment | null>;
uploadFile?: (file: T) => Promise<FileAttachment | null>;
+ /** Images the message can still take; the rest are left out and named in the notice. */
+ imageSlots?: number;
},
): Promise<{ attachments: Attachment[]; notice: string | null }> {
- const files = [..._files];
const { allowImages, getPath, uploadImage } = _opts;
+ const images = allowImages ? _files.filter((file) => isImageFile(file)) : [];
+ const overflow = new Set(fitImagesToSlots(images, _opts.imageSlots ?? Infinity).leftOut);
+ const leftOut = [...overflow].map((file) => file.name);
+ const files = _files.filter((file) => !overflow.has(file));
const uploadFile = _opts.uploadFile ?? (async (file: T) => {
if (!file.arrayBuffer) return null;
return fileAttachmentFromFile(file as unknown as File);
@@ -757,14 +797,19 @@ export async function intakeFiles<T extends DroppedFile & { type: string }>(
}));
const attachments = results.flatMap((result) => result.attachments);
const rejectedNames = results.flatMap((result) => result.rejectedNames);
+ const archives = rejectedNames.filter((name) => ARCHIVE_NAME.test(name));
+ const unsupported = rejectedNames.filter((name) => !ARCHIVE_NAME.test(name));
const uploadErrors = results.flatMap((result) => result.uploadError ? [result.uploadError] : []);
- const pathless = rejectedNames.length
- ? `Unable to attach ${rejectedNames.join(", ")}. Choose a supported image, document, or audio file.`
- : null;
+ const pathless = [
+ unsupported.length ? `Unable to attach ${unsupported.join(", ")}. Choose a supported image, document, or audio file.` : "",
+ archives.length ? `Archives can't be attached: unzip ${archives.join(", ")} and attach the files inside.` : "",
+ ].filter(Boolean).join(" ") || null;
const failed = uploadErrors.length ? uploadErrors.join("; ") : null;
+ const notice = pathless && failed ? `${pathless} (${failed})` : (pathless ?? failed);
+ const limited = leftOut.length ? imageLimitNotice(leftOut) : null;
return {
attachments,
- notice: pathless && failed ? `${pathless} (${failed})` : (pathless ?? failed),
+ notice: limited && notice ? `${limited} ${notice}` : (limited ?? notice),
};
}
diff --git a/src/lib/intake-files.test.ts b/src/lib/intake-files.test.ts
index a220f02282..3fb3fb2e71 100644
--- a/src/lib/intake-files.test.ts
+++ b/src/lib/intake-files.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from "vitest";
-import { intakeFiles, type Attachment } from "./composer-attachments";
+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";
type Fake = { name: string; size: number; type: string; text: () => Promise<string> };
const file = (name: string, type: string, size = 10): Fake => ({
@@ -118,4 +119,69 @@ describe("intakeFiles", () => {
expect(out.attachments).toHaveLength(1);
expect(out.notice).toMatch(/bad\.png: too large/);
});
+
+ it("stops at the images a message can still take and names the rest", async () => {
+ const uploadImage = vi.fn(upload);
+ const out = await intakeFiles(
+ [file("1.png", "image/png"), file("notes.txt", "text/plain"), file("2.png", "image/png"), file("3.png", "image/png")],
+ { allowImages: true, getPath: onDisk, uploadImage, imageSlots: 1 },
+ );
+ 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.`);
+ });
+
+ it("lets an oversized image fail on its own without taking the last slot", async () => {
+ const out = await intakeFiles([file("huge.png", "image/png", IMAGE_MAX_BYTES + 1), file("ok.png", "image/png")], {
+ allowImages: true,
+ getPath: onDisk,
+ uploadImage: async (f) => {
+ if (f.size > IMAGE_MAX_BYTES) throw new Error(`${f.name} exceeds 10 MB`);
+ return upload(f);
+ },
+ imageSlots: 1,
+ });
+ expect(out.attachments.map((a) => "name" in a ? a.name : "")).toEqual(["ok.png"]);
+ expect(out.notice).toBe("huge.png: huge.png exceeds 10 MB");
+ });
+
+ it("splits pasted images by the slots left, passing oversized ones through", () => {
+ const images = [{ size: 1 }, { size: IMAGE_MAX_BYTES + 1 }, { size: 2 }, { size: 3 }];
+ expect(fitImagesToSlots(images, 2)).toEqual({ kept: [images[0], images[1], images[2]], leftOut: [images[3]] });
+ expect(fitImagesToSlots(images, 0)).toEqual({ kept: [images[1]], leftOut: [images[0], images[2], images[3]] });
+ });
+
+ it("leaves images uncounted when the engine takes them as plain files", async () => {
+ const out = await intakeFiles([file("1.png", "image/png"), file("2.png", "image/png")], {
+ allowImages: false, getPath: onDisk, uploadImage: upload, uploadFile: async () => null, imageSlots: 0,
+ });
+ expect(out.attachments).toHaveLength(2);
+ expect(out.notice).toBeNull();
+ });
+
+ it("explains that an archive needs unzipping instead of calling it unsupported", async () => {
+ const out = await intakeFiles([file("아카이브.zip", "application/zip"), file("run.exe", "application/octet-stream")], {
+ allowImages: true, getPath: () => "", uploadImage: upload, uploadFile: async () => null,
+ });
+ expect(out.attachments).toEqual([]);
+ expect(out.notice).toBe(
+ "Unable to attach run.exe. Choose a supported image, document, or audio file. Archives can't be attached: unzip 아카이브.zip and attach the files inside.",
+ );
+ });
+
+ it("counts the images already in the draft, and names pasted images past the slots left", () => {
+ const draft = [{ kind: "image" }, { kind: "file" }, { kind: "image" }] as unknown as Attachment[];
+ expect(imageSlotsLeft(draft)).toBe(TURN_IMAGE_MAX_COUNT - 2);
+ expect(imageSlotsLeft(Array.from({ length: TURN_IMAGE_MAX_COUNT + 1 }, () => ({ kind: "image" })) as unknown as Attachment[])).toBe(0);
+ 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(imagesThatFit(pasted, 3, (notice) => notices.push(notice))).toHaveLength(3);
+ expect(notices).toHaveLength(1);
+ });
+
+ it("keeps the image cap in step with the server", () => {
+ expect(TURN_IMAGE_MAX_COUNT).toBe(SERVER_TURN_IMAGE_MAX_COUNT);
+ });
});