char-slop/berry

multipurpose self-modifiable agentic harness

git clone https://git.t4t.associates/char-slop/berry

Charlotte Somspeed up conversation switchingd1e4a76

main
2.2 KiB43 linesraw
1import { assert, assertEquals } from "@std/assert";
2import { applyImmutable, type Op } from "@earendil-works/chord/delta";
3import { published, servePubsub, type ServerMessage } from "./pubsub.ts";
4
5Deno.test("a history's snapshot brings its newest entries first, then the older ones before any ops", async () => {
6  const sent: ServerMessage[] = [];
7  let receive = (_: { data: string }) => {};
8  const socket = {
9    readyState: WebSocket.OPEN,
10    send: (frame: string) => sent.push(JSON.parse(frame)),
11    addEventListener(type: string, listener: (event: { data: string }) => void) {
12      if (type === "message") receive = listener;
13    },
14    close() {},
15  } as unknown as WebSocket;
16  const entry = (id: number) => ({ id, text: `${id} `.repeat(1000) });
17  const history = published({ docs: {}, entries: Array.from({ length: 200 }, (_, i) => entry(i)) });
18  servePubsub(socket, { authorize: () => true, resolve: () => Promise.resolve(history.feed()) });
19  receive({ data: JSON.stringify({ t: "auth", token: "token" }) });
20  receive({ data: JSON.stringify({ t: "sub", topic: "conversation:a" }) });
21  while (!sent.some((message) => message.t === "snapshot")) await Promise.resolve();
22  history.set({ ...history.value, entries: [...history.value.entries, entry(200)] });
23
24  const [ready, first, ...rest] = sent;
25  assertEquals(ready, { t: "ready" });
26  assert(first.t === "snapshot" && first.older !== undefined);
27  const tail = (first.value as typeof history.value).entries;
28  assertEquals(tail.at(-1)!.id, 199);
29  assertEquals(first.older + tail.length, 200);
30  const older = rest.slice(0, -1);
31  assert(older.length > 1 && older.every((message) => message.t === "older"));
32  assertEquals(rest.at(-1)!.t, "ops");
33
34  let value = first.value as typeof history.value;
35  for (const message of rest) {
36    if (message.t === "older") {
37      // newest first: each chunk ends just before what came already
38      assertEquals((message.entries.at(-1) as { id: number }).id, value.entries[0].id - 1);
39      value = { ...value, entries: [...message.entries as typeof tail, ...value.entries] };
40    } else if (message.t === "ops") value = applyImmutable(value, message.ops as Op[]);
41  }
42  assertEquals(value, history.value);
43});