Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Phone layout: back button steps back inside the web app
AdityaUmale2466e221f90c
diff --git a/src/App.tsx b/src/App.tsxindex af177fe740..ba806ef501 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -23,7 +23,7 @@ import { ChatView } from "@/components/ChatView";import { HandoffExchangeHost } from "@/components/HandoffExchange";import { GroupView } from "@/components/GroupView";import { ForkPanel } from "@/components/ForkPanel";-import { SIDEBAR_AND_BOT_PANEL_FIT, SIDEBAR_AND_NARROW_PANEL_FIT, SIDEBAR_AND_PANEL_FIT, SIDEBAR_INLINE, TWO_SIDE_PANELS_FIT, useMediaQuery } from "@/lib/use-media-query";+import { PHONE_LAYOUT, SIDEBAR_AND_BOT_PANEL_FIT, SIDEBAR_AND_NARROW_PANEL_FIT, SIDEBAR_AND_PANEL_FIT, SIDEBAR_INLINE, TWO_SIDE_PANELS_FIT, useMediaQuery } from "@/lib/use-media-query";import { anySidePanel, botPanelFloats, panelsMovingSidebar, sidebarFoldsForPanel, type OpenSidePanels } from "@/lib/sidebar-fold";import { preloadConnectedApps } from "@/lib/connected-apps";import {@@ -31,7 +31,7 @@ import {PluginsPanel, preloadScreens, PublishedAppsPage, RemoteAgentSettingsPanel, SkillBurgersPage, RemoteDesktopPanel, RoomPanel, SettingsModal, TeamFilesPage, TeamMapPage, TriggersPage,} from "@/components/lazy-screens";import { useAdvancedMode } from "@/lib/interface-mode";-import { useRoomPanelShown } from "@/lib/room-panel";+import { closeRoomPanel, useRoomPanelShown } from "@/lib/room-panel";import { WorkspaceBackupRecovery } from "@/components/WorkspaceBackupRecovery";import { NotificationRail, NotificationsPanel } from "@/components/NotificationsPanel";import { useNotificationFeed } from "@/lib/notification-preferences";@@ -48,7 +48,7 @@ import { useTeamChats } from "@/state/team-chats";import { needsYouVersion, useTeamPeopleLoader } from "@/state/team-people";import { newChatBot } from "@/state/new-chat";import { useTeamPresence } from "@/state/team-presence";-import { inboxVersion, useInboxLoader, useInboxPanel, useInboxReady } from "@/state/inbox";+import { closeInbox, inboxVersion, useInboxLoader, useInboxPanel, useInboxReady } from "@/state/inbox";import { PlacesRail } from "@/components/PlacesRail";import { NewLocalFromMenu } from "@/components/PlaceAddSheet";import { CloudHowTo } from "@/components/CloudHowTo";@@ -77,7 +77,9 @@ import { botUnreadCount, showBrowserUnread } from "@/lib/bot-unread";import { phonePairingSettingsAction, takePhonePairingRequest } from "@/lib/phone-pairing"; import { useConnectLink } from "@/lib/use-connect-link";import { isSettingsPage } from "@/components/settings/settings-index";import { useBotListDrawer } from "@/hooks/use-bot-list-drawer";+import { usePhoneBack } from "@/hooks/use-phone-back";import { useRememberedSidePanel } from "@/hooks/use-remembered-side-panel";+import { closeSidePanels } from "@/lib/page-open";import { useDesktopNotificationOpens, useExternalChatLinks } from "@/hooks/use-external-chat-links"; import { useNewBotFromOtherPlace } from "@/lib/places-together";import { useUsageSnapshot } from "@/hooks/use-usage-snapshot";import { useReadShownChatOnFocus } from "@/hooks/use-read-shown-chat";@@ -176,7 +178,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {const chiefStep = useChiefStepOpen();const bot = group || chiefStep ? undefined : (state.bots.find((b) => b.id === state.selectedId) ?? state.bots[0]);const chatBot = useMemo(() => bot && newChatBot(bot, state.newChat), [bot, state.newChat]);- const { open: drawerOpen, show: openDrawer, hide: hideDrawer, noteAction: noteDrawerAction } = useBotListDrawer({ selectedId: state.selectedId, botThread: chatBot?.threadId, groupThread: group?.threadId,+ const { open: drawerOpen, show: openDrawer, hide: hideDrawer, noteAction: noteDrawerAction, back: drawerBack, backSteps: drawerBackSteps } = useBotListDrawer({ selectedId: state.selectedId, botThread: chatBot?.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;@@ -187,6 +189,17 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {notifications: notificationFeed && state.notificationsOpen,wide: (Boolean(bot) && (state.computerOpen || state.inspectorOpen || state.activityOpen)) || Boolean(state.forkPanel),};+ const panelOpen = anySidePanel(sidePanels);+ // On a phone, back closes the open list or side panel, and from a chat picked in the list goes back to the list.+ const phoneLayout = useMediaQuery(PHONE_LAYOUT, false);+ usePhoneBack(phoneLayout, drawerBackSteps + (panelOpen ? 1 : 0), () => {+ if (drawerOpen || !panelOpen) return drawerBack();+ closeSidePanels(dispatch);+ dispatch({ type: "toggleNotifications", open: false });+ dispatch({ type: "closeForkPanel" });+ closeRoomPanel();+ closeInbox();+ });// A 320 panel leaves room for the open sidebar from 1040 up; a wider one from 1280. Narrower, the sidebar folds.const collapseSidebar = sidebarFoldsForPanel(sidePanels, { wide: sidebarAndPanelFit, narrow: sidebarAndNarrowPanelFit });// Open beside a panel below 1280, the sidebar keeps to 280 so the chat keeps its 440; Simple's bot panel never moves it.diff --git a/src/hooks/use-bot-list-drawer.dom.test.ts b/src/hooks/use-bot-list-drawer.dom.test.tsindex 649b5d2b73..5f947df895 100644--- a/src/hooks/use-bot-list-drawer.dom.test.ts+++ b/src/hooks/use-bot-list-drawer.dom.test.ts@@ -14,14 +14,16 @@ 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("aside", { "data-back-steps": drawer.backSteps },h("div", { "data-team-side": "me" }, h("button", { "data-option": "team" })),h("button", { "data-row": "thread" }),- h("button", { "data-row": "close", onClick: drawer.hide })));+ h("button", { "data-row": "close", onClick: drawer.hide })),+ h("button", { "data-back": "", onClick: drawer.back }));}const show = (place: DrawerPlace) => act(async () => root.render(h(Shell, { place })));const press = (selector: string) => act(async () => container.querySelector<HTMLElement>(selector)!.click());+const backSteps = () => Number(container.querySelector("aside")!.getAttribute("data-back-steps"));const expanded = () => container.querySelector('[aria-label="Open bot list"]')!.getAttribute("aria-expanded");beforeEach(async () => {@@ -98,3 +100,43 @@ it.each([await show({ ...START, ...change });expect(expanded()).toBe("false");});++it("gives back nothing to do on the chat the app opened with", () => {+ expect(backSteps()).toBe(0);+});++it("closes the list opened from the menu with one step back", async () => {+ await press('[aria-label="Open bot list"]');+ expect(backSteps()).toBe(1);+ await press("[data-back]");+ expect(expanded()).toBe("false");+ expect(backSteps(), "back again leaves the app").toBe(0);+});++it("goes back from a chat picked in the list to the list, and from there out of the app", async () => {+ await press('[aria-label="Open bot list"]');+ await press('[data-row="thread"]');+ await show({ ...START, botThread: "picked" });+ expect(expanded()).toBe("false");+ expect(backSteps(), "the picked chat goes back to the list").toBe(1);+ await press("[data-back]");+ expect(expanded()).toBe("true");+ expect(backSteps(), "the list is the first screen now").toBe(0);+});++it("counts the list opened over a picked chat as one more step", async () => {+ await show({ ...START, selectedId: "other" });+ await press('[aria-label="Open bot list"]');+ await show({ ...START, selectedId: "picked" });+ await press('[aria-label="Open bot list"]');+ expect(backSteps()).toBe(2);+ await press("[data-back]");+ expect(expanded(), "first back shows the picked chat").toBe("false");+ expect(backSteps()).toBe(1);+});++it("keeps no step when the list is closed without going anywhere", async () => {+ await press('[aria-label="Open bot list"]');+ await press('[data-row="close"]');+ expect(backSteps()).toBe(0);+});diff --git a/src/hooks/use-bot-list-drawer.ts b/src/hooks/use-bot-list-drawer.tsindex dcfb169af2..099685feab 100644--- a/src/hooks/use-bot-list-drawer.ts+++ b/src/hooks/use-bot-list-drawer.ts@@ -11,24 +11,41 @@ export interface DrawerPlace {const KEEPS_LIST_OPEN = "[data-team-side]";+interface DrawerState {+ open: boolean;+ /** What is on screen was reached from the list, so going back shows the list again. */+ fromList: boolean;+ /** The list came back with the back button: it is the first screen, and back from it leaves the app. */+ first: boolean;+}++const CLOSED: DrawerState = { open: false, fromList: false, first: false };+/*** 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 [state, setState] = useState<DrawerState>(CLOSED);const acted = useRef(false);- const show = useCallback(() => { acted.current = false; setOpen(true); }, []);- const hide = useCallback(() => setOpen(false), []);+ const show = useCallback(() => { acted.current = false; setState((s) => ({ ...s, open: true, first: false })); }, []);+ const hide = useCallback(() => setState((s) => ({ ...s, open: false, first: false })), []);const noteAction = useCallback((event: SyntheticEvent) => {if (!(event.target instanceof Element && event.target.closest(KEEPS_LIST_OPEN))) acted.current = true;}, []);+ const leave = useCallback(() => setState((s) => (s.open ? { open: false, fromList: true, first: false } : s)), []);useEffect(() => {- setOpen(false);- }, [place.selectedId, place.view, place.pluginsOpen, place.settingsOpen]);+ leave();+ }, [place.selectedId, place.view, place.pluginsOpen, place.settingsOpen, leave]);useEffect(() => {- if (acted.current) setOpen(false);- }, [place.botThread, place.groupThread]);- return { open, show, hide, noteAction };+ if (acted.current) leave();+ }, [place.botThread, place.groupThread, leave]);+ /** One step back: the open list closes, and a screen reached from the list brings the list back. */+ const back = useCallback(() => {+ acted.current = false;+ setState((s) => (s.open ? { ...s, open: false, first: false } : s.fromList ? { open: true, fromList: false, first: true } : s));+ }, []);+ const backSteps = (state.open && !state.first ? 1 : 0) + (state.fromList ? 1 : 0);+ return { open: state.open, show, hide, noteAction, back, backSteps };}diff --git a/src/hooks/use-phone-back.dom.test.ts b/src/hooks/use-phone-back.dom.test.tsnew file mode 100644index 0000000000..92df441a9c--- /dev/null+++ b/src/hooks/use-phone-back.dom.test.ts@@ -0,0 +1,95 @@+// @vitest-environment happy-dom+import { act, createElement as h, useState } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { usePhoneBack } from "./use-phone-back";++let root: Root;+let container: HTMLElement;+let above = 0;+const back = vi.fn();++function Shell({ enabled, steps }: { enabled: boolean; steps: number }) {+ usePhoneBack(enabled, steps, back);+ return null;+}++/** Two open steps that close one at a time, as the app's panel and list do. */+function Stack() {+ const [steps, setSteps] = useState(2);+ usePhoneBack(true, steps, () => { back(); setSteps((open) => open - 1); });+ return h("output", null, steps);+}++const show = (enabled: boolean, steps: number) => act(async () => root.render(h(Shell, { enabled, steps })));+const pop = () => act(async () => { window.dispatchEvent(new PopStateEvent("popstate")); });+/** The phone's back button: the browser leaves the top entry, then tells the page. */+const pressBack = async () => {+ above = Math.max(0, above - 1);+ await pop();+};++beforeEach(async () => {+ above = 0;+ back.mockReset();+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.spyOn(window.history, "pushState").mockImplementation(() => { above += 1; });+ vi.spyOn(window.history, "go").mockImplementation((delta = 0) => {+ above = Math.max(0, above + delta);+ queueMicrotask(() => window.dispatchEvent(new PopStateEvent("popstate")));+ });+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});+afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++it("keeps one entry per step on a phone, and a back press steps back once", async () => {+ await act(async () => root.render(h(Stack)));+ expect(above).toBe(2);+ await pressBack();+ expect(back).toHaveBeenCalledTimes(1);+ expect(container.textContent).toBe("1");+ expect(above, "the press used its own entry").toBe(1);+ await pressBack();+ expect(container.textContent).toBe("0");+ expect(above).toBe(0);+ expect(window.history.go, "no entry left over to take away").not.toHaveBeenCalled();+});++it("adds nothing and handles no back press on a wide layout", async () => {+ await show(false, 2);+ expect(window.history.pushState).not.toHaveBeenCalled();+ await pop();+ expect(back).not.toHaveBeenCalled();+});++it("takes the entry away when the step is closed in the app, without stepping back again", async () => {+ await show(true, 1);+ expect(above).toBe(1);+ await show(true, 0);+ expect(window.history.go).toHaveBeenCalledWith(-1);+ expect(above, "back from here leaves the app at once").toBe(0);+ expect(back, "the entry it took away is not a back press").not.toHaveBeenCalled();+});++it("puts the entry back when a press leaves the steps as they were", async () => {+ await show(true, 1);+ await pressBack();+ expect(back).toHaveBeenCalledTimes(1);+ expect(above).toBe(1);+});++it("takes every entry away when the window grows past the phone layout", async () => {+ await show(true, 2);+ await show(false, 2);+ expect(window.history.go).toHaveBeenCalledWith(-2);+ expect(above).toBe(0);+ await pop();+ expect(back).not.toHaveBeenCalled();+});diff --git a/src/hooks/use-phone-back.ts b/src/hooks/use-phone-back.tsnew file mode 100644index 0000000000..15987f9518--- /dev/null+++ b/src/hooks/use-phone-back.ts@@ -0,0 +1,39 @@+import { useEffect, useReducer, useRef } from "react";+import { useStableCallback } from "./use-stable-callback";++/**+ * Lets a phone's back button (Android's, or a phone browser's) step back inside the app instead of leaving it. While+ * `enabled`, the page keeps one history entry above where it started for each of the `steps` the person can go back,+ * and a back press calls `back` once. A step closed in the app takes its entry away again, so back never does nothing;+ * a press that leaves the steps as they were gets its entry back.+ */+export function usePhoneBack(enabled: boolean, steps: number, back: () => void): void {+ const added = useRef(0);+ const ownPops = useRef(0);+ const stepBack = useStableCallback(back);+ const [, redraw] = useReducer((draws: number) => draws + 1, 0);+ useEffect(() => {+ const wanted = enabled ? steps : 0;+ if (wanted > added.current) {+ for (let entry = added.current; entry < wanted; entry += 1) window.history.pushState(window.history.state, "", window.location.href);+ } else if (wanted < added.current) {+ ownPops.current += 1;+ window.history.go(wanted - added.current);+ }+ added.current = wanted;+ });+ useEffect(() => {+ const onPop = () => {+ if (ownPops.current > 0) {+ ownPops.current -= 1;+ return;+ }+ if (added.current === 0) return;+ added.current -= 1;+ stepBack();+ redraw();+ };+ window.addEventListener("popstate", onPop);+ return () => window.removeEventListener("popstate", onPop);+ }, [stepBack]);+}