Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Send messages on a self-hosted server opened over plain http (#4381)
Aditya Umale3bda0a23b84f
diff --git a/src/components/CanvasComputers.tsx b/src/components/CanvasComputers.tsxindex 07a4ce2631..7182e963cd 100644--- a/src/components/CanvasComputers.tsx+++ b/src/components/CanvasComputers.tsx@@ -7,6 +7,7 @@ import { ConfirmDialog } from "./ConfirmDialog";import { Select } from "./Select";import { t } from "@/lib/i18n";import type { LocaleKey } from "@/locales";+import { randomUuid } from "@/lib/random-uuid";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";@@ -39,7 +40,7 @@ export function CanvasComputers({ open, createRequest, drop, sections, onClose,const [busy, setBusy] = useState<string | null>(null);const [creating, setCreating] = useState(false);const [name, setName] = useState("");- const requestId = useRef(crypto.randomUUID());+ const requestId = useRef(randomUuid());const submittedName = useRef<string | null>(null);const nameInput = useRef<HTMLInputElement>(null);const closeButton = useRef<HTMLButtonElement>(null);@@ -51,7 +52,7 @@ export function CanvasComputers({ open, createRequest, drop, sections, onClose,const [assignment, setAssignment] = useState<{ computer: TeamComputer; section: string | null } | null>(null);const [viewer, setViewer] = useState<{ id: string; url: string } | null>(null);const [heldHere, setHeldHere] = useState<string | null>(null);- const controlLeaseId = useRef(crypto.randomUUID());+ const controlLeaseId = useRef(randomUuid());const heldHereRef = useRef<string | null>(null);const shelf = useRef<HTMLElement>(null);const pointer = useRef<{ id: number; x: number; y: number; moved: boolean; computer: TeamComputer; handle: HTMLElement } | null>(null);@@ -208,7 +209,7 @@ export function CanvasComputers({ open, createRequest, drop, sections, onClose,if (!value || !inventory?.configured) return;submittedName.current = value;void mutate("create", () => api("/api/team-computers", { method: "POST", body: JSON.stringify({ name: value, requestId: requestId.current, acknowledgeCost: true }) }), () => {- setName(""); setCreating(false); requestId.current = crypto.randomUUID(); submittedName.current = null;+ setName(""); setCreating(false); requestId.current = randomUuid(); submittedName.current = null;}, () => {submittedName.current = null;});diff --git a/src/components/CloudIntent.tsx b/src/components/CloudIntent.tsxindex 5ccae4176a..88eb59971d 100644--- a/src/components/CloudIntent.tsx+++ b/src/components/CloudIntent.tsx@@ -16,6 +16,7 @@ import type { MausMotion, MausState } from "@/lib/mascot";import type { OnboardingStatus } from "@/lib/onboarding";import type { LocaleKey } from "@/locales";import { api, useStore, type Action, type AppState } from "@/state/store";+import { randomUuid } from "@/lib/random-uuid";const IDEAS: Array<{ id: string; icon: LucideIcon; label: LocaleKey; text: LocaleKey }> = [{ id: "digest", icon: Newspaper, label: "cloudIntent.idea.digest", text: "cloudIntent.idea.digestText" },@@ -44,7 +45,7 @@ export function startCloudSetup(job: string, state: Pick<AppState, "bots" | "seldispatch({ type: "showChat" });dispatch({ type: "select", id: bot.id });dispatch({- type: "send", botId: bot.id, text, sendId: crypto.randomUUID(), threadId: bot.threadId,+ type: "send", botId: bot.id, text, sendId: randomUuid(), threadId: bot.threadId,onError: () => restoreComposerDraft(`bot:${bot.id}:${bot.threadId}`, { text, attachments: [] }),});});diff --git a/src/components/Composer.tsx b/src/components/Composer.tsxindex 4cd18a8d85..6ebdf38a25 100644--- a/src/components/Composer.tsx+++ b/src/components/Composer.tsx@@ -95,6 +95,7 @@ import {type ComposerSlashCommand,} from "@/lib/composer-commands";import { useSlashSkills } from "@/lib/use-slash-skills";+import { randomUuid } from "@/lib/random-uuid";const supportsAgents = (instances: InstanceInfo[], candidate?: Bot) =>Boolean(candidate && instances.find((instance) => instance.instanceId === candidate.modelSelection.instanceId)?.capabilities?.agentsMcp);@@ -579,7 +580,7 @@ export function Composer({const sentDraft: ComposerDraftSnapshot = {draftId,revision: draftRevision(draftId),- sendId: restoredSendId(draftId) ?? crypto.randomUUID(),+ sendId: restoredSendId(draftId) ?? randomUuid(),text,requestText: body,attachments: [...attachments],diff --git a/src/components/LocalVmWorkspace.tsx b/src/components/LocalVmWorkspace.tsxindex 0bed17e211..eed31a1a56 100644--- a/src/components/LocalVmWorkspace.tsx+++ b/src/components/LocalVmWorkspace.tsx@@ -36,6 +36,7 @@ import {import { z } from "zod";import { Select } from "./Select";import { productName } from "@/lib/brand";+import { randomUuid } from "@/lib/random-uuid";const SLOT_CONTEXTS = ["local-vm-workspace:left", "local-vm-workspace:right"] as const;@@ -552,7 +553,7 @@ export function LocalVmWorkspace({const [controlledBotId, setControlledBotId] = useState<string | null>(null);const controlledBotIdRef = useRef<string | null>(null);const controlLeaseIdRef = useRef<string | null>(null);- const controlLeaseId = controlLeaseIdRef.current ?? crypto.randomUUID();+ const controlLeaseId = controlLeaseIdRef.current ?? randomUuid();controlLeaseIdRef.current = controlLeaseId;// A second discrete event can arrive before React commits the disabled buttons, so the mutation itself is guarded.const controlBusyRef = useRef(false);diff --git a/src/components/MapComposer.tsx b/src/components/MapComposer.tsxindex 37be9f35d4..fa977bb10a 100644--- a/src/components/MapComposer.tsx+++ b/src/components/MapComposer.tsx@@ -10,6 +10,7 @@ import { useShowThreads } from "@/lib/thread-preferences";import { MentionMenu, type MentionChoice } from "./MentionMenu";import { MentionTextarea } from "./MentionTextarea";import { useMenuMotion } from "./MenuMotion";+import { randomUuid } from "@/lib/random-uuid";/** Message bots from the Team map: tag bots, a team or @everyone; each tagged bot gets it as a normal message in its own chat. */export function MapComposer({ bots, teams, onTagged, onSent }: {@@ -70,7 +71,7 @@ export function MapComposer({ bots, teams, onTagged, onSent }: {const send = () => {if (!canSend) return;const message = text.trim();- for (const botId of targets.botIds) dispatch({ type: "send", botId, text: message, sendId: crypto.randomUUID() });+ for (const botId of targets.botIds) dispatch({ type: "send", botId, text: message, sendId: randomUuid() });onSent(targets.botIds);setSent({ botIds: targets.botIds, expanded: false });setText("");diff --git a/src/components/app/app-api.ts b/src/components/app/app-api.tsindex f74671be36..f26b7ffba3 100644--- a/src/components/app/app-api.ts+++ b/src/components/app/app-api.ts@@ -2,6 +2,7 @@ import { api, ApiError } from "@/state/store";import type { AppBlockedReason, AppDocument } from "../../../shared/app";import type { PublishedPageCard } from "../../../shared/published-page";import { RPC_HOST_REFUSED, type AppContextUpdate, type AppRpcMethod, type JsonRpcError } from "../../../shared/app-frame/bridge";+import { randomUuid } from "@/lib/random-uuid";export function appDocumentPath(threadId: string, messageId: string): string {return `/api/threads/${encodeURIComponent(threadId)}/messages/${encodeURIComponent(messageId)}/app`;@@ -99,7 +100,7 @@ export async function postAppContext(args: { botId: string; threadId: string; me});}-export const newAppSendId = (): string => crypto.randomUUID();+export const newAppSendId = (): string => randomUuid();/** Rejects with the server's sentence, or "Offline". */export async function sendAppMessage(args: { botId: string; threadId: string; messageId: string; text: string; sendId: string }): Promise<void> {diff --git a/src/components/widget/widget-send.ts b/src/components/widget/widget-send.tsindex 3297fb630e..0e3fe753a8 100644--- a/src/components/widget/widget-send.ts+++ b/src/components/widget/widget-send.ts@@ -1,5 +1,6 @@import { api } from "@/state/store";import type { WidgetOther, WidgetValues } from "../../../shared/widget";+import { randomUuid } from "@/lib/random-uuid";export interface WidgetPress {botId: string;@@ -17,7 +18,7 @@ export type WidgetSendResult =/** `refused`: the server said no, in `error`. Otherwise no answer came, and the same sendId may be sent again. */| { ok: false; refused: boolean; error?: string };-export const newWidgetSendId = (): string => crypto.randomUUID();+export const newWidgetSendId = (): string => randomUuid();export async function sendWidgetAction(press: WidgetPress): Promise<WidgetSendResult> {try {diff --git a/src/lib/bot-creation-draft.ts b/src/lib/bot-creation-draft.tsindex 1f04eb09d8..d9c1e2d1ee 100644--- a/src/lib/bot-creation-draft.ts+++ b/src/lib/bot-creation-draft.ts@@ -3,6 +3,7 @@ import { api, type Bot, type ModelSelection } from "@/state/store";import type { BotUpdatePatch } from "@/state/bot-patch-queue";import type { Routine, RoutineInput } from "./routines";import type { ChosenPreset } from "./bot-presets";+import { randomUuid } from "./random-uuid";export const EMPTY_BOT_DEFAULTS: NewBotDefaults = { profile: {}, memory: {}, skills: [], routines: [] };@@ -14,7 +15,7 @@ const routineTemplate = (routine: Routine): BotRoutineTemplate => ({});export class BotCreationDraft {- readonly id = `draft-${crypto.randomUUID()}`;+ readonly id = `draft-${randomUuid()}`;template: NewBotDefaults;consent: Pick<BotUpdatePatch, "acknowledgeLocalAuto"> & { acknowledgePeerScope?: boolean } = {};routines: Routine[];@@ -97,7 +98,7 @@ export class BotCreationDraft {window: schedule.window ?? undefined, endsAt: schedule.endsAt ?? undefined,} : schedule.type === "limit_reset" ? { ...schedule, repeat: schedule.repeat ?? "once", at: schedule.at ?? null } : schedule;return {- id: previous?.id ?? `draft-${crypto.randomUUID()}`, createdAt: previous?.createdAt ?? Date.now(),+ id: previous?.id ?? `draft-${randomUuid()}`, createdAt: previous?.createdAt ?? Date.now(),updatedAt: Date.now(), nextRunAt: null, runOn: "maus", ...previous, ...fields,enabled: input.enabled ?? previous?.enabled ?? true, target: "bot", botId: this.id,timeoutMinutes: input.timeoutMinutes ?? undefined,diff --git a/src/lib/browser-profiles.ts b/src/lib/browser-profiles.tsindex a49aabfa0e..ee1f7d9b74 100644--- a/src/lib/browser-profiles.ts+++ b/src/lib/browser-profiles.ts@@ -1,4 +1,5 @@import { t } from "./i18n";+import { randomUuid } from "./random-uuid";interface BrowserProfileUser {name: string;@@ -27,7 +28,7 @@ export function browserProfilesMutation(current: BrowserProfileRecord[], next: B}export function newBrowserProfileId(): string {- return `profile-${crypto.randomUUID().replaceAll("-", "")}`;+ return `profile-${randomUuid().replaceAll("-", "")}`;}/** A live turn may still be acting on this partition: refuse deletion rather than race the wipe. */diff --git a/src/lib/composer-attachments.ts b/src/lib/composer-attachments.tsindex d82dbde39c..3fa8aedccc 100644--- a/src/lib/composer-attachments.ts+++ b/src/lib/composer-attachments.ts@@ -1,4 +1,5 @@import { isCitationAttachment, serializeCitation, type CitationAttachment } from "./citations.ts";+import { randomUuid } from "./random-uuid.ts";export { dataContextFor, type DataContext, type DataViewContext } from "../../shared/data-context.ts";export type PasteAttachment = {@@ -82,21 +83,7 @@ function newId(): string {}/** Stable across the one retry, so a lost success response cannot create a second file. */-function newUploadId(): string {- if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();- const bytes = new Uint8Array(16);- if (globalThis.crypto?.getRandomValues) {- globalThis.crypto.getRandomValues(bytes);- } else {- for (let index = 0; index < bytes.length; index += 1) {- bytes[index] = Math.floor(Math.random() * 256);- }- }- bytes[6] = (bytes[6]! & 0x0f) | 0x40;- bytes[8] = (bytes[8]! & 0x3f) | 0x80;- const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));- return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;-}+const newUploadId = randomUuid;export function fileAttachment(name: string, path: string, size: number): FileAttachment {return { kind: "file", id: newId(), path, name, size };diff --git a/src/lib/pointed-chips.ts b/src/lib/pointed-chips.tsindex 0f20e5a7a9..2243cb8f5f 100644--- a/src/lib/pointed-chips.ts+++ b/src/lib/pointed-chips.ts@@ -1,6 +1,7 @@// The parts of a bot's page the person pointed at, waiting in the composer for their next message.import { useSyncExternalStore } from "react";import { POINT_LIMITS, type PointedElement } from "../../shared/app-frame/point";+import { randomUuid } from "./random-uuid";export interface PointedChip extends PointedElement {id: string;@@ -30,7 +31,7 @@ export function usePointedChips(threadId: string): readonly PointedChip[] {/** The same part picked twice stays one chip; past the limit the oldest goes. */export function addPointedChip(threadId: string, chip: Omit<PointedChip, "id">): void {const kept = (chips[threadId] ?? EMPTY).filter((each) => !(each.appId === chip.appId && each.selector === chip.selector));- set({ ...chips, [threadId]: [...kept, { ...chip, id: crypto.randomUUID() }].slice(-POINT_LIMITS.perMessage) });+ set({ ...chips, [threadId]: [...kept, { ...chip, id: randomUuid() }].slice(-POINT_LIMITS.perMessage) });}export function removePointedChip(threadId: string, id: string): void {diff --git a/src/lib/random-uuid.test.ts b/src/lib/random-uuid.test.tsnew file mode 100644index 0000000000..48f99ef918--- /dev/null+++ b/src/lib/random-uuid.test.ts@@ -0,0 +1,47 @@+import { readdirSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import { randomUuid } from "./random-uuid";++const V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;++afterEach(() => {+ vi.unstubAllGlobals();+});++describe("randomUuid", () => {+ it("uses crypto.randomUUID where the page has it", () => {+ vi.stubGlobal("crypto", { randomUUID: () => "11111111-2222-4333-8444-555555555555", getRandomValues: crypto.getRandomValues.bind(crypto) });+ expect(randomUuid()).toBe("11111111-2222-4333-8444-555555555555");+ });++ it("still makes v4 ids on plain http, where crypto.randomUUID is missing", () => {+ vi.stubGlobal("crypto", { getRandomValues: crypto.getRandomValues.bind(crypto) });+ const ids = Array.from({ length: 200 }, () => randomUuid());+ for (const id of ids) expect(id).toMatch(V4);+ expect(new Set(ids).size).toBe(ids.length);+ });+});++// A self-hosted server opened by its IP over plain http is not a secure+// context, so a bare crypto.randomUUID() call there throws and, in the+// composer, stopped every message from sending.+describe("browser code", () => {+ it("never calls crypto.randomUUID() without a fallback", () => {+ const src = join(import.meta.dirname, "..");+ const offenders: string[] = [];+ const walk = (dir: string) => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) walk(path);+ else if (/\.tsx?$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name)) {+ readFileSync(path, "utf8").split("\n").forEach((line, index) => {+ if (/(?<![?.])\bcrypto\.randomUUID\(\)/.test(line) && !/typeof crypto\?\.randomUUID/.test(line)) offenders.push(`${path.slice(src.length + 1)}:${index + 1}`);+ });+ }+ }+ };+ walk(src);+ expect(offenders).toEqual([]);+ });+});diff --git a/src/lib/random-uuid.ts b/src/lib/random-uuid.tsnew file mode 100644index 0000000000..c7ebcac28b--- /dev/null+++ b/src/lib/random-uuid.ts@@ -0,0 +1,19 @@+/**+ * A random v4 UUID. `crypto.randomUUID` exists only in secure contexts (https+ * or localhost), so a self-hosted server opened by its IP over plain http has+ * none; `crypto.getRandomValues` works there and builds the same format.+ */+export function randomUuid(): string {+ const webCrypto = globalThis.crypto;+ if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();+ const bytes = new Uint8Array(16);+ if (typeof webCrypto?.getRandomValues === "function") {+ webCrypto.getRandomValues(bytes);+ } else {+ for (let index = 0; index < bytes.length; index += 1) bytes[index] = Math.floor(Math.random() * 256);+ }+ bytes[6] = (bytes[6]! & 0x0f) | 0x40;+ bytes[8] = (bytes[8]! & 0x3f) | 0x80;+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;+}diff --git a/src/state/inbox.ts b/src/state/inbox.tsindex 13b3f9ba37..92d64fc5b1 100644--- a/src/state/inbox.ts+++ b/src/state/inbox.ts@@ -4,6 +4,7 @@import { useEffect, useSyncExternalStore } from "react";import type { InboxRow, InboxView } from "../../shared/inbox";import { api } from "./api";+import { randomUuid } from "../lib/random-uuid";type InboxTaskLike = { threadId: string; inbox?: true; openAsks?: number; inboxChangedAt?: number };@@ -85,7 +86,7 @@ export function doneInboxRow(row: Pick<InboxRow, "id">): void {/** A reply to a line of news that waits on one: it goes back where the line came from, as a Reply in the chat does. */export async function replyToInboxRow(view: Pick<InboxView, "botId" | "threadId">, row: Pick<InboxRow, "id">, text: string): Promise<void> {- await api(`/api/bots/${view.botId}/messages`, { method: "POST", body: JSON.stringify({ text, threadId: view.threadId, replyToId: row.id, sendId: crypto.randomUUID() }) });+ await api(`/api/bots/${view.botId}/messages`, { method: "POST", body: JSON.stringify({ text, threadId: view.threadId, replyToId: row.id, sendId: randomUuid() }) });void refreshInbox();}diff --git a/src/state/store.tsx b/src/state/store.tsxindex 7b552bdc5d..c977bf6ff9 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -62,6 +62,7 @@ import { forgetLiveTurns, noteRuntimeTurn, sendStop } from "@/lib/stop-turn";import { readLastConversation, rememberConversation } from "@/lib/last-conversation";import { readLastBotSection, rememberBotSection } from "@/lib/last-bot-section";import { showNotification } from "@/lib/notify";+import { randomUuid } from "@/lib/random-uuid";import { useShowThreads } from "@/lib/thread-preferences";import { speechOwner, spokenReplyStream } from "@/lib/spoken-reply-stream";import { t } from "@/lib/i18n";@@ -2265,9 +2266,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {action = pinBotThreadAction(action, stateRef.current.bots);if (action.type === "taskSwitched") action = { ...action, bot: withTaskWrites(action.bot) as Bot };if (action.type === "botPatched") action = { ...action, bot: withTaskWrites(action.bot) };- if ((action.type === "send" || action.type === "sendGroup" || action.type === "editMessage") && !action.sendId) {- action = { ...action, sendId: crypto.randomUUID() };- }+ if ((action.type === "send" || action.type === "sendGroup" || action.type === "editMessage") && !action.sendId) action = { ...action, sendId: randomUuid() };const botBeforeUpdate =action.type === "updateBot" || action.type === "setModel"? stateRef.current.bots.find((candidate) => candidate.id === action.botId)@@ -2449,7 +2448,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {if (quizBeforeSend) persistCard(action.botId, quizBeforeSend.id, { dismissed: true });const threadId =action.threadId ?? stateRef.current.bots.find((bot) => bot.id === action.botId)?.threadId;- const sendId = action.sendId ?? crypto.randomUUID();+ const sendId = action.sendId ?? randomUuid();const arrived = () => sendArrived(stateRef.current.bots.find((bot) => bot.id === action.botId && bot.threadId === threadId)?.messages, sendId);void waitForExecutionSettings(botBeforeSend ? [botBeforeSend] : [], threadId).then(() => sendReconciled(() => api(`/api/bots/${action.botId}/messages`, {@@ -2493,7 +2492,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {case "editMessage": {const threadId =action.threadId ?? stateRef.current.bots.find((bot) => bot.id === action.botId)?.threadId;- const sendId = action.sendId ?? crypto.randomUUID();+ const sendId = action.sendId ?? randomUuid();void waitForExecutionSettings(executionBotsBeforeAction, threadId).then(() => api(`/api/bots/${action.botId}/messages/${action.messageId}/edit`, {method: "POST",@@ -2695,7 +2694,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {case "sendGroup": {const threadId =action.threadId ?? stateRef.current.groups.find((group) => group.id === action.groupId)?.threadId;- const sendId = action.sendId ?? crypto.randomUUID();+ const sendId = action.sendId ?? randomUuid();void waitForExecutionSettings(executionBotsBeforeAction).then(() => api(`/api/groups/${action.groupId}/messages`, {method: "POST",