Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(updates): let Check for updates look again instead of the hour-old answer
Bugfixer 2159b3e1b143a
diff --git a/server/routes/update-check.test.ts b/server/routes/update-check.test.tsindex 9b06948694..9827d70042 100644--- a/server/routes/update-check.test.ts+++ b/server/routes/update-check.test.ts@@ -14,7 +14,7 @@ afterEach(async () => {await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));});-async function serve(check: () => Promise<UpdateCheck>, updater?: ServerUpdater, auth: RequestAuth = { kind: "loopback", scopes: ["admin"] }): Promise<string> {+async function serve(check: (options?: { fresh?: boolean }) => Promise<UpdateCheck>, updater?: ServerUpdater, auth: RequestAuth = { kind: "loopback", scopes: ["admin"] }): Promise<string> {const routes = [createUpdateCheckRoutes({ check, ...(updater ? { server: updater, actor: () => ({ kind: "loopback" as const }) } : {}) })];const server = createServer(async (req, res) => {const url = new URL(req.url ?? "/", "http://localhost");@@ -44,6 +44,17 @@ describe("update check route", () => {expect((await fetch(`${base}/api/updates`)).status).toBe(404);});+ it("asks for a fresh lookup only when the request says fresh=1", async () => {+ const asked: Array<{ fresh?: boolean } | undefined> = [];+ const base = await serve(async (options?: { fresh?: boolean }) => {+ asked.push(options);+ return { current: "0.1.177", install: "docker", available: false };+ });+ await fetch(`${base}/api/updates/check`);+ await fetch(`${base}/api/updates/check?fresh=1`);+ expect(asked).toEqual([{ fresh: false }, { fresh: true }]);+ });+it("reports a failed lookup as a 502 with the reason", async () => {const base = await serve(async () => { throw new Error("GitHub answered 403"); });const response = await fetch(`${base}/api/updates/check`);diff --git a/server/routes/update-check.ts b/server/routes/update-check.tsindex 286a54a6b6..6ac6250fb1 100644--- a/server/routes/update-check.ts+++ b/server/routes/update-check.ts@@ -1,4 +1,5 @@// GET /api/updates/check: whether a newer version exists, and how this install is updated. Read-only, so client sessions may ask.+// ?fresh=1 is a press of Check for updates, which skips the hour-long cache (server/update-check.ts).// GET and POST /api/updates/server: the Update server button, for an admin's session only (server/server-update.ts).import type { IncomingMessage } from "node:http";@@ -11,7 +12,7 @@ import { createUpdateChecker, installKind, updateChannel, type UpdateCheck } froimport { PASS, type RouteHandler } from "./table.ts";export interface UpdateCheckRouteDeps {- check(): Promise<UpdateCheck>;+ check(options?: { fresh?: boolean }): Promise<UpdateCheck>;server?: ServerUpdater;actor?(auth: RequestAuth, req: IncomingMessage): AdminActor;}@@ -25,7 +26,7 @@ export function mayUpdateServer(auth: RequestAuth): boolean {}export function createUpdateCheckRoutes(deps: UpdateCheckRouteDeps): RouteHandler {- return async ({ req, res, path, method, json, auth }) => {+ return async ({ req, res, url, path, method, json, auth }) => {if (path === "/api/updates/server" && deps.server && (method === "GET" || method === "POST")) {if (!mayUpdateServer(auth)) return json(res, 403, { error: "Only an admin of this server, signed in, can update it.", code: "admin_only" });if (method === "GET") return json(res, 200, await deps.server.status());@@ -34,7 +35,7 @@ export function createUpdateCheckRoutes(deps: UpdateCheckRouteDeps): RouteHandle}if (path !== "/api/updates/check" || method !== "GET") return PASS;try {- return json(res, 200, await deps.check());+ return json(res, 200, await deps.check({ fresh: url.searchParams.get("fresh") === "1" }));} catch (error) {return json(res, 502, { error: `Could not check for updates: ${error instanceof Error ? error.message : String(error)}` });}diff --git a/server/update-check.test.ts b/server/update-check.test.tsindex d52a0c3c24..5c3fa6bf5e 100644--- a/server/update-check.test.ts+++ b/server/update-check.test.ts@@ -136,6 +136,34 @@ describe("server update check", () => {expect(fetch).toHaveBeenCalledTimes(2);});+ it("looks again when someone presses Check for updates, unless the last lookup is under five minutes old", async () => {+ let now = 0;+ let newest = "v0.1.177";+ const fetch = vi.fn(async () => release(newest));+ const check = createUpdateChecker({ current: "0.1.177", install: "docker", channel: "newest", fetch, now: () => now });+ expect(await check()).toMatchObject({ available: false, latest: "0.1.177" });+ newest = "v0.1.178";+ now = 34 * 60_000;+ expect(await check()).toMatchObject({ available: false, latest: "0.1.177" });+ expect(await check({ fresh: true })).toMatchObject({ available: true, latest: "0.1.178" });+ expect(fetch).toHaveBeenCalledTimes(2);+ now += 4 * 60_000;+ await check({ fresh: true });+ expect(fetch).toHaveBeenCalledTimes(2);+ });++ it("tells a press of Check for updates that the lookup failed, instead of giving the old answer", async () => {+ let now = 0;+ const fetch = vi.fn(async () => release("v0.1.177"));+ const check = createUpdateChecker({ current: "0.1.177", install: "docker", channel: "newest", fetch, now: () => now });+ await check();+ fetch.mockImplementation(async () => ({ ok: false, status: 403, json: async () => ({}) }) as Response);+ now = 10 * 60_000;+ await expect(check({ fresh: true })).rejects.toThrow("GitHub answered 403");+ now = 2 * 60 * 60_000;+ expect(await check()).toMatchObject({ available: false, latest: "0.1.177" });+ });+it("does not look anything up for a desktop or hosted server", async () => {const fetch = vi.fn();for (const install of ["desktop", "managed"] as const) {diff --git a/server/update-check.ts b/server/update-check.tsindex 1c83874b85..48a0d2ca0d 100644--- a/server/update-check.ts+++ b/server/update-check.ts@@ -6,6 +6,9 @@ export const LATEST_RELEASE_URL = "https://api.github.com/repos/milind-soni/Open/** Written by .github/workflows/promote-stable.yml: the released version our own Clouds have run for 48 hours. */export const STABLE_CHANNEL_URL = "https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json";const CACHE_MS = 60 * 60_000;+/** A press of Check for updates looks again unless the last lookup is younger than this. Any session may press it, and+ * GitHub allows a server 60 lookups an hour without a token: presses keep to 12 of them. */+const FRESH_MS = 5 * 60_000;/** How long the last answer stands in when the channel cannot be read: an outage of GitHub is no reason to say nothing. */const STALE_MS = 24 * 60 * 60_000;@@ -149,9 +152,10 @@ export function createUpdateChecker(options: {return { version: release.tag_name.replace(/^v/, ""), ...(typeof release.html_url === "string" ? { releaseUrl: release.html_url } : {}) };}- return async function check(): Promise<UpdateCheck> {+ /** `fresh`: someone pressed Check for updates, so an answer from up to an hour ago is not good enough. */+ return async function check({ fresh = false }: { fresh?: boolean } = {}): Promise<UpdateCheck> {if (options.install === "desktop" || options.install === "managed") return base();- if (cached && now() - cached.at < CACHE_MS) return cached.result;+ if (cached && now() - cached.at < (fresh ? FRESH_MS : CACHE_MS)) return cached.result;inflight ??= (async () => {try {const promoted = channel === "stable" ? await stable() : null;@@ -166,15 +170,18 @@ export function createUpdateChecker(options: {};cached = lastGood = { at: now(), result };return result;- } catch (error) {- // Never a fall back to the newest release, which the stable channel has not taken yet: the last answer it gave,- // when there is one from the last day, else the error.- if (lastGood && now() - lastGood.at < STALE_MS) return lastGood.result;- throw error;} finally {inflight = undefined;}})();- return inflight;+ try {+ return await inflight;+ } catch (error) {+ // Never a fall back to the newest release, which the stable channel has not taken yet: the last answer it gave,+ // when there is one from the last day, else the error. A press of Check for updates gets the error: an old+ // answer there reads as "up to date".+ if (!fresh && lastGood && now() - lastGood.at < STALE_MS) return lastGood.result;+ throw error;+ }};}diff --git a/src/components/ServerUpdateRow.tsx b/src/components/ServerUpdateRow.tsxindex f3c1253966..76513bdeaa 100644--- a/src/components/ServerUpdateRow.tsx+++ b/src/components/ServerUpdateRow.tsx@@ -41,11 +41,12 @@ export function useServerUpdate() {return next;}, []);- const load = useCallback(async () => {+ /** `fresh`: the Check for updates button, which must not get the server's answer from up to an hour ago. */+ const load = useCallback(async (fresh = false) => {setChecking(true);setFailed(false);try {- const next = await api<ServerUpdateCheck>("/api/updates/check", { timeoutMs: 20_000 });+ const next = await api<ServerUpdateCheck>(fresh ? "/api/updates/check?fresh=1" : "/api/updates/check", { timeoutMs: 20_000 });setCheck(next);if (next.install !== "desktop" && next.install !== "managed") await readStatus().catch(() => null);} catch {@@ -129,7 +130,7 @@ export function ServerUpdateRow({ title }: { title: string }) {const [confirming, setConfirming] = useState(false);const { view, check, status } = update;const press = () => {- if (view.action === "check") return void update.load();+ if (view.action === "check") return void update.load(true);if (view.action === "reload") return window.location.reload();if (view.action === "update-app") return void update.updateApp();if (view.action === "update-server") {diff --git a/src/components/SidebarProfileMenu.tsx b/src/components/SidebarProfileMenu.tsxindex 83ad44aedc..69f9b59d2a 100644--- a/src/components/SidebarProfileMenu.tsx+++ b/src/components/SidebarProfileMenu.tsx@@ -255,7 +255,7 @@ export function useServerUpdateItem(enabled: boolean): UpdateEntry | null {if (phase === "available" && check?.releaseUrl) return void openExternalLink(check.releaseUrl);if (phase === "reload") return window.location.reload();setPhase("checking");- void api<ServerUpdateCheck>("/api/updates/check", { timeoutMs: 20_000 })+ void api<ServerUpdateCheck>("/api/updates/check?fresh=1", { timeoutMs: 20_000 }).then((next) => {setCheck(next);setPhase(serverCheckPhase(next));