Skip to content

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

fix(inbox): fence snapshots against later row mutations

Sebastian B339df65ba178
diff --git a/src/state/inbox.test.ts b/src/state/inbox.test.ts
new file mode 100644
index 0000000000..9716baa558
--- /dev/null
+++ b/src/state/inbox.test.ts
@@ -0,0 +1,117 @@
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import type { InboxView } from "../../shared/inbox";
+import { inboxView, messageRow, reportRow } from "@/testing/inbox-fixture";
+import { api } from "./api";
+import { currentInbox, doneInboxRow, readInboxRow, refreshInbox, replyToInboxRow, setInboxView } from "./inbox";
+
+vi.mock("./api", () => ({ api: vi.fn() }));
+
+type Request = { path: string; resolve: (view: InboxView) => void; reject: (error: Error) => void; settled?: boolean };
+let requests: Request[];
+const done = inboxView([{ ...messageRow, unread: false, tab: "done" }]);
+const flush = async () => { for (let n = 0; n < 10; n++) await Promise.resolve(); };
+const reply = async (index: number, view: InboxView) => {
+ requests[index]!.settled = true;
+ requests[index]!.resolve(view);
+ await flush();
+};
+
+beforeEach(() => {
+ requests = [];
+ vi.mocked(api).mockImplementation((path) => new Promise<InboxView>((resolve, reject) => {
+ requests.push({ path, resolve, reject });
+ }));
+ setInboxView(inboxView([messageRow]));
+});
+afterEach(async () => {
+ for (let n = 0; n < requests.length; n++) {
+ if (!requests[n]!.settled) await reply(n, done);
+ }
+ setInboxView(null);
+ vi.clearAllMocks();
+});
+
+it("keeps Done when an older read response arrives last, then reconciles the discarded snapshot", async () => {
+ readInboxRow(messageRow);
+ doneInboxRow(messageRow);
+ await reply(1, done);
+ await reply(0, inboxView([{ ...messageRow, unread: false }]));
+ expect(currentInbox()?.rows[0]?.tab).toBe("done");
+ expect(requests[2]?.path).toBe("/api/inbox");
+ await reply(2, inboxView([{ ...done.rows[0]!, text: "Fresh server text" }]));
+ expect(currentInbox()?.rows[0]?.text).toBe("Fresh server text");
+});
+
+it("discards a GET started before a successful mutation and reads again", async () => {
+ const loading = refreshInbox();
+ doneInboxRow(messageRow);
+ await reply(1, done);
+ await reply(0, inboxView([messageRow]));
+ expect(currentInbox()?.rows[0]?.tab).toBe("done");
+ expect(requests[2]?.path).toBe("/api/inbox");
+ await reply(2, done);
+ await loading;
+});
+
+it("keeps a newer refresh when an older mutation response arrives afterward", async () => {
+ readInboxRow(messageRow);
+ const loading = refreshInbox();
+ await reply(1, inboxView([{ ...messageRow, unread: false, text: "Newer text" }]));
+ await loading;
+ await reply(0, inboxView([{ ...messageRow, unread: false }]));
+ expect(currentInbox()?.rows[0]?.text).toBe("Newer text");
+ expect(requests[2]?.path).toBe("/api/inbox");
+});
+
+it("overlays pending Done on a GET and refreshes after that mutation settles", async () => {
+ doneInboxRow(messageRow);
+ const loading = refreshInbox();
+ await reply(1, inboxView([messageRow]));
+ await loading;
+ expect(currentInbox()?.rows[0]).toMatchObject({ tab: "done", unread: false });
+ await reply(0, done);
+ expect(requests[2]?.path).toBe("/api/inbox");
+});
+
+it("keeps another row's pending read when a Done snapshot lands", async () => {
+ setInboxView(inboxView([messageRow, reportRow]));
+ readInboxRow(messageRow);
+ doneInboxRow(reportRow);
+ await reply(1, inboxView([messageRow, { ...reportRow, tab: "done" }]));
+ expect(currentInbox()?.rows[0]?.unread).toBe(false);
+ expect(currentInbox()?.rows[1]?.tab).toBe("done");
+});
+
+it("discards a GET started during a mutation that completed before the GET landed", async () => {
+ doneInboxRow(messageRow);
+ const loading = refreshInbox();
+ await reply(0, done);
+ await reply(1, inboxView([messageRow]));
+ expect(currentInbox()?.rows[0]?.tab).toBe("done");
+ expect(requests[2]?.path).toBe("/api/inbox");
+ await reply(2, done);
+ await loading;
+});
+
+it("discards a GET that predates a successful message reply", async () => {
+ const loading = refreshInbox();
+ const sending = replyToInboxRow(inboxView(), messageRow, "Thanks");
+ await reply(1, done);
+ await sending;
+ await reply(0, inboxView([{ ...messageRow, text: "Old snapshot" }]));
+ expect(currentInbox()?.rows[0]?.text).toBe(messageRow.text);
+ expect(requests[2]?.path).toBe("/api/inbox");
+ await reply(2, done);
+ await loading;
+ expect(currentInbox()?.rows[0]?.tab).toBe("done");
+});
+
+it("removes a failed mutation's overlay and reconciles from the server", async () => {
+ doneInboxRow(messageRow);
+ requests[0]!.settled = true;
+ requests[0]!.reject(new Error("offline"));
+ await flush();
+ expect(requests[1]?.path).toBe("/api/inbox");
+ await reply(1, inboxView([messageRow]));
+ expect(currentInbox()?.rows[0]).toMatchObject({ tab: "info", unread: true });
+});
diff --git a/src/state/inbox.ts b/src/state/inbox.ts
index 39cb37229d..63cbdbb9d7 100644
--- a/src/state/inbox.ts
+++ b/src/state/inbox.ts
@@ -34,6 +34,17 @@ export const setInboxView = list.set;
let reading: Promise<void> | null = null;
let readAgain = false;
+let revision = 0;
+const pending = new Map<number, { id: string; patch: Partial<InboxRow> }>();
+const replaceList = (view: InboxView) => {
+ const rows = view.rows.map((row) => {
+ for (const change of pending.values()) {
+ if (change.id === row.id) row = { ...row, ...change.patch };
+ }
+ return row;
+ });
+ list.set({ ...view, rows });
+};
/** Reads the list now, or once more after the read on its way, so the newest answer always lands last. */
export function refreshInbox(): Promise<void> {
if (reading) { readAgain = true; return reading; }
@@ -41,8 +52,10 @@ export function refreshInbox(): Promise<void> {
try {
do {
readAgain = false;
+ const request = ++revision;
const view = await api<InboxView>("/api/inbox", { background: true }).catch(() => null);
- if (view && Array.isArray(view.rows)) list.set(view);
+ if (request !== revision) { readAgain = true; continue; }
+ if (view && Array.isArray(view.rows)) replaceList(view);
} while (readAgain);
} finally {
reading = null;
@@ -64,29 +77,38 @@ const patchRow = (id: string, patch: Partial<InboxRow>) => {
if (view) list.set({ ...view, rows: view.rows.map((row) => (row.id === id ? { ...row, ...patch } : row)) });
};
-async function mark(id: string, what: "read" | "done"): Promise<void> {
+async function mark(id: string, what: "read" | "done", patch: Partial<InboxRow>): Promise<void> {
+ const request = ++revision;
+ pending.set(request, { id, patch });
+ patchRow(id, patch);
const view = await api<InboxView>(`/api/inbox/${id}/${what}`, { method: "POST", background: true }).catch(() => null);
- if (view && Array.isArray(view.rows)) list.set(view);
+ const current = request === revision;
+ ++revision;
+ pending.delete(request);
+ if (current && view && Array.isArray(view.rows)) replaceList(view);
else void refreshInbox();
}
/** The person read a line: it is no longer bold. */
export function readInboxRow(row: Pick<InboxRow, "id" | "unread">): void {
if (!row.unread) return;
- patchRow(row.id, { unread: false });
- void mark(row.id, "read");
+ void mark(row.id, "read", { unread: false });
}
/** The person is done with a line of news: it moves to Done. */
export function doneInboxRow(row: Pick<InboxRow, "id">): void {
- patchRow(row.id, { tab: "done", unread: false });
- void mark(row.id, "done");
+ void mark(row.id, "done", { tab: "done", unread: false });
}
/** A reply to a line of news that waits on one: it goes back where the line came from, as a Reply in the chat does. */
export async function replyToInboxRow(view: Pick<InboxView, "botId" | "threadId">, row: Pick<InboxRow, "id">, text: string): Promise<void> {
- await api(`/api/bots/${view.botId}/messages`, { method: "POST", body: JSON.stringify({ text, threadId: view.threadId, replyToId: row.id, sendId: crypto.randomUUID() }) });
- void refreshInbox();
+ ++revision;
+ try {
+ await api(`/api/bots/${view.botId}/messages`, { method: "POST", body: JSON.stringify({ text, threadId: view.threadId, replyToId: row.id, sendId: crypto.randomUUID() }) });
+ } finally {
+ ++revision;
+ void refreshInbox();
+ }
}
export interface InboxPanelState { open: boolean; tab: InboxTab; reading: string | null }