Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
// @vitest-environment happy-dom
import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vitest";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
import {
AttachedFileChips,
AttachedImageGallery,
AttachmentPreviewDialog,
MarkdownImagePreview,
OutsideWorkspaceFile,
canonicalDownloadFilename,
contentDispositionFilename,
imageGalleryLayout,
isExternalImageSource,
messageImagePreviewUrl,
previewImage,
previewKeyAction,
requestMessageFile,
safeDownloadFilename,
saveFailureText,
useLocalFileSave,
wrappedImageIndex,
} from "./AttachmentPreview";
import { messageFileOutsideWorkspace } from "./outside-workspace-probe";
describe("attachment image navigation", () => {
it("wraps previous and next navigation", () => {
expect(wrappedImageIndex(0, -1, 3)).toBe(2);
expect(wrappedImageIndex(2, 1, 3)).toBe(0);
expect(wrappedImageIndex(0, 1, 0)).toBe(0);
});
it("maps preview keys only when the action is available", () => {
expect(previewKeyAction("Escape", 1)).toBe("close");
expect(previewKeyAction("ArrowLeft", 3)).toBe("previous");
expect(previewKeyAction("ArrowRight", 3)).toBe("next");
expect(previewKeyAction("ArrowRight", 1)).toBeNull();
expect(previewKeyAction("Enter", 3)).toBeNull();
});
it("uses compact responsive grids for one, two, and many images", () => {
expect(imageGalleryLayout(1)).toContain("grid-cols-1");
expect(imageGalleryLayout(2)).toContain("grid-cols-2");
expect(imageGalleryLayout(3)).toContain("sm:grid-cols-3");
});
});
describe("attachment download filenames", () => {
it("prefers the UTF-8 server filename and makes it portable", () => {
expect(contentDispositionFilename(
`attachment; filename="fallback.md"; filename*=UTF-8''..%2Fnotes%2Fr%C3%A9sum%C3%A9%20%22final%22.md`,
)).toBe("résumé _final_.md");
expect(safeDownloadFilename("../../AUX.txt")).toBe("_AUX.txt");
expect(safeDownloadFilename(`bad\u202ename\ud800.txt`)).toBe("badname.txt");
});
it("uses a safe fallback when the response has no filename", () => {
expect(canonicalDownloadFilename({
fallback: "../reports/quarterly?.pdf",
source: "/private/attachment.pdf",
mime: "application/pdf",
})).toBe("quarterly_.pdf");
});
it("lets image bytes or their canonical source override a spoofed extension", () => {
expect(canonicalDownloadFilename({
contentDisposition: `attachment; filename="setup.exe"`,
source: "/private/opaque",
mime: "image/png",
})).toBe("setup.png");
expect(canonicalDownloadFilename({
contentDisposition: `attachment; filename="holiday.pdf"`,
source: "/api/attachments/123.jpeg?download=1",
})).toBe("holiday.jpeg");
});
});
describe("external image privacy", () => {
it("classifies the image source independently from an outer link", () => {
expect(isExternalImageSource("https://assets.example/image.png")).toBe(true);
expect(isExternalImageSource("//assets.example/image.png")).toBe(true);
expect(isExternalImageSource("https:assets.example/image.png")).toBe(true);
expect(isExternalImageSource("https:/assets.example/image.png")).toBe(true);
expect(isExternalImageSource("https:\\assets.example\\image.png")).toBe(true);
expect(isExternalImageSource("HTTP:assets.example/pixel.gif")).toBe(true);
expect(isExternalImageSource("/\t/assets.example/pixel.gif")).toBe(true);
expect(isExternalImageSource("/\n/assets.example/pixel.gif")).toBe(true);
expect(isExternalImageSource("/\r/assets.example/pixel.gif")).toBe(true);
expect(isExternalImageSource("\\\\assets.example\\pixel.gif")).toBe(true);
expect(isExternalImageSource("/api/attachments/image.png")).toBe(false);
});
});
describe("attachment preview surfaces", () => {
it("keeps a stable loading tile and the original image name", () => {
const html = renderToStaticMarkup(createElement(AttachedImageGallery, {
paths: [{
path: "/store/123e4567-e89b-12d3-a456-426614174000.png",
name: "Launch artwork.png",
private: true,
}],
}));
expect(html).toContain("aspect-[4/3]");
expect(html).toContain("Loading Launch artwork.png");
expect(html).toContain("Preview attached image Launch artwork.png");
expect(html).toContain("/api/attachments/123e4567-e89b-12d3-a456-426614174000.png");
expect(html).toContain("loading=\"lazy\"");
expect(html).not.toContain("fetchPriority=\"high\"");
});
it("can prioritize a newly sent image without making old galleries eager", () => {
const html = renderToStaticMarkup(createElement(AttachedImageGallery, {
paths: ["/store/123e4567-e89b-12d3-a456-426614174000.png"],
eager: true,
}));
expect(html).toContain("loading=\"eager\"");
expect(html).toContain("fetchPriority=\"high\"");
});
it("keeps remote Markdown images private until explicitly loaded", () => {
const html = renderToStaticMarkup(createElement(MarkdownImagePreview, {
src: "https://assets.example/preview.png?signature=abc",
name: "Result image",
openUrl: "https://assets.example/preview.png?signature=abc",
}));
expect(html).toContain("External image hidden for privacy");
expect(html).toContain("Load image");
expect(html).not.toContain("src=\"https://assets.example/preview.png?signature=abc\"");
expect(html).toContain("https://assets.example/preview.png?signature=abc");
});
it("does not need an outer link to hide a remote Markdown image", () => {
const html = renderToStaticMarkup(createElement(MarkdownImagePreview, {
src: "//assets.example/preview.png",
name: "Result image",
}));
expect(html).toContain("External image hidden for privacy");
expect(html).not.toContain("src=\"//assets.example/preview.png\"");
});
it("uses the stored image extension for downloads, not the display label", () => {
expect(previewImage(
"/store/123e4567-e89b-12d3-a456-426614174000.png",
"quarterly-report.pdf",
)?.downloadName).toBe("quarterly-report.png");
});
it("keeps legacy transcript file chips visible but inert", () => {
const html = renderToStaticMarkup(createElement(AttachedFileChips, {
files: [{ path: "/store/123e4567-e89b-42d3-a456-426614174000.pdf", name: "Final report.pdf", private: true }],
}));
expect(html).toContain("Final report.pdf");
expect(html).toContain("Unavailable");
expect(html).not.toContain("type=\"button\"");
});
it("makes message-authorized transcript files explicit save actions", () => {
const html = renderToStaticMarkup(createElement(AttachedFileChips, {
files: [{ path: "/store/123e4567-e89b-42d3-a456-426614174000.pdf", name: "Final report.pdf", private: true }],
message: { threadId: "thread-1", messageId: "message-1" },
}));
expect(html).toContain("Save a copy of Final report.pdf");
expect(html).toContain("type=\"button\"");
});
});
describe("Show in folder for a file outside the workspace", () => {
const render = (filePath: string) => renderToStaticMarkup(createElement(OutsideWorkspaceFile, { filePath }));
it("offers the reveal only for an absolute local path, and only in the local desktop app", () => {
vi.stubGlobal("window", { ogb: { revealInFolder: vi.fn(), remoteClient: { active: false } } });
try {
expect(render("/Users/maus/_draft/ollama-gen.js")).toContain("Show in folder");
expect(render("C:\\Users\\Maus\\_draft\\ollama-gen.js")).toContain("Show in folder");
for (const filePath of ["_draft/ollama-gen.js", "\\\\server\\share\\ollama-gen.js"]) {
expect(render(filePath)).not.toContain("Show in folder");
expect(render(filePath)).toContain(`>${filePath}</code>`);
}
} finally {
vi.unstubAllGlobals();
}
});
it("gives a remote client the path, since the file is not on its computer", () => {
vi.stubGlobal("window", { ogb: { revealInFolder: vi.fn(), remoteClient: { active: true } } });
try {
expect(render("/Users/maus/_draft/ollama-gen.js")).toContain(">/Users/maus/_draft/ollama-gen.js</code>");
} finally {
vi.unstubAllGlobals();
}
});
});
describe("messageFileOutsideWorkspace", () => {
it("maps an outside_workspace refusal to true and an openable path to false", async () => {
const refused = () => new Response(JSON.stringify({ code: "outside_workspace" }), { status: 403, headers: { "content-type": "application/json" } });
const opened = () => new Response(new Blob(["x"]), { status: 200, headers: { "content-type": "text/plain" } });
vi.stubGlobal("fetch", vi.fn()
.mockImplementationOnce(async () => refused())
.mockImplementationOnce(async () => opened()));
const message = { threadId: "t", messageId: "m" };
try {
await expect(messageFileOutsideWorkspace("C:\\outside\\a.js", message, new AbortController().signal)).resolves.toBe(true);
await expect(messageFileOutsideWorkspace("inside/a.js", message, new AbortController().signal)).resolves.toBe(false);
} finally {
vi.unstubAllGlobals();
}
});
});
describe("a failed save", () => {
it("explains a file outside the working folder instead of echoing the server", () => {
const server = "the linked file is outside this conversation's workspace";
expect(saveFailureText({ reason: server, outsideWorkspace: true }))
.toBe("This file is outside this chat's working folder, so it can't be saved from here");
expect(saveFailureText({ reason: "the linked file is unavailable", outsideWorkspace: false }))
.toBe("the linked file is unavailable");
});
});
describe("a file over the download limit", () => {
it("shows the server's plain explanation and keeps its code, not the raw byte count", async () => {
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({
error: "file exceeds 524288000 bytes",
code: "file_too_large",
errorKey: "serverError.file.tooLarge",
errorParams: { size: "612 MB", limit: "500 MB", name: "reel.mp4" },
}), { status: 413, headers: { "content-type": "application/json" } })));
try {
await expect(requestMessageFile("reel.mp4", { threadId: "t", messageId: "m" }, new AbortController().signal))
.rejects.toMatchObject({
code: "file_too_large",
message: "This file is 612 MB, over the 500 MB limit for opening files from chat. The file itself is still saved as reel.mp4.",
});
} finally {
vi.unstubAllGlobals();
}
});
});
describe("a folder linked in a message", () => {
const folderPath = "/work/Reports";
const listing = { name: "Reports", entries: [{ name: "q3.pdf", bytes: 2048, mime: "application/pdf" }], truncated: false };
const authorized = () => new Response(JSON.stringify(listing), { status: 200, headers: { "content-type": "application/json", "x-openmausbot-folder": "1" } });
const refused = () => new Response(JSON.stringify({ error: "the linked file is outside this conversation's workspace", code: "outside_workspace" }), { status: 403, headers: { "content-type": "application/json" } });
async function clickLink(answer: () => Response) {
vi.stubGlobal("fetch", vi.fn(async () => answer()));
const seen: { current: ReturnType<typeof useLocalFileSave> | null } = { current: null };
const Probe = () => {
seen.current = useLocalFileSave(folderPath, undefined, { threadId: "thread-1", messageId: "message-1" });
return null;
};
const root = createRoot(document.createElement("div"));
await act(async () => { root.render(createElement(Probe)); });
await act(async () => { await seen.current!.save(); });
const result = { state: seen.current!.state, folder: seen.current!.folder };
await act(async () => { root.unmount(); });
return result;
}
it("opens in the file manager once the route authorized it, with no listing", async () => {
const openFolder = vi.fn(async () => "opened");
vi.stubGlobal("ogb", { openFolder, remoteClient: { active: false } });
try {
expect(await clickLink(authorized)).toEqual({ state: "idle", folder: null });
expect(openFolder).toHaveBeenCalledWith(folderPath);
} finally {
vi.unstubAllGlobals();
}
});
it("shows the listing when the desktop would not open it", async () => {
const openFolder = vi.fn(async () => "not-folder");
vi.stubGlobal("ogb", { openFolder, remoteClient: { active: false } });
try {
expect(await clickLink(authorized)).toEqual({ state: "idle", folder: listing });
} finally {
vi.unstubAllGlobals();
}
});
it("shows the listing where there is no desktop bridge", async () => {
vi.stubGlobal("ogb", undefined);
try {
expect(await clickLink(authorized)).toEqual({ state: "idle", folder: listing });
} finally {
vi.unstubAllGlobals();
}
});
it("never reaches the desktop when the route refuses the link", async () => {
const openFolder = vi.fn(async () => "opened");
vi.stubGlobal("ogb", { openFolder, remoteClient: { active: false } });
try {
expect(await clickLink(refused)).toEqual({ state: "failed", folder: null });
expect(openFolder).not.toHaveBeenCalled();
} finally {
vi.unstubAllGlobals();
}
});
});
describe("local Markdown image lifecycle", () => {
it("builds a path-free, directly streamable message preview URL", () => {
expect(messageImagePreviewUrl(
{ threadId: "thread-one", messageId: "message-two" },
42,
)).toBe(
"/api/threads/thread-one/messages/message-two/file?preview=1&ref=42",
);
});
});
describe("image preview copy button", () => {
const image = { src: "/api/files/shot.png", name: "shot.png", downloadUrl: "/api/files/shot.png" };
async function openPreview() {
const container = document.createElement("div");
document.body.append(container);
const root = createRoot(container);
await act(async () => { root.render(createElement(AttachmentPreviewDialog, { image, onClose: () => {} })); });
const button = () => document.querySelector<HTMLButtonElement>('button[title="Copy image"], button[title="Image copied"]');
return { button, close: () => act(() => root.unmount()) };
}
it("copies the shown image as a PNG and says so", async () => {
const write = vi.fn(async (items: { items: Record<string, Promise<Blob>> }[]) => {
await items[0]!.items["image/png"];
});
vi.stubGlobal("ClipboardItem", class { constructor(readonly items: Record<string, Promise<Blob>>) {} });
vi.stubGlobal("fetch", vi.fn(async () => new Response(new Blob(["png"], { type: "image/png" }))));
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { write } });
const preview = await openPreview();
try {
expect(preview.button()?.getAttribute("aria-label")).toBe("Copy shot.png as an image");
await act(async () => { preview.button()!.click(); });
expect(write).toHaveBeenCalledOnce();
expect(fetch).toHaveBeenCalledWith("/api/files/shot.png");
expect(preview.button()?.title).toBe("Image copied");
} finally {
await preview.close();
vi.unstubAllGlobals();
}
});
it("is hidden where the clipboard cannot take images", async () => {
vi.stubGlobal("ClipboardItem", undefined);
const preview = await openPreview();
try {
expect(preview.button()).toBeNull();
expect(document.querySelector('a[title="Download"]')).not.toBeNull();
} finally {
await preview.close();
vi.unstubAllGlobals();
}
});
});
describe("image preview wheel", () => {
const images = [
{ src: "/api/files/tall.png", name: "tall.png" },
{ src: "/api/files/next.png", name: "next.png" },
];
it("zooms around the pointer, back to fit, and never scrolls the chat behind it", async () => {
const chatWheel = vi.fn();
const container = document.createElement("div");
document.body.append(container);
const root = createRoot(container);
await act(async () => {
root.render(createElement("div", { onWheel: chatWheel }, createElement(AttachmentPreviewDialog, { image: images[0]!, images, onClose: () => {} })));
});
const picture = () => document.querySelector<HTMLImageElement>("[role=dialog] img")!;
const wheel = async (deltaY: number, target: Element = picture()) => {
const event = new WheelEvent("wheel", { deltaY, bubbles: true, cancelable: true });
// happy-dom 21's WheelEvent drops clientX and clientY from its init.
Object.defineProperties(event, { clientX: { value: 120 }, clientY: { value: 80 } });
await act(async () => { target.dispatchEvent(event); });
return event;
};
const zoom = () => {
const [x, y, scale] = (/^translate\((\S+)px, (\S+)px\) scale\((\S+)\)$/.exec(picture().style.transform) ?? []).slice(1).map(Number);
return { x, y, scale };
};
try {
const zoomIn = await wheel(-200);
expect(zoomIn.defaultPrevented).toBe(true);
const { x, y, scale } = zoom();
expect(scale).toBeCloseTo(Math.E);
expect((120 - x!) / scale!).toBeCloseTo(120);
expect((80 - y!) / scale!).toBeCloseTo(80);
expect((await wheel(400)).defaultPrevented).toBe(true);
expect(picture().style.transform).toBe("");
expect((await wheel(-200, document.querySelector("[role=dialog] header")!)).defaultPrevented).toBe(true);
expect(picture().style.transform).toBe("");
const beside = picture().parentElement!;
expect((await wheel(-200, beside)).defaultPrevented).toBe(true);
expect(picture().style.transform).toBe("");
await wheel(-200);
await wheel(400, beside);
expect(picture().style.transform).toBe("");
await wheel(-200);
await act(async () => { window.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight" })); });
expect(picture().alt).toBe("next.png");
expect(picture().style.transform).toBe("");
await wheel(-200);
expect(picture().style.transform).not.toBe("");
const replaced = [images[0]!, { src: "/api/files/replaced.png", name: "replaced.png" }];
await act(async () => {
root.render(createElement("div", { onWheel: chatWheel }, createElement(AttachmentPreviewDialog, { image: replaced[0]!, images: replaced, onClose: () => {} })));
});
expect(picture().alt).toBe("replaced.png");
expect(picture().style.transform).toBe("");
expect(chatWheel).not.toHaveBeenCalled();
} finally {
act(() => root.unmount());
container.remove();
}
});
});
describe("opening a single outside-workspace file when permitted by owner", () => {
it("preserves canOpenOutside on outside_workspace errors and omits listFolder on retry", async () => {
const fetch = vi.fn()
.mockResolvedValueOnce(new Response(JSON.stringify({
error: "the linked file is outside this conversation's workspace",
code: "outside_workspace",
canOpenOutside: true,
}), { status: 403, headers: { "content-type": "application/json" } }))
.mockResolvedValueOnce(new Response(new Blob(["hello"], { type: "text/plain" }), { status: 200 }));
vi.stubGlobal("fetch", fetch);
vi.stubGlobal("URL", { createObjectURL: vi.fn(() => "blob:test"), revokeObjectURL: vi.fn() });
const seen: { current: ReturnType<typeof useLocalFileSave> | null } = { current: null };
const Probe = () => {
seen.current = useLocalFileSave("/outside/notes.md", "notes.md", { threadId: "t1", messageId: "m1" });
return null;
};
const root = createRoot(document.createElement("div"));
try {
await act(async () => { root.render(createElement(Probe)); });
await act(async () => { await seen.current!.save(); });
expect(seen.current!.state).toBe("failed");
expect(seen.current!.outsideWorkspace).toBe(true);
expect(seen.current!.canOpenOutside).toBe(true);
await act(async () => { await seen.current!.save({ allowOutsideWorkspace: true }); });
expect(seen.current!.state).toBe("saved");
expect(JSON.parse(String(fetch.mock.calls[1]![1]!.body))).toEqual({
path: "/outside/notes.md",
allowOutsideWorkspace: true,
});
} finally {
await act(async () => { root.unmount(); });
vi.unstubAllGlobals();
}
});
});