Skip to content

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

20.0 KB
Raw Blame
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { afterEach, describe, expect, it, vi } from "vitest";

import { chatUserContent } from "./drivers/chat-images.ts";
import { extractReplayImages, extractSteerImages, extractTurnImages, nativeClips, REPLAYED_IMAGE_NOTE, turnMedia, videoFramesWithin } from "./turn-images.ts";
import { videoFrameImages } from "./turn-video.ts";

vi.mock("./turn-video.ts", async (original) => {
  const actual = await original<typeof import("./turn-video.ts")>();
  return { ...actual, videoFrameImages: vi.fn(actual.videoFrameImages) };
});

const IDS = [
  "123e4567-e89b-42d3-a456-426614174000",
  "123e4567-e89b-42d3-a456-426614174001",
  "123e4567-e89b-42d3-a456-426614174002",
  "123e4567-e89b-42d3-a456-426614174003",
  "123e4567-e89b-42d3-a456-426614174004",
] as const;

describe("turn image admission", () => {
  const temporary: string[] = [];

  const store = (suffix = "") => {
    const root = mkdtempSync(join(tmpdir(), `omb-turn-images${suffix}-`));
    temporary.push(root);
    return root;
  };

  const image = (root: string, index: number, extension = ".png", bytes = 4) => {
    const path = join(root, `${IDS[index]}${extension}`);
    writeFileSync(path, Buffer.alloc(bytes, index + 1));
    return path;
  };

  const video = (root: string, index: number, extension = ".mp4", bytes = 4) => {
    const path = join(root, `${IDS[index]}${extension}`);
    writeFileSync(path, Buffer.alloc(bytes, index + 1));
    return path;
  };

  afterEach(() => {
    for (const path of temporary.splice(0)) rmSync(path, { recursive: true, force: true });
  });

  it("turns standalone app-owned tags into structured images and keeps the source immutable", () => {
    const root = store();
    const png = image(root, 0, ".png", 7);
    const jpg = image(root, 1, ".jpg", 9);
    const source = [
      "compare these",
      "",
      `<attached-image path="${png}" name="first.png" />`,
      "",
      `<attached-image path="${jpg}" name="second.jpg" />`,
    ].join("\n");

    const result = extractTurnImages(source, { attachmentsDir: root });

    expect(source).toContain(png);
    expect(result.text).toBe(source.replaceAll("<attached-image", "<attached-file"));
    expect(result.images).toEqual([
      { path: png, mime: "image/png", bytes: 7 },
      { path: jpg, mime: "image/jpeg", bytes: 9 },
    ]);
    expect(result.text).toContain(root);
  });

  it("extracts a handoff picture before a following coordination reminder", () => {
    const root = store();
    const png = image(root, 0);
    const source = `Files with this assignment:\n\n<attached-image path="${png}" name="tiny.png" />\n\nIts words are the request above.`;

    const result = extractTurnImages(source, { attachmentsDir: root });
    expect(result.images).toEqual([{ path: png, mime: "image/png", bytes: 4 }]);
    expect(result.text).toBe(source.replace("<attached-image", "<attached-file"));
  });

  it("emits the admitted path while preserving the encoded display name", () => {
    const root = store("&uploads");
    const path = image(root, 0);
    const encoded = path.replaceAll("&", "&amp;");
    const raw = `${root}/missing/../${IDS[0]}.png`.replaceAll("&", "&amp;");
    const result = extractTurnImages(`<attached-image path="${raw}" name="mug &amp; &quot;cup&quot;.png" />`, { attachmentsDir: root });

    expect(result.text).toBe(`<attached-file path="${encoded}" name="mug &amp; &quot;cup&quot;.png" />`);
    expect(result.images).toEqual([{ path, mime: "image/png", bytes: 4 }]);
  });

  it("leaves inline, fenced, missing, outside-store, and non-generated tags as text", () => {
    const root = store();
    const outside = store("-outside");
    const valid = image(root, 0);
    const outsideImage = image(outside, 1);
    const ordinary = join(root, "ordinary.png");
    writeFileSync(ordinary, "not generated by the attachment store");
    const source = [
      `Example: <attached-image path="${valid}" />`,
      "```xml",
      `<attached-image path="${valid}" />`,
      "```",
      `<attached-image path="${join(root, `${IDS[2]}.png`)}" />`,
      `<attached-image path="${outsideImage}" />`,
      `<attached-image path="${ordinary}" />`,
    ].join("\n");

    expect(extractTurnImages(source, { attachmentsDir: root })).toEqual({ text: source, images: [], videos: [] });
  });

  it("decodes composer entities once before validating the exact store path", () => {
    const parent = store();
    const root = join(parent, "images&more");
    mkdirSync(root);
    const path = image(root, 0, ".webp", 5);
    const encoded = path.replaceAll("&", "&amp;");

    expect(extractTurnImages(`<attached-image path="${encoded}" />`, { attachmentsDir: root })).toEqual({
      text: `<attached-file path="${encoded}" />`,
      images: [{ path, mime: "image/webp", bytes: 5 }],
      videos: [],
    });
  });

  it("resolves a video delivered through the generic <attached-file> tag and keeps the tag for engines that read files", () => {
    const root = store();
    const clip = video(root, 0, ".mp4", 9);
    const source = `watch this\n\n<attached-file path="${clip}" name="clip.mp4" />`;

    expect(extractTurnImages(source, { attachmentsDir: root })).toEqual({
      text: source,
      images: [],
      videos: [{ path: clip, mime: "video/mp4", bytes: 9 }],
    });
  });

  it("leaves a non-video <attached-file> tag untouched, since other file kinds still need it intact", () => {
    const root = store();
    const doc = join(root, `${IDS[0]}.pdf`);
    writeFileSync(doc, "not a video");
    const source = `see the brief\n\n<attached-file path="${doc}" name="brief.pdf" />`;

    expect(extractTurnImages(source, { attachmentsDir: root })).toEqual({ text: source, images: [], videos: [] });
  });

  it("admits both an image and a video from the same message", () => {
    const root = store();
    const png = image(root, 0, ".png", 4);
    const clip = video(root, 1, ".webm", 6);
    const source = [
      `<attached-image path="${png}" name="a.png" />`,
      `<attached-file path="${clip}" name="clip.webm" />`,
    ].join("\n\n");

    const result = extractTurnImages(source, { attachmentsDir: root });
    expect(result.text).toBe(source.replace("<attached-image", "<attached-file"));
    expect(result.images).toEqual([{ path: png, mime: "image/png", bytes: 4 }]);
    expect(result.videos).toEqual([{ path: clip, mime: "video/webm", bytes: 6 }]);
  });

  it("samples only the first video and leaves every video's tag in place", () => {
    const root = store();
    const first = video(root, 0, ".mp4", 4);
    const second = video(root, 1, ".mov", 4);
    const source = `<attached-file path="${first}" />\n\n<attached-file path="${second}" />`;

    expect(extractTurnImages(source, { attachmentsDir: root })).toEqual({
      text: source,
      images: [],
      videos: [{ path: first, mime: "video/mp4", bytes: 4 }],
    });
  });

  it("rejects count and aggregate limits before partially rewriting the prompt", () => {
    const root = store();
    const first = image(root, 0, ".png", 4);
    const second = image(root, 1, ".gif", 4);
    const source = `<attached-image path="${first}" />\n\n<attached-image path="${second}" />`;

    expect(() => extractTurnImages(source, { attachmentsDir: root, maxCount: 1 })).toThrow(
      "Send no more than 1 images",
    );
    expect(() => extractTurnImages(source, { attachmentsDir: root, maxBytes: 7 })).toThrow(
      "Attached images exceed 0 MB total",
    );
  });

  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");
    const target = image(outside, 0);
    const link = join(root, `${IDS[1]}.png`);
    symlinkSync(target, link);
    const source = `<attached-image path="${link}" />`;

    expect(extractTurnImages(source, { attachmentsDir: root })).toEqual({ text: source, images: [], videos: [] });
  });

  it("resolves a steer's texts one by one and keeps its images in order", () => {
    const root = store();
    const first = image(root, 0, ".png", 5);
    const second = image(root, 1, ".webp", 6);
    const texts = [
      `look\n\n<attached-image path="${first}" name="a.png" />`,
      "plain words stay exactly as sent",
      `and this\n\n<attached-image path="${second}" name="b.webp" />`,
    ];

    expect(extractSteerImages(texts, { attachmentsDir: root })).toEqual({
      texts: texts.map((text) => text.replace("<attached-image", "<attached-file")),
      images: [
        { path: first, mime: "image/png", bytes: 5 },
        { path: second, mime: "image/webp", bytes: 6 },
      ],
    });
    expect(extractSteerImages(["just text"], { attachmentsDir: root })).toEqual({ texts: ["just text"], images: [] });
  });

  it("gives up on a steer whose images together would not fit one turn", () => {
    const root = store();
    const one = (index: number) => `<attached-image path="${image(root, index, ".png", 4)}" name="${index}.png" />`;
    expect(extractSteerImages([one(0), one(1), one(2)], { attachmentsDir: root, maxCount: 2 })).toBeNull();
    expect(extractSteerImages([one(3), one(4)], { attachmentsDir: root, maxBytes: 7 })).toBeNull();
    expect(extractSteerImages([`${one(0)}\n\n${one(1)}\n\n${one(2)}`], { attachmentsDir: root, maxCount: 2 })).toBeNull();
  });

  it("re-sends the newest replayed user images within what the current turn leaves", () => {
    const root = store();
    const tag = (index: number) => `<attached-image path="${image(root, index)}" name="${index}.png" />`;
    const current = [{ path: image(root, 4), mime: "image/png" as const, bytes: 4 }];
    const transcript = [
      { role: "user" as const, text: `oldest\n\n${tag(0)}` },
      { role: "assistant" as const, text: `quoted\n\n${tag(1)}` },
      { role: "user" as const, text: `older\n\n${tag(2)}` },
      { role: "user" as const, text: `newest\n\n${tag(3)}` },
    ];

    const result = extractReplayImages(transcript, current, { attachmentsDir: root, maxCount: 3 });

    expect(result.images.map((entry) => entry.path)).toEqual([join(root, `${IDS[2]}.png`), join(root, `${IDS[3]}.png`)]);
    expect(result.transcript.map((entry) => entry.text)).toEqual([
      transcript[0]!.text, transcript[1]!.text, `older\n\n${REPLAYED_IMAGE_NOTE}\n\n${tag(2).replace("<attached-image", "<attached-file")}`, `newest\n\n${REPLAYED_IMAGE_NOTE}\n\n${tag(3).replace("<attached-image", "<attached-file")}`,
    ]);
    expect(transcript[3]!.text).toContain("<attached-image");
  });

  it("marks where a replayed image was sent, so a later text-only turn never looks like it carries a new image", () => {
    const root = store();
    const tag = (index: number) => `<attached-image path="${image(root, index)}" name="${index}.png" />`;
    const transcript = [
      { role: "user" as const, text: `login fails, see screenshot\n\n${tag(0)}` },
      { role: "assistant" as const, text: "I see the error." },
      { role: "user" as const, text: "A" },
    ];

    const result = extractReplayImages(transcript, [], { attachmentsDir: root });

    expect(result.images.map((entry) => entry.path)).toEqual([join(root, `${IDS[0]}.png`)]);
    expect(result.transcript[0]!.text).toBe(`login fails, see screenshot\n\n${REPLAYED_IMAGE_NOTE}\n\n${tag(0).replace("<attached-image", "<attached-file")}`);
    expect(REPLAYED_IMAGE_NOTE).toMatch(/earlier/i);
    expect(result.transcript[2]!.text).toBe("A");
  });

  it("keeps a current turn's own images unmarked", () => {
    const root = store();
    const result = extractTurnImages(`look\n\n<attached-image path="${image(root, 0)}" name="0.png" />`, { attachmentsDir: root });
    expect(result.text).toBe(`look\n\n<attached-file path="${join(root, `${IDS[0]}.png`)}" name="0.png" />`);
  });

  it("stops at the first replayed message whose images no longer fit", () => {
    const root = store();
    const tag = (index: number, bytes = 4) => `<attached-image path="${image(root, index, ".png", bytes)}" name="${index}.png" />`;
    const transcript = [
      { role: "user" as const, text: tag(0) },
      { role: "user" as const, text: tag(1, 9) },
      { role: "user" as const, text: tag(2) },
    ];

    const result = extractReplayImages(transcript, [], { attachmentsDir: root, maxBytes: 12 });

    expect(result.images.map((entry) => entry.path)).toEqual([join(root, `${IDS[2]}.png`)]);
    expect(result.transcript.slice(0, 2)).toEqual(transcript.slice(0, 2));
  });
});

describe("native video clips", () => {
  const clip = (bytes: number) => ({ path: `/attachments/${bytes}.mp4`, mime: "video/mp4" as const, bytes });

  it("gives an engine that takes video the clips that fit its limit", () => {
    const engine = { nativeImageInput: true, nativeVideoBytes: 100 };
    expect(nativeClips([clip(60), clip(50), clip(40)], engine)).toEqual([clip(60), clip(40)]);
  });

  const MiB = 1024 * 1024;
  const gemini = { nativeImageInput: true, nativeVideoBytes: 12 * MiB };
  const image = (bytes: number) => ({ path: `/attachments/${bytes}.png`, mime: "image/png" as const, bytes });

  it("leaves a clip to frames when the turn's pictures and clips would pass the request's media budget", () => {
    const engine = gemini;
    expect(nativeClips([clip(10 * MiB)], engine, [image(8 * MiB), image(8 * MiB)])).toEqual([]);
    expect(nativeClips([clip(10 * MiB), clip(2 * MiB)], engine, [image(8 * MiB)])).toEqual([clip(10 * MiB), clip(2 * MiB)]);
  });

  it("chooses a burst's clips against the pictures of every line, not only the lines before", async () => {
    const media = await turnMedia([{ images: [], videos: [clip(10 * MiB)] }, { images: [image(8 * MiB), image(8 * MiB)], videos: [] }], gemini);
    expect(media.videos).toEqual([]);
    expect(media.images.slice(-2)).toEqual([image(8 * MiB), image(8 * MiB)]);
    expect((await turnMedia([{ images: [image(MiB)], videos: [clip(10 * MiB)] }], gemini)).videos).toEqual([clip(10 * MiB)]);
  });

  const folder = () => mkdtempSync(join(tmpdir(), "omb-native-clips-"));
  const png = (root: string, name: string, bytes: number) => {
    const data = Buffer.alloc(bytes);
    Buffer.from("89504e470d0a1a0a0000000d49484452", "hex").copy(data);
    writeFileSync(join(root, name), data);
    return { path: join(root, name), mime: "image/png" as const, bytes };
  };

  it("counts each picture's and clip's full data URL, so a chosen clip never breaks the request's budget", () => {
    const root = folder();
    try {
      writeFileSync(join(root, "clip.mp4"), Buffer.alloc(12 * MiB));
      const video = { path: join(root, "clip.mp4"), mime: "video/mp4" as const, bytes: 12 * MiB };
      const full = [png(root, "a.png", 6 * MiB), png(root, "b.png", 6 * MiB)];
      expect(nativeClips([video], gemini, full)).toEqual([]);
      const fits = [png(root, "c.png", 6 * MiB - 30), png(root, "d.png", 6 * MiB - 30)];
      const videos = nativeClips([video], gemini, fits);
      expect(videos).toEqual([video]);
      const content = chatUserContent({ text: "look", images: fits, videos } as Parameters<typeof chatUserContent>[0]);
      expect(content).toContainEqual({ type: "image_url", image_url: { url: `data:video/mp4;base64,${Buffer.alloc(12 * MiB).toString("base64")}` } });
    } finally { rmSync(root, { recursive: true, force: true }); }
  });

  it("leaves out replayed pictures that would push a turn with a clip past the request's budget", () => {
    const root = folder();
    try {
      const earlier = png(root, `${IDS[0]}.png`, 5 * MiB);
      const transcript = [{ role: "user" as const, text: `earlier\n\n<attached-image path="${earlier.path}" name="e.png" />` }];
      expect(extractReplayImages(transcript, [], { attachmentsDir: root }, [clip(12 * MiB)]).images).toEqual([earlier]);
      expect(extractReplayImages(transcript, [image(8 * MiB)], { attachmentsDir: root }, [clip(12 * MiB)]).images).toEqual([]);
      expect(extractReplayImages(transcript, [image(8 * MiB)], { attachmentsDir: root }).images).toEqual([earlier]);
    } finally { rmSync(root, { recursive: true, force: true }); }
  });

  it("keeps only the frames that fit beside a sent clip, and every frame that fits when no clip is sent", async () => {
    const frame = (bytes: number) => ({ path: `/tmp/frame-${bytes}.jpg`, mime: "image/jpeg" as const, bytes, source: "video-frame" as const });
    const frames = [frame(2 * MiB), frame(4 * MiB), frame(MiB)];
    const sampler = vi.mocked(videoFrameImages), actual = sampler.getMockImplementation()!;
    sampler.mockImplementation(async (videos) => videos?.length ? frames : []);
    try {
      const lines = [{ images: [], videos: [clip(12 * MiB)] }, { images: [image(8 * MiB)], videos: [clip(MiB)] }];
      const media = await turnMedia(lines, gemini);
      expect(media.videos).toEqual([clip(12 * MiB)]);
      expect(media.images).toEqual([image(8 * MiB), frame(2 * MiB), frame(MiB)]);
      expect((await turnMedia(lines, { nativeImageInput: true })).images).toEqual([...frames, image(8 * MiB), ...frames]);
    } finally { sampler.mockImplementation(actual); }
  });

  it("samples no frames from a clip that is sent, even when its record is a copy", async () => {
    const sampler = vi.mocked(videoFrameImages), actual = sampler.getMockImplementation()!;
    sampler.mockImplementation(async (videos) => videos?.length ? [{ path: "/tmp/f.jpg", mime: "image/jpeg", bytes: 1, source: "video-frame" }] : []);
    try {
      expect(await videoFramesWithin(0, [clip(MiB)], [{ ...clip(MiB) }])).toEqual([]);
    } finally { sampler.mockImplementation(actual); }
  });

  it("keeps a burst's frames and pictures within the turn's picture count, counting later lines' pictures", async () => {
    const frame = (n: number) => ({ path: `/tmp/frame-${n}.jpg`, mime: "image/jpeg" as const, bytes: 1, source: "video-frame" as const });
    const frames = Array.from({ length: 10 }, (_, n) => frame(n));
    const sampler = vi.mocked(videoFrameImages), actual = sampler.getMockImplementation()!;
    sampler.mockImplementation(async (videos, limit = Infinity) => videos?.length ? frames.slice(0, Math.max(0, limit)) : []);
    try {
      const pictures = Array.from({ length: 6 }, (_, n) => image(n + 1));
      const media = await turnMedia([{ images: [], videos: [clip(20 * MiB)] }, { images: pictures, videos: [] }], gemini);
      expect(media.images).toHaveLength(10);
      expect(media.images.slice(-6)).toEqual(pictures);
    } finally { sampler.mockImplementation(actual); }
  });

  it("sends a file attached twice in a burst once, so a different clip still fits the engine's limit", () => {
    expect(nativeClips([clip(5 * MiB), clip(5 * MiB), clip(4 * MiB)], gemini)).toEqual([clip(5 * MiB), clip(4 * MiB)]);
  });

  it("keeps only the frames that fit beside the turn's pictures when no clip is sent", async () => {
    const frame = (bytes: number) => ({ path: `/tmp/frame-${bytes}.jpg`, mime: "image/jpeg" as const, bytes, source: "video-frame" as const });
    const frames = [frame(2 * MiB), frame(6 * MiB), frame(MiB)];
    const sampler = vi.mocked(videoFrameImages), actual = sampler.getMockImplementation()!;
    sampler.mockImplementation(async (videos) => videos?.length ? frames : []);
    try {
      expect(await videoFramesWithin(2, [clip(MiB)], [], [image(9 * MiB), image(9 * MiB)])).toEqual([frame(2 * MiB), frame(MiB)]);
    } finally { sampler.mockImplementation(actual); }
  });

  it("gives no clip to an engine without a video limit, so it keeps getting frames", () => {
    expect(nativeClips([clip(10)], { nativeImageInput: true })).toEqual([]);
    expect(nativeClips([clip(10)], { nativeVideoBytes: 100 })).toEqual([]);
  });
});