Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Web app on a relay pairing: send api() requests and live events through RelayLink
Bugfixer 2a82ba00ed36b
diff --git a/src/lib/live-events.ts b/src/lib/live-events.tsindex 940fdf0b89..bd564082a6 100644--- a/src/lib/live-events.ts+++ b/src/lib/live-events.ts@@ -1,6 +1,7 @@// EventSource hides SSE comment keepalives, so liveness comes from the server's visible `ping` frame.import type { ServerFrame } from "../../shared/wire";import { cloudAsleep, markCloudAsleep, onCloudPower, sleepingFrame } from "./cloud-power";+import { relayEventSource, relayLink } from "./relay-server";import { recordBotTextMessage, recordRuntimeEvent } from "./voice-latency-probe";import { noteTurnEvent } from "@/state/turn-status";import { forgetLiveReplies, noteLiveReplyEvent, noteLiveReplyMessage } from "@/state/live-reply";@@ -156,22 +157,23 @@ function browserPlatform(overrides: Partial<LiveEventsPlatform>): LiveEventsPlatconst NativeEventSource = globalThis.EventSource;const createEventSource =overrides.createEventSource ??- (!NativeEventSource- ? undefined- : (url: string) => {- const native = new NativeEventSource(url);- const adapter: LiveEventSourceLike = {- onopen: null,- onerror: null,- onmessage: null,- close: () => native.close(),- };- native.onopen = () => adapter.onopen?.();- native.onerror = () => adapter.onerror?.();- native.onmessage = (event) => adapter.onmessage?.(event);- return adapter;- });- if (!createEventSource) return null;+ ((url: string) => {+ const relay = relayLink();+ if (relay) return relayEventSource(relay, url);+ if (!NativeEventSource) throw new Error("no EventSource");+ const native = new NativeEventSource(url);+ const adapter: LiveEventSourceLike = {+ onopen: null,+ onerror: null,+ onmessage: null,+ close: () => native.close(),+ };+ native.onopen = () => adapter.onopen?.();+ native.onerror = () => adapter.onerror?.();+ native.onmessage = (event) => adapter.onmessage?.(event);+ return adapter;+ });+ if (!overrides.createEventSource && !NativeEventSource && !relayLink()) return null;const browserWindow = globalThis.window;const browserDocument = globalThis.document;diff --git a/src/lib/relay-server.e2e.test.ts b/src/lib/relay-server.e2e.test.tsnew file mode 100644index 0000000000..11e512d99d--- /dev/null+++ b/src/lib/relay-server.e2e.test.ts@@ -0,0 +1,61 @@+// The web app's own request helper and live events on a relay pairing, against the real `serve --relay` server.+import { afterAll, beforeAll, describe, expect, it, onTestFinished } from "vitest";++import { waitFor } from "../../companion/test/e2e/wait.ts";+import { startPhoneRelayRig, type PhoneRelayRig } from "../../server/testing/phone-relay-rig.ts";+import { api, ApiError } from "../state/api.ts";+import { fromB64u } from "./e2e/bytes.ts";+import { pairThroughRelay, RelayLink, relayRoute } from "./e2e/relay-link.ts";+import { openLiveEvents } from "./live-events.ts";+import { setRelayLink } from "./relay-server.ts";++let rig: PhoneRelayRig;+let base: string;++beforeAll(async () => {+ rig = await startPhoneRelayRig();+ ({ base } = await rig.boot());+}, 60_000);++afterAll(async () => {+ setRelayLink(null);+ await rig?.close();+});++const owner = async (path: string, init: RequestInit = {}) => {+ const res = await fetch(`${base}${path}`, { ...init, headers: { "content-type": "application/json", ...init.headers } });+ return { status: res.status, body: (await res.json()) as Record<string, any> };+};++describe("the web app on a relay pairing", () => {+ it("sends its api requests and opens its live events through the relay", async () => {+ await waitFor(async () => (await owner("/api/auth/pairing")).body.relay?.relay === "connected", 15_000);+ const minted = await owner("/api/auth/pairing", { method: "POST", body: JSON.stringify({ scopes: ["client"], label: "Web" }) });+ const descriptor = JSON.parse(new TextDecoder().decode(fromB64u(new URL(minted.body.inviteUrl).searchParams.get("e2e")!)!));+ const nodeUrl = () => `${rig.relay.url}/v1/phone`;+ const paired = await waitFor(() => pairThroughRelay(relayRoute(descriptor, { nodeUrl })!, minted.body.credential, "Phone browser").catch(() => null), 8_000);+ setRelayLink(new RelayLink(relayRoute(paired.descriptor, { nodeUrl })!, paired.token));+ onTestFinished(() => setRelayLink(null));++ // Relative paths: with no relay they would have no server to reach in this test.+ const who = await waitFor(() => api<{ kind: string; id: string; scopes: string[] }>("/api/auth/session").catch(() => null), 8_000);+ expect(who).toMatchObject({ kind: "session", scopes: ["client"] });+ expect(await api("/api/bots")).toEqual((await owner("/api/bots")).body);+ const refused = await api("/api/auth/pairing", { method: "POST", body: "{}" }).catch((error: unknown) => error);+ expect(refused).toBeInstanceOf(ApiError);+ expect((refused as ApiError).status).toBe(403);++ let opened = 0;+ let snapshots = 0;+ const stop = openLiveEvents(+ { onOpen: () => (opened += 1), onFrame: () => {}, onSnapshotRequired: async () => ((snapshots += 1), true) },+ { isVisible: () => true, isOnline: () => true },+ );+ onTestFinished(stop);+ // The server's first frame, a fresh `hello`, asks for a snapshot: the stream's events reached the page.+ await waitFor(() => (opened && snapshots ? true : null), 8_000);+ stop();++ expect((await owner(`/api/auth/sessions/${who.id}`, { method: "DELETE" })).status).toBe(200);+ }, 60_000);+});diff --git a/src/lib/relay-server.test.ts b/src/lib/relay-server.test.tsnew file mode 100644index 0000000000..b8d60f089c--- /dev/null+++ b/src/lib/relay-server.test.ts@@ -0,0 +1,223 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import type { RelayLink, RelayRequest } from "./e2e/relay-link";+import { openLiveEvents } from "./live-events";+import { api } from "@/state/api";+import { relayEventSource, serverFetch, setRelayLink } from "./relay-server";++type Sent = { path: string; request: RelayRequest };++/** A RelayLink that answers each request with `answer`, recording what it was asked. */+function fakeLink(answer: (sent: Sent) => Response | Promise<Response>) {+ const sent: Sent[] = [];+ const link = {+ fetch: vi.fn(async (path: string, request: RelayRequest = {}) => {+ const one = { path, request };+ sent.push(one);+ return answer(one);+ }),+ close: vi.fn(),+ };+ return { link: link as unknown as RelayLink, sent, close: link.close };+}++/** An event stream whose chunks the test pushes. */+function eventStream() {+ let controller!: ReadableStreamDefaultController<Uint8Array>;+ const cancelled = vi.fn();+ const body = new ReadableStream<Uint8Array>({+ start: (c) => {+ controller = c;+ },+ cancel: cancelled,+ });+ const encoder = new TextEncoder();+ return {+ response: new Response(body, { headers: { "content-type": "text/event-stream" } }),+ push: (text: string) => controller.enqueue(encoder.encode(text)),+ end: () => controller.close(),+ cancelled,+ };+}++const tick = () => new Promise((resolve) => setTimeout(resolve, 0));++afterEach(() => {+ setRelayLink(null);+ vi.unstubAllGlobals();+});++describe("serverFetch", () => {+ it("is a plain fetch while no relay link is set, and for paths outside /api", async () => {+ const plain = vi.fn(async (_path: string) => new Response("plain"));+ vi.stubGlobal("fetch", plain);+ await serverFetch("/api/bots");+ const { link, sent } = fakeLink(() => new Response("relayed"));+ setRelayLink(link);+ await serverFetch("/apiary");+ await serverFetch("/assets/app.js");+ expect(plain.mock.calls.map(([path]) => path)).toEqual(["/api/bots", "/apiary", "/assets/app.js"]);+ expect(sent).toEqual([]);+ });++ it("sends /api requests through the link, with the method, headers and body as bytes", async () => {+ const plain = vi.fn();+ vi.stubGlobal("fetch", plain);+ const { link, sent } = fakeLink(() => Response.json({ ok: true }));+ setRelayLink(link);++ const reply = await serverFetch("/api/bots?x=1", {+ method: "post",+ headers: { "content-type": "application/json", "x-omb-background": "1" },+ body: JSON.stringify({ name: "Ada" }),+ });+ expect(await reply.json()).toEqual({ ok: true });+ expect(plain).not.toHaveBeenCalled();+ expect(sent[0].path).toBe("/api/bots?x=1");+ expect(sent[0].request.method).toBe("POST");+ const headers = new Headers(sent[0].request.headers);+ expect(headers.get("content-type")).toBe("application/json");+ expect(headers.get("x-omb-background")).toBe("1");+ expect(new TextDecoder().decode(sent[0].request.body as Uint8Array)).toBe('{"name":"Ada"}');++ await serverFetch("/api/auth/session");+ expect(sent[1].request).toMatchObject({ method: "GET", body: null });+ });++ it("gives a form upload its multipart content type and bytes", async () => {+ const { link, sent } = fakeLink(() => new Response(null, { status: 204 }));+ setRelayLink(link);+ const form = new FormData();+ form.set("file", new Blob(["hello"], { type: "text/plain" }), "a.txt");+ await serverFetch("/api/files", { method: "POST", body: form });+ const type = new Headers(sent[0].request.headers).get("content-type") ?? "";+ expect(type).toMatch(/^multipart\/form-data; boundary=/);+ const text = new TextDecoder().decode(sent[0].request.body as Uint8Array);+ expect(text).toContain('filename="a.txt"');+ expect(text).toContain("hello");+ });++ it("passes the caller's signal to the link", async () => {+ const { link, sent } = fakeLink(() => new Response("{}"));+ setRelayLink(link);+ const stop = new AbortController();+ await serverFetch("/api/bots", { signal: stop.signal });+ expect(sent[0].request.signal).toBe(stop.signal);+ });++ it("closes a link that is replaced or cleared", () => {+ const first = fakeLink(() => new Response());+ const second = fakeLink(() => new Response());+ setRelayLink(first.link);+ setRelayLink(first.link);+ expect(first.close).not.toHaveBeenCalled();+ setRelayLink(second.link);+ expect(first.close).toHaveBeenCalledTimes(1);+ setRelayLink(null);+ expect(second.close).toHaveBeenCalledTimes(1);+ });+});++describe("api through a relay link", () => {+ it("sends the app's JSON requests through the link", async () => {+ const plain = vi.fn();+ vi.stubGlobal("fetch", plain);+ const { link, sent } = fakeLink(() => Response.json([{ id: "b1" }]));+ setRelayLink(link);+ expect(await api("/api/bots")).toEqual([{ id: "b1" }]);+ expect(plain).not.toHaveBeenCalled();+ expect(sent.map(({ path }) => path)).toEqual(["/api/bots"]);+ });+});++describe("relayEventSource", () => {+ it("opens, then hands each unnamed or message event to onmessage across chunk and line-ending splits", async () => {+ const stream = eventStream();+ const { link, sent } = fakeLink(() => stream.response);+ const source = relayEventSource(link, "/api/events?since=7");+ const opened = vi.fn();+ const messages: Array<{ data: string; lastEventId?: string }> = [];+ source.onopen = opened;+ source.onmessage = (event) => messages.push(event);+ source.onerror = vi.fn();++ await tick();+ expect(sent[0].path).toBe("/api/events?since=7");+ expect(new Headers(sent[0].request.headers).get("accept")).toBe("text/event-stream");+ expect(opened).toHaveBeenCalledTimes(1);++ stream.push(": keepalive\n\nid: 8\ndata: {\"kind\":\"pi");+ stream.push("ng\"}\n\nevent: other\ndata: skipped\n\ndata: a\r\ndata:b\r");+ stream.push("\n\r\nretry: 10\nid: 9\ndata\n\n");+ await tick();+ expect(messages).toEqual([+ { data: '{"kind":"ping"}', lastEventId: "8" },+ { data: "a\nb", lastEventId: "8" },+ { data: "", lastEventId: "9" },+ ]);+ expect(source.onerror).not.toHaveBeenCalled();+ });++ it("reports onerror once when the stream ends, so live events reconnect", async () => {+ const stream = eventStream();+ const { link } = fakeLink(() => stream.response);+ const source = relayEventSource(link, "/api/events");+ source.onerror = vi.fn();+ await tick();+ stream.end();+ await tick();+ expect(source.onerror).toHaveBeenCalledTimes(1);+ });++ it("reports onerror without opening for a refusal or a reply that isn't an event stream, and for a failed request", async () => {+ for (const answer of [+ () => Response.json({ error: "unauthorized" }, { status: 401 }),+ () => Response.json({ ok: true }),+ () => Promise.reject(new Error("relay unreachable")),+ ]) {+ const { link } = fakeLink(answer);+ const source = relayEventSource(link, "/api/events");+ source.onopen = vi.fn();+ source.onerror = vi.fn();+ await tick();+ expect(source.onopen).not.toHaveBeenCalled();+ expect(source.onerror).toHaveBeenCalledTimes(1);+ }+ });++ it("stops delivering and cancels the stream on close, with no onerror", async () => {+ const stream = eventStream();+ const { link, sent } = fakeLink(() => stream.response);+ const source = relayEventSource(link, "/api/events");+ source.onmessage = vi.fn();+ source.onerror = vi.fn();+ await tick();+ source.close();+ expect(sent[0].request.signal?.aborted).toBe(true);+ stream.push("data: late\n\n");+ await tick();+ expect(source.onmessage).not.toHaveBeenCalled();+ expect(source.onerror).not.toHaveBeenCalled();+ expect(stream.cancelled).toHaveBeenCalled();+ });+});++describe("live events through a relay link", () => {+ it("opens the live events stream through the link when one is set, even with no EventSource in the page", async () => {+ vi.stubGlobal("EventSource", undefined);+ const stream = eventStream();+ const { link, sent } = fakeLink(() => stream.response);+ setRelayLink(link);+ const frames: string[] = [];+ const opened = vi.fn();+ const stop = openLiveEvents({ onOpen: opened, onFrame: (frame) => frames.push(frame.kind), onSnapshotRequired: async () => true });+ await tick();+ expect(sent[0].path).toMatch(/^\/api\/events/);+ expect(opened).toHaveBeenCalledTimes(1);+ stream.push('id: c1\ndata: {"kind":"relay-test"}\n\n');+ await tick();+ expect(frames).toEqual(["relay-test"]);+ stop();+ expect(sent[0].request.signal?.aborted).toBe(true);+ });+});diff --git a/src/lib/relay-server.ts b/src/lib/relay-server.tsnew file mode 100644index 0000000000..dec1a5a0cb--- /dev/null+++ b/src/lib/relay-server.ts@@ -0,0 +1,95 @@+// The page's way to its own server's `/api` routes: through MausBot Relay while it holds a relay pairing (a phone+// browser away from home, src/lib/e2e/relay-link.ts), as a plain same-origin request otherwise.+import type { RelayLink } from "./e2e/relay-link";+import type { LiveEventSourceLike } from "./live-events";++let link: RelayLink | null = null;++/** Sends this page's `/api` requests and live events through `next` from now on; null goes back to plain requests. A link+ * that is replaced is closed. */+export function setRelayLink(next: RelayLink | null): void {+ if (link === next) return;+ link?.close();+ link = next;+}++export function relayLink(): RelayLink | null {+ return link;+}++const API = /^\/api(?:[/?#]|$)/;++/** `fetch` for a path on this page's own server. */+export async function serverFetch(path: string, init: RequestInit = {}): Promise<Response> {+ const current = link;+ if (!current || !API.test(path)) return fetch(path, init);+ // A Request turns any body fetch takes (FormData, Blob, URLSearchParams…) into bytes and gives it its content type.+ const request = new Request(new URL(path, "http://relay.invalid"), { ...init, signal: undefined });+ const body = request.method === "GET" || request.method === "HEAD" ? null : new Uint8Array(await request.arrayBuffer());+ return current.fetch(path, { method: request.method, headers: request.headers, body, signal: init.signal ?? undefined });+}++/** An EventSource on `url` through `current`, as the live events transport uses it (src/lib/live-events.ts): `onerror`+ * once, when the stream can't open or ends, and the caller reconnects. Like EventSource, only unnamed and `message`+ * events reach `onmessage`. */+export function relayEventSource(current: RelayLink, url: string): LiveEventSourceLike {+ const stop = new AbortController();+ const source: LiveEventSourceLike = { onopen: null, onerror: null, onmessage: null, close: () => stop.abort() };+ void (async () => {+ try {+ const reply = await current.fetch(url, { headers: { accept: "text/event-stream" }, signal: stop.signal });+ if (!reply.ok || !reply.body || !/^text\/event-stream\b/i.test(reply.headers.get("content-type") ?? "")) {+ await reply.body?.cancel().catch(() => {});+ throw new Error(`live events refused (${reply.status})`);+ }+ if (stop.signal.aborted) return;+ source.onopen?.();+ await readEvents(reply.body, stop.signal, (data, lastEventId) => source.onmessage?.({ data, lastEventId }));+ } catch {+ // Reported below, as the end of the stream.+ }+ if (!stop.signal.aborted) source.onerror?.();+ })();+ return source;+}++/** The text/event-stream format (HTML Living Standard, "Interpreting an event stream"). */+async function readEvents(body: ReadableStream<Uint8Array>, signal: AbortSignal, dispatch: (data: string, lastEventId: string) => void): Promise<void> {+ const reader = body.getReader();+ const decoder = new TextDecoder();+ let pending = "";+ let data: string[] = [];+ let type = "";+ let lastEventId = "";+ const line = (text: string) => {+ if (text === "") {+ if (data.length && (type === "" || type === "message")) dispatch(data.join("\n"), lastEventId);+ data = [];+ type = "";+ return;+ }+ if (text.startsWith(":")) return;+ const colon = text.indexOf(":");+ const field = colon < 0 ? text : text.slice(0, colon);+ const value = colon < 0 ? "" : text.slice(text[colon + 1] === " " ? colon + 2 : colon + 1);+ if (field === "data") data.push(value);+ else if (field === "event") type = value;+ else if (field === "id" && !value.includes("\0")) lastEventId = value;+ };+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done || signal.aborted) return;+ pending += decoder.decode(value, { stream: true });+ // A lone CR at the end may be the first half of a CRLF: it waits for the next chunk.+ const parts = pending.split(/\r\n|\r(?!$)|\n/);+ pending = parts.pop()!;+ for (const part of parts) {+ line(part);+ if (signal.aborted) return;+ }+ }+ } finally {+ void reader.cancel().catch(() => {});+ }+}diff --git a/src/state/api.ts b/src/state/api.tsindex 6f7312d02e..9df65ca158 100644--- a/src/state/api.ts+++ b/src/state/api.ts@@ -6,6 +6,7 @@ import { isBotLimitRefusal, isBotPausedRefusal, showBotLimit } from "../lib/bot-import { noteRefusedRequest } from "../lib/session-ended";import { forgetSharedSession } from "../lib/session-reuse";import { serverErrorText } from "../lib/server-error";+import { serverFetch } from "../lib/relay-server";export class ApiError extends Error {readonly status: number;@@ -39,7 +40,7 @@ export async function api<T = any>(path: string, init?: ApiInit): Promise<T> {// answer from before it is served again.const writes = (rest.method ?? "GET").toUpperCase() !== "GET";if (writes) forgetSharedSession();- const res = await fetch(path, {+ const res = await serverFetch(path, {...rest,headers: sent,signal: timeoutMs === undefined