Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
A User isn't offered New bot or Templates on a team
milind-soni82dc9eab938b
diff --git a/src/components/Sidebar.plus-menu.test.ts b/src/components/Sidebar.plus-menu.test.tsnew file mode 100644index 0000000000..e9821467b4--- /dev/null+++ b/src/components/Sidebar.plus-menu.test.ts@@ -0,0 +1,76 @@+// @vitest-environment happy-dom+import { Children, isValidElement, type ReactElement, type ReactNode } from "react";+import { describe, expect, it, vi } from "vitest";++const fixture = vi.hoisted(() => ({ values: [] as unknown[], index: 0, admin: true as boolean | null }));+vi.mock("react", async (original) => ({+ ...await original<typeof import("react")>(),+ useState: (initial: unknown) => {+ const index = fixture.index++;+ if (!(index in fixture.values)) fixture.values[index] = typeof initial === "function" ? (initial as () => unknown)() : initial;+ return [fixture.values[index], (next: unknown) => {+ fixture.values[index] = typeof next === "function" ? (next as (value: unknown) => unknown)(fixture.values[index]) : next;+ }];+ },+ useRef: (initial: unknown) => {+ const index = fixture.index++;+ if (!(index in fixture.values)) fixture.values[index] = { current: initial };+ return fixture.values[index];+ },+ useCallback: (callback: unknown) => callback,+ useSyncExternalStore: (_subscribe: unknown, snapshot: () => unknown) => snapshot(),+ useEffect: () => {},+ useLayoutEffect: () => {},+}));+vi.mock("react-dom", () => ({ createPortal: (node: ReactNode) => node }));+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => fixture.admin }));+vi.mock("./MenuMotion", () => ({+ useMenuMotion: (open: boolean) => ({ shown: open, closing: false, className: "", exitProps: {} }),+ useHeldMenuMotion: (value: unknown) => ({ shown: value !== null, value, closing: false, className: "", exitProps: {} }),+}));+vi.mock("./DesktopCapabilities", async () => {+ const { initialDesktopCapabilities } = await import("@/lib/desktop");+ return { useDesktopCapabilities: () => ({ capabilities: initialDesktopCapabilities() }), windowFramed: () => false };+});+vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => true }));+vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => false, setAdvancedMode: () => {} }));+vi.mock("@/state/store", async (importOriginal) => {+ const original = await importOriginal<typeof import("@/state/store")>();+ return { ...original, useStore: () => ({ state: original.initialState, dispatch: vi.fn() }) };+});++import { Sidebar } from "./Sidebar";++type Props = { children?: ReactNode; onClick?: () => void; role?: string; [key: string]: unknown };+function nodes(value: ReactNode): ReactElement<Props>[] {+ return Children.toArray(value).flatMap((child) => {+ if (!isValidElement<Props>(child)) return [];+ return [child, ...nodes(child.props.children)];+ });+}+function words(value: ReactNode): string {+ return Children.toArray(value).map((child) => {+ if (typeof child === "string" || typeof child === "number") return String(child);+ return isValidElement<Props>(child) ? words(child.props.children) : "";+ }).join("");+}+function render() {+ fixture.index = 0;+ return nodes(Sidebar({ open: true, onClose: () => {} }));+}+function plusMenu(admin: boolean | null) {+ fixture.values = [];+ fixture.admin = admin;+ render().find((node) => node.type === "button" && String(node.props["aria-label"]).startsWith("New"))!.props.onClick!();+ return render().filter((node) => node.props.role === "menuitem").map((node) => words(node.props.children));+}++describe("the sidebar's + menu", () => {+ it("offers a new bot and templates to someone who can make one, and while that isn't known yet", () => {+ for (const admin of [true, null]) expect(plusMenu(admin)).toEqual(["New bot", "New group chat", "Templates"]);+ });++ it("offers neither to a User, who keeps New group chat", () => {+ expect(plusMenu(false)).toEqual(["New group chat"]);+ });+});diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsxindex a63333e14b..fac1b970fa 100644--- a/src/components/Sidebar.tsx+++ b/src/components/Sidebar.tsx@@ -1184,7 +1184,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {<MessageSquarePlus size={16} className="text-ink-secondary" />{t("sidebar.newChat.title")}</button>}- <button+ {teamSettingsAllowed !== false && <buttononClick={() => { setPlusOpen(false); dispatch({ type: "newBot" }); }}role="menuitem"className={plusItem}@@ -1192,7 +1192,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {<BotIcon size={16} className="text-ink-secondary" /><span className="flex-1">{advanced ? t("sidebar.newBot") : t("sidebar.newBotSimple")}</span>{advanced && <ShortcutHint id="new-bot" />}- </button>+ </button>}<buttononClick={() => {setPlusOpen(false);@@ -1212,14 +1212,14 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {<FolderPlus size={16} className="text-ink-secondary" /> {t("team.create")}</button>}{!remoteClient && <>- <button+ {teamSettingsAllowed !== false && <buttononClick={() => { setPlusOpen(false); setTeamLibraryOpen(true); }}role="menuitem"className={plusItem}><Library size={16} className="text-ink-secondary" />{t("sidebar.teamLibrary")}- </button>+ </button>}{advanced && archivedBots.length > 0 && (<buttononClick={() => {@@ -1676,7 +1676,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {anchor={sidebarRef.current}style={windowNoDragStyle}onClose={() => setNewChatOpen(false)}- onNewBot={() => { setNewChatOpen(false); dispatch({ type: "newBot" }); }}+ onNewBot={teamSettingsAllowed === false ? undefined : () => { setNewChatOpen(false); dispatch({ type: "newBot" }); }}onNewGroup={() => { setNewChatOpen(false); setNewRoom(true); }}/>,document.body,diff --git a/src/components/SidebarNewChatPanel.test.ts b/src/components/SidebarNewChatPanel.test.tsindex 1d515a9fff..59b76ff27d 100644--- a/src/components/SidebarNewChatPanel.test.ts+++ b/src/components/SidebarNewChatPanel.test.ts@@ -66,8 +66,8 @@ describe("SidebarNewChatPanel", () => {fixture.showThreads = true;});- function open() {- const props = { anchor: null, onClose: vi.fn(), onNewBot: vi.fn(), onNewGroup: vi.fn() };+ function open(makesBots = true) {+ const props = { anchor: null, onClose: vi.fn(), onNewBot: makesBots ? vi.fn() : undefined, onNewGroup: vi.fn() };container = document.createElement("div");document.body.append(container);root = createRoot(container);@@ -94,6 +94,14 @@ describe("SidebarNewChatPanel", () => {expect(text).not.toContain("Ghost");});+ it("offers no new bot to someone who can't make one, and Enter still starts with the first bot", () => {+ const { input } = open(false);+ expect(container!.textContent).not.toContain("Create new bot");+ expect(container!.textContent).toContain("Create group chat");+ key(input, "Enter");+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "newTask", botId: "scout" });+ });+it("starts a new thread with the first bot on Enter", () => {const { props, input } = open();key(input, "Enter");diff --git a/src/components/SidebarNewChatPanel.tsx b/src/components/SidebarNewChatPanel.tsxindex f5fdab5fd8..57c6a01261 100644--- a/src/components/SidebarNewChatPanel.tsx+++ b/src/components/SidebarNewChatPanel.tsx@@ -10,7 +10,6 @@ import { BotAvatar } from "./Avatar";const MIN_BESIDE_WIDTH = 320;const PANEL_WIDTH = 360;-const ACTION_COUNT = 2;const GAP = 8;export const FLOATING_TOP = 56;@@ -46,14 +45,15 @@ export function SidebarNewChatPanel({}: {anchor: HTMLElement | null;onClose: () => void;- onNewBot: () => void;+ /** Absent for someone who can't make a bot here. */+ onNewBot?: () => void;onNewGroup: () => void;style?: CSSProperties;}) {const { state, dispatch } = useStore();const showThreads = useShowThreads();const [query, setQuery] = useState("");- const [cursor, setCursor] = useState(ACTION_COUNT);+ const [cursor, setCursor] = useState(onNewBot ? 2 : 1);const [place, setPlace] = useState(() => newChatPanelPlacement(null, typeof window === "undefined" ? 0 : window.innerWidth));const [maxHeight, setMaxHeight] = useState(() => newChatPanelMaxHeight(typeof window === "undefined" ? 0 : window.innerHeight));const rootRef = useRef<HTMLDivElement>(null);@@ -84,7 +84,7 @@ export function SidebarNewChatPanel({const bots = rankByName(state.bots.filter((bot) => !bot.hidden), query);const actions = [- { key: "bot", icon: <Plus size={16} />, label: t("sidebar.newChat.createBot"), run: onNewBot },+ ...(onNewBot ? [{ key: "bot", icon: <Plus size={16} />, label: t("sidebar.newChat.createBot"), run: onNewBot }] : []),{ key: "group", icon: <Users size={16} />, label: t("sidebar.newChat.createGroup"), run: onNewGroup },];const count = actions.length + bots.length;diff --git a/src/lib/new-bot.test.ts b/src/lib/new-bot.test.tsindex bfadb9c6aa..b98e5db753 100644--- a/src/lib/new-bot.test.ts+++ b/src/lib/new-bot.test.ts@@ -13,7 +13,7 @@ import { makeNewBot, type BotDefaultsAnswer } from "./new-bot";const ME = { email: "[email protected]", name: "Ada", role: "member", you: true as const };const BOB = { email: "[email protected]", name: "Bob", role: "admin" };-const team: TeamPeople = { people: [ME, BOB], me: ME, admin: false, needsYou: [] };+const team: TeamPeople = { people: [ME, BOB], me: ME, admin: true, needsYou: [] };function server(answer: Partial<BotDefaultsAnswer> = {}, fail?: { on: "POST" | "PATCH"; error: string }) {const calls: Array<{ method: string; path: string; body: Record<string, unknown> }> = [];@@ -47,6 +47,13 @@ beforeEach(() => { fixture.track.mockReset(); fixture.openBot.mockReset(); });afterEach(() => { vi.unstubAllGlobals(); setTeamPeople(null); setTeamChats(null); });describe("New bot", () => {+ it("makes nothing for a User on a team, however it was asked for", async () => {+ setTeamPeople({ ...team, admin: false });+ const { calls, request } = server();+ expect(await newBot(request)).toEqual([]);+ expect(calls).toEqual([]);+ });+it("makes a bot at once from the New bot defaults and opens its chat", async () => {const { calls, request, created } = server();const sent = await newBot(request);diff --git a/src/lib/new-bot.ts b/src/lib/new-bot.tsindex c55cd23051..33755f445a 100644--- a/src/lib/new-bot.ts+++ b/src/lib/new-bot.ts@@ -69,6 +69,7 @@ async function createNewBot(section: string | undefined, bots: readonly Bot[], t/** New bot: a bot made at once from the New bot defaults, with its chat open and ready for the first message. */export async function makeNewBot(action: Extract<Action, { type: "newBot" }>, bots: readonly Bot[], dispatch: (action: Action) => void,showThreads: boolean, request: typeof api = api): Promise<void> {+ if (currentTeamPeople()?.admin === false) return;let made: Awaited<ReturnType<typeof createNewBot>>;try {made = await createNewBot(action.section, bots, currentTeamPeople(), request);