Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Send the app's direct requests through serverFetch (part of #5665)
Bugfixer 27eef66d12dba
diff --git a/src/App.tsx b/src/App.tsxindex e84653a833..1636b3872c 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -91,6 +91,7 @@ import { WebPanelPage } from "@/components/WebPanelPage";import { AppPreviewPanel } from "@/components/published-apps/AppPreviewPanel";import { FilePreviewPanel } from "@/components/FilePreviewPanel";import { refreshPublishedApps } from "@/lib/own-published-apps";+import { serverFetch } from "@/lib/relay-server";function Shell({ viewer }: { viewer: WelcomeViewer | null }) {const { state, dispatch } = useStore();@@ -330,7 +331,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {return window.ogb?.desktopViewer?.onState((viewer) => {if (viewer.open || !viewer.contextId) return;const botId = viewer.contextId, release = viewerClosedRelease(botId);- if (release) void fetch(`/api/bots/${botId}/computer/control`, {+ if (release) void serverFetch(`/api/bots/${botId}/computer/control`, {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify(release),@@ -340,7 +341,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {if (snap) dispatch({ type: "computerControl", botId, held: snap.held === true, helpReason: snap.helpReason ?? null, help: parseComputerHelp(snap.help) });}).catch(() => {});- void fetch(`/api/bots/${botId}/computer/viewer-close`, {+ void serverFetch(`/api/bots/${botId}/computer/viewer-close`, {method: "POST",headers: { "content-type": "application/json" },body: "{}",diff --git a/src/components/ActivityPanel.tsx b/src/components/ActivityPanel.tsxindex 533363bdb5..bf16e4769c 100644--- a/src/components/ActivityPanel.tsx+++ b/src/components/ActivityPanel.tsx@@ -16,6 +16,7 @@ import {import { listenLiveFrames } from "@/lib/live-events";import { useActivityFocus } from "@/lib/activity-focus";import { t } from "@/lib/i18n";+import { serverFetch } from "@/lib/relay-server";const LIMIT = 300;@@ -38,7 +39,7 @@ export function ActivityPanel({ bot }: { bot: Bot }) {const controller = new AbortController();loadAbort.current = controller;try {- const res = await fetch(`/api/bots/${bot.id}/activity?limit=${LIMIT}`, { signal: controller.signal });+ const res = await serverFetch(`/api/bots/${bot.id}/activity?limit=${LIMIT}`, { signal: controller.signal });if (!res.ok) throw new Error(`${res.status}`);// SAFETY: the same-version harness's typed activity endpoint; malformed transport data is handled by catch.const next = (await res.json()) as { rows: ActivityRow[] };diff --git a/src/components/AttachmentPreview.tsx b/src/components/AttachmentPreview.tsxindex a313107cd3..411079009b 100644--- a/src/components/AttachmentPreview.tsx+++ b/src/components/AttachmentPreview.tsx@@ -37,7 +37,7 @@ import { serverErrorText } from "@/lib/server-error";import { CopyImageButton } from "./CopyImageButton";import { FilePreviewButton } from "./FilePreviewButton";import { chipNameAction, SaveIconButton, useHtmlPreview } from "./HtmlFilePreview";-import { ImageLoading } from "./ImageLoading"; import { openLinkedFolder } from "./RevealOriginalMenu";+import { ImageLoading } from "./ImageLoading"; import { openLinkedFolder } from "./RevealOriginalMenu"; import { serverFetch } from "@/lib/relay-server";export interface PreviewImage {src: string;@@ -203,7 +203,7 @@ export function messageImagePreviewUrl(export async function messageImageOutsideWorkspace(src: string): Promise<boolean> {try {- const response = await fetch(src, { cache: "no-store" });+ const response = await serverFetch(src, { cache: "no-store" });if (response.ok) {await response.body?.cancel();return false;@@ -226,7 +226,7 @@ export async function requestMessageFile(signal: AbortSignal,options?: { entry?: string; list?: boolean; mediaLink?: boolean },): Promise<Response> {- const response = await fetch(`/api/threads/${encodeURIComponent(message.threadId)}/messages/${encodeURIComponent(message.messageId)}/file`, {+ const response = await serverFetch(`/api/threads/${encodeURIComponent(message.threadId)}/messages/${encodeURIComponent(message.messageId)}/file`, {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify({diff --git a/src/components/CanvasComputers.tsx b/src/components/CanvasComputers.tsxindex 7182e963cd..ce5b37e250 100644--- a/src/components/CanvasComputers.tsx+++ b/src/components/CanvasComputers.tsx@@ -8,6 +8,7 @@ import { Select } from "./Select";import { t } from "@/lib/i18n";import type { LocaleKey } from "@/locales";import { randomUuid } from "@/lib/random-uuid";+import { serverFetch } from "@/lib/relay-server";const control = "rounded-lg px-3 py-2 text-[12px] text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-40";const field = "w-full rounded-lg border border-hairline/60 bg-inset px-3 py-2 text-[12px] text-ink outline-none focus:border-accent";@@ -75,7 +76,7 @@ export function CanvasComputers({ open, createRequest, drop, sections, onClose,useEffect(() => () => {const held = heldHereRef.current;if (!held) return;- void fetch(`/api/team-computers/${encodeURIComponent(held)}/control`, {+ void serverFetch(`/api/team-computers/${encodeURIComponent(held)}/control`, {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify({ action: "release", controlLeaseId: controlLeaseId.current }),diff --git a/src/components/InspectorPanel.tsx b/src/components/InspectorPanel.tsxindex 2f5e49a2f6..ba3e005d03 100644--- a/src/components/InspectorPanel.tsx+++ b/src/components/InspectorPanel.tsx@@ -12,6 +12,7 @@ import { activeLocale, t } from "@/lib/i18n";import { capital } from "@/lib/automations";import type { LocaleKey } from "@/locales";import { appendInspectorRuntime, mergeInspectorSnapshot, INSPECTOR_WINDOW_LIMIT } from "@/lib/inspector-window";+import { serverFetch } from "@/lib/relay-server";const tabLabel = (key: LocaleKey) => (activeLocale() === "en" ? t(key) : capital(t(key)));@@ -40,7 +41,7 @@ export function InspectorPanel({ bot }: { bot: Bot }) {const controller = new AbortController();loadAbort.current = controller;try {- const res = await fetch(`/api/threads/${threadId}/events?limit=${INSPECTOR_WINDOW_LIMIT}`, { signal: controller.signal });+ const res = await serverFetch(`/api/threads/${threadId}/events?limit=${INSPECTOR_WINDOW_LIMIT}`, { signal: controller.signal });if (!res.ok) throw new Error(`${res.status}`);// SAFETY: the same-version harness's typed inspector endpoint; malformed transport data is handled by catch.const next = (await res.json()) as InspectorPage;diff --git a/src/components/LinuxLocalControl.tsx b/src/components/LinuxLocalControl.tsxindex 73c892cc51..c785c4e2bf 100644--- a/src/components/LinuxLocalControl.tsx+++ b/src/components/LinuxLocalControl.tsx@@ -12,6 +12,7 @@ import {import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { useDesktopCapabilities } from "./DesktopCapabilities";+import { serverFetch } from "@/lib/relay-server";const LINUX_GUIDE_URL ="https://github.com/milind-soni/OpenMausBot/blob/main/docs/linux-desktop.md#enable-local-control";@@ -40,7 +41,7 @@ export function LinuxLocalControl() {setError(null);try {if (action === "disable" || action === "retry") {- const response = await fetch("/api/local-computer/interrupt", { method: "POST" });+ const response = await serverFetch("/api/local-computer/interrupt", { method: "POST" });if (!response.ok) {setError({ key: "computer.linux.stopFailed" });return;diff --git a/src/components/LocalComputerSection.tsx b/src/components/LocalComputerSection.tsxindex d1de10b4cf..464dab1c63 100644--- a/src/components/LocalComputerSection.tsx+++ b/src/components/LocalComputerSection.tsx@@ -20,7 +20,7 @@ import { cn } from "@/lib/cn";import { localizeComputerProblem } from "@/lib/computer-messages";import { computerInventoryRequest, jsonPostRequest, type ComputerApiRequest } from "@/lib/computer-requests";import { useStore } from "@/state/store";-import { VpsComputersCard } from "./VpsComputersCard"; import { KeysLink } from "./keys/KeysLink";+import { VpsComputersCard } from "./VpsComputersCard"; import { KeysLink } from "./keys/KeysLink"; import { serverFetch } from "@/lib/relay-server";type Action = "pull" | "run" | "start" | "stop" | "remove" | "recreate";@@ -798,7 +798,7 @@ export function LocalComputerSection({ privateOnly = false }: { privateOnly?: boconst [announcement, setAnnouncement] = useState("");const refresh = useCallback(async (signal?: AbortSignal) => {- const response = await fetch(...computerInventoryRequest("status", signal));+ const response = await serverFetch(...computerInventoryRequest("status", signal));const body = await response.json().catch(() => ({}));if (signal?.aborted) return;if (!response.ok) throw new Error(body.error ?? t("vm.err.status", { code: response.status }));@@ -808,7 +808,7 @@ export function LocalComputerSection({ privateOnly = false }: { privateOnly?: bo}, []);const refreshInventory = useCallback(async (signal?: AbortSignal) => {- const response = await fetch(...computerInventoryRequest("local-vms", signal));+ const response = await serverFetch(...computerInventoryRequest("local-vms", signal));const body = await response.json().catch(() => ({}));if (!response.ok) throw new Error(body.error ?? t("vm.err.inventory", { code: response.status }));const payload = body as LocalVmInventoryPayload;@@ -819,7 +819,7 @@ export function LocalComputerSection({ privateOnly = false }: { privateOnly?: bo}, []);const refreshCloudInventory = useCallback(async (signal?: AbortSignal) => {- const response = await fetch(...computerInventoryRequest("cloud", signal));+ const response = await serverFetch(...computerInventoryRequest("cloud", signal));const body = await response.json().catch(() => ({}));if (!response.ok) throw new Error(body.error ?? t("vm.err.cloudInventory", { code: response.status }));const payload = body as CloudComputerInventoryPayload;@@ -841,7 +841,7 @@ export function LocalComputerSection({ privateOnly = false }: { privateOnly?: bo}, []);const refreshVpsInventory = useCallback(async (signal?: AbortSignal) => {- const response = await fetch(...computerInventoryRequest("vps", signal));+ const response = await serverFetch(...computerInventoryRequest("vps", signal));const body = await response.json().catch(() => ({}));if (!response.ok) throw new Error(body.error ?? t("vm.err.vpsInventory", { code: response.status }));const payload = body as VpsComputerInventoryPayload;@@ -940,7 +940,7 @@ export function LocalComputerSection({ privateOnly = false }: { privateOnly?: bo}, [privateOnly, refreshVpsInventory, vpsRefreshKey]);const post = async (action: Exclude<Action, "recreate">, signal: AbortSignal) => {- const response = await fetch(`/api/local-computer/${action}`, {+ const response = await serverFetch(`/api/local-computer/${action}`, {method: "POST",headers: { "content-type": "application/json" },body: "{}",@@ -1007,7 +1007,7 @@ export function LocalComputerSection({ privateOnly = false }: { privateOnly?: bosetPolicyPending(true);setError(null);try {- const response = await fetch("/api/config", {+ const response = await serverFetch("/api/config", {method: "PATCH",headers: { "content-type": "application/json" },body: JSON.stringify({ localVm: { mode, maxInstances } }),@@ -1024,7 +1024,7 @@ export function LocalComputerSection({ privateOnly = false }: { privateOnly?: bo};const saveIdleTimeout = async (idleTimeoutMinutes: number) => {- const response = await fetch("/api/config", {+ const response = await serverFetch("/api/config", {method: "PATCH",headers: { "content-type": "application/json" },body: JSON.stringify({ localVm: { idleTimeoutMinutes } }),@@ -1047,7 +1047,7 @@ export function LocalComputerSection({ privateOnly = false }: { privateOnly?: bosetDeletingBotId(instance.botId);setInventoryError(null);try {- const response = await fetch(...request);+ const response = await serverFetch(...request);const body = await response.json().catch(() => ({}));if (!response.ok) throw new Error(body.error ?? t("vm.deleteError"));await refreshInventory();@@ -1069,7 +1069,7 @@ export function LocalComputerSection({ privateOnly = false }: { privateOnly?: bosetCloudError(null);setAnnouncement("");try {- const response = await fetch(...request);+ const response = await serverFetch(...request);const body = await response.json().catch(() => ({}));if (!response.ok) throw new Error(body.error ?? t(action === "delete" ? "vm.cloud.deleteError" : "vm.cloud.sleepError"));const deletionPending = action === "delete" && body?.pending === true;@@ -1153,7 +1153,7 @@ export function LocalComputerSection({ privateOnly = false }: { privateOnly?: bosetVpsRemovingName(instance.name);setVpsError(null);try {- const response = await fetch(...request);+ const response = await serverFetch(...request);const body = await response.json().catch(() => ({}));if (!response.ok) throw new Error(body.error ?? t("vm.vpsRemoveError"));await refreshVpsInventory();diff --git a/src/components/LocalVmWorkspace.tsx b/src/components/LocalVmWorkspace.tsxindex 16ab921dd6..9d5b80c4ce 100644--- a/src/components/LocalVmWorkspace.tsx+++ b/src/components/LocalVmWorkspace.tsx@@ -37,6 +37,7 @@ import { Select } from "./Select";import { productName } from "@/lib/brand";import { randomUuid } from "@/lib/random-uuid";import { useNativeViewObscured } from "@/lib/native-view-obscured";+import { serverFetch } from "@/lib/relay-server";const SLOT_CONTEXTS = ["local-vm-workspace:left", "local-vm-workspace:right"] as const;@@ -81,7 +82,7 @@ async function readComputerControl(botId: string): Promise<LocalVmWorkspaceContr}function bestEffortRelease(botId: string, controlLeaseId: string) {- void fetch(`/api/bots/${botId}/computer/control`, {+ void serverFetch(`/api/bots/${botId}/computer/control`, {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify({ action: "release", controlLeaseId }),diff --git a/src/components/PeopleSection.tsx b/src/components/PeopleSection.tsxindex 7bd1335d42..07b37c2bc9 100644--- a/src/components/PeopleSection.tsx+++ b/src/components/PeopleSection.tsx@@ -13,6 +13,7 @@ import { canPairDevices } from "./ServerPairingCard";import { normalizeAccessEntry, withEntry, withoutEntry, type SignInLists } from "./SignInAccessCard";import { Card } from "./SettingsPrimitives";import { Select } from "./Select";+import { serverFetch } from "@/lib/relay-server";export type Role = "admin" | "member";@@ -203,7 +204,7 @@ export function PeopleSection({ simple = false, startOpen = false }: { simple?:api("/api/auth/sessions").catch(() => ({ sessions: [] })),api("/api/usage?groupBy=user").catch(() => ({ groups: [] })),api("/api/settings/custom-domain").catch(() => null),- fetch("/.well-known/openmausbot/environment").then((res) => (res.ok ? res.json() : null)).catch(() => null),+ serverFetch("/.well-known/openmausbot/environment").then((res) => (res.ok ? res.json() : null)).catch(() => null),]);const current: SignInLists = {admins: Array.isArray(config?.signIn?.admins) ? config.signIn.admins : [],diff --git a/src/components/ProfileSettings.tsx b/src/components/ProfileSettings.tsxindex 62bba6fa5b..ce91ea2483 100644--- a/src/components/ProfileSettings.tsx+++ b/src/components/ProfileSettings.tsx@@ -12,6 +12,7 @@ import { SETTINGS_INPUT, SettingsField } from "./SettingsPrimitives";import { profileInitials } from "./SidebarProfileMenu";import { User } from "lucide-react";import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";+import { serverFetch } from "@/lib/relay-server";const PHOTO_MIN_SIDE = 64;const PHOTO_MAX_SIDE = 8192;@@ -171,7 +172,7 @@ export function ProfileFields() {.catch(() => {});return;}- void fetch("/api/config", {+ void serverFetch("/api/config", {method: "PUT",headers: { "content-type": "application/json" },body: JSON.stringify({ profile: { name: name.trim(), email: email.trim().toLowerCase() } }),diff --git a/src/components/SkillsSection.tsx b/src/components/SkillsSection.tsxindex f1f10abb66..cbbc5f0a32 100644--- a/src/components/SkillsSection.tsx+++ b/src/components/SkillsSection.tsx@@ -8,6 +8,7 @@ import { Card, Switch } from "./SettingsPrimitives";import type { SkillsLibrarySkillWire } from "../../shared/wire";import { Layer } from "./Layer";import { Select } from "./Select";+import { serverFetch } from "@/lib/relay-server";export function filterLibrarySkills(skills: readonly SkillsLibrarySkillWire[],@@ -59,7 +60,7 @@ export function SkillsSection() {const refresh = async (cancelled?: () => boolean) => {try {- const response = await fetch("/api/skills-library");+ const response = await serverFetch("/api/skills-library");const body = (await response.json()) as { skills?: SkillsLibrarySkillWire[]; error?: string };if (!response.ok) throw new Error(body.error ?? t("skills.library.loadError"));if (cancelled?.()) return;@@ -90,12 +91,12 @@ export function SkillsSection() {try {// Read the complete current list while mutations are serialized, so a second row never overwrites an earlier// assignment.- const listing = await fetch("/api/skills-library");+ const listing = await serverFetch("/api/skills-library");const listed = (await listing.json()) as { skills?: SkillsLibrarySkillWire[]; error?: string };if (!listing.ok) throw new Error(listed.error ?? t("skills.library.loadError"));const current = (listed.skills ?? []).filter((skill) => skill.assignedBots.some((bot) => bot.id === botId)).map((skill) => skill.name);const next = remove ? current.filter((skill) => skill !== name) : [...new Set([...current, name])];- const response = await fetch(`/api/bots/${encodeURIComponent(botId)}/skills-library`, {+ const response = await serverFetch(`/api/bots/${encodeURIComponent(botId)}/skills-library`, {method: "PUT",headers: { "content-type": "application/json" },body: JSON.stringify({ skills: next }),@@ -127,7 +128,7 @@ export function SkillsSection() {setWorking(skill.name);setError("");try {- const response = await fetch(`/api/skills-library/${encodeURIComponent(skill.name)}`, {+ const response = await serverFetch(`/api/skills-library/${encodeURIComponent(skill.name)}`, {method: "PATCH",headers: { "content-type": "application/json" },body: JSON.stringify({ enabled: !skill.enabled }),@@ -150,7 +151,7 @@ export function SkillsSection() {setWorking(skill.name);setError("");try {- const response = await fetch(`/api/skills-library/${encodeURIComponent(skill.name)}`, {+ const response = await serverFetch(`/api/skills-library/${encodeURIComponent(skill.name)}`, {method: "PATCH",headers: { "content-type": "application/json" },body: JSON.stringify({ everyBot: !skill.everyBot }),@@ -169,7 +170,7 @@ export function SkillsSection() {const view = async (skill: SkillsLibrarySkillWire, review = false) => {setError("");try {- const response = await fetch(`/api/skills-library/${encodeURIComponent(skill.name)}`);+ const response = await serverFetch(`/api/skills-library/${encodeURIComponent(skill.name)}`);const body = (await response.json()) as { text?: string; error?: string };if (!response.ok) throw new Error(body.error ?? t("skills.error.load"));if (!body.text) throw new Error(t("skills.error.contentsImport"));@@ -186,7 +187,7 @@ export function SkillsSection() {setError("");setImportMessage("");try {- const response = await fetch("/api/skills-library", {+ const response = await serverFetch("/api/skills-library", {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify({ text }),diff --git a/src/components/app/PageTools.tsx b/src/components/app/PageTools.tsxindex 9d55b0b28e..adc52c96e1 100644--- a/src/components/app/PageTools.tsx+++ b/src/components/app/PageTools.tsx@@ -20,6 +20,7 @@ import { appDownloadPath, publishAppPage, unpublishPage } from "./app-api";import { AppFrame, type AppFrameHandle } from "./AppFrame";import type { AppSelection } from "./app-frame-host";import { ASK_CHIP, ASK_CHIP_IDLE, ASK_CHIP_PICKED, ASK_PRIMARY_BUTTON } from "../AskCard";+import { serverFetch } from "@/lib/relay-server";/** A page starts at this height in the chat and grows to its content up to the cap, then scrolls inside. */export const PAGE_HEIGHT = { start: 520, cap: 560 } as const;@@ -114,7 +115,7 @@ export function usePageSave(threadId: string, messageId: string, title: string)setBusy(true);setReason("");try {- const response = await fetch(appDownloadPath(threadId, messageId, rev));+ const response = await serverFetch(appDownloadPath(threadId, messageId, rev));if (!response.ok) throw new Error(serverErrorText(await response.json().catch(() => null), t("chat.preview.saveFailed")));const name = canonicalDownloadFilename({ contentDisposition: response.headers.get("content-disposition"), fallback: `${title}.html` });await saveToDevice(new File([await response.blob()], name, { type: "text/html" }));diff --git a/src/components/computer-takeover.ts b/src/components/computer-takeover.tsindex 7ea6ca9ba6..0f68b6859d 100644--- a/src/components/computer-takeover.ts+++ b/src/components/computer-takeover.ts@@ -1,5 +1,6 @@import { useCallback, useEffect, useRef, useState } from "react";import { LocalizedPanelError } from "@/lib/computer-messages";+import { serverFetch } from "@/lib/relay-server";export interface TakeoverSnapshot {held: boolean;@@ -96,7 +97,7 @@ export async function openProviderDesktop({ botId, title, request, join, current}function post(path: string, body: unknown): void {- void fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), keepalive: true })+ void serverFetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), keepalive: true }).catch(() => {});}diff --git a/src/components/settings/DesktopKinds.tsx b/src/components/settings/DesktopKinds.tsxindex f569b428a9..f6b456a237 100644--- a/src/components/settings/DesktopKinds.tsx+++ b/src/components/settings/DesktopKinds.tsx@@ -10,12 +10,13 @@ import { useAccountSummary } from "./account-summary";import { useOtherPlaces } from "./settings-context";import { SettingsDialog } from "./SettingsDialog";import { useSettingsShell } from "./settings-shell";+import { serverFetch } from "@/lib/relay-server";type PrivateStatus = { runtime: string | null; daemonUp: boolean; image: boolean; ready: boolean } | null;type Kind = "ready" | "setup" | "none" | "attention" | "elsewhere";const read = async <T,>(which: "status" | "cloud" | "vps"): Promise<T | null> => {- const response = await fetch(...computerInventoryRequest(which)).catch(() => null);+ const response = await serverFetch(...computerInventoryRequest(which)).catch(() => null);if (!response?.ok) return null;return await response.json().catch(() => null) as T | null;};diff --git a/src/components/team-files/TeamFilesPage.tsx b/src/components/team-files/TeamFilesPage.tsxindex 13beb3ffe3..9c4e1b201b 100644--- a/src/components/team-files/TeamFilesPage.tsx+++ b/src/components/team-files/TeamFilesPage.tsx@@ -9,6 +9,7 @@ import type { LocaleKey } from "@/locales";import { api, ApiError } from "@/state/api";import { useStore } from "@/state/store";import { TOOL_PAGE_TITLE, ToolPage, ToolPageActions, ToolPageHeader } from "../ToolPageShell";+import { serverFetch } from "@/lib/relay-server";// Team files: the Team Cloud's one shared folder (server/routes/team-files.ts), for every teammate and bot. A folder list// with breadcrumbs, upload by button or drop, new folder, download, rename, delete (an admin anything, a member what they@@ -57,7 +58,7 @@ export function refusalText(error: unknown, limits: { uploadMax: number; cap: nu/** One file up, the bytes as the request body. */async function uploadFile(folder: string, file: File): Promise<void> {- const res = await fetch(`${BASE}/file?path=${encodeURIComponent(folder)}&name=${encodeURIComponent(file.name)}`, {+ const res = await serverFetch(`${BASE}/file?path=${encodeURIComponent(folder)}&name=${encodeURIComponent(file.name)}`, {method: "PUT", body: file, headers: { "content-type": "application/octet-stream" },});if (!res.ok) throw new ApiError(`${res.status}`, res.status, await res.json().catch(() => ({})));@@ -136,7 +137,7 @@ export function TeamFilesPage() {if (kind !== "text") { setPreview({ entry }); return; }if (entry.size > PREVIEW_MAX_BYTES) { setPreview({ entry, tooLarge: true }); return; }try {- const res = await fetch(fileUrl(entry.path));+ const res = await serverFetch(fileUrl(entry.path));setPreview({ entry, text: res.ok ? await res.text() : "" });} catch {setPreview({ entry, text: "" });diff --git a/src/lib/bot-creation-draft.ts b/src/lib/bot-creation-draft.tsindex 26240d1a3d..7f2280f15a 100644--- a/src/lib/bot-creation-draft.ts+++ b/src/lib/bot-creation-draft.ts@@ -5,6 +5,7 @@ import type { Routine, RoutineInput } from "./routines";import type { ChosenPreset } from "./bot-presets";import { t } from "@/lib/i18n";import { randomUuid } from "./random-uuid";+import { serverFetch } from "./relay-server";export const EMPTY_BOT_DEFAULTS: NewBotDefaults = { profile: {}, memory: {}, skills: [], routines: [] };@@ -139,7 +140,7 @@ export class BotCreationDraft {const { dataUrl } = await this.network<{ dataUrl: string }>("/api/bot-defaults/avatar", {method: "POST", body: JSON.stringify({ profile: { name, title, description }, prompt: body.prompt }),});- const blob = await (await fetch(dataUrl)).blob();+ const blob = await (await serverFetch(dataUrl)).blob();const avatarUrl = await this.uploadAvatar(new File([blob], "avatar.png", { type: blob.type }));result = { avatarUrl, bot: { ...this.bot, avatarUrl, avatarCrop: "circle" } };} else if ((path === "/api/routines" && method === "POST") || (path.startsWith("/api/routines/draft-") && method === "PATCH")) {diff --git a/src/lib/browser-stream-client.ts b/src/lib/browser-stream-client.tsindex 8680230aaa..2cb4c5999f 100644--- a/src/lib/browser-stream-client.ts+++ b/src/lib/browser-stream-client.ts@@ -4,6 +4,7 @@// reconnect opens with the newest size and cap, and OpenMausBot's own messages are passed on.import { t } from "./i18n";+import { serverFetch } from "./relay-server";/** Refusals before open a client that was connected takes as its server restarting: about 45 s with the backoff. */const RESTART_RETRIES = 8;@@ -190,7 +191,7 @@ export async function uploadPreviewStreamFiles(): Promise<void> {const body = new FormData();for (const file of files) body.append("file", file, file.name ?? "file");- const response = await fetch(chooser.uploadUrl, {+ const response = await serverFetch(chooser.uploadUrl, {method: "POST",body,credentials: chooser.credentials ? "include" : "omit",diff --git a/src/lib/cloud-power.ts b/src/lib/cloud-power.tsindex 9ad2f6c81c..eef106b15a 100644--- a/src/lib/cloud-power.ts+++ b/src/lib/cloud-power.ts@@ -1,3 +1,4 @@+import { serverFetch } from "./relay-server";// A Cloud home on a plan that sleeps tells its pages it is going to sleep (a `power` frame on the event stream, or an// "asleep" answer). From then on the page sends nothing in the background: any request reaching the Cloud would wake it.// The next thing the person does (a click, a key, the window regaining focus) wakes it again, which takes about a second.@@ -34,7 +35,7 @@ function set(next: boolean) {* "asleep". */export function markCloudAwake(): void {if (!asleep) return;- void fetch(WAKE_PATH).catch(() => {});+ void serverFetch(WAKE_PATH).catch(() => {});detach?.();detach = null;set(false);diff --git a/src/lib/composer-attachments.ts b/src/lib/composer-attachments.tsindex e65cb3a51e..a5ccf29e29 100644--- a/src/lib/composer-attachments.ts+++ b/src/lib/composer-attachments.ts@@ -1,6 +1,7 @@import { isCitationAttachment, serializeCitation, type CitationAttachment } from "./citations.ts";import { randomUuid } from "./random-uuid.ts";import { FILE_MAX_BYTES } from "../../shared/upload-limits.ts";+import { serverFetch } from "./relay-server.ts";export { dataContextFor, type DataContext, type DataViewContext } from "../../shared/data-context.ts";export type PasteAttachment = {@@ -301,7 +302,7 @@ async function uploadWithRetry<T>(url: string, init: RequestInit): Promise<T> {for (let attempt = 0; attempt < UPLOAD_ATTEMPTS; attempt += 1) {let response: Response;try {- response = await fetch(url, init);+ response = await serverFetch(url, init);} catch (error) {const aborted = typeof error === "object" && error !== null && "name" in error && error.name === "AbortError";if (aborted || attempt === UPLOAD_ATTEMPTS - 1) throw error;@@ -724,7 +725,7 @@ export function discardUnsentUpload(attachment: Attachment): void {if ((attachment.kind !== "image" && attachment.kind !== "file") || !attachment.path) return;const name = attachmentBasename(attachment.path);if (!/^[A-Za-z0-9-]+\.[A-Za-z0-9]{1,10}$/.test(name)) return;- void fetch(`/api/attachments/${encodeURIComponent(name)}`, { method: "DELETE" }).catch(() => undefined);+ void serverFetch(`/api/attachments/${encodeURIComponent(name)}`, { method: "DELETE" }).catch(() => undefined);}export function attachmentBasename(path: string): string {diff --git a/src/lib/copy-image.ts b/src/lib/copy-image.tsindex 86d747a907..ce2c4bba56 100644--- a/src/lib/copy-image.ts+++ b/src/lib/copy-image.ts@@ -1,4 +1,5 @@import type { CopyResult } from "./copy-text";+import { serverFetch } from "./relay-server";/** PNG is the one image type every browser clipboard accepts, so other types are redrawn as PNG first. */export function canCopyImage(): boolean {@@ -30,7 +31,7 @@ async function drawAsPng(blob: Blob): Promise<Blob> {}async function imageAsPng(source: string, toPng: (blob: Blob) => Promise<Blob>): Promise<Blob> {- const response = await fetch(source);+ const response = await serverFetch(source);if (!response.ok) throw new Error(`image ${response.status}`);const blob = await response.blob();return blob.type === "image/png" ? blob : toPng(blob);diff --git a/src/lib/desktop-connection.ts b/src/lib/desktop-connection.tsindex 8ac5a31753..5beb997040 100644--- a/src/lib/desktop-connection.ts+++ b/src/lib/desktop-connection.ts@@ -1,6 +1,7 @@import RFB from "@novnc/novnc";import { DESKTOP_VIEWER_TARGET } from "../../shared/desktop-viewer";import { isMacPlatform } from "./keyboard-shortcuts";+import { serverFetch } from "./relay-server";export interface DesktopConnectionEvents {connected(): void;@@ -29,13 +30,13 @@ export async function connectDesktop(screen: HTMLElement, target: string, optionconst signal = AbortSignal.any([cancelled, AbortSignal.timeout(30_000)]);if (target.startsWith("vps/")) {const query = options.threadId ? `?${new URLSearchParams({ threadId: options.threadId })}` : "";- const joined = await fetch(`/api/bots/${target.slice(4)}/computer/join${query}`, {+ const joined = await serverFetch(`/api/bots/${target.slice(4)}/computer/join${query}`, {method: "POST", headers: { "content-type": "application/json" }, body: "{}", signal,});if (!joined.ok) throw new DesktopUnreachable();}const path = `/api/desktop-viewer/${target}`;- const response = await fetch(path, { signal, credentials: "same-origin", cache: "no-store" });+ const response = await serverFetch(path, { signal, credentials: "same-origin", cache: "no-store" });if (!response.ok) throw new DesktopUnreachable();const config = await response.json();cancelled.throwIfAborted();diff --git a/src/lib/launch-marks.ts b/src/lib/launch-marks.tsindex 30895209f3..50e712415c 100644--- a/src/lib/launch-marks.ts+++ b/src/lib/launch-marks.ts@@ -1,3 +1,4 @@+import { serverFetch } from "./relay-server";// The page's part of the desktop app's launch record: when it first painted, when the sidebar and the open chat were// drawn, and how many requests left this computer before then. Marks and counts only, posted once to the local server;// a page that cannot post loses the record and nothing else.@@ -100,7 +101,7 @@ export function startDesktopLaunchMarks(): void {now: () => performance.now(), timeOrigin: performance.timeOrigin, origin: location.origin,entries: (type) => (type === "longtask" ? longtasks : performance.getEntriesByType(type)) as ReturnType<LaunchMarkDeps["entries"]>,later: (run, ms) => { setTimeout(run, ms); },- post: (part) => { void fetch("/api/diagnostics/launch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(part), keepalive: true }).catch(() => {}); },+ post: (part) => { void serverFetch("/api/diagnostics/launch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(part), keepalive: true }).catch(() => {}); },});} catch {}}diff --git a/src/lib/live-events.ts b/src/lib/live-events.tsindex bd564082a6..3536d0f79b 100644--- a/src/lib/live-events.ts+++ b/src/lib/live-events.ts@@ -1,7 +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 { relayEventSource, relayLink, type LiveEventSourceLike } from "./relay-server";import { recordBotTextMessage, recordRuntimeEvent } from "./voice-latency-probe";import { noteTurnEvent } from "@/state/turn-status";import { forgetLiveReplies, noteLiveReplyEvent, noteLiveReplyMessage } from "@/state/live-reply";@@ -23,17 +23,7 @@ export interface LiveFrame {event?: unknown;}-interface LiveMessageEvent {- data: string;- lastEventId?: string;-}--export interface LiveEventSourceLike {- onopen: (() => void) | null;- onerror: (() => void) | null;- onmessage: ((event: LiveMessageEvent) => void) | null;- close: () => void;-}+export type { LiveEventSourceLike };interface ListenerTarget {addEventListener: (type: string, listener: () => void) => void;diff --git a/src/lib/memory.ts b/src/lib/memory.tsindex 8676c7e886..9d7e2745d0 100644--- a/src/lib/memory.ts+++ b/src/lib/memory.ts@@ -1,6 +1,7 @@import { ApiError, api } from "@/state/store";import { intlLocale, t } from "@/lib/i18n";import { serverErrorText } from "@/lib/server-error";+import { serverFetch } from "./relay-server";export const MEMORY_INDEX = "MEMORY.md";export const SOUL_PATH = "SOUL.md";@@ -76,7 +77,7 @@ export function fetchMemoryDoc(botId: string, path: string, mine = false): Promi}export async function saveMemoryDoc(botId: string, path: string, text: string, expectedHash: string | undefined, mine = false): Promise<SaveResult> {- const response = await fetch(`${memoryRoute(botId, mine)}/file`, {+ const response = await serverFetch(`${memoryRoute(botId, mine)}/file`, {method: "PUT",headers: { "content-type": "application/json" },body: JSON.stringify({ path, text, expectedHash }),diff --git a/src/lib/relay-server-callers.test.ts b/src/lib/relay-server-callers.test.tsnew file mode 100644index 0000000000..bacbbf474f--- /dev/null+++ b/src/lib/relay-server-callers.test.ts@@ -0,0 +1,28 @@+// While the page holds a relay pairing (a phone browser away from home), its own server is reachable only through+// MausBot Relay, so every request the app makes goes through serverFetch (src/lib/relay-server.ts), which keeps any+// path outside /api a plain fetch. A bare fetch( in app code is a screen that breaks away from home.+import { execFileSync } from "node:child_process";+import { readFileSync } from "node:fs";+import { describe, expect, it } from "vitest";++const ROOT = new URL("../../", import.meta.url);++/** App code: not tests, the relay itself, test rigs, or the preview pages that stand in a fake server for fetch. */+function appFiles(): string[] {+ const out = execFileSync("git", ["ls-files", "src"], { cwd: ROOT, encoding: "utf8" });+ return out.split("\n").filter((file) => /\.(ts|tsx)$/.test(file))+ .filter((file) => !/\.test\.|\.e2e\./.test(file) && !file.startsWith("src/testing/") && !file.startsWith("src/lib/e2e/"))+ .filter((file) => file !== "src/lib/relay-server.ts" && !file.endsWith("-preview.tsx"));+}++describe("app requests to its own server", () => {+ it("all go through serverFetch, never a bare fetch", () => {+ const bare: string[] = [];+ for (const file of appFiles()) {+ readFileSync(new URL(file, ROOT), "utf8").split("\n").forEach((line, index) => {+ if (/(?<![\w$.])fetch\(/.test(line.replace(/\/\/.*$/, ""))) bare.push(`${file}:${index + 1}`);+ });+ }+ expect(bare).toEqual([]);+ });+});diff --git a/src/lib/relay-server.ts b/src/lib/relay-server.tsindex 4e2d33f8b8..6720a79e49 100644--- a/src/lib/relay-server.ts+++ b/src/lib/relay-server.ts@@ -1,40 +1,56 @@// 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";+// It imports nothing: server code type-checks src/lib/composer-attachments.ts, whose uploads come through here, and+// must not take in the browser's relay crypto (e2e/) or the live events store with it.-let link: RelayLink | null = null;+/** What this file uses of a RelayLink (src/lib/e2e/relay-link.ts). */+export interface ServerLink {+ fetch(path: string, request?: { method?: string; headers?: Headers | Record<string, string>; body?: Uint8Array | null; signal?: AbortSignal }): Promise<Response>;+ close(): void;+}++/** An EventSource as the live events transport uses it (src/lib/live-events.ts): the browser's own, or one through+ * the relay link. */+export interface LiveEventSourceLike {+ onopen: (() => void) | null;+ onerror: (() => void) | null;+ onmessage: ((event: { data: string; lastEventId?: string }) => void) | null;+ close: () => void;+}++let link: ServerLink | 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 {+export function setRelayLink(next: ServerLink | null): void {if (link === next) return;link?.close();link = next;}-export function relayLink(): RelayLink | null {+export function relayLink(): ServerLink | 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> {+export async function serverFetch(path: string, init?: RequestInit): Promise<Response> {const current = link;- if (!current || !API.test(path)) return fetch(path, init);+ // Called as the caller called it: with no options when it gave none.+ if (!current || !API.test(path)) return init ? fetch(path, init) : fetch(path);// 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());// The normalized target: spaces and other unsafe characters encoded, any fragment left out.const { pathname, search } = new URL(request.url);- return current.fetch(pathname + search, { method: request.method, headers: request.headers, body, signal: init.signal ?? undefined });+ return current.fetch(pathname + search, { 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 {+export function relayEventSource(current: ServerLink, url: string): LiveEventSourceLike {const stop = new AbortController();const source: LiveEventSourceLike = { onopen: null, onerror: null, onmessage: null, close: () => stop.abort() };void (async () => {diff --git a/src/lib/template-share.ts b/src/lib/template-share.tsindex b39fc2d0c9..0b46a65525 100644--- a/src/lib/template-share.ts+++ b/src/lib/template-share.ts@@ -3,6 +3,7 @@ import { SKILL_FILE_LIMITS, skillFilePathProblem } from "../../shared/skill-fileimport { t } from "./i18n";import { api, type Action, type Bot, type Group } from "@/state/store";import type { Routine } from "@/lib/routines";+import { serverFetch } from "./relay-server";/** The most a chosen folder may hold, as the server's own folder cap. */export const TEMPLATE_FOLDER_MAX_BYTES = 4 * 1024 * 1024;@@ -84,7 +85,7 @@ export async function saveTemplateFolder(card: Pick<TemplateCard, "id" | "name">if (!chosen) return null;return (await api<{ path: string }>(`/api/share/${encodeURIComponent(card.id)}/save`, post({ path: chosen }))).path;}- const response = await fetch(`/api/share/${encodeURIComponent(card.id)}/download`);+ const response = await serverFetch(`/api/share/${encodeURIComponent(card.id)}/download`);if (!response.ok) throw new Error(t("template.failed"));const url = URL.createObjectURL(new Blob([await response.blob()], { type: "application/zip" }));const link = document.createElement("a");diff --git a/src/lib/theme/runtime.ts b/src/lib/theme/runtime.tsindex 6750ceeaa4..f2a590bf21 100644--- a/src/lib/theme/runtime.ts+++ b/src/lib/theme/runtime.ts@@ -5,6 +5,7 @@ import { readColorScheme } from "../color-scheme";import { DEFAULT_SKIN_CHOICE, SKIN_IDS, applySkinChoice, readSkin, resolveSkin, subscribeSkin, THEME_SKINS, wearSkin, type SkinChoice } from "../skins";import { accentPalette, canvasPalette, modeOf } from "./palette";import { applyThemeCss } from "./theme-css";+import { serverFetch } from "../relay-server";const CACHE_KEY = "omb-theme";const SAFE_KEY = "omb-safe-look";@@ -124,7 +125,7 @@ function cachedTheme(): WornTheme | null {/** Asks the server which theme this person wears and wears it. A failed read keeps what is painted. */export async function loadTheme(): Promise<void> {try {- const res = await fetch("/api/themes/active", { headers: { accept: "application/json" } });+ const res = await serverFetch("/api/themes/active", { headers: { accept: "application/json" } });if (!res.ok) return;const active = (await res.json()) as ActiveTheme;const theme = active.theme ? themeFileSchema.safeParse(active.theme) : null;@@ -141,7 +142,7 @@ export function applyThemeFrame(frame: { skin?: string }): void {}const wearOnServer = (id: string | null, skin?: SkinChoice) =>- fetch("/api/themes/active", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ id, ...(skin ? { skin } : {}) }) })+ serverFetch("/api/themes/active", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ id, ...(skin ? { skin } : {}) }) }).then((res) => res.ok, () => false);/** Takes the custom theme off for this person, here at once and on the server for their other windows. */diff --git a/src/lib/tts/index.ts b/src/lib/tts/index.tsindex ad4015caa4..8ddb983a4d 100644--- a/src/lib/tts/index.ts+++ b/src/lib/tts/index.ts@@ -5,6 +5,7 @@ import { recordBlockTiming, recordPrepared, recordSpeakEnter } from "../voice-laimport { t, tFromServer } from "@/lib/i18n";import { serverErrorText } from "@/lib/server-error";import type { ServerErrorBody } from "../../../shared/server-text";+import { serverFetch } from "../relay-server";export type SpeechStatus = "idle" | "preparing" | "speaking";@@ -367,7 +368,7 @@ export class Speaker {}private async prepare(text: string, voiceId: string | undefined, signal: AbortSignal): Promise<string[]> {- const res = await fetch("/api/tts/prepare", {+ const res = await serverFetch("/api/tts/prepare", {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify({ text, voiceId }),@@ -382,7 +383,7 @@ export class Speaker {}private async render(text: string, voiceId: string | undefined, signal: AbortSignal): Promise<Blob> {- const res = await fetch("/api/tts/speak", {+ const res = await serverFetch("/api/tts/speak", {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify({ text, voiceId }),diff --git a/src/lib/window-prefs.ts b/src/lib/window-prefs.tsindex c634ad824a..9ad7a85b38 100644--- a/src/lib/window-prefs.ts+++ b/src/lib/window-prefs.ts@@ -21,6 +21,7 @@ import { readColorUserBubbles, setColorUserBubbles } from "./user-bubble-prefereimport { latestWebPanels, setWebPanels } from "./web-panel-preferences";import { newWebPanelId, validateWebPanel, type WebPanel } from "./web-panels";import { onWindowPrefChanged } from "./window-pref-changes";+import { serverFetch } from "./relay-server";type Pref<I extends WindowPrefId> = { read(): unknown; write(value: WindowPrefValue<I>): unknown };const ogb = () => (typeof window === "undefined" ? undefined : window.ogb);@@ -118,7 +119,7 @@ export function reportWindowPrefs(): void {report = setTimeout(() => {report = null;void windowPrefValues()- .then((values) => fetch("/api/window-prefs", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ values }) }))+ .then((values) => serverFetch("/api/window-prefs", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ values }) })).catch(() => undefined);}, 200);}diff --git a/src/main.tsx b/src/main.tsxindex e098e7bb71..9962472f8e 100644--- a/src/main.tsx+++ b/src/main.tsx@@ -20,6 +20,7 @@ import { PageBoundary } from "./components/PageBoundary";import { endedBeforeReload, forgetEndedSession } from "./lib/session-ended";import { signInGateShown } from "./lib/sign-in-gate";import { startDesktopLaunchMarks } from "./lib/launch-marks";+import { serverFetch } from "./lib/relay-server";import "./styles.css";// Before first paint; settleInterfaceMode must run before applySkin writes omb-skin.@@ -39,7 +40,7 @@ const appPage = PAGES_WITHOUT_THE_APP.has(location.pathname) ? null : loadApp();if (appPage) startDesktopLaunchMarks();/** A team's name as its server describes itself to anyone (the descriptor's label), null when it can't say. */-const teamName = () => fetch("/.well-known/openmausbot/environment").then((res) => res.json() as Promise<{ label?: unknown; capabilities?: { cloudTeam?: unknown } }>)+const teamName = () => serverFetch("/.well-known/openmausbot/environment").then((res) => res.json() as Promise<{ label?: unknown; capabilities?: { cloudTeam?: unknown } }>).then((descriptor) => (descriptor.capabilities?.cloudTeam === true && typeof descriptor.label === "string" ? descriptor.label : null), () => null);async function chooseRoot(): Promise<React.ReactNode> {diff --git a/src/pair/PairPage.tsx b/src/pair/PairPage.tsxindex d1372c720e..a2a1829b15 100644--- a/src/pair/PairPage.tsx+++ b/src/pair/PairPage.tsx@@ -19,6 +19,7 @@ import { pairedDestination } from "../lib/phone-pairing";import { t } from "../lib/i18n";import { formatPairingCode, PAIRING_INPUT_PROBLEM_KEY, readPairingInput } from "../../shared/pairing-code";import { isPrivateHost } from "../../shared/private-host";+import { serverFetch } from "../lib/relay-server";const input = "mt-1 w-full rounded-md border border-hairline/40 bg-inset px-3 py-2 text-[14px] text-ink outline-none focus:border-accent-border";const button = "mt-5 w-full rounded-md bg-accent px-4 py-2 text-[14px] font-medium text-accent-ink disabled:opacity-50";@@ -110,7 +111,7 @@ export function PairPage({ initialCode, initialEmail = null, reason }: { initial}, []);useEffect(() => {- void fetch("/.well-known/openmausbot/environment")+ void serverFetch("/.well-known/openmausbot/environment").then((r) => (r.ok ? r.json() : null)).then((d: EnvironmentDescriptor | null) => {setEnvironment(d);diff --git a/src/state/read-visible.ts b/src/state/read-visible.tsindex 35025b59b4..021536c706 100644--- a/src/state/read-visible.ts+++ b/src/state/read-visible.ts@@ -1,9 +1,10 @@import { botShowsUnread } from "@/lib/bot-unread";import type { AppState, BotAnnouncement, Group } from "./store";+import { serverFetch } from "@/lib/relay-server";type SendRead = (path: string, threadId: string, updatedAt: number) => void;const sendRead: SendRead = (path, threadId) => {- void fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ threadId }) }).catch(() => {});+ void serverFetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ threadId }) }).catch(() => {});};function visibleThreadIds(state: AppState, kind: "bot" | "group", ownerId: string, shown?: string): string[] {diff --git a/src/state/store.tsx b/src/state/store.tsxindex 16f48ff253..bdc160ac3f 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -1,5 +1,5 @@import { cloudAsleep, onCloudPower } from "../lib/cloud-power";-import { api, ApiError, retryRequest, snapshotArrays } from "./api";+import { api, ApiError, retryRequest, snapshotArrays } from "./api"; import { serverFetch } from "@/lib/relay-server";import { capHeldInBackground, loadOlderPage, MESSAGE_PAGE_SIZE, olderThanHeld, reduceOlderMessages, reduceTrimHeldMessages } from "./message-history";import { readChatSnapshot } from "./chat-snapshot";import { followHeldTails, noteAppPagePatch } from "./held-tails";@@ -2114,7 +2114,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {return { host, card: cardMessages(stateRef.current, action.botId, action.groupId, action.threadId)?.find((m) => m.id === action.messageId)?.card, inRoom: !!action.groupId };};const persistCard = (botId: string, messageId: string, patch: Partial<OptionCardData>, threadId?: string) => {- fetch(`/api/bots/${botId}/cards/${messageId}`, {+ serverFetch(`/api/bots/${botId}/cards/${messageId}`, {method: "PATCH",headers: { "content-type": "application/json" },body: JSON.stringify({ ...patch, threadId }),@@ -3035,7 +3035,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {const readsInFlight = new Map<string, { covers: number; again: boolean }>();const sendRead = (botId: string, threadId: string | undefined, key: string, covers: number): void => {readsInFlight.set(key, { covers, again: false });- void fetch(`/api/bots/${botId}/read`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ threadId }) }).catch(() => {}).finally(() => {+ void serverFetch(`/api/bots/${botId}/read`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ threadId }) }).catch(() => {}).finally(() => {const open = readsInFlight.get(key); readsInFlight.delete(key);if (open?.again && alive) sendRead(botId, threadId, key, open.covers);});