Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Phone bot list stays open at start, and the app no longer opens a team bot's shared chat as it starts (#5612)
Milind Soni42978f7c2dbf
diff --git a/src/App.tsx b/src/App.tsxindex d97b1604c4..50c218207a 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -68,6 +68,7 @@ import { botCycleStep, shouldOpenKeyboardShortcuts } from "@/lib/keyboard-shortcimport { effectiveLanguage, useLanguageChoice, usePageLanguage } from "@/lib/language-preference";import { botUnreadCount, showBrowserUnread } from "@/lib/bot-unread";import { phonePairingSettingsAction, takePhonePairingRequest } from "@/lib/phone-pairing"; import { useConnectLink } from "@/lib/use-connect-link";+import { useBotListDrawer } from "@/hooks/use-bot-list-drawer";import { useDesktopNotificationOpens, useExternalChatLinks } from "@/hooks/use-external-chat-links";import { useUsageSnapshot } from "@/hooks/use-usage-snapshot";import { useReadShownChatOnFocus } from "@/hooks/use-read-shown-chat";@@ -135,7 +136,6 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {useConnectLink(dispatch, Boolean(state.config?.team));useExternalChatLinks(state, dispatch); useDesktopNotificationOpens(state, dispatch);usePresence(state, dispatch); useTeamPresence(state);- const [drawerOpen, setDrawerOpen] = useState(false);usePageLanguage(effectiveLanguage(useLanguageChoice(), state.config?.language), true);const [paletteOpen, setPaletteOpen] = useState(false);// Stays mounted once opened: a Cloud bought in it can arrive after the sheet is closed.@@ -143,13 +143,15 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {cloudAddOpened.current ||= Boolean(state.cloudAdd);const [localVmWorkspaceBotId, setLocalVmWorkspaceBotId] = useState<string | null>(null);const menuButtonRef = useRef<HTMLButtonElement>(null);- const closeDrawer = useCallback(() => { setDrawerOpen(false); menuButtonRef.current?.focus(); }, []);const previousViewRef = useRef(state.activeView);const calendarOriginRef = useRef<"chat" | "team-map" | "web-panel">("chat");const loading = loadingLine({ connected: state.connected, hydrated: state.hydrated === true, developer: import.meta.env.DEV });const group = state.groups.find((g) => g.id === state.selectedId);const chiefStep = useChiefStepOpen();const bot = group || chiefStep ? undefined : (state.bots.find((b) => b.id === state.selectedId) ?? state.bots[0]);+ const { open: drawerOpen, show: openDrawer, hide: hideDrawer, noteAction: noteDrawerAction } = useBotListDrawer({ selectedId: state.selectedId, botThread: bot?.threadId, groupThread: group?.threadId,+ view: state.activeView, pluginsOpen: state.pluginsOpen, settingsOpen: state.settingsOpen });+ const closeDrawer = useCallback(() => { hideDrawer(); menuButtonRef.current?.focus(); }, [hideDrawer]);const notificationFeed = useNotificationFeed() && !remoteClient;const advanced = useAdvancedMode();const roomPanelOpen = useRoomPanelShown({ group, state, simple: !advanced && !remoteClient });@@ -231,10 +233,6 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {useEffect(() => preloadScreens(), []);- useEffect(() => {- setDrawerOpen(false);- }, [state.selectedId, bot?.threadId, group?.threadId, state.activeView, state.pluginsOpen, state.settingsOpen]);-useEffect(() => {if (state.activeView === "routines" && previousViewRef.current !== "routines") {calendarOriginRef.current = previousViewRef.current === "team-map" || previousViewRef.current === "web-panel" ? previousViewRef.current : "chat";@@ -329,7 +327,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {<AppNotices quiet={paletteOpen || drawerOpen || Boolean(localVmWorkspaceBotId)} viewer={viewer} /></>;return (- <div className={cn("flex h-full flex-col", framed && "bg-frame")}>+ <div className={cn("flex h-full flex-col", framed && "bg-frame")} onClickCapture={drawerOpen ? noteDrawerAction : undefined} onKeyDownCapture={drawerOpen ? noteDrawerAction : undefined}><WindowFrameBar notifications={notificationTray} /><BotLimitPopup /><ConversationShareDialogs />@@ -340,7 +338,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {ref={menuButtonRef}aria-label={t("app.openBotList")}aria-expanded={drawerOpen}- onClick={() => setDrawerOpen(true)}+ onClick={openDrawer}className="absolute left-3 top-3 z-30 rounded-md p-1.5 text-ink-secondary hover:bg-raised hover:text-ink max-md:flex max-md:size-9 max-md:items-center max-md:justify-center max-md:rounded-full max-md:border max-md:border-hairline max-md:bg-card max-md:p-0 max-md:text-ink md:hidden"><Menu size={18} className="max-md:hidden" />@@ -349,7 +347,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {{drawerOpen && !calendarFocus && (<divaria-hidden- onMouseDown={(e) => e.target === e.currentTarget && setDrawerOpen(false)}+ onMouseDown={(e) => e.target === e.currentTarget && hideDrawer()}className="absolute inset-0 z-30 bg-black/50 md:hidden"/>)}diff --git a/src/hooks/use-bot-list-drawer.dom.test.ts b/src/hooks/use-bot-list-drawer.dom.test.tsnew file mode 100644index 0000000000..649b5d2b73--- /dev/null+++ b/src/hooks/use-bot-list-drawer.dom.test.ts@@ -0,0 +1,100 @@+// @vitest-environment happy-dom+import { act, createElement as h } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { useBotListDrawer, type DrawerPlace } from "./use-bot-list-drawer";++const START: DrawerPlace = { selectedId: "scout", botThread: "private", groupThread: undefined, view: "chat", pluginsOpen: false, settingsOpen: false };++let root: Root;+let container: HTMLElement;++/** The app's wiring: the menu button, and the list with a conversation row and the "Just me / Team" switch. */+function Shell({ place }: { place: DrawerPlace }) {+ const drawer = useBotListDrawer(place);+ return h("div", { onClickCapture: drawer.open ? drawer.noteAction : undefined, onKeyDownCapture: drawer.open ? drawer.noteAction : undefined },+ h("button", { "aria-label": "Open bot list", "aria-expanded": drawer.open, onClick: drawer.show }),+ h("aside", null,+ h("div", { "data-team-side": "me" }, h("button", { "data-option": "team" })),+ h("button", { "data-row": "thread" }),+ h("button", { "data-row": "close", onClick: drawer.hide })));+}++const show = (place: DrawerPlace) => act(async () => root.render(h(Shell, { place })));+const press = (selector: string) => act(async () => container.querySelector<HTMLElement>(selector)!.click());+const expanded = () => container.querySelector('[aria-label="Open bot list"]')!.getAttribute("aria-expanded");++beforeEach(async () => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ await show(START);+});+afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+});++it("opens from the menu button and says so", async () => {+ expect(expanded()).toBe("false");+ await press('[aria-label="Open bot list"]');+ expect(expanded()).toBe("true");+ await press('[data-row="close"]');+ expect(expanded()).toBe("false");+});++it("stays open while the conversation under it changes by itself, as it does when the app starts", async () => {+ await press('[aria-label="Open bot list"]');+ await show({ ...START, botThread: "shared" });+ expect(expanded(), "the app opened the shared chat").toBe("true");+ await show({ ...START, botThread: "private" });+ expect(expanded(), "and went back to the person's own").toBe("true");+ await show({ ...START, selectedId: "room", botThread: undefined, groupThread: "room-1" });+ await press('[aria-label="Open bot list"]');+ await show({ ...START, selectedId: "room", botThread: undefined, groupThread: "room-2" });+ expect(expanded(), "a group chat's conversation too").toBe("true");+});++it("closes when a conversation the person picked in the list comes on screen", async () => {+ await press('[aria-label="Open bot list"]');+ await press('[data-row="thread"]');+ expect(expanded(), "still open while the switch is on its way").toBe("true");+ await show({ ...START, botThread: "picked" });+ expect(expanded()).toBe("false");+});++it("closes for a conversation picked with the keyboard", async () => {+ await press('[aria-label="Open bot list"]');+ await act(async () => { container.querySelector('[data-row="thread"]')!.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); });+ await show({ ...START, botThread: "picked" });+ expect(expanded()).toBe("false");+});++it("stays open after the Just me / Team switch, which only changes what the list shows", async () => {+ await press('[aria-label="Open bot list"]');+ await press('[data-option="team"]');+ await show({ ...START, botThread: "shared" });+ expect(expanded()).toBe("true");+});++it("forgets an earlier pick each time it opens", async () => {+ await press('[aria-label="Open bot list"]');+ await press('[data-row="thread"]');+ await show({ ...START, botThread: "picked" });+ await press('[aria-label="Open bot list"]');+ await show({ ...START, botThread: "shared" });+ expect(expanded()).toBe("true");+});++it.each([+ ["another chat", { selectedId: "other" }],+ ["another page", { view: "routines" }],+ ["the apps page", { pluginsOpen: true }],+ ["a bot's settings", { settingsOpen: true }],+] as const)("closes when the person goes to %s, however they got there", async (_where, change) => {+ await press('[aria-label="Open bot list"]');+ await show({ ...START, ...change });+ expect(expanded()).toBe("false");+});diff --git a/src/hooks/use-bot-list-drawer.ts b/src/hooks/use-bot-list-drawer.tsnew file mode 100644index 0000000000..dcfb169af2--- /dev/null+++ b/src/hooks/use-bot-list-drawer.ts@@ -0,0 +1,34 @@+import { useCallback, useEffect, useRef, useState, type SyntheticEvent } from "react";++export interface DrawerPlace {+ selectedId: string;+ botThread: string | undefined;+ groupThread: string | undefined;+ view: string;+ pluginsOpen: boolean;+ settingsOpen: boolean;+}++const KEEPS_LIST_OPEN = "[data-team-side]";++/**+ * The bot list that covers a narrow window. It closes when the person goes somewhere: another chat or page, or a+ * conversation they picked while it was open. A conversation that changes under it by itself (the one the app settles on+ * as it starts, a switch made on another device) leaves it open.+ */+export function useBotListDrawer(place: DrawerPlace) {+ const [open, setOpen] = useState(false);+ const acted = useRef(false);+ const show = useCallback(() => { acted.current = false; setOpen(true); }, []);+ const hide = useCallback(() => setOpen(false), []);+ const noteAction = useCallback((event: SyntheticEvent) => {+ if (!(event.target instanceof Element && event.target.closest(KEEPS_LIST_OPEN))) acted.current = true;+ }, []);+ useEffect(() => {+ setOpen(false);+ }, [place.selectedId, place.view, place.pluginsOpen, place.settingsOpen]);+ useEffect(() => {+ if (acted.current) setOpen(false);+ }, [place.botThread, place.groupThread]);+ return { open, show, hide, noteAction };+}diff --git a/src/state/store.tsx b/src/state/store.tsxindex a66fbbb808..6e9cf63f4b 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -2894,11 +2894,11 @@ export function StoreProvider({ children }: { children: ReactNode }) {const launched = useRef(false);useEffect(() => {- if (!state.hydrated || launched.current) return;+ if (!state.hydrated || !state.config || launched.current) return;launched.current = true;const bot = state.bots.find((candidate) => candidate.id === state.selectedId);if (bot && state.activeView === "chat" && botOpensTo(bot, showThreads) !== bot.threadId) openBot(dispatch, bot, showThreads);- }, [state.hydrated, state.bots, state.selectedId, state.activeView, showThreads, dispatch]);+ }, [state.hydrated, state.config, state.bots, state.selectedId, state.activeView, showThreads, dispatch]);useEffect(() => {let alive = true;diff --git a/src/state/team-launch.test.ts b/src/state/team-launch.test.tsnew file mode 100644index 0000000000..8bec71361a--- /dev/null+++ b/src/state/team-launch.test.ts@@ -0,0 +1,96 @@+// @vitest-environment happy-dom+// The real provider and its live stream on a team's Cloud, with a fake server whose config answers after its bot list.+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterAll, afterEach, beforeAll, expect, it, vi } from "vitest";+import type { AppState, BotAnnouncement } from "./store";+import { LAST_CONVERSATION_KEY } from "@/lib/last-conversation";++class FixtureEventSource {+ static opened: FixtureEventSource[] = [];+ onopen: (() => void) | null = null;+ onerror: (() => void) | null = null;+ onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;+ constructor(readonly url: string) { FixtureEventSource.opened.push(this); }+ close() {}+ send(frame: object) { this.onmessage?.({ data: JSON.stringify(frame) }); }+}++// Ada was last in her own chat with Scout; with threads hidden a bot opens to its main chat, which on a team is everyone's.+const scout: BotAnnouncement = {+ id: "scout", threadId: "ada-own", mainThreadId: "team-chat", name: "Scout", title: "", description: "", notifications: true, unread: false,+ color: "green", modelSelection: { instanceId: "fake", model: "m" }, visibility: "everyone", yourAccess: "chat",+ tasks: [{ threadId: "ada-own", title: "Mine", createdAt: 2, private: true }, { threadId: "team-chat", title: "Team", createdAt: 1, sharedChat: true }],+};+const json = (body: unknown) => new Response(JSON.stringify(body), { status: 200 });+const later = (body: unknown, ms: number) => new Promise<Response>((resolve) => setTimeout(() => resolve(json(body)), ms));+const switches: string[] = [];+let server: BotAnnouncement;+let configAfter = 0;+let state: AppState;++const { StoreProvider, useStore } = await import("./store");+const { useTeamChats, setTeamChats } = await import("./team-chats");++let root: Root;+const stream = () => FixtureEventSource.opened.at(-1)!;+const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++function Probe() {+ ({ state } = useStore());+ useTeamChats(state.config);+ return null;+}++beforeAll(() => {+ const saved = new Map<string, string>();+ vi.stubGlobal("localStorage", {+ getItem: (key: string) => saved.get(key) ?? null,+ setItem: (key: string, value: string) => saved.set(key, value),+ removeItem: (key: string) => saved.delete(key),+ });+ vi.stubGlobal("EventSource", FixtureEventSource);+ vi.stubGlobal("fetch", (path: string, init?: RequestInit) => {+ if (path.startsWith("/api/bots?")) return Promise.resolve(json({ bots: [{ ...server, messages: [] }], groups: [] }));+ if (path === "/api/config") return later({ team: { id: "team-acme", name: "Acme" } }, configAfter);+ if (path === "/api/auth/session") return Promise.resolve(json({ kind: "session", id: "s1", scopes: ["client"], email: "[email protected]", team: { id: "team-acme", name: "Acme", role: "member" }, openedThreads: ["ada-own"] }));+ const switched = path.match(/^\/api\/bots\/scout\/tasks\/([\w-]+)/);+ if (switched && init?.method === "POST") {+ switches.push(switched[1]!);+ server = { ...server, threadId: switched[1]! };+ return Promise.resolve(json({ bot: { ...structuredClone(server), messages: [] } }));+ }+ if (path.startsWith("/api/routines?since=")) return Promise.resolve(json({ routines: [], runs: [] }));+ if (path === "/api/webhooks") return Promise.resolve(json({ webhooks: [], attempts: [] }));+ if (path === "/api/instances") return Promise.resolve(json({ instances: [] }));+ return Promise.resolve(json({}));+ });+});+afterAll(() => vi.unstubAllGlobals());+afterEach(() => {+ flushSync(() => root.unmount());+ setTeamChats(null);+});++async function launch(configDelay: number) {+ server = structuredClone(scout);+ configAfter = configDelay;+ switches.length = 0;+ localStorage.setItem(LAST_CONVERSATION_KEY, "scout");+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(Probe))));+ await wait(0);+ stream().send({ kind: "hello", resumed: false, cursor: "run:0" });+ await wait(configDelay + 60);+}++it.each([["after", 40], ["with", 0]] as const)("never opens a team bot's shared chat as it starts when the config answers %s the bot list", async (_order, delay) => {+ await launch(delay);+ expect(state.config?.team?.id).toBe("team-acme");+ expect(state.selectedId).toBe("scout");+ expect(switches, "no conversation but her own was asked for").not.toContain("team-chat");+ expect(state.bots.find((bot) => bot.id === "scout")!.threadId).toBe("ada-own");+});