Skip to content

Open-source AI coworkers that each get a computer of their own: a browser, files and tools, with every action decided before it happens and recorded after. Bring any AG-UI agent.

11.9 KB
Raw Blame
import { describe, expect, test } from "bun:test";
import type {
  AgentChannel,
  ChannelPage,
  ChannelSummary,
} from "../src/lib/channels/queries";
import {
  applyChannelEvent,
  applyChannelWork,
  type ChannelActivityEvent,
} from "../src/lib/channels/use-channel-events";

/** A minimal but fully-typed channel summary, so tests build real objects rather than casts. */
function channel(
  id: string,
  overrides: Partial<ChannelSummary> = {},
): ChannelSummary {
  return {
    id,
    name: id,
    agentIds: [],
    threadId: `thread-${id}`,
    active: true,
    summary: null,
    lastMessage: null,
    lastMessageAt: null,
    lastMessageAgentId: null,
    createdAt: "2024-01-01T00:00:00.000Z",
    pinned: false,
    lastReadAt: null,
    ...overrides,
  };
}

function cache(...pages: ChannelSummary[][]) {
  return {
    pages: pages.map(
      (channels): ChannelPage => ({ channels, nextCursor: null }),
    ),
    pageParams: pages.map(() => ""),
  };
}

function event(
  overrides: Partial<ChannelActivityEvent> & { channelId: string },
): ChannelActivityEvent {
  return {
    lastMessage: null,
    lastMessageAt: null,
    lastMessageAgentId: null,
    ...overrides,
  };
}

describe("an ordinary activity event", () => {
  test("patches the row inside the page that holds it and re-sorts that page", () => {
    const data = cache([
      channel("a", { lastMessageAt: "2024-03-01T00:00:00.000Z" }),
      channel("b"),
    ]);

    const patched = applyChannelEvent(
      data,
      event({
        channelId: "b",
        lastMessage: "Said something.",
        lastMessageAt: "2024-04-01T00:00:00.000Z",
      }),
    );

    expect(patched).not.toBe("unknown");
    if (patched === "unknown") return;
    expect(patched.pages[0]?.channels.map((row) => row.id)).toEqual(["b", "a"]);
    expect(patched.pages[0]?.channels[0]?.lastMessage).toBe("Said something.");
  });

  test("is unknown when no page holds the channel, so the caller refetches", () => {
    expect(
      applyChannelEvent(cache([channel("a")]), event({ channelId: "z" })),
    ).toBe("unknown");
  });
});

/**
 * A channel somebody deleted in another tab, or on another replica.
 *
 * The tab that issued the delete moves itself; every other tab only ever hears about it here, so
 * without this the row stays on their roster until something else makes them refetch.
 */
describe("a deleted channel", () => {
  test("is removed from the page that held it", () => {
    const data = cache([channel("a"), channel("b")], [channel("c")]);

    const patched = applyChannelEvent(
      data,
      event({ channelId: "b", deleted: true }),
    );

    expect(patched).not.toBe("unknown");
    if (patched === "unknown") return;
    expect(patched.pages[0]?.channels.map((row) => row.id)).toEqual(["a"]);
    // The other page is untouched, object identity included, so its rows do not re-render.
    expect(patched.pages[1]).toBe(data.pages[1]);
  });

  test("is never spread onto the row instead of removing it", () => {
    const patched = applyChannelEvent(
      cache([channel("a")]),
      event({ channelId: "a", deleted: true }),
    );

    expect(patched).not.toBe("unknown");
    if (patched === "unknown") return;
    // The failure this guards is a row left on the roster carrying `deleted: true`, which renders
    // as an ordinary channel whose every query now 404s.
    expect(patched.pages[0]?.channels).toEqual([]);
  });

  test("changes nothing when this cache never had the channel", () => {
    const data = cache([channel("a")]);

    // Unlike an ordinary event, an unknown id here is not a stale roster: the channel is already
    // gone from this cache, so there is nothing to patch and nothing to refetch for.
    expect(
      applyChannelEvent(data, event({ channelId: "z", deleted: true })),
    ).toBe(data);
  });
});

/**
 * A pin this person made in one of their own tabs.
 *
 * Scoped to them by the server, so arriving here means it is the reader's own pin.
 */
describe("a pin", () => {
  test("patches only the pinned flag, leaving the last message alone", () => {
    const data = cache([
      channel("a", {
        lastMessage: "Said something.",
        lastMessageAt: "2024-04-01T00:00:00.000Z",
        lastMessageAgentId: "agent-1",
      }),
    ]);

    const patched = applyChannelEvent(
      data,
      event({ channelId: "a", pinned: true }),
    );

    expect(patched).not.toBe("unknown");
    if (patched === "unknown") return;
    expect(patched.pages[0]?.channels[0]).toEqual({
      ...(data.pages[0]?.channels[0] as ChannelSummary),
      pinned: true,
    });
  });

  test("unpins the same way", () => {
    const patched = applyChannelEvent(
      cache([channel("a", { pinned: true })]),
      event({ channelId: "a", pinned: false }),
    );

    expect(patched).not.toBe("unknown");
    if (patched === "unknown") return;
    expect(patched.pages[0]?.channels[0]?.pinned).toBe(false);
  });

  test("returns the same cache when the row already says so", () => {
    const data = cache([channel("a", { pinned: true })]);

    // A duplicate, or the tab that made the pin hearing its own event back. Identity preserved, so
    // React re-renders nothing at all.
    expect(
      applyChannelEvent(data, event({ channelId: "a", pinned: true })),
    ).toBe(data);
  });
});

/**
 * A busy signal: a turn started or ended in the channel.
 *
 * Server-side headless work — a handoff hop, a relay — that no browser streamed, surfaced on the
 * roster as a working indicator. Message-less on purpose: it must not disturb the preview or the
 * order the way an ordinary activity event does.
 */
describe("a busy signal", () => {
  test("patches only the busy flag, leaving the last message and order alone", () => {
    const data = cache([
      channel("a", {
        lastMessage: "Said something.",
        lastMessageAt: "2024-04-01T00:00:00.000Z",
        lastMessageAgentId: "agent-1",
      }),
      channel("b", { lastMessageAt: "2024-05-01T00:00:00.000Z" }),
    ]);

    const patched = applyChannelEvent(
      data,
      event({ channelId: "a", busy: true }),
    );

    expect(patched).not.toBe("unknown");
    if (patched === "unknown") return;
    // Only `busy` changed on row a; its message survives, and b did not jump ahead of it.
    expect(patched.pages[0]?.channels.map((row) => row.id)).toEqual(["a", "b"]);
    expect(patched.pages[0]?.channels[0]).toEqual({
      ...(data.pages[0]?.channels[0] as ChannelSummary),
      busy: true,
    });
  });

  test("clears the same way", () => {
    const patched = applyChannelEvent(
      cache([channel("a", { busy: true })]),
      event({ channelId: "a", busy: false }),
    );

    expect(patched).not.toBe("unknown");
    if (patched === "unknown") return;
    expect(patched.pages[0]?.channels[0]?.busy).toBe(false);
  });

  test("returns the same cache when the row already says so", () => {
    const data = cache([channel("a", { busy: true })]);

    expect(applyChannelEvent(data, event({ channelId: "a", busy: true }))).toBe(
      data,
    );
  });
});

/**
 * What the channel is waiting on, carried whole on every busy event and alone on a settle.
 *
 * Replaced rather than merged, so the newest event is the answer and a retried hop never shows
 * twice. The sidebar lights from it as well as from `busy`, so a hop still running after a turn
 * ended keeps the row lit.
 */
describe("a work list", () => {
  const work = [
    {
      kind: "handoff" as const,
      key: "hop-1",
      botId: "ana",
      botName: "Ana",
      since: "2026-10-26T10:00:00.000Z",
    },
  ];

  test("rides on a busy event and patches only the busy flag and the list", () => {
    const data = cache([
      channel("a", { lastMessage: "Said something." }),
      channel("b"),
    ]);

    const patched = applyChannelEvent(
      data,
      event({ channelId: "a", busy: true, work }),
    );

    expect(patched).not.toBe("unknown");
    if (patched === "unknown") return;
    expect(patched.pages[0]?.channels[0]).toEqual({
      ...(data.pages[0]?.channels[0] as ChannelSummary),
      busy: true,
      work,
    });
  });

  test("a settle replaces the list and leaves the busy flag as it was", () => {
    const patched = applyChannelEvent(
      cache([channel("a", { busy: true, work })]),
      event({ channelId: "a", work: [] }),
    );

    expect(patched).not.toBe("unknown");
    if (patched === "unknown") return;
    expect(patched.pages[0]?.channels[0]?.busy).toBe(true);
    expect(patched.pages[0]?.channels[0]?.work).toEqual([]);
  });

  test("the same list again changes nothing", () => {
    const data = cache([channel("a", { busy: true, work })]);

    expect(
      applyChannelEvent(
        data,
        event({ channelId: "a", busy: true, work: [...work] }),
      ),
    ).toBe(data);
  });

  test("an older list arriving late does not undo a newer one", () => {
    const settled = applyChannelEvent(
      cache([channel("a", { busy: true, work })]),
      event({
        channelId: "a",
        work: [],
        workAt: "2026-10-26T10:00:02.000000Z",
      }),
    );
    if (settled === "unknown") throw new Error("expected a patch");

    const late = applyChannelEvent(
      settled,
      event({
        channelId: "a",
        busy: false,
        work,
        workAt: "2026-10-26T10:00:01.000000Z",
      }),
    );

    if (late === "unknown") throw new Error("expected a patch");
    // The busy flag still moves; the list read before the settle is ignored.
    expect(late.pages[0]?.channels[0]?.busy).toBe(false);
    expect(late.pages[0]?.channels[0]?.work).toEqual([]);
  });

  test("the open conversation's read ignores an older list too", () => {
    const held: AgentChannel = {
      id: "a",
      name: "A",
      agentIds: [],
      threadId: "thread-a",
      active: true,
      lastMessageAt: null,
      work: [],
      workAt: "2026-10-26T10:00:02.000000Z",
    };

    expect(
      applyChannelWork(
        held,
        event({ channelId: "a", work, workAt: "2026-10-26T10:00:01.000000Z" }),
      ),
    ).toBe(held);
    expect(
      applyChannelWork(
        held,
        event({ channelId: "a", work, workAt: "2026-10-26T10:00:03.000000Z" }),
      )?.work,
    ).toEqual(work);
  });
});

/**
 * A conversation the server has just named.
 *
 * Written by a sweep some seconds after the message that prompted it, so it arrives on its own long
 * after that message was announced.
 */
describe("a summary", () => {
  test("patches only the summary, leaving the last message alone", () => {
    const data = cache([
      channel("a", {
        lastMessage: "Said something.",
        lastMessageAt: "2024-04-01T00:00:00.000Z",
        lastMessageAgentId: "agent-1",
      }),
    ]);

    const patched = applyChannelEvent(
      data,
      event({ channelId: "a", summary: "Expense categories" }),
    );

    expect(patched).not.toBe("unknown");
    if (patched === "unknown") return;
    expect(patched.pages[0]?.channels[0]).toEqual({
      ...(data.pages[0]?.channels[0] as ChannelSummary),
      summary: "Expense categories",
    });
  });

  test("does not move the row it names", () => {
    // Naming a conversation is not something anybody said in it. A row that jumped to the top
    // seconds after the message that put it there would read as a second message arriving.
    const data = cache([
      channel("recent", { lastMessageAt: "2024-04-02T00:00:00.000Z" }),
      channel("older", { lastMessageAt: "2024-04-01T00:00:00.000Z" }),
    ]);

    const patched = applyChannelEvent(
      data,
      event({ channelId: "older", summary: "Something older" }),
    );

    expect(patched).not.toBe("unknown");
    if (patched === "unknown") return;
    expect(patched.pages[0]?.channels.map((row) => row.id)).toEqual([
      "recent",
      "older",
    ]);
  });

  test("returns the same cache when the row already says so", () => {
    const data = cache([channel("a", { summary: "Expense categories" })]);

    expect(
      applyChannelEvent(
        data,
        event({ channelId: "a", summary: "Expense categories" }),
      ),
    ).toBe(data);
  });
});