Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Memory: edit the whole MEMORY.md as text from What it remembers
Bugfixer 2a4b37645f440
diff --git a/src/components/bot-panel/MemoryPage.text.test.ts b/src/components/bot-panel/MemoryPage.text.test.tsnew file mode 100644index 0000000000..fcea36cb52--- /dev/null+++ b/src/components/bot-panel/MemoryPage.text.test.ts@@ -0,0 +1,128 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";++import type { Bot } from "@/state/store";++vi.mock("@/state/store", async (importOriginal) => {+ const original = await importOriginal<typeof import("@/state/store")>();+ return { ...original, useStore: () => ({ state: { ...original.initialState, config: {} }, dispatch: vi.fn() }) };+});++const { MemoryPage } = await import("./pages");++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+const bot = { id: "scout", threadId: "t1", name: "Scout", title: "", description: "", notifications: true, color: "green", unread: false, messages: [],+ modelSelection: { instanceId: "x", model: "x" } } as unknown as Bot;+const files: Record<string, string> = {};+const puts: Array<{ text: string; expectedHash?: string }> = [];+const reply = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });+const hash = (text: string) => `h${text.length}:${text.split("\n").length}`;+let host: HTMLDivElement;+let root: Root;++beforeEach(() => {+ puts.length = 0;+ files["MEMORY.md"] = "# Memory\n\n- Prefers short replies.\n";+ // The memory file route, hash check and all: a save against a stale hash is a 409 with the file as it is now.+ vi.stubGlobal("fetch", vi.fn(async (input: string, init?: RequestInit) => {+ const url = new URL(input, "http://x");+ if (init?.method === "PUT") {+ const body = JSON.parse(String(init.body)) as { path: string; text: string; expectedHash?: string };+ puts.push({ text: body.text, expectedHash: body.expectedHash });+ const current = files[body.path];+ if (body.expectedHash !== hash(current)) return reply(409, { error: "conflict", current, currentHash: hash(current) });+ files[body.path] = body.text;+ return reply(200, { path: body.path, text: body.text, hash: hash(body.text), exists: true, overview: {} });+ }+ const path = url.searchParams.get("path") ?? "MEMORY.md";+ return reply(200, { path, text: files[path], hash: hash(files[path]), exists: true });+ }));+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => {+ act(() => root.unmount());+ host.remove();+ vi.unstubAllGlobals();+});++const settle = () => act(async () => { for (let i = 0; i < 5; i += 1) await new Promise((resolve) => setTimeout(resolve, 0)); });+const click = async (element: Element | null | undefined) => {+ expect(element).toBeTruthy();+ await act(async () => (element as HTMLElement).click());+ await settle();+};+const textarea = () => host.querySelector<HTMLTextAreaElement>("[data-memory-text]");+const type = (text: string) => act(() => {+ const field = textarea()!;+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(field, text);+ field.dispatchEvent(new Event("input", { bubbles: true }));+});+const button = (label: string) => [...host.querySelectorAll("button")].find((candidate) => candidate.textContent === label);+const open = async () => {+ await act(async () => root.render(createElement(MemoryPage, { bot, derived: {} as never })));+ await settle();+ await click(host.querySelector('[data-panel-link="memory-text"]'));+};++it("opens the whole MEMORY.md as text from What it remembers and saves it against the hash it was opened at", async () => {+ await open();+ expect(textarea()?.value).toBe("# Memory\n\n- Prefers short replies.\n");+ await type("# Memory\n\n- Prefers short replies in plain words.\n- Standup is at 10:30.\n");+ await click(host.querySelector('[data-panel-done="memory-text"]'));+ expect(puts).toEqual([{ text: "# Memory\n\n- Prefers short replies in plain words.\n- Standup is at 10:30.\n", expectedHash: hash("# Memory\n\n- Prefers short replies.\n") }]);+ expect(files["MEMORY.md"]).toContain("Standup is at 10:30.");+ expect(textarea()).toBeNull();+ expect(host.textContent).toContain("Standup is at 10:30.");+});++it("never overwrites a note the bot wrote while the text was open: the person reloads or overwrites", async () => {+ await open();+ await type("# Memory\n\n- Mine.\n");+ files["MEMORY.md"] += "- The bot's note.\n";+ await click(host.querySelector('[data-panel-done="memory-text"]'));+ expect(files["MEMORY.md"]).toContain("The bot's note.");+ expect(host.textContent).toContain("Scout changed this file while you were editing.");++ await click(button("Reload"));+ expect(textarea()?.value).toContain("The bot's note.");+ expect(host.querySelector("[data-memory-draft] pre")?.textContent).toBe("# Memory\n\n- Mine.\n");+ await type(`${textarea()!.value}- Mine.\n`);+ await click(host.querySelector('[data-panel-done="memory-text"]'));+ expect(files["MEMORY.md"]).toBe("# Memory\n\n- Prefers short replies.\n- The bot's note.\n- Mine.\n");+ expect(textarea()).toBeNull();+});++it("can overwrite the bot's version on purpose", async () => {+ await open();+ await type("# Memory\n\n- Only this.\n");+ files["MEMORY.md"] += "- The bot's note.\n";+ await click(host.querySelector('[data-panel-done="memory-text"]'));+ await click(button("Overwrite with mine"));+ expect(files["MEMORY.md"]).toBe("# Memory\n\n- Only this.\n");+ expect(textarea()).toBeNull();+});++it("Cancel leaves the file alone", async () => {+ await open();+ await type("# Memory\n");+ await click(button("Cancel"));+ expect(puts).toEqual([]);+ expect(textarea()).toBeNull();+ expect(host.textContent).toContain("Prefers short replies.");+});++it("closes the text when the person moves to another bot, so coming back shows the notes again", async () => {+ await open();+ const other = { ...bot, id: "atlas", name: "Atlas" } as Bot;+ await act(async () => root.render(createElement(MemoryPage, { bot: other, derived: {} as never })));+ await settle();+ expect(textarea()).toBeNull();+ await act(async () => root.render(createElement(MemoryPage, { bot, derived: {} as never })));+ await settle();+ expect(textarea()).toBeNull();+ expect(host.querySelector('[data-panel-link="memory-text"]')).toBeTruthy();+});diff --git a/src/components/bot-panel/pages.tsx b/src/components/bot-panel/pages.tsxindex 5e84d10425..e94bbd5039 100644--- a/src/components/bot-panel/pages.tsx+++ b/src/components/bot-panel/pages.tsx@@ -1,7 +1,8 @@-import { useState, type ReactNode } from "react";-import { FolderOpen, Plus, Server } from "lucide-react";+import { useEffect, useRef, useState, type ReactNode } from "react";+import { FileText, FolderOpen, Plus, Server } from "lucide-react";import { appSwitchPatch } from "@/lib/bot-app-access";+import { cn } from "@/lib/cn";import { skillsLibraryEnabled } from "@/lib/feature-flags";import { t } from "@/lib/i18n";import { mcpServersForBot, mcpServersOfBot, mcpSwitch, useMcpServers } from "@/lib/mcp-servers";@@ -17,6 +18,8 @@ import { ServiceIcon } from "../ServiceIcon";import { RoutineEditor } from "../RoutinesPage";import { useWorkingFolder } from "../bot-settings/AccessSection";import { useBotEditor } from "../bot-settings/BotEditorContext";+import { inputCls } from "../bot-settings/field";+import { ConflictNotice } from "../bot-settings/MemorySection";import { OrgSkillsCard } from "../bot-settings/OrgSkillsCard";import { SkillReviewDialog, skillSwitchOn, useManagedSkills, type ManagedSkill } from "../bot-settings/SkillsSection";import { useBotApps, type BotApp } from "../bot-settings/useBotApps";@@ -28,7 +31,7 @@ import { useOpenComputer, WherePage } from "./ComputerTab";import { SettingsPage } from "./SettingsPage";import { panelMemoryNotes, withMemoryNote, withoutMemoryNote, type PanelMemoryNote } from "./memory-notes";import type { SimplePageId } from "./page-registry";-import { BotSwitch, buttonCls, Card, LinkRow, NoteRow, RadioRow, RowIcon, rowCls, RowText, SwitchRow, TextRow, TrashButton } from "./rows";+import { BotSwitch, buttonCls, Card, ColRow, LinkRow, NoteRow, RadioRow, RowIcon, rowCls, RowText, SwitchRow, TextRow, TrashButton } from "./rows";import { MemoryUpkeepCards } from "./MemoryUpkeepCards";import { useMemoryDoc } from "./use-memory-doc";@@ -167,11 +170,13 @@ export function RoutinesPage({ bot, derived }: PageContext) {export function MemoryPage({ bot }: PageContext) {const memory = useMemoryDoc(bot);const [draft, setDraft] = useState("");+ const [asText, setAsText] = useState<{ botId: string; doc: MemoryDoc } | null>(null);const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);const memoryOn = bot.memoryEnabled !== false;const notes = memory.docs ? panelMemoryNotes(memory.docs) : null;const index = memory.docs?.find((doc) => doc.path === MEMORY_INDEX) ?? null;+ useEffect(() => setAsText(null), [bot.id, memoryOn]);const change = async (save: () => Promise<boolean>) => {if (saving) return false;@@ -211,6 +216,21 @@ export function MemoryPage({ bot }: PageContext) {if (await write(index, withMemoryNote(index.text, draft))) setDraft("");};+ if (memoryOn && asText?.botId === bot.id) {+ return (+ <MemoryTextEditor+ bot={bot}+ doc={asText.doc}+ mine={memory.mine}+ onDone={(saved) => {+ if (saved) memory.setDoc(saved);+ setAsText(null);+ setError(null);+ }}+ />+ );+ }+return (<><Card>@@ -242,6 +262,11 @@ export function MemoryPage({ bot }: PageContext) {onChange={setDraft}onSubmit={() => void add()}/>+ {index && (+ <LinkRow data-panel-link="memory-text" icon={FileText} onClick={() => setAsText({ botId: bot.id, doc: index })}>+ {t("botPanel.memory.editText")}+ </LinkRow>+ )}</Card>)}{memoryOn && !memory.mine && <MemoryUpkeepCards bot={bot} onChanged={memory.reload} />}@@ -249,6 +274,89 @@ export function MemoryPage({ bot }: PageContext) {);}+/** The whole MEMORY.md as text, saved against the hash it was opened at, so a note the bot writes meanwhile is a+ * conflict to settle, never silently lost: Reload shows the bot's version and keeps what the person typed beside it. */+function MemoryTextEditor({ bot, doc, mine, onDone }: {+ bot: Bot;+ doc: MemoryDoc;+ mine: boolean;+ onDone: (saved: MemoryDoc | null) => void;+}) {+ // A file not written yet has the empty file's hash, so the bot creating it meanwhile is a conflict too.+ const [base, setBase] = useState({ text: doc.text, hash: doc.hash });+ const [text, setText] = useState(doc.text);+ const [conflict, setConflict] = useState<{ current: string; currentHash: string } | null>(null);+ const [savedDraft, setSavedDraft] = useState<string | null>(null);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ // The file is saved either way; a save that lands after the person moved to another bot must not show in that bot's list.+ const mounted = useRef(true);+ useEffect(() => {+ mounted.current = true;+ return () => { mounted.current = false; };+ }, []);++ const save = async (expectedHash: string) => {+ setSaving(true);+ setError(null);+ try {+ const result = await saveMemoryDoc(bot.id, doc.path, text, expectedHash, mine);+ if (!mounted.current) return;+ if (result.ok) onDone(result.doc);+ else setConflict({ current: result.current, currentHash: result.currentHash });+ } catch (cause) {+ setError(errorText(cause, t("botPanel.library.memoryError")));+ } finally {+ setSaving(false);+ }+ };+ const reload = () => {+ if (!conflict) return;+ setSavedDraft(text);+ setBase({ text: conflict.current, hash: conflict.currentHash });+ setText(conflict.current);+ setConflict(null);+ };++ return (+ <Card>+ <ColRow data-panel-row="memory-text">+ {conflict && <ConflictNotice botName={bot.name} busy={saving} onReload={reload} onOverwrite={() => void save(conflict.currentHash)} />}+ <textarea+ data-memory-text=""+ className={cn(inputCls, "min-h-[280px] resize-y font-mono text-[13px] leading-relaxed")}+ value={text}+ placeholder={t("memory.indexPlaceholder")}+ aria-label={t("memory.botMemory")}+ onChange={(event) => setText(event.target.value)}+ />+ {error && <div className="text-[13px] text-warning">{error}</div>}+ {savedDraft !== null && (+ <div data-memory-draft="">+ <div className="mb-1 text-[12px] text-ink-secondary">{t("memory.unsavedDraft")}</div>+ <pre className="max-h-[160px] overflow-auto whitespace-pre-wrap rounded-lg border border-hairline/40 bg-inset p-3 font-mono text-[12px] leading-relaxed text-ink">+ {savedDraft}+ </pre>+ <button type="button" className={cn(buttonCls, "mt-1")} onClick={() => setSavedDraft(null)}>{t("memory.dismissDraft")}</button>+ </div>+ )}+ <div className="flex justify-end gap-2">+ <button type="button" className={buttonCls} disabled={saving} onClick={() => onDone(null)}>{t("common.cancel")}</button>+ <button+ type="button"+ data-panel-done="memory-text"+ className={buttonCls}+ disabled={saving || text === base.text}+ onClick={() => void save(base.hash)}+ >+ {saving ? t("memory.saving") : t("memory.save")}+ </button>+ </div>+ </ColRow>+ </Card>+ );+}+export function SkillsPage({ bot }: PageContext) {const { request: api } = useBotEditor();const { state, dispatch } = useStore();diff --git a/src/locales/en.json b/src/locales/en.jsonindex 1354da1a07..2c7fef17c4 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -4336,6 +4336,7 @@"botPanel.memory.forget": "Forget","botPanel.memory.empty": "Nothing remembered yet.","botPanel.memory.addPlaceholder": "Tell {name} something to remember",+ "botPanel.memory.editText": "Edit as text","botPanel.skills.remove": "Remove {name}","botPanel.skills.removeConfirm": "Remove the skill “{name}”?","botPanel.skills.removeFailed": "Could not remove this skill.",