Skip to content

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

20.1 KB
Raw Blame
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";

import {
  calendarsFromData, createConnectedReads, emailsFromData, eventsFromData, messageFromData, outlookMessageFromData, outlookMessagesFromData, profileFromData, SourceError, threadFromData, toolData,
} from "./connected-reads.ts";

const fixture = (name: string): unknown => JSON.parse(readFileSync(new URL(`./testing/fixtures/${name}.json`, import.meta.url), "utf8"));

/** One relay that answers like Composio's multi-execute tool, from `answers` by tool slug. */
function relay(answers: Record<string, (args: Record<string, unknown>) => { successful: boolean; data?: unknown; data_preview?: unknown; error?: string }>) {
  const frames: Array<{ method: string; session?: string; slug?: string; args?: Record<string, unknown>; item?: Record<string, unknown> }> = [];
  let sessions = 0;
  const deps = {
    connected: async () => ({ gmail: true, googlecalendar: true }),
    relay: async (payload: unknown, session: string | undefined) => {
      const frame = payload as { method: string; params?: { arguments?: { tools?: Array<Record<string, unknown>> } } };
      const item = frame.params?.arguments?.tools?.[0];
      frames.push({ method: frame.method, ...(session ? { session } : {}), ...(item ? { slug: String(item.tool_slug), args: item.arguments as Record<string, unknown>, item } : {}) });
      if (frame.method === "initialize") return { status: 200, bytes: new TextEncoder().encode("{}"), transportSessionId: `s-${++sessions}` };
      if (frame.method !== "tools/call") return { status: 202, bytes: new Uint8Array() };
      const response = answers[String(item!.tool_slug)]!(item!.arguments as Record<string, unknown>);
      const text = JSON.stringify({ successful: true, data: { results: [{ tool_slug: item!.tool_slug, response }] } });
      return { status: 200, bytes: new TextEncoder().encode(JSON.stringify({ jsonrpc: "2.0", id: "omb-check-call", result: { content: [{ type: "text", text }] } })) };
    },
  };
  return { deps, frames };
}

describe("reading Composio's answers", () => {
  it("reads events, skipping resources and id-less entries, with https join links only", () => {
    const events = eventsFromData(fixture("composio-calendar-events"), { id: "primary", owned: true });
    expect(events.map((event) => [event.id, event.status])).toEqual([["demo-1", "confirmed"], ["weekly-2_20261017", "confirmed"], ["holiday", "confirmed"], ["gone", "cancelled"]]);
    expect(events[0]).toMatchObject({ title: "Supamaus demo with Jake", joinUrl: "https://meet.google.com/abc-defg-hij", ownedCalendar: true });
    expect(events[0]!.attendees.map((one) => one.email)).toEqual(["[email protected]", "[email protected]"]);
    expect(events[1]).toMatchObject({ seriesId: "weekly-2", selfDeclined: true, joinUrl: "https://zoom.us/j/1" });
    expect(events[2]).toMatchObject({ allDay: true });
  });

  it("takes a Teams link from an invite's description when the event has no conference link", () => {
    const teams = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_abc%40thread.v2/0?context=x";
    const [event] = eventsFromData({ items: [{ id: "teams-1", summary: "Vendor call", status: "confirmed", start: { dateTime: "2026-11-09T10:00:00Z" }, end: { dateTime: "2026-11-09T10:30:00Z" },
      description: `Microsoft Teams meeting. Join: <${teams}> Meeting ID: 123` }] }, { id: "primary", owned: true });
    expect(event).toMatchObject({ id: "teams-1", joinUrl: teams });
  });

  it("reads whether Gmail and Outlook mail is still unread, and says nothing when the answer did not", () => {
    expect(messageFromData({ messageId: "m-1", threadId: "t-1", labelIds: ["INBOX"] }).unread).toBe(false);
    expect(threadFromData({ messages: [{ messageId: "m-1", labelIds: ["UNREAD"] }, { messageId: "m-2", labelIds: [] }, { messageId: "m-3" }] }).map((message) => message.unread))
      .toEqual([true, false, undefined]);
    expect(outlookMessagesFromData({ value: [{ id: "o-1", isRead: false }, { id: "o-2", isRead: true }, { id: "o-3" }] }).map((message) => message.unread))
      .toEqual([true, false, undefined]);
    expect(outlookMessageFromData({ id: "o-1", isRead: true }).unread).toBe(false);
  });

  it("reads mail headers, profiles, single messages, threads and the calendar list", () => {
    const emails = emailsFromData(fixture("composio-gmail-fetch"));
    expect(emails.map((email) => [email.id, email.threadId, email.from, email.subject])).toEqual([
      ["important-1", "thread-important", "Ada <[email protected]>", "Q3 numbers due Friday"],
      ["newsletter-1", "thread-news", "News <[email protected]>", "This week in tech"],
    ]);
    expect(emails[0]!.preview).toBe("Can you send the Q3 numbers by Friday? Thanks");
    expect(emails.map((email) => email.unread)).toEqual([true, undefined]);
    expect(profileFromData(fixture("composio-gmail-profile"))).toBe("[email protected]");
    expect(messageFromData(fixture("composio-gmail-message"))).toMatchObject({ id: "m-1", threadId: "t-1", subject: "Q3 numbers" });
    expect(threadFromData(fixture("composio-gmail-thread")).map((message) => message.from)).toEqual(["[email protected]", "[email protected]"]);
    expect(calendarsFromData(fixture("composio-calendar-list")).filter((calendar) => calendar.read).map((calendar) => calendar.id))
      .toEqual(["[email protected]", "[email protected]", "[email protected]"]);
  });

  it("an answer of another shape is an error, never an empty list", () => {
    expect(() => emailsFromData({ items: [] })).toThrow("no message list");
    expect(() => eventsFromData({ messages: [] }, { id: "primary", owned: true })).toThrow("no event list");
    expect(() => emailsFromData({ messages: [{ subject: "no id" }] })).toThrow("none of the Gmail messages could be read");
    expect(() => toolData("GMAIL_FETCH_EMAILS", { result: { content: [{ type: "text", text: "<html>" }] } })).toThrow("not JSON");
    expect(emailsFromData({ messages: [] })).toEqual([]);
  });
});

describe("a check's reads", () => {
  it("share one connected-apps session, page through mail newest first, and never name an account", async () => {
    const pages: Record<string, unknown> = {
      first: { messages: [{ messageId: "a", threadId: "ta", messageTimestamp: "2026-10-22T08:00:00Z", sender: "A <[email protected]>", subject: "A" }], nextPageToken: "p2" },
      p2: { messages: [{ messageId: "b", threadId: "tb", messageTimestamp: "2026-10-22T09:00:00Z", sender: "B <[email protected]>", subject: "B" }] },
    };
    const { deps, frames } = relay({
      GMAIL_FETCH_EMAILS: (args) => ({ successful: true, data: pages[String(args.page_token ?? "first")] }),
      GMAIL_GET_PROFILE: () => ({ successful: true, data: { emailAddress: "[email protected]" } }),
    });
    const session = createConnectedReads(deps).session();
    expect(await session.address()).toBe("[email protected]");
    const read = await session.emails(Date.parse("2026-10-22T00:00:00Z"), 10);
    expect(read).toMatchObject({ more: false });
    expect(read.emails.map((email) => email.id)).toEqual(["b", "a"]);
    expect(frames.filter((frame) => frame.method === "initialize")).toHaveLength(1);
    expect(new Set(frames.filter((frame) => frame.method === "tools/call").map((frame) => frame.session))).toEqual(new Set(["s-1"]));
    for (const frame of frames.filter((one) => one.item)) expect(Object.keys(frame.item!).sort()).toEqual(["arguments", "tool_slug"]);
    expect(frames.find((frame) => frame.slug === "GMAIL_FETCH_EMAILS")!.args!.query).toContain("in:inbox after:");
  });

  it("says more mail waits beyond the limit", async () => {
    const messages = Array.from({ length: 5 }, (_, index) => ({ messageId: `m${index}`, threadId: `t${index}`, messageTimestamp: `2026-10-22T0${index}:00:00Z`, sender: "[email protected]", subject: "s" }));
    const { deps } = relay({ GMAIL_FETCH_EMAILS: () => ({ successful: true, data: { messages } }) });
    const read = await createConnectedReads(deps).session().emails(0, 3);
    expect(read.more).toBe(true);
    expect(read.emails.map((email) => email.id)).toEqual(["m4", "m3", "m2"]);
  });

  it("reads mail in smaller pages when the connected-apps service sends a page back shortened", async () => {
    const messages = Array.from({ length: 30 }, (_, index) => ({ messageId: `m${index}`, threadId: `t${index}`, messageTimestamp: new Date(Date.UTC(2026, 9, 22, 0, index)).toISOString(), sender: "[email protected]", subject: "s" }));
    // Like the real service: an answer past its size limit comes back as a short preview with no data.
    const { deps, frames } = relay({
      GMAIL_FETCH_EMAILS: (args) => {
        const size = Number(args.max_results);
        const start = Number(args.page_token ?? 0);
        const page = messages.slice(start, start + size);
        if (size > 10) return { successful: true, data_preview: { messages: [...page.slice(0, 2), `...${page.length - 2} more items`] } };
        return { successful: true, data: { messages: page, ...(start + size < messages.length ? { nextPageToken: String(start + size) } : {}) } };
      },
    });
    const read = await createConnectedReads(deps).session().emails(0, 100);
    expect(read).toMatchObject({ more: false });
    expect(read.emails).toHaveLength(30);
    expect(frames.filter((frame) => frame.slug === "GMAIL_FETCH_EMAILS").every((frame) => Number(frame.args!.max_results) <= 50)).toBe(true);
  });

  it("asking again at a smaller size does not use up the pages a read may take", async () => {
    const messages = Array.from({ length: 90 }, (_, index) => ({ messageId: `m${index}`, threadId: `t${index}`, messageTimestamp: new Date(Date.UTC(2026, 9, 22, 0, index)).toISOString(), sender: "[email protected]", subject: "s" }));
    // Four whole pages of 20, then the next page comes back shortened at 20 and at 10, and whole at 5.
    const { deps, frames } = relay({
      GMAIL_FETCH_EMAILS: (args) => {
        const size = Number(args.max_results);
        const start = Number(args.page_token ?? 0);
        const page = messages.slice(start, start + size);
        if (start >= 80 && size > 5) return { successful: true, data_preview: { messages: [...page.slice(0, 2), `...${page.length - 2} more items`] } };
        return { successful: true, data: { messages: page, ...(start + size < messages.length ? { nextPageToken: String(start + size) } : {}) } };
      },
    });
    const read = await createConnectedReads(deps).session().emails(0, 100);
    expect(frames.filter((frame) => frame.slug === "GMAIL_FETCH_EMAILS").map((frame) => Number(frame.args!.max_results))).toEqual([20, 20, 20, 20, 20, 10, 5, 5]);
    expect(read).toMatchObject({ more: false });
    expect(read.emails).toHaveLength(90);
  });

  it("a shortened answer is an error that says so, never an empty list", async () => {
    const { deps } = relay({ GMAIL_FETCH_EMAILS: () => ({ successful: true, data_preview: { messages: ["...50 more items"] } }) });
    const mail = await createConnectedReads(deps).session().emails(0, 5).catch((error: unknown) => error);
    expect(mail).toMatchObject({ app: "gmail", signedOut: false });
    expect((mail as Error).message).toMatch(/too large/);
  });

  it("names the app that failed, and whether reconnecting fixes it", async () => {
    const { deps } = relay({
      GMAIL_FETCH_EMAILS: () => ({ successful: false, error: "Connected account is not ACTIVE: token expired" }),
      GOOGLECALENDAR_LIST_CALENDARS: () => ({ successful: false, error: "Backend error 500" }),
    });
    const session = createConnectedReads(deps).session();
    const mail = await session.emails(0, 5).catch((error: unknown) => error);
    expect(mail).toBeInstanceOf(SourceError);
    expect(mail).toMatchObject({ app: "gmail", signedOut: true });
    const calendar = await session.events(0, 1).catch((error: unknown) => error);
    expect(calendar).toMatchObject({ app: "googlecalendar", signedOut: false });
  });

  it("names the account the host chose for an app with several, asking once per session, and says so when it fails", async () => {
    const { deps, frames } = relay({
      GMAIL_GET_PROFILE: () => ({ successful: true, data: { emailAddress: "[email protected]" } }),
      GMAIL_FETCH_EMAILS: () => ({ successful: false, error: "Backend error 500" }),
      GOOGLECALENDAR_LIST_CALENDARS: () => ({ successful: true, data: { items: [] } }),
      GOOGLECALENDAR_EVENTS_LIST: () => ({ successful: true, data: { items: [] } }),
    });
    let asked = 0;
    const session = createConnectedReads({ ...deps, accounts: async () => { asked += 1; return { gmail: "ca_newest" }; } }).session();
    expect(await session.address()).toBe("[email protected]");
    const mail = await session.emails(0, 5).catch((error: unknown) => error);
    expect(mail).toMatchObject({ app: "gmail", signedOut: false, severalAccounts: true });
    await session.events(0, 1);
    expect(asked).toBe(1);
    for (const frame of frames.filter((one) => one.slug?.startsWith("GMAIL_"))) expect(frame.item!.account).toBe("ca_newest");
    for (const frame of frames.filter((one) => one.slug?.startsWith("GOOGLECALENDAR_"))) expect(frame.item).not.toHaveProperty("account");
  });

  it("asks again for the account after a failed lookup, and a relay error is not blamed on the named account", async () => {
    const { deps, frames } = relay({ GMAIL_GET_PROFILE: () => ({ successful: true, data: { emailAddress: "[email protected]" } }) });
    let asked = 0;
    const accounts = async () => {
      asked += 1;
      if (asked === 1) throw new Error("inventory down");
      return { gmail: "ca_newest" };
    };
    let broken = false;
    const session = createConnectedReads({ ...deps, accounts, relay: async (payload, transport) =>
      broken ? { status: 502, bytes: new Uint8Array() } : deps.relay(payload, transport) }).session();
    expect(await session.address()).toBe("[email protected]");
    expect(await session.address()).toBe("[email protected]");
    expect(asked).toBe(2);
    expect(frames.filter((one) => one.slug === "GMAIL_GET_PROFILE").map((one) => one.item!.account)).toEqual([undefined, "ca_newest"]);
    broken = true;
    const error = await session.address().catch((caught: unknown) => caught);
    expect(error).toMatchObject({ app: "gmail", severalAccounts: false });
  });

  it("names the fallback account while the lookup fails, and still asks again on the next read", async () => {
    const { deps, frames } = relay({
      GMAIL_GET_PROFILE: () => ({ successful: true, data: { emailAddress: "[email protected]" } }),
      GOOGLECALENDAR_LIST_CALENDARS: () => ({ successful: true, data: { items: [] } }),
      GOOGLECALENDAR_EVENTS_LIST: () => ({ successful: true, data: { items: [] } }),
    });
    let asked = 0;
    const accounts = async () => {
      asked += 1;
      if (asked === 1) throw new Error("inventory down");
      return { gmail: "ca_older", googlecalendar: "ca_cal_newest" };
    };
    const session = createConnectedReads({ ...deps, accounts, fallbackAccounts: () => ({ gmail: "ca_older" }) }).session("bot-1");
    expect(await session.address()).toBe("[email protected]");
    await session.events(0, 1);
    expect(asked).toBe(2);
    expect(frames.filter((one) => one.slug === "GMAIL_GET_PROFILE").map((one) => one.item!.account)).toEqual(["ca_older"]);
    for (const frame of frames.filter((one) => one.slug?.startsWith("GOOGLECALENDAR_"))) expect(frame.item!.account).toBe("ca_cal_newest");
  });

  it("names one account for every request of a calendar or mail read, even when the lookup recovers part-way", async () => {
    const { deps, frames } = relay({
      GOOGLECALENDAR_LIST_CALENDARS: () => ({ successful: true, data: { items: [{ id: "[email protected]", selected: true, accessRole: "reader" }] } }),
      GOOGLECALENDAR_EVENTS_LIST: () => ({ successful: true, data: { items: [] } }),
      GMAIL_FETCH_EMAILS: (args) => ({ successful: true, data: { messages: [], ...(args.page_token ? {} : { nextPageToken: "page-2" }) } }),
    });
    let asked = 0;
    const accounts = async () => {
      asked += 1;
      if (asked === 1 || asked === 3) throw new Error("inventory down");
      return { gmail: "ca_mail_new", googlecalendar: "ca_cal_new" };
    };
    const session = createConnectedReads({ ...deps, accounts, fallbackAccounts: () => ({ gmail: "ca_mail_old", googlecalendar: "ca_cal_old" }) }).session("bot-1");
    await session.events(0, 1);
    const calendar = frames.filter((one) => one.slug?.startsWith("GOOGLECALENDAR_"));
    expect(calendar.map((one) => one.slug)).toEqual(["GOOGLECALENDAR_LIST_CALENDARS", "GOOGLECALENDAR_EVENTS_LIST", "GOOGLECALENDAR_EVENTS_LIST"]);
    for (const frame of calendar) expect(frame.item!.account).toBe("ca_cal_old");
    await session.events(0, 1);
    expect(frames.filter((one) => one.slug?.startsWith("GOOGLECALENDAR_")).slice(3).map((one) => one.item!.account)).toEqual(["ca_cal_new", "ca_cal_new", "ca_cal_new"]);
    asked = 2;
    const fresh = createConnectedReads({ ...deps, accounts, fallbackAccounts: () => ({ gmail: "ca_mail_old", googlecalendar: "ca_cal_old" }) }).session("bot-1");
    await fresh.emails(0, 5);
    expect(frames.filter((one) => one.slug === "GMAIL_FETCH_EMAILS").map((one) => one.item!.account)).toEqual(["ca_mail_old", "ca_mail_old"]);
  });

  it("gives up on an account lookup that outlasts the read's time limit, and asks again on the next read", async () => {
    const { deps, frames } = relay({ GMAIL_GET_PROFILE: () => ({ successful: true, data: { emailAddress: "[email protected]" } }) });
    let asked = 0;
    const accounts = () => {
      asked += 1;
      return asked === 1 ? new Promise<never>(() => {}) : Promise.resolve({ gmail: "ca_newest" });
    };
    const session = createConnectedReads({ ...deps, accounts, readTimeoutMs: 50 }).session();
    const error = await session.address().catch((caught: unknown) => caught);
    expect(error).toMatchObject({ app: "gmail", message: expect.stringMatching(/did not answer within/) });
    expect(await session.address()).toBe("[email protected]");
    expect(asked).toBe(2);
    expect(frames.filter((one) => one.slug === "GMAIL_GET_PROFILE").map((one) => one.item!.account)).toEqual(["ca_newest"]);
  });

  it("reads Outlook inbox messages and single messages with preview, conversation id, and shortened-page fallback", async () => {
    const messages = [
      { id: "o1", conversationId: "conv-1", receivedDateTime: "2026-10-22T08:00:00Z", from: { emailAddress: { name: "Ada", address: "[email protected]" } }, subject: "First", bodyPreview: "Can you review?", webLink: "https://outlook.office365.com/owa/?ItemID=o1" },
      { id: "o2", conversationId: "conv-2", receivedDateTime: "2026-10-22T09:00:00Z", from: { emailAddress: { address: "[email protected]" } }, subject: "Second", bodyPreview: "Latest update" },
    ];
    expect(outlookMessagesFromData({ value: messages }).map((m) => [m.id, m.threadId, m.from, m.preview, m.app])).toEqual([
      ["o2", "conv-2", "[email protected]", "Latest update", "outlook"],
      ["o1", "conv-1", "Ada <[email protected]>", "Can you review?", "outlook"],
    ]);
    expect(outlookMessageFromData(messages[0])).toMatchObject({ id: "o1", threadId: "conv-1", from: "Ada <[email protected]>", preview: "Can you review?", app: "outlook", link: "https://outlook.office365.com/owa/?ItemID=o1" });
    expect(outlookMessageFromData(messages[1]).link).toBeUndefined();

    const { deps, frames } = relay({
      OUTLOOK_LIST_MESSAGES: (args) => {
        if (Number(args.top) > 10) return { successful: true, data_preview: { value: ["...too many"] } };
        return { successful: true, data: { value: messages } };
      },
      OUTLOOK_GET_MESSAGE: (args) => (args.message_id === "gone"
        ? { successful: false, error: "Requested entity was not found." }
        : { successful: true, data: messages[0] }),
    });
    const session = createConnectedReads(deps).session();
    const list = await session.outlookEmails(Date.parse("2026-10-22T00:00:00Z"), 20);
    expect(list.map((m) => m.id)).toEqual(["o2", "o1"]);
    expect(frames.filter((one) => one.slug === "OUTLOOK_LIST_MESSAGES").map((one) => Number(one.args!.top))).toEqual([20, 10]);
    expect(await session.outlookMessage("o1")).toMatchObject({ id: "o1", app: "outlook" });
    expect(await session.outlookMessage("gone")).toBeNull();
    const outlookReads = frames.filter((one) => one.slug?.startsWith("OUTLOOK_"));
    expect(outlookReads.length).toBeGreaterThan(0);
    expect(outlookReads.every((one) => (one.args!.select as string[]).includes("webLink"))).toBe(true);
  });
});