Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(bot-settings): open standing instructions in a large editor
Absterrg0a241b4022992
diff --git a/src/components/SoulField.large.dom.test.ts b/src/components/SoulField.large.dom.test.tsnew file mode 100644index 0000000000..6e13a20fce--- /dev/null+++ b/src/components/SoulField.large.dom.test.ts@@ -0,0 +1,83 @@+// @vitest-environment happy-dom+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { setLocale } from "@/lib/i18n";+import type { Bot } from "@/state/store";++const fx = vi.hoisted(() => ({ request: vi.fn() }));+vi.mock("@/state/store", async (importOriginal) => {+ const original = await importOriginal<typeof import("@/state/store")>();+ return { ...original, useStore: () => ({ state: original.initialState, dispatch: vi.fn(), flushBotPatches: () => Promise.resolve() }) };+});++const { SoulField } = await import("./SoulField");+const { BotEditorContext } = await import("./bot-settings/BotEditorContext");++let host: HTMLDivElement;+let root: Root;+const bot = (soul: string): Bot => ({+ id: "bot-1", threadId: "thread-1", name: "Scout", title: "Scout", description: "", notifications: false, color: "green", unread: false,+ modelSelection: { instanceId: "local", model: "test-model" }, messages: [], soul,+});+const render = (value: Bot, onPatch: (patch: { soul?: string }) => void) => flushSync(() => root.render(+ createElement(BotEditorContext.Provider, { value: { request: fx.request } }, createElement(SoulField, { bot: value, onPatch })),+));+const openLarge = () => [...host.querySelectorAll("button")].find((button) => button.textContent === "Open large");+const dialog = () => document.body.querySelector<HTMLElement>('[role="dialog"]');+const type = (box: HTMLTextAreaElement, value: string) => flushSync(() => {+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(box, value);+ box.dispatchEvent(new Event("input", { bubbles: true }));+});++beforeEach(() => {+ setLocale("en");+ fx.request.mockReset();+ fx.request.mockRejectedValue(new Error("offline"));+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => {+ flushSync(() => root.unmount());+ host.remove();+});++describe("the standing instructions editor opened large", () => {+ it("edits the same instructions with the byte count, and Escape returns to the settings", () => {+ const onPatch = vi.fn();+ render(bot("# Rules\nBe brief."), onPatch);+ expect(openLarge(), "the Soul editor offers a large view").toBeDefined();+ openLarge()!.focus();+ flushSync(() => openLarge()!.click());++ const panel = dialog()!;+ expect(panel.getAttribute("aria-modal")).toBe("true");+ const large = panel.querySelector("textarea")!;+ expect(large.value).toBe("# Rules\nBe brief.");+ expect(document.activeElement).toBe(large);+ expect(panel.textContent).toContain("17 / 24,000 bytes");++ type(large, "# Rules\nBe brief and kind.");+ expect(onPatch).toHaveBeenLastCalledWith({ soul: "# Rules\nBe brief and kind." });+ expect(panel.textContent).toContain("26 / 24,000 bytes");++ const settingsEscape = vi.fn();+ window.addEventListener("keydown", settingsEscape);+ flushSync(() => large.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true })));+ window.removeEventListener("keydown", settingsEscape);+ expect(dialog()).toBeNull();+ expect(settingsEscape, "the bot settings stay open").not.toHaveBeenCalled();+ expect(host.querySelector("textarea")!.value).toBe("# Rules\nBe brief and kind.");+ expect(document.activeElement).toBe(openLarge());+ });++ it("closes with Done", () => {+ render(bot(""), vi.fn());+ flushSync(() => openLarge()!.click());+ const done = [...dialog()!.querySelectorAll("button")].find((button) => button.textContent === "Done")!;+ flushSync(() => done.click());+ expect(dialog()).toBeNull();+ });+});diff --git a/src/components/SoulField.tsx b/src/components/SoulField.tsxindex 5c62c86dfd..556ca76dbf 100644--- a/src/components/SoulField.tsx+++ b/src/components/SoulField.tsx@@ -1,9 +1,11 @@-import { useEffect, useState } from "react";+import { useEffect, useRef, useState, type ReactNode } from "react";import { BOT_PROFILE_LIMITS } from "../../shared/bot-profile";import { cn } from "@/lib/cn";import { firstSentence, soulPatchFor, utf8Bytes } from "@/lib/soul";import { useStore, type Bot } from "@/state/store";+import { useModalDialog } from "@/hooks/use-modal-dialog";+import { Layer } from "./Layer";import { useBotEditor } from "./bot-settings/BotEditorContext";import { inputCls } from "./bot-settings/field";import { intlLocale, t } from "@/lib/i18n";@@ -25,6 +27,7 @@ export function SoulField({const [draft, setDraft] = useState(bot.soul ?? "");const [info, setInfo] = useState<SoulRead | null>(null);const [resolving, setResolving] = useState(false);+ const [large, setLarge] = useState(false);useEffect(() => {setDraft(bot.soul ?? "");@@ -63,23 +66,46 @@ export function SoulField({}};const canMigrate = bot.description.length > 400 && !(bot.soul ?? "").trim();+ const label = simple ? simple.label : t("botIdentity.soul.label");+ const editor = (className: string, id?: string) => (+ <textarea+ id={id}+ aria-label={id ? undefined : label}+ className={cn(inputCls, className, over && "ring-2 ring-red-500/60")}+ placeholder={simple ? simple.placeholder : t("bot.soul.placeholder")}+ aria-invalid={over || undefined}+ disabled={resolving}+ value={draft}+ onChange={(e) => change(e.target.value)}+ />+ );+ const byteCount = (+ <span className={cn("shrink-0 tabular-nums", over && "font-medium text-red-500")}>+ {t(over ? "botIdentity.soul.bytesOver" : "botIdentity.soul.bytes", { bytes: bytes.toLocaleString(intlLocale()), limit: limit.toLocaleString(intlLocale()) })}+ </span>+ );return (<div className="block"><div className="mb-1.5 flex items-center justify-between gap-3"><label htmlFor={`bot-soul-${bot.id}`} className={simple ? "text-[12px] text-ink-secondary" : "text-[13px] text-ink-secondary"}>- {simple ? simple.label : t("botIdentity.soul.label")}+ {label}</label>- {!simple && canMigrate && (- <button- type="button"- disabled={resolving}- onClick={() => onPatch({ soul: bot.description, description: firstSentence(bot.description) })}- className="rounded-md px-1.5 py-1 text-[12px] font-medium text-accent-text hover:bg-accent/10"- >- {t("botIdentity.soul.moveToFile")}+ <div className="flex items-center gap-1">+ {!simple && canMigrate && (+ <button+ type="button"+ disabled={resolving}+ onClick={() => onPatch({ soul: bot.description, description: firstSentence(bot.description) })}+ className={HEADER_BUTTON}+ >+ {t("botIdentity.soul.moveToFile")}+ </button>+ )}+ <button type="button" disabled={resolving} onClick={() => setLarge(true)} className={HEADER_BUTTON}>+ {t("botIdentity.soul.openLarge")}</button>- )}+ </div></div>{info?.drift && (<div className="mb-2 rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-[12px] text-ink">@@ -98,27 +124,49 @@ export function SoulField({</div></div>)}- <textarea- id={`bot-soul-${bot.id}`}- className={cn(- inputCls,- simple ? "min-h-[140px] resize-y rounded-xl text-[14px] leading-relaxed" : "min-h-[220px] resize-y font-mono leading-relaxed",- over && "ring-2 ring-red-500/60",- )}- placeholder={simple ? simple.placeholder : t("bot.soul.placeholder")}- aria-invalid={over || undefined}- disabled={resolving}- value={draft}- onChange={(e) => change(e.target.value)}- />+ {editor(simple ? "min-h-[140px] resize-y rounded-xl text-[14px] leading-relaxed" : "min-h-[220px] resize-y font-mono leading-relaxed", `bot-soul-${bot.id}`)}{(!simple || over) && <div className="mt-1.5 flex items-start justify-between gap-3 text-[11px] text-ink-secondary"><span>{!simple && <>{t("botIdentity.soul.contextHelp")}{info?.file ? <> {t("botIdentity.soul.mirroredTo")} <span className="break-all">{info.file}</span>.</> : null}</>}</span>- <span className={cn("shrink-0 tabular-nums", over && "font-medium text-red-500")}>- {t(over ? "botIdentity.soul.bytesOver" : "botIdentity.soul.bytes", { bytes: bytes.toLocaleString(intlLocale()), limit: limit.toLocaleString(intlLocale()) })}- </span>+ {byteCount}</div>}+ {large && (+ <Layer modal>+ <SoulLargeDialog title={label} byteCount={byteCount} onClose={() => setLarge(false)}>+ {editor("min-h-0 flex-1 resize-none font-mono text-[14px] leading-relaxed")}+ </SoulLargeDialog>+ </Layer>+ )}+ </div>+ );+}++const HEADER_BUTTON = "rounded-md px-1.5 py-1 text-[12px] font-medium text-accent-text hover:bg-accent/10 disabled:opacity-50";++function SoulLargeDialog({ title, byteCount, onClose, children }: { title: string; byteCount: ReactNode; onClose: () => void; children: ReactNode }) {+ const dialogRef = useRef<HTMLDivElement>(null);+ useModalDialog(dialogRef, onClose);+ useEffect(() => { dialogRef.current?.querySelector("textarea")?.focus(); }, []);+ return (+ <div+ ref={dialogRef}+ tabIndex={-1}+ role="dialog"+ aria-modal="true"+ aria-labelledby="bot-soul-large-title"+ className="fixed inset-0 z-[90] flex items-center justify-center bg-black/45 p-6"+ >+ <div className="flex h-[min(760px,90vh)] w-full max-w-3xl flex-col rounded-2xl bg-card p-5 shadow-2xl">+ <div className="mb-3 flex items-center justify-between gap-3">+ <h2 id="bot-soul-large-title" className="min-w-0 truncate text-[16px] font-semibold text-ink">{title}</h2>+ <button type="button" onClick={onClose} className="rounded-md px-2 py-1 text-[13px] text-ink-secondary hover:bg-control hover:text-ink">+ {t("common.done")}+ </button>+ </div>+ {children}+ <div className="mt-1.5 flex justify-end text-[11px] text-ink-secondary">{byteCount}</div>+ </div></div>);}diff --git a/src/locales/en.json b/src/locales/en.jsonindex cf38252006..a79b7425bd 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -7889,6 +7889,7 @@"botIdentity.soul.keepSaved": "Keep the saved version","botIdentity.soul.contextHelp": "In this bot’s context on every turn.","botIdentity.soul.mirroredTo": "Mirrored to",+ "botIdentity.soul.openLarge": "Open large","botIdentity.dialog.title": "Bot instructions","botIdentity.dialog.close": "Close bot instructions","botIdentity.dialog.empty": "No instructions yet",