Skip to content

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

2.3 KB
Raw Blame
import { describe, expect, it } from "vitest";
import { RoomMemberLock } from "./room-member-lock.ts";

describe("RoomMemberLock", () => {
  it("lets one bot hold several room threads at once", () => {
    const lock = new RoomMemberLock();
    lock.claim("scout", "thread-a");
    lock.claim("scout", "thread-a");
    lock.claim("scout", "thread-b");
    expect(lock.threads("scout").sort()).toEqual(["thread-a", "thread-b"]);
    expect(lock.heldElsewhere("scout", "thread-a")).toBe(true);
    lock.release("scout", "thread-b");
    expect(lock.heldElsewhere("scout", "thread-a")).toBe(false);
    expect(lock.heldElsewhere("pixel", "thread-b")).toBe(false);
  });

  it("releases only that thread's claim and wakes waiters after the claim is gone", () => {
    const lock = new RoomMemberLock();
    lock.claim("scout", "thread-a");
    const woken: Array<{ botId: string; threads: string[] }> = [];
    const stop = lock.onRelease((botId) => woken.push({ botId, threads: lock.threads(botId) }));
    expect(lock.release("scout", "thread-b")).toBe(false);
    expect(woken).toEqual([]);
    expect(lock.release("scout", "thread-a")).toBe(true);
    expect(woken).toEqual([{ botId: "scout", threads: [] }]);
    expect(lock.release("scout", "thread-a")).toBe(false);
    stop();
    lock.claim("scout", "thread-b");
    lock.release("scout", "thread-b");
    expect(woken).toHaveLength(1);
  });

  it("drops every claim of a thread whose drive ended", () => {
    const lock = new RoomMemberLock();
    lock.claim("scout", "thread-a");
    lock.claim("scout", "thread-b");
    lock.claim("pixel", "thread-a");
    lock.claim("echo", "thread-b");
    const woken: string[] = [];
    lock.onRelease((botId) => woken.push(botId));
    expect(lock.releaseThread("thread-a").sort()).toEqual(["pixel", "scout"]);
    expect(woken.sort()).toEqual(["pixel", "scout"]);
    expect(lock.threads("scout")).toEqual(["thread-b"]);
    expect(lock.threads("echo")).toEqual(["thread-b"]);
  });

  it("keeps notifying when one listener throws", () => {
    const lock = new RoomMemberLock();
    lock.claim("scout", "thread-a");
    const woken: string[] = [];
    lock.onRelease(() => { throw new Error("listener failed"); });
    lock.onRelease((botId) => woken.push(botId));
    lock.release("scout", "thread-a");
    expect(woken).toEqual(["scout"]);
  });
});