Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(pages): keep interrupted uploads recoverable
Sebastian B0ac78443e0b7
diff --git a/server/pages/client.ts b/server/pages/client.tsindex bbed9fcea2..0aef6e934d 100644--- a/server/pages/client.ts+++ b/server/pages/client.ts@@ -11,11 +11,12 @@ export type PagesFailure = {usage?: PageUsage;upgrade?: boolean;plan?: string;+ /** The PUT may have committed even though its answer was lost. Keep this page removable. */+ uncertain?: { pageId: string; url: string };};/** A bot's tool call: `assertActive` throws once its turn has ended, and `signal` aborts once its turn ends or its request* is gone. Security: each token and each upload or delete is preceded by `assertActive`, and `signal` aborts the one in- * flight, so a stopped turn shows no card and records no page. Known risk: an upload the Worker stored before the abort- * stays published. */+ * flight. An upload the Worker may have stored keeps its id and a recovery card even after Stop. */export interface PagesCall { assertActive?: () => void; signal?: AbortSignal }export type Published = { ok: true; pageId: string; url: string; usage: PageUsage; badge: boolean };export type Unpublished = { ok: true; pageId: string; usage: PageUsage | null };@@ -105,7 +106,9 @@ export function createPagesClient(options: { access: () => PagesAccess | null; nreturn {/** A new page (no `pageId`), or new files at an existing page's same link. */- async publish(input: { title: string; files: readonly PageFile[]; pageId?: string }, call: PagesCall = {}): Promise<Published | PagesFailure> {+ async publish(input: { title: string; files: readonly PageFile[]; pageId?: string;+ /** Persists the minted id before the PUT, so a lost answer cannot leave an unknown public page. */+ beforeUpload: (page: { pageId: string; url: string }) => void }, call: PagesCall = {}): Promise<Published | PagesFailure> {const minted = await mint(input.pageId ? "update" : "create", call, input.pageId);if ("ok" in minted) return minted;const bytes = input.files.reduce((sum, file) => sum + file.data.byteLength, 0);@@ -116,15 +119,23 @@ export function createPagesClient(options: { access: () => PagesAccess | null; ninput.files.forEach((file, index) => form.set(`f${index}`, new Blob([new Uint8Array(file.data)])));let response: Response;call.assertActive?.();+ const signal = callSignal(call, UPLOAD_TIMEOUT_MS);+ if (signal.aborted) return fail("unavailable", UNAVAILABLE);+ const page = { pageId: minted.pageId, url: minted.pageUrl };+ input.beforeUpload(page);+ const uncertain = () => fail("unavailable", UNAVAILABLE, { uncertain: page });try {- response = await http(`${minted.uploadUrl}/v1/pages/${minted.pageId}`, { method: "PUT", redirect: "error", signal: callSignal(call, UPLOAD_TIMEOUT_MS),+ response = await http(`${minted.uploadUrl}/v1/pages/${minted.pageId}`, { method: "PUT", redirect: "error", signal,headers: { authorization: `Bearer ${minted.token}`, accept: "application/json" }, body: form });} catch {- return fail("unavailable", UNAVAILABLE);+ return uncertain();}const body = await readJson(response);- if (call.signal?.aborted) return fail("unavailable", UNAVAILABLE);- if (!response.ok) return workerFailure(response.status, body, minted);+ if (signal.aborted) return uncertain();+ if (!response.ok) {+ const failure = workerFailure(response.status, body, minted);+ return failure.reason === "unavailable" ? uncertain() : failure;+ }const usage = usageOf(body.usage);return { ok: true, pageId: minted.pageId, url: minted.pageUrl, usage: usage ?? { pages: 0, limit: minted.limits.pages }, badge: body.badge === true };},diff --git a/server/pages/published-pages.test.ts b/server/pages/published-pages.test.tsindex 6f19ad577a..92b708ad6e 100644--- a/server/pages/published-pages.test.ts+++ b/server/pages/published-pages.test.ts@@ -125,6 +125,39 @@ describe("publishing a page", () => {expect([...f.service.pages.keys()][0]).not.toBe(first);});+ it("recovers a lost PUT response by updating the remembered page instead of creating another", async () => {+ const f = setup();+ signIn();+ writeSite(join(f.work, "site"));+ const fetch = f.service.fetch;+ f.service.fetch = async (input, init) => {+ const response = await fetch(input, init);+ if (init?.method === "PUT") throw new TypeError("response lost");+ return response;+ };+ const outcome = await f.publish({ path: "site" });+ const [pageId] = [...f.service.pages.keys()];+ expect(outcome).toMatchObject({ status: 503, card: { pageId, uncertain: true } });+ expect(new PublishedPagesStore(join(f.data, "published-pages.json")).get(pageId!)).toMatchObject({ uncertain: true });+ f.service.fetch = fetch;+ expect(await f.publish({ path: "site" })).toMatchObject({ status: 200, card: { pageId } });+ expect(f.service.pages.size).toBe(1);+ expect(f.service.minted.map((each) => each.action)).toEqual(["create", "update"]);+ expect(new PublishedPagesStore(join(f.data, "published-pages.json")).get(pageId!)?.uncertain).toBeUndefined();+ });++ it.each([402, 410, 413])("drops a new pending record when the Worker confirms rejection with %s", async (status) => {+ const f = setup();+ signIn();+ writeSite(join(f.work, "site"));+ const fetch = f.service.fetch;+ f.service.fetch = (input, init) => init?.method === "PUT" ? Promise.resolve(Response.json({}, { status })) : fetch(input, init);+ expect((await f.publish({ path: "site" })).status).not.toBe(200);+ expect(f.service.pages.size).toBe(0);+ expect(f.pages.store.list()).toEqual([]);+ expect(f.cards.every(({ card }) => card.state === "limit")).toBe(true);+ });+it("at the plan's limit, says so for the bot to pass on and shows a card offering more pages, with the usage", async () => {const f = setup({ quota: 1 });signIn();@@ -286,7 +319,7 @@ describe("a page tool call whose turn ends", () => {expect(f.service.pages.size).toBe(0);});- it("shows no card when the tool call's request goes while the upload's answer is still arriving", async () => {+ it("keeps a removable page when the request goes while the committed upload's answer is still arriving", async () => {const f = setup();signIn();writeSite(join(f.work, "site"));@@ -303,6 +336,10 @@ describe("a page tool call whose turn ends", () => {const { call, sent } = tool(f, { signal: gone.signal });await call("/api/internal/pages/publish", { path: "site", title: "Bake sale" });expect(sent.status).toBe(503);+ const [pageId] = [...f.service.pages.keys()];+ expect(new PublishedPagesStore(join(f.data, "published-pages.json")).get(pageId!)).toMatchObject({ uncertain: true, cards: [{ threadId: "thread-1", messageId: "m1" }] });+ expect(await f.pages.publisher.unpublish({ path: "site", botId: "bot-1", roots: [f.work] })).toMatchObject({ status: 200 });+ expect(f.service.pages.size).toBe(0);expect(f.pages.store.list()).toEqual([]);});});diff --git a/server/pages/publisher.ts b/server/pages/publisher.tsindex 96b71b44fd..1636f6f27d 100644--- a/server/pages/publisher.ts+++ b/server/pages/publisher.ts@@ -16,7 +16,7 @@ export interface PublishInput {pageId?: string;/** The bot's own folders: nothing outside them is read. */roots: readonly string[];- /** Puts a card in the conversation the tool was called from; its message id, or null when the turn has ended. A live+ /** Puts a card in the conversation the tool was called from; its message id, or null when the conversation is gone. A live* card comes with the files published, so it can show the page itself. */post: (text: string, card: PublishedPageCard, bundle?: PageBundle) => string | null;/** The bot's tool call: nothing is sent to the pages service once its turn has ended or its request is gone. */@@ -32,6 +32,7 @@ const usageWords = (usage: PageUsage) => `${usage.pages} of ${usage.limit} pagesexport function cardText(card: PublishedPageCard): string {if (card.state === "limit") return card.message ?? "This account's pages are used up.";if (card.state === "unpublished") return `Unpublished “${card.title}”. Its link no longer opens.`;+ if (card.uncertain) return `“${card.title}” may be live: ${card.url}. Unpublish it to remove it.`;return `Published “${card.title}”: ${card.url}${card.usage ? ` (${usageWords(card.usage)})` : ""}`;}@@ -103,13 +104,27 @@ export function createPagePublisher(deps: {const title = pageTitle(input.title);if (!title) return TITLE_REQUIRED;const remembered = target ? store.get(target) : null;- let result = await client.publish({ title, files: bundle.files, ...(target ? { pageId: target } : {}) }, input.call);+ let pending: string | undefined;+ const beforeUpload = (page: { pageId: string; url: string }) => {+ if (store.get(page.pageId)) return;+ store.published({ ...page, title, botId: remembered?.botId ?? input.botId, source: bundle.source, card: null, uncertain: true });+ pending = page.pageId;+ };+ let result = await client.publish({ title, files: bundle.files, ...(target ? { pageId: target } : {}), beforeUpload }, input.call);// The page this folder was published to before is gone (unpublished, or taken down): it gets a new link.if (!result.ok && result.reason === "gone" && !input.pageId && target) {store.forget(target);- result = await client.publish({ title, files: bundle.files }, input.call);+ result = await client.publish({ title, files: bundle.files, beforeUpload }, input.call);}if (!result.ok) {+ if (result.uncertain) {+ const card: PublishedPageCard = { state: "live", title, ...result.uncertain, uncertain: true };+ const messageId = input.post(cardText(card), card);+ store.published({ ...result.uncertain, title, botId: remembered?.botId ?? input.botId, source: bundle.source, uncertain: true,+ card: messageId ? { threadId: input.threadId, messageId } : null });+ return { status: failureStatus[result.reason], text: cardText(card), card };+ }+ if (pending) store.forget(pending);if (result.reason === "limit") {const card: PublishedPageCard = { state: "limit", title, message: result.message, ...(result.usage ? { usage: result.usage } : {}), ...(result.upgrade ? { upgrade: true } : {}),...(result.plan ? { plan: result.plan } : {}) };diff --git a/server/pages/store.ts b/server/pages/store.tsindex 8a62e96d31..e6da2586e2 100644--- a/server/pages/store.ts+++ b/server/pages/store.ts@@ -14,6 +14,7 @@ export interface PublishedPageRecord {cards: Array<{ threadId: string; messageId: string }>;createdAt: number;updatedAt: number;+ uncertain?: boolean;}const MAX_RECORDS = 5_000, MAX_CARDS = 50;@@ -58,11 +59,11 @@ export class PublishedPagesStore {}/** Records a publish (a new page or an update) and the card that shows it. */- published(input: { pageId: string; url: string; title: string; botId: string; source: string; card: { threadId: string; messageId: string } | null }, now = Date.now()): PublishedPageRecord {+ published(input: { pageId: string; url: string; title: string; botId: string; source: string; card: { threadId: string; messageId: string } | null; uncertain?: boolean }, now = Date.now()): PublishedPageRecord {const existing = this.get(input.pageId);const cards = [...(existing?.cards ?? []), ...(input.card ? [input.card] : [])].slice(-MAX_CARDS);const record: PublishedPageRecord = { pageId: input.pageId, url: input.url, title: input.title, botId: input.botId, source: input.source, cards,- createdAt: existing?.createdAt ?? now, updatedAt: now };+ createdAt: existing?.createdAt ?? now, updatedAt: now, ...(input.uncertain ? { uncertain: true } : {}) };this.records = [...this.records.filter((each) => each.pageId !== input.pageId), record].slice(-MAX_RECORDS);this.save();return record;diff --git a/server/published-pages.e2e.test.ts b/server/published-pages.e2e.test.tsindex 98518003b1..bd05085e7a 100644--- a/server/published-pages.e2e.test.ts+++ b/server/published-pages.e2e.test.ts@@ -17,7 +17,7 @@ let fixture: Awaited<ReturnType<typeof launchVerificationServer>>;async function serveStub() {let service!: ReturnType<typeof fakePagesService>;- let hold: { arrived: () => void; aborted: () => void; released: Promise<void> } | null = null;+ let hold: { committed: boolean; arrived: () => void; aborted: () => void; released: Promise<void> } | null = null;const server = createServer((req, res) => {const chunks: Buffer[] = [];let gone = false;@@ -27,13 +27,18 @@ async function serveStub() {req.on("data", (chunk: Buffer) => chunks.push(chunk));req.on("end", async () => {const body = Buffer.concat(chunks);- if (held) {+ if (held && !held.committed) {held.arrived();await held.released;if (gone) return;}const answer = await service.fetch(new Request(`${url}${req.url}`, { method: req.method, headers: req.headers as Record<string, string>,...(body.length ? { body } : {}) })).catch(() => new Response("{}", { status: 404 }));+ if (held?.committed) {+ held.arrived();+ await held.released;+ if (gone) return;+ }res.writeHead(answer.status, { "content-type": "application/json" });res.end(Buffer.from(await answer.arrayBuffer()));});@@ -44,10 +49,10 @@ async function serveStub() {const url = `http://127.0.0.1:${address.port}`;service = fakePagesService({ admin: url, upload: url });/** Keeps the next upload unanswered until `release`, the way a large upload is still in flight. */- const holdUpload = () => {+ const holdUpload = (committed: boolean) => {let arrived!: () => void, aborted!: () => void, release!: () => void;const upload = { arrived: new Promise<void>((resolve) => { arrived = resolve; }), aborted: new Promise<void>((resolve) => { aborted = resolve; }), release: () => release() };- hold = { arrived, aborted, released: new Promise<void>((resolve) => { release = resolve; }) };+ hold = { committed, arrived, aborted, released: new Promise<void>((resolve) => { release = resolve; }) };return upload;};return { server, url, service, holdUpload };@@ -110,7 +115,7 @@ it("publishes a bot's page to a link shown inline, keeps the link and the card o.toEqual([["app", "[App] Bake sale\nBake sale, Saturday", "unpublished"]]);}, 120_000);-it("aborts a page upload still in flight when Stop ends its turn, and shows no card for it", async () => {+it.each([false, true])("keeps an Unpublish card when Stop aborts an upload whose Worker committed: %s", async (committed) => {const cli = (...args: string[]) => runControlOmb(args, { env: { OPENMAUSBOT_URL: fixture.info.url } }) as Promise<any>;const api = async (path: string, init: RequestInit & { headers?: Record<string, string> } = {}) =>fetch(`${fixture.info.url}${path}`, { ...init, headers: { "content-type": "application/json", ...init.headers } });@@ -122,18 +127,31 @@ it("aborts a page upload still in flight when Stop ends its turn, and shows no cbody: JSON.stringify({ botId: bot.id, threadId: bot.activeTaskId }) });const { token } = await minted.json() as { token: string };const pagesBefore = stub.service.pages.size;- const upload = stub.holdUpload();+ const upload = stub.holdUpload(committed);const published = api("/api/internal/pages/publish", { method: "POST", headers: { authorization: `Bearer ${token}` },body: JSON.stringify({ path: "site", title: "Draft" }) });await upload.arrived;+ const storePath = join(fixture.info.dataDir, "published-pages.json");+ const records = existsSync(storePath) ? JSON.parse(readFileSync(storePath, "utf8")).pages : [];+ const record = records.find((page: any) => page.botId === bot.id);+ expect(stub.service.pages.size).toBe(pagesBefore + Number(committed));expect((await api(`/api/bots/${bot.id}/interrupt`, { method: "POST", body: JSON.stringify({ threadId: bot.activeTaskId }) })).status).toBe(200);const outcome = await Promise.race([upload.aborted.then(() => "aborted"), new Promise((resolve) => setTimeout(resolve, 2_000, "still uploading"))]);upload.release();expect(outcome).toBe("aborted");expect((await published).status).not.toBe(200);- expect(stub.service.pages.size).toBe(pagesBefore);+ expect(record).toMatchObject({ uncertain: true, title: "Draft" });+ expect(stub.service.pages.size).toBe(pagesBefore + Number(committed));const thread = await (await api(`/api/threads/${bot.activeTaskId}/messages?limit=50`)).json() as any;- expect(thread.messages.filter((message: any) => message.publishedPage)).toEqual([]);+ const cards = thread.messages.filter((message: any) => message.publishedPage);+ expect(cards).toHaveLength(1);+ expect(cards[0].publishedPage).toMatchObject({ state: "live", pageId: record.pageId, uncertain: true });+ expect(await (await api(`/api/published-pages/${record.pageId}/unpublish`, { method: "POST", body: "{}" })).json())+ .toMatchObject({ ok: true, card: { state: "unpublished" } });+ expect(stub.service.pages.size).toBe(pagesBefore);+ const after = await (await api(`/api/threads/${bot.activeTaskId}/messages?limit=50`)).json() as any;+ expect(after.messages.find((message: any) => message.id === cards[0].id).publishedPage.state).toBe("unpublished");+ expect(JSON.parse(readFileSync(join(fixture.info.dataDir, "published-pages.json"), "utf8")).pages.some((page: any) => page.pageId === record.pageId)).toBe(false);}, 60_000);diff --git a/shared/published-page.ts b/shared/published-page.tsindex 1f0bce6f4b..8a7fe35c10 100644--- a/shared/published-page.ts+++ b/shared/published-page.ts@@ -1,9 +1,11 @@/** A page a bot published to a public link, as its chat card shows it (WireMessage.publishedPage). The message's `text`* says the same in words, with the link, for every client that does not draw the card. */export interface PublishedPageCard {- /** live: the link works. unpublished: its owner took it down. limit: the plan's pages are used up, so nothing was- * published; `message` says so and `upgrade` offers a bigger plan. */+ /** live: the link works, or may work when `uncertain` is true. unpublished: its owner took it down. limit: the plan's+ * pages are used up, so nothing was published; `message` says so and `upgrade` offers a bigger plan. */state: "live" | "unpublished" | "limit";+ /** The upload's answer was lost. The page may be live and can still be unpublished. */+ uncertain?: boolean;title: string;pageId?: string;url?: string;diff --git a/src/components/PublishedPageCard.test.ts b/src/components/PublishedPageCard.test.tsindex 7168f9794c..f976c222da 100644--- a/src/components/PublishedPageCard.test.ts+++ b/src/components/PublishedPageCard.test.ts@@ -40,6 +40,15 @@ const buttons = (container: HTMLElement) => [...container.querySelectorAll("buttafterEach(() => { vi.clearAllMocks(); delete (window as { ogb?: unknown }).ogb; });describe("a published page's card", () => {+ it("warns when an upload is uncertain and still lets the person unpublish it", async () => {+ const { container, root } = render(page({ ...live.publishedPage!, uncertain: true }));+ try {+ expect(container.textContent).toContain("This page may be live. Unpublish it to remove it.");+ buttons(container).find((button) => button.textContent === "Unpublish")!.click();+ await vi.waitFor(() => expect(api).toHaveBeenCalledWith("/api/published-pages/abcdefghijklmnopqrstuvwxyz/unpublish", { method: "POST", body: "{}" }));+ } finally { root.unmount(); }+ });+it("shows the title, the link and the usage; on the web Open and the link open a new tab; and it unpublishes the page", async () => {const { container, root, panel } = render(live);try {diff --git a/src/components/PublishedPageCard.tsx b/src/components/PublishedPageCard.tsxindex 4af979ead6..1f9b00f380 100644--- a/src/components/PublishedPageCard.tsx+++ b/src/components/PublishedPageCard.tsx@@ -45,6 +45,7 @@ export function PublishedPageCard({ message }: { message: Message }) {{usage && <span className="ms-auto shrink-0 text-xs text-ink-tertiary">{usage}</span>}</div>{card.state === "live" && card.url && <>+ {card.uncertain && <p role="status" className="mt-1 text-[13px] text-ink-secondary">{t("chat.page.uncertain")}</p>}<a href={card.url} dir="ltr" onClick={(event) => { event.preventDefault(); openPage(card.url!); }}className="mt-1 block truncate text-[13px] text-accent-text hover:underline">{card.url}</a><div className="mt-2 flex flex-wrap gap-1.5">diff --git a/src/locales/en.json b/src/locales/en.jsonindex 461edc14af..85d5d08bab 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -6766,6 +6766,7 @@"chat.page.open": "Open","chat.page.unpublish": "Unpublish","chat.page.unpublished": "Unpublished. The link no longer opens.",+ "chat.page.uncertain": "This page may be live. Unpublish it to remove it.","chat.page.unpublishFailed": "Couldn’t unpublish this page. Try again in a moment.","chat.page.freeLimit": "You’ve used your {limit} free pages. MausBot Cloud gives you more, and pages without the badge.","chat.page.planLimit": "You’ve used all {limit} pages on your {plan} plan. Unpublish a page to make room.",