Skip to content

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

8.9 KB
Raw Blame
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { afterEach, describe, expect, it, vi } from "vitest";

import { json, readBody } from "../harness/http.ts";
import type { NotificationLogEntry } from "../../shared/notification.ts";
import { clearNotificationLog, forgetNotificationReader, insertNotificationLog, markNotificationLogRead, recentNotificationLog } from "../message-db.ts";
import type { RequestAuth } from "../request-auth.ts";
import { createNotificationRoutes, notificationListedFor, readThreadNotifications } from "./notifications.ts";
import { dispatchRoutes } from "./table.ts";

const servers: Server[] = [];
afterEach(async () => {
  await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));
});

const sample: NotificationLogEntry = { id: "n1", at: 1, kind: "done", botId: "b1", botName: "Scout", threadId: "t1", title: "done", body: "", read: false };

async function serve(
  entries: NotificationLogEntry[] = [sample],
  shown?: (auth: RequestAuth) => (threadId: string) => boolean,
  reaches?: (auth: RequestAuth, entry: NotificationLogEntry) => boolean,
) {
  const deps = { recent: vi.fn(() => entries), markRead: vi.fn(), clear: vi.fn() };
  const routes = [createNotificationRoutes(deps, notificationListedFor(shown, reaches))];
  const server = createServer(async (req, res) => {
    const url = new URL(req.url ?? "/", "http://localhost");
    const handled = await dispatchRoutes(routes, {
      req, res, url, path: url.pathname, method: req.method ?? "GET",
      auth: { kind: "loopback", scopes: ["admin", "client"] }, json, readBody,
    });
    if (!handled) json(res, 404, { from: "inline routes" });
  });
  servers.push(server);
  await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));
  const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  return { deps, base };
}

describe("notification routes", () => {
  it("lists the feed", async () => {
    const { base } = await serve();
    const res = await fetch(`${base}/api/notifications`);
    expect(res.status).toBe(200);
    expect(await res.json()).toEqual({ notifications: [sample] });
  });

  it("marks one entry read, and all entries read", async () => {
    const { base, deps } = await serve();
    expect((await fetch(`${base}/api/notifications/n1/read`, { method: "POST" })).status).toBe(200);
    expect(deps.markRead).toHaveBeenLastCalledWith(["n1"]);
    expect((await fetch(`${base}/api/notifications/read-all`, { method: "POST" })).status).toBe(200);
    expect(deps.markRead).toHaveBeenLastCalledWith(["n1"]);
    expect(deps.markRead).toHaveBeenCalledTimes(2);
  });

  it("marks read only what the viewer's own list shows", async () => {
    const hiddenThread = { ...sample, id: "n2", threadId: "private" };
    const elsewhere = { ...sample, id: "n3", threadId: "t2" };
    const alreadyRead = { ...sample, id: "n4", read: true };
    const { base, deps } = await serve([sample, hiddenThread, elsewhere, alreadyRead],
      () => (threadId) => threadId !== "private", (_auth, entry) => entry.id !== "n3");
    const listed = await (await fetch(`${base}/api/notifications`)).json() as { notifications: NotificationLogEntry[] };
    expect(listed.notifications.map((entry) => entry.id)).toEqual(["n1", "n4"]);

    expect((await fetch(`${base}/api/notifications/read-all`, { method: "POST" })).status).toBe(200);
    expect(deps.markRead).toHaveBeenCalledExactlyOnceWith(["n1"]);
    for (const id of ["n2", "n3", "missing"]) {
      expect((await fetch(`${base}/api/notifications/${id}/read`, { method: "POST" })).status, id).toBe(404);
    }
    expect(deps.markRead).toHaveBeenCalledTimes(1);
  });

  it("clears what the viewer's own list shows, all of it or what came before a time", async () => {
    const old = { ...sample, id: "n2", at: 10 };
    const hidden = { ...sample, id: "n3", threadId: "private" };
    const { base, deps } = await serve([sample, old, hidden], () => (threadId) => threadId !== "private");
    expect((await fetch(`${base}/api/notifications/clear?before=5`, { method: "POST" })).status).toBe(200);
    expect(deps.clear).toHaveBeenLastCalledWith(["n1"]);
    expect((await fetch(`${base}/api/notifications/clear`, { method: "POST" })).status).toBe(200);
    expect(deps.clear).toHaveBeenLastCalledWith(["n1", "n2"]);
    expect((await fetch(`${base}/api/notifications/clear?before=soon`, { method: "POST" })).status).toBe(400);
    expect(deps.clear).toHaveBeenCalledTimes(2);
  });

  it("opening a conversation reads only what the opener's own list shows", () => {
    const ask = { ...sample, id: "n2", kind: "question" as const };
    const elsewhere = { ...sample, id: "n3", threadId: "t2" };
    for (const entry of [sample, ask, elsewhere]) insertNotificationLog(entry);
    const broadcast = vi.fn();
    const auth: RequestAuth = { kind: "loopback", scopes: ["admin", "client"] };
    readThreadNotifications("t1", broadcast, notificationListedFor(undefined, (_auth, entry) => entry.kind !== "question")(auth));
    expect(broadcast).toHaveBeenCalledExactlyOnceWith({ kind: "notifications.read", threadId: "t1", ids: ["n1"] });
    expect(recentNotificationLog().filter((entry) => entry.read).map((entry) => entry.id)).toEqual(["n1"]);

    readThreadNotifications("t1", broadcast, notificationListedFor(() => (threadId) => threadId !== "t1")(auth));
    expect(broadcast).toHaveBeenCalledTimes(1);
    expect(recentNotificationLog().filter((entry) => entry.read).map((entry) => entry.id)).toEqual(["n1"]);

    readThreadNotifications("t1", broadcast, notificationListedFor()(auth));
    expect(broadcast).toHaveBeenLastCalledWith({ kind: "notifications.read", threadId: "t1", ids: ["n2"] });
    expect(recentNotificationLog().filter((entry) => !entry.read).map((entry) => entry.id)).toEqual(["n3"]);
  });

  it("on a team, reads each entry as one person read it, marks it for them alone and tells only their streams", () => {
    const team = { ...sample, threadId: "team-t" };
    for (const id of ["a0", "a1", "a2"]) insertNotificationLog({ ...team, id });
    markNotificationLogRead(["a0"]);
    const auth: RequestAuth = { kind: "loopback", scopes: ["admin", "client"] };
    const as = (person: string) => notificationListedFor(undefined, undefined, () => person)(auth);
    const unreadFor = (person: string) => recentNotificationLog(undefined, person).filter((entry) => entry.threadId === "team-t" && !entry.read).map((entry) => entry.id).sort();
    const broadcast = vi.fn();
    markNotificationLogRead(["a1"], "p_ada");
    expect(unreadFor("p_ada")).toEqual(["a2"]);
    expect(unreadFor("p_cleo"), "a mark from before marks were each person's own stays read").toEqual(["a1", "a2"]);
    readThreadNotifications("team-t", broadcast, as("p_cleo"));
    expect(broadcast).toHaveBeenCalledExactlyOnceWith({ kind: "notifications.read", threadId: "team-t", ids: ["a2", "a1"] }, { person: "p_cleo" });
    expect(unreadFor("p_cleo")).toEqual([]);
    expect(unreadFor("p_ada")).toEqual(["a2"]);
    expect(recentNotificationLog().filter((entry) => entry.threadId === "team-t" && !entry.read).map((entry) => entry.id).sort(), "the one mark is untouched").toEqual(["a1", "a2"]);
    expect(Object.keys(recentNotificationLog(undefined, "p_ada")[0]!)).not.toContain("readBy");
  });

  it("forgets one person's read marks, a row they alone read included, and nobody else's", () => {
    for (const id of ["f1", "f2"]) insertNotificationLog({ ...sample, id, threadId: "leave-t" });
    markNotificationLogRead(["f1", "f2"], "p_ada");
    markNotificationLogRead(["f2"], "p_cleo");
    forgetNotificationReader("p_ada");
    const unread = (person: string) => recentNotificationLog(undefined, person).filter((entry) => entry.threadId === "leave-t" && !entry.read).map((entry) => entry.id).sort();
    expect(unread("p_ada")).toEqual(["f1", "f2"]);
    expect(unread("p_cleo")).toEqual(["f1"]);
  });

  it("clearing deletes the entries, and on a team hides them from that person alone", () => {
    for (const id of ["c1", "c2", "c3"]) insertNotificationLog({ ...sample, id, threadId: "clear-t" });
    const ids = (person?: string) => recentNotificationLog(undefined, person).filter((entry) => entry.threadId === "clear-t").map((entry) => entry.id).sort();
    clearNotificationLog(["c1"]);
    expect(ids()).toEqual(["c2", "c3"]);
    clearNotificationLog(["c2"], "p_ada");
    expect(ids("p_ada")).toEqual(["c3"]);
    expect(ids("p_cleo")).toEqual(["c2", "c3"]);
    forgetNotificationReader("p_ada");
    expect(ids("p_ada")).toEqual(["c2", "c3"]);
  });

  it("leaves other paths and methods to the next handler", async () => {
    const { base, deps } = await serve();
    expect((await fetch(`${base}/api/notifications`, { method: "POST" })).status).toBe(404);
    expect((await fetch(`${base}/api/notifications/n1/read`)).status).toBe(404);
    expect((await fetch(`${base}/api/notifications/n1/other`, { method: "POST" })).status).toBe(404);
    expect(deps.markRead).not.toHaveBeenCalled();
  });
});