Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Save waiting bot edits when a relayed page is hidden (#5665)
Bugfixer 2ff0a7bbb632c
diff --git a/src/state/bot-patch-queue.ts b/src/state/bot-patch-queue.tsindex b7f06fc0e7..24a018d5a8 100644--- a/src/state/bot-patch-queue.ts+++ b/src/state/bot-patch-queue.ts@@ -1,4 +1,5 @@import type { Bot, BotAnnouncement } from "./store";+import { relayLink } from "../lib/relay-server";export type BotUpdatePatch = Partial<Pick<@@ -312,13 +313,19 @@ export function createBotPatchQueue(options: BotPatchQueueOptions): BotPatchQueu/** Browsers cancel an ordinary request when the page reloads; a keepalive one still arrives, if its body is under 64 KiB. */export const keepaliveFits = (body: string) => new TextEncoder().encode(body).length < 60_000;-/** Saves every edit still waiting at once (`flushAll`) when the page is left; returns the listeners' removal. */-export function flushWhenLeaving(queue: Pick<BotPatchQueue, "flushAll">, target: Pick<Window, "addEventListener" | "removeEventListener">): () => void {+/** Saves every edit still waiting at once (`flushAll`) when the page is left; returns the listeners' removal. On a relay+ * pairing a leaving page's save can't be kept alive (the link ends with the page), so there it also saves when the page+ * is hidden, which comes first when a phone or tab puts the page away. */+export function flushWhenLeaving(queue: Pick<BotPatchQueue, "flushAll">, target: Pick<Window, "addEventListener" | "removeEventListener">,+ page: Pick<Document, "visibilityState" | "addEventListener" | "removeEventListener"> = document): () => void {const leaving = () => queue.flushAll();+ const hidden = () => { if (page.visibilityState === "hidden" && relayLink()) queue.flushAll(); };target.addEventListener("pagehide", leaving);target.addEventListener("beforeunload", leaving);+ page.addEventListener("visibilitychange", hidden);return () => {target.removeEventListener("pagehide", leaving);target.removeEventListener("beforeunload", leaving);+ page.removeEventListener("visibilitychange", hidden);};}diff --git a/src/state/bot-patch-unload.test.ts b/src/state/bot-patch-unload.test.tsindex 77df0f4b9c..d71a253f0c 100644--- a/src/state/bot-patch-unload.test.ts+++ b/src/state/bot-patch-unload.test.ts@@ -1,7 +1,8 @@// @vitest-environment happy-domimport { act, createElement, type Dispatch } from "react";import { createRoot } from "react-dom/client";-import { afterEach, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";+import { setRelayLink } from "../lib/relay-server";import { initialState, StoreProvider, useStore, type Action, type BotAnnouncement } from "./store";(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -51,3 +52,50 @@ it("sends only the leaving page's save as keepalive, so ordinary saves never useexpect(keepalive.map(Boolean)).toEqual([false, true]);act(() => root.unmount());});++describe("on a relay pairing", () => {+ const hide = (state: DocumentVisibilityState) => {+ Object.defineProperty(document, "visibilityState", { configurable: true, get: () => state });+ document.dispatchEvent(new Event("visibilitychange"));+ };+ afterEach(() => { setRelayLink(null); Reflect.deleteProperty(document, "visibilityState"); });++ async function mount(relayed: boolean) {+ vi.useFakeTimers();+ initialState.bots = [{ ...bot, messages: [] }];+ const patches: string[] = [];+ const answer = (path: string, method?: string, body?: string) => {+ if (path === "/api/bots/bot" && method === "PATCH") patches.push(String(body));+ return new Response(JSON.stringify(path === "/api/bots/bot" ? { bot } : {}));+ };+ vi.stubGlobal("fetch", vi.fn<typeof fetch>(async (path, init) => answer(String(path), init?.method, String(init?.body))));+ if (relayed) setRelayLink({ fetch: async (path, request) => answer(path, request?.method, new TextDecoder().decode(request?.body ?? undefined)), close: () => {} });+ let dispatch!: Dispatch<Action>;+ function Capture() { dispatch = useStore().dispatch; return null; }+ const root = createRoot(document.createElement("div"));+ await act(async () => root.render(createElement(StoreProvider, null, createElement(Capture))));+ act(() => dispatch({ type: "updateBot", botId: "bot", patch: { soul: "written on a phone away from home." } }));+ return { patches, root };+ }++ it("saves a waiting edit as soon as the page is hidden, while the link still carries it", async () => {+ const { patches, root } = await mount(true);+ hide("hidden");+ await act(async () => { for (let i = 0; i < 20; i++) await Promise.resolve(); });+ expect(patches.map((body) => JSON.parse(body).soul)).toEqual(["written on a phone away from home."]);+ act(() => root.unmount());+ });++ it("leaves the save's pause alone when the page is hidden off the relay, or shown again", async () => {+ const { patches, root } = await mount(false);+ hide("hidden");+ setRelayLink({ fetch: async () => new Response("{}"), close: () => {} });+ hide("visible");+ await act(async () => { for (let i = 0; i < 20; i++) await Promise.resolve(); });+ expect(patches).toEqual([]);+ setRelayLink(null);+ await act(async () => { await vi.advanceTimersByTimeAsync(1_000); });+ expect(patches.map((body) => JSON.parse(body).soul)).toEqual(["written on a phone away from home."]);+ act(() => root.unmount());+ });+});