Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { ChevronLeft, Loader2, Menu } from "lucide-react";
import { CLOUD_LINK_SETTINGS, openBot, StoreProvider, useStore } from "@/state/store";
import { nextShortcutBot, shortcutBots, shownBotIds } from "@/lib/sidebar-shortcut-order";
import { useShowThreads } from "@/lib/thread-preferences";
import { useWelcomeViewer } from "@/components/onboarding/welcome-viewer";
import {
LazyAppNotices, LazyConversationShareDialogs, LazyFirstConversationTour, LazyGuidedTour,
LazyMausBotWelcome, LazyPublishTemplateHost, LazyWelcomeGate,
} from "@/components/lazy-overlays";
import { NewBotNameHost } from "@/components/NewBotName";
import { CloudTimeZoneSync } from "@/components/CloudTimeZone";
import { cloudSignInDue, noEnginesDue, spotlightsQuiet, workedEarlier, type WelcomeViewer } from "@/lib/onboarding";
import { LiveCallHost } from "@/components/LiveCallHost";
import { ThreadRefsProvider } from "@/components/ThreadRefs";
import { initAnalytics } from "@/lib/analytics";
import { useAppLoadSignal } from "@/lib/app-load";
import { cloudAccountBridge, openCloudOnWeb } from "@/lib/cloud-add-web";
import { parseComputerHelp } from "@/lib/computer-control";
import { viewerClosedRelease } from "@/components/computer-takeover";
import { Sidebar } from "@/components/Sidebar";
import { ChatView } from "@/components/ChatView";
import { HandoffExchangeHost } from "@/components/HandoffExchange";
import { useRoomFeed } from "@/components/room-feed/use-room-feed";
import { useFeedThreadFull } from "@/components/room-feed/feed-fit";
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 {
ActivityPanel, AnnouncementsPage, BotSettingsDialog, CloudAddDialog, ComputerPanel, FilesView, InboxPanel, InspectorPanel, KeyboardShortcutsModal, LocalVmWorkspace,
PluginsPanel, preloadScreens, PublishedAppsPage, RemoteAgentSettingsPanel, SkillBurgersPage, RemoteDesktopPanel, RoomPanel, SettingsModal, TeamFilesPage, TeamMapPage, TriggersPage,
} from "@/components/lazy-screens";
import {
CloudEngineSignIn, CloudIntent, CloudWelcome, ForkPanel, GroupView, MemberApps, NoEngines, RoomFeedView, TeamWelcome, WebPanelPage,
} from "@/components/lazy-views";
import { useAdvancedMode } from "@/lib/interface-mode";
import { closeRoomPanel, useRoomPanelShown } from "@/lib/room-panel";
import { closeAppPreview, useAppPreview } from "@/lib/app-preview";
import { closeFilePreview, useFilePreview } from "@/lib/file-preview";
import { WorkspaceBackupRecovery } from "@/components/WorkspaceBackupRecovery";
import { NotificationRail, NotificationsPanel } from "@/components/NotificationsPanel";
import { useNotificationFeed } from "@/lib/notification-preferences";
import { UpdateBanner } from "@/components/UpdateBanner";
import { CliLoginCard } from "@/components/CliLoginCard";
import { AppGrantNotice } from "@/components/AppGrantPrompt";
import { BotLimitPopup } from "@/components/BotLimitPopup";
import { CloudAsleepStrip } from "@/components/CloudAsleepStrip";
import { LiveConnectionStrip } from "@/components/LiveConnectionStrip";
import { CloudSendStrip } from "@/components/CloudSendStrip";
import { HomeLine } from "@/components/HomeLine";
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 { closeInbox, inboxVersion, useInboxLoader, useInboxPanel, useInboxReady } from "@/state/inbox";
import { PlacesRail } from "@/components/PlacesRail";
import { NewLocalFromMenu } from "@/components/PlaceAddSheet";
import { CloudHowTo } from "@/components/CloudHowTo";
import { DesktopCapabilitiesProvider, useCaptionChrome, useDesktopCapabilities, WindowDragStrip, windowFramed } from "@/components/DesktopCapabilities";
import { WindowCaptionButtons } from "@/components/WindowCaptionButtons";
import { WindowFrameBar } from "@/components/WindowFrameBar";
import { cn } from "@/lib/cn";
import { cloudIntentDue, cloudIntentShown, useCloudIntent } from "@/lib/cloud-intent";
import { CloudSetup } from "@/components/CloudSetup";
import { invitedToTeam, teamWelcomeDue, useTeamWelcomeRecord } from "@/lib/team-welcome";
import { WelcomeKeeper } from "@/components/cloud-welcome/WelcomeKeeper";
import { EmptyChatShell } from "@/components/onboarding/EmptyChatShell";
import { cloudFirstRun, cloudWelcomeVisible, useCloudWelcome } from "@/lib/cloud-welcome";
import { engineReady } from "@/components/EngineLibrary";
import { CommandPalette } from "@/components/CommandPalette";
import { t } from "@/lib/i18n";
import { botCycleStep, shouldOpenKeyboardShortcuts } from "@/lib/keyboard-shortcuts";
import { isStartFreshShortcut, startFreshRefusal } from "@/lib/start-fresh";
import { useThreadCycleKeys } from "@/components/thread-cycle";
import { 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 { isSettingsPage } from "@/components/settings/settings-pages";
import { useBotListDrawer } from "@/hooks/use-bot-list-drawer";
import { useSwitchHold } from "@/hooks/use-switch-hold";
import { usePhoneBack } from "@/hooks/use-phone-back";
import { useRememberedSidePanel } from "@/hooks/use-remembered-side-panel";
import { closeSidePanels } from "@/lib/page-open";
import { phoneBackStep, phoneBackSteps } from "@/lib/phone-back";
import { useDesktopNotificationOpens, useExternalChatLinks } from "@/hooks/use-external-chat-links"; import { useNewBotFromOtherPlace } from "@/lib/places-together"; import { isPlaceId } from "@/lib/place-chat"; import { PlaceChatKeeper, PlacedBotPanel } from "@/components/PlacedBotMenu";
import { useUsageSnapshot } from "@/hooks/use-usage-snapshot";
import { useReadShownChatOnFocus } from "@/hooks/use-read-shown-chat";
import { usePresence } from "@/hooks/use-presence"; import { useFeature } from "@/lib/use-feature";
import { ChatNotice } from "@/components/ChatErrorBanner";
import { loadingLine } from "@/lib/app-loading";
import { useAiSwitchKeeper } from "@/lib/ai-switch";
import { useChiefStepOpen } from "@/lib/default-bot";
import { useSessionEnded } from "@/lib/session-ended";
import { PairPage } from "./pair/PairPage";
import { AppPreviewPanel } from "@/components/published-apps/AppPreviewPanel";
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
import { refreshPublishedApps } from "@/lib/own-published-apps";
import { serverFetch } from "@/lib/relay-server";
import { replaceUrl } from "@/lib/replace-url";
import { api } from "@/state/api";
function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
const { state, dispatch } = useStore();
useTeamChats(state.config);
const needsYou = needsYouVersion(state.bots, state.groups, state.notifications);
useTeamPeopleLoader(state.config, needsYou);
useInboxLoader(`${inboxVersion(state.bots) ?? ""}|${needsYou}`);
useEffect(() => { refreshPublishedApps(); }, []);
const inboxReady = useInboxReady();
const inboxPanel = useInboxPanel();
const inboxShown = inboxPanel.open && inboxReady;
// A Switch AI pick lands once its stopped turn's chat is idle, wherever the person is by then.
useAiSwitchKeeper({ bots: state.bots, dispatch });
const showThreads = useShowThreads();
const { capabilities } = useDesktopCapabilities();
const captionChrome = useCaptionChrome();
const unreadCount =
state.bots.filter((bot) => !bot.hidden && !isPlaceId(bot.id)).reduce((sum, bot) => sum + botUnreadCount(bot), 0) +
state.groups.filter((group) => group.unread).length;
const remoteClient = window.ogb?.remoteClient?.active === true;
const twoSidePanelsFit = useMediaQuery(TWO_SIDE_PANELS_FIT, true);
const sidebarAndPanelFit = useMediaQuery(SIDEBAR_AND_PANEL_FIT, true);
const sidebarAndNarrowPanelFit = useMediaQuery(SIDEBAR_AND_NARROW_PANEL_FIT, true);
const sidebarAndBotPanelFit = useMediaQuery(SIDEBAR_AND_BOT_PANEL_FIT, true);
const sidebarInline = useMediaQuery(SIDEBAR_INLINE, false);
useEffect(() => {
if (!sidebarInline && state.forkPanel) dispatch({ type: "closeForkPanel" });
}, [sidebarInline, state.forkPanel, dispatch]);
useRememberedSidePanel(state, dispatch, { enabled: sidebarInline, inspector: !remoteClient });
useEffect(() => {
if (!window.ogb?.environments) return;
const open = (computerId?: string | null) => {
if (computerId) {
const target = new URL(window.location.href);
target.searchParams.set("share-computer", computerId);
replaceUrl(`${target.pathname}${target.search}${target.hash}`);
}
dispatch({ type: "toggleAppSettings", open: true, section: "desktopWorkspaces" });
};
const url = new URL(window.location.href);
const requestedSettings = url.searchParams.get("desktop-settings");
const cloud = ["cloud", "cloud-settings", "cloud-add", "cloud-add-howto"].includes(requestedSettings ?? "");
if (requestedSettings === "workspaces" || (requestedSettings === "organization" && window.ogb.organization && !remoteClient) ||
(cloud && window.ogb.cloudAccount && !remoteClient)) {
url.searchParams.delete("desktop-settings");
replaceUrl(`${url.pathname}${url.search}${url.hash}`);
if (requestedSettings === "organization") dispatch({ type: "toggleAppSettings", open: true, section: "organization" });
else if (requestedSettings === "cloud") dispatch(CLOUD_LINK_SETTINGS);
else if (requestedSettings === "cloud-settings") dispatch({ type: "toggleAppSettings", open: true, section: "cloudAccount" });
else if (requestedSettings === "cloud-add" || requestedSettings === "cloud-add-howto") dispatch({ type: "openCloudAdd", source: requestedSettings === "cloud-add" ? "app_menu" : "app_howto" });
else open();
}
return window.ogb.environments.onOpenSettings?.(open);
}, [dispatch]);
useEffect(() => {
const rest = takePhonePairingRequest(window.location.href);
if (rest === null) return;
replaceUrl(rest);
dispatch(phonePairingSettingsAction());
}, [dispatch]);
useConnectLink(dispatch, Boolean(state.config?.team));
useExternalChatLinks(state, dispatch); useDesktopNotificationOpens(state, dispatch); useNewBotFromOtherPlace(state.hydrated === true, useCallback(() => dispatch({ type: "newBot" }), [dispatch]));
usePresence(state, dispatch); useTeamPresence(state);
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.
const cloudAddOpened = useRef(false);
cloudAddOpened.current ||= Boolean(state.cloudAdd && cloudAccountBridge());
// A layout effect runs inside the tap that asked, so a browser lets it open a tab.
useLayoutEffect(() => {
if (!state.cloudAdd || cloudAccountBridge()) return;
openCloudOnWeb(state.cloudAdd, { cloudHome: state.config?.cloudHome === true, teamCloudPage: state.config?.team?.cloudPage });
dispatch({ type: "closeCloudAdd" });
}, [state.cloudAdd]);
const [localVmWorkspaceBotId, setLocalVmWorkspaceBotId] = useState<string | null>(null);
const menuButtonRef = useRef<HTMLButtonElement>(null);
const previousViewRef = useRef(state.activeView);
const freshPending = useRef(new Set<string>());
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 chatBot = useMemo(() => bot && newChatBot(bot, state.newChat), [bot, state.newChat]);
// A switch to a conversation still being read keeps the chat on screen until it lands (hooks/use-switch-hold).
const shownChat = useSwitchHold(state.activeView === "chat" ? chatBot : undefined, (id) => state.bots.find((held) => held.id === id)) ?? chatBot;
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;
const advanced = useAdvancedMode(), skillBurger = useFeature("skillBurger"), roomFeed = useRoomFeed(group);
// A thread opened from a room's feed sits beside it while both fit, and takes the feed's place when they don't.
const feedThreadFull = useFeedThreadFull(group && roomFeed && sidebarInline && state.forkPanel?.kind === "group" && state.forkPanel.ownerId === group.id ? state.forkPanel.threadId : null);
const roomPanelOpen = useRoomPanelShown({ group, state, simple: !advanced && !remoteClient });
const sidePanels: OpenSidePanels = {
simple: !advanced, remoteClient, bot: Boolean(bot) && state.settingsOpen, room: roomPanelOpen, inbox: inboxShown, inboxWide: inboxPanel.wide === true,
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);
const calendarFocus = state.activeView === "routines" && state.routinesFocus.view === "calendar";
const appPreview = useAppPreview();
const filePreview = useFilePreview();
const preview = state.activeView === "chat" && (appPreview !== null || filePreview !== null);
const backPlace = { calendar: calendarFocus, drawerOpen, panelOpen, preview, appsPage: state.pluginsOpen, drawerSteps: drawerBackSteps };
usePhoneBack(phoneLayout, phoneBackSteps(backPlace), () => {
const step = phoneBackStep(backPlace);
if (step === "calendar") return dispatch({ type: "showRoutines", view: "list", botId: state.routinesFocus.botId });
if (step === "apps-page") dispatch({ type: "togglePlugins", open: false });
if (step !== "panels") return drawerBack();
closeSidePanels(dispatch);
dispatch({ type: "toggleNotifications", open: false });
dispatch({ type: "closeForkPanel" });
closeRoomPanel();
closeInbox();
closeAppPreview();
closeFilePreview();
});
// 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.
const sidebarBesidePanel = anySidePanel(panelsMovingSidebar(sidePanels)) && !sidebarAndPanelFit;
const notificationTray = notificationFeed && !calendarFocus;
// Only engines truly absent, never status checks that could not finish on a busy machine (onboarding.ts).
const noEngines = noEnginesDue(state);
const cloudSignIn = cloudSignInDue(viewer, state, (instance) => engineReady(instance) || instance.snapshot.busy === true || (workedEarlier(instance) && instance.snapshot.authenticated !== false));
const cloudIntent = useCloudIntent();
const cloudAsk = cloudIntentShown(cloudIntentDue({
viewer, connected: state.connected, enginesKnown: state.instances.length > 0,
onboarding: state.config?.onboarding, reopened: false,
}), cloudIntent);
const cloudJobWaiting = Boolean(viewer?.cloudHome && viewer.canSave && cloudIntent.pending);
const welcome = useCloudWelcome();
const welcomeOnScreen = cloudWelcomeVisible({ viewer, connected: state.connected, enginesKnown: state.instances.length > 0, onboarding: state.config?.onboarding }, welcome)
&& state.activeView === "chat" && !(!remoteClient && localVmWorkspaceBotId);
const firstRun = cloudFirstRun({ welcome: welcomeOnScreen, intent: cloudAsk, signIn: cloudSignIn || cloudJobWaiting });
const team = state.config?.team ?? null;
const invited = invitedToTeam(viewer);
const teamWelcomeRecord = useTeamWelcomeRecord(team && invited ? team.id : null);
const teamWelcomeOn = teamWelcomeDue({ team, invited, record: teamWelcomeRecord }) && state.activeView === "chat";
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.defaultPrevented || e.isComposing || state.shortcutsOpen) return;
if (shouldOpenKeyboardShortcuts(e)) {
e.preventDefault();
dispatch({ type: "toggleShortcuts", open: true });
return;
}
const mod = e.metaKey || e.ctrlKey;
if (!mod) return;
const bots = shortcutBots(state.bots.filter((b) => !b.hidden), shownBotIds(document.querySelector("[data-sidebar-root]")));
const step = e.shiftKey ? botCycleStep(e) : null;
const newThreadKey = e.key.toLowerCase() === "t" && !e.shiftKey && !e.altKey;
if (isStartFreshShortcut(e)) {
const selected = state.bots.find((bot) => bot.id === state.selectedId && !bot.hidden);
if (
!e.repeat && selected && chatBot && state.activeView === "chat"
&& selected.yourAccess !== "view" && !chatBot.switchingTo && startFreshRefusal(chatBot) === null
&& !freshPending.current.has(selected.id)
) {
e.preventDefault();
freshPending.current.add(selected.id);
void api(`/api/bots/${selected.id}/start-fresh`, {
method: "POST",
body: JSON.stringify({ threadId: chatBot.threadId }),
})
.catch((cause: unknown) => dispatch({ type: "error", message: cause instanceof Error ? cause.message : String(cause) }))
.finally(() => freshPending.current.delete(selected.id));
}
return;
}
if ((e.key.toLowerCase() === "n" || newThreadKey) && !e.altKey) {
e.preventDefault();
if (e.shiftKey || newThreadKey) {
const selected = state.bots.find((bot) => bot.id === state.selectedId && !bot.hidden);
if (!e.repeat && selected && selected.yourAccess !== "view") dispatch({ type: "newTask", botId: selected.id });
} else {
dispatch({ type: "newBot" });
}
} else if (/^[1-9]$/.test(e.key)) {
const target = bots[Number(e.key) - 1];
if (target) {
e.preventDefault();
openBot(dispatch, target, showThreads);
}
} else if (step !== null) {
const next = nextShortcutBot(bots, state.selectedId, step);
if (next) {
e.preventDefault();
openBot(dispatch, next, showThreads);
}
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [state.bots, state.selectedId, state.activeView, state.shortcutsOpen, chatBot, showThreads, dispatch]);
useThreadCycleKeys();
useReadShownChatOnFocus();
useEffect(() => {
if (window.ogb?.setUnreadCount) window.ogb.setUnreadCount(unreadCount);
else showBrowserUnread(unreadCount);
}, [unreadCount]);
useEffect(() => {
if (!state.connected) return;
void preloadConnectedApps(false, true).catch(() => {}); // a background read: a reconnect is nobody using a Cloud home
}, [state.connected]);
useUsageSnapshot();
useEffect(() => preloadScreens(), []);
useEffect(() => {
if (state.activeView === "routines" && previousViewRef.current !== "routines") {
calendarOriginRef.current = previousViewRef.current === "team-map" || previousViewRef.current === "web-panel" ? previousViewRef.current : "chat";
}
previousViewRef.current = state.activeView;
}, [state.activeView]);
useEffect(() => {
if (
localVmWorkspaceBotId &&
(state.activeView !== "chat" || state.selectedId !== localVmWorkspaceBotId)
) {
setLocalVmWorkspaceBotId(null);
}
}, [localVmWorkspaceBotId, state.activeView, state.selectedId]);
const openLocalVmWorkspace = (botId: string) => {
dispatch({ type: "toggleComputer", open: false });
setLocalVmWorkspaceBotId(botId);
};
const openComputerFromWorkspace = (botId: string) => {
setLocalVmWorkspaceBotId(null);
dispatch({ type: "select", id: botId });
dispatch({ type: "toggleComputer", open: true });
};
const closeCalendar = useCallback(() => {
if (calendarOriginRef.current === "team-map") {
dispatch({ type: "showTeamMap" });
return;
}
if (calendarOriginRef.current === "web-panel" && state.webPanelId) {
dispatch({ type: "showWebPanel", id: state.webPanelId });
return;
}
dispatch({ type: "select", id: state.selectedId });
}, [dispatch, state.selectedId, state.webPanelId]);
const openCalendarRoom = useCallback((id: string) => {
dispatch({ type: "select", id });
}, [dispatch]);
const nativeViewOverlayOpen =
drawerOpen ||
paletteOpen ||
state.settingsOpen ||
state.computerOpen ||
state.inspectorOpen ||
state.activityOpen ||
state.appSettingsOpen ||
state.pluginsOpen;
useEffect(() => {
return window.ogb?.onOpenAppSettings?.(section => dispatch(section === "phone" ? phonePairingSettingsAction() : (section === "cloud-add" || section === "cloud-add-howto") && window.ogb?.cloudAccount && !remoteClient
? { type: "openCloudAdd", source: section === "cloud-add" ? "app_menu" : "app_howto" }
: section === "cloud" && window.ogb?.cloudAccount && !remoteClient
? CLOUD_LINK_SETTINGS
: section === "cloud-settings" && (window.ogb?.cloudAccount || window.ogb?.cloudPlan) && !remoteClient
? { type: "toggleAppSettings", open: true, section: "cloudAccount" }
: { type: "toggleAppSettings", open: true, ...((section === "organization" && window.ogb?.organization && !remoteClient) || isSettingsPage(section) ? { section } : {}) }));
}, [dispatch]);
useEffect(() => {
return window.ogb?.desktopViewer?.onState((viewer) => {
if (viewer.open || !viewer.contextId) return;
const botId = viewer.contextId, release = viewerClosedRelease(botId);
if (release) void serverFetch(`/api/bots/${botId}/computer/control`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(release),
})
.then((res) => (res.ok ? res.json() : null))
.then((snap) => {
if (snap) dispatch({ type: "computerControl", botId, held: snap.held === true, helpReason: snap.helpReason ?? null, help: parseComputerHelp(snap.help) });
})
.catch(() => {});
void serverFetch(`/api/bots/${botId}/computer/viewer-close`, {
method: "POST",
headers: { "content-type": "application/json" },
body: "{}",
}).catch(() => {});
});
}, [dispatch]);
const framed = windowFramed(capabilities);
// The sidebar is on screen, so its update button is too. In Simple that button is the one; the top bar leaves its own out.
const sidebarShown = !calendarFocus && (sidebarInline || drawerOpen);
const strips = <>
<UpdateBanner sidebarIndicator={framed || sidebarShown} />
<CloudAsleepStrip />
<LiveConnectionStrip connected={state.connected} hydrated={state.hydrated === true} />
<CloudSendStrip cloudHome={state.config?.cloudHome === true} />
<HomeLine />
<LazyAppNotices quiet={paletteOpen || drawerOpen || Boolean(localVmWorkspaceBotId)} viewer={viewer} />
<CliLoginCard />
</>;
return (
<div data-look="app" className={cn("flex h-full flex-col", framed && "bg-frame")} onClickCapture={drawerOpen ? noteDrawerAction : undefined} onKeyDownCapture={drawerOpen ? noteDrawerAction : undefined}>
<WindowFrameBar notifications={notificationTray} sidebarUpdate={!advanced && sidebarShown} />
<BotLimitPopup />
<LazyConversationShareDialogs />
<LazyPublishTemplateHost />
{!framed && strips}
<div className="relative flex min-h-0 flex-1 overflow-x-clip">
{!calendarFocus && <button
type="button"
ref={menuButtonRef}
aria-label={t("app.openBotList")}
aria-expanded={drawerOpen}
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" />
<ChevronLeft size={20} aria-hidden="true" className="hidden max-md:block" />
</button>}
{drawerOpen && !calendarFocus && (
<div
aria-hidden
onMouseDown={(e) => e.target === e.currentTarget && hideDrawer()}
className="absolute inset-0 z-30 bg-black/50 md:hidden"
/>
)}
{!calendarFocus && <PlacesRail />}
<NewLocalFromMenu />
{/* A framed window shows the app, its sidebar and the chat or page, in a rounded card under the top bar and beside
the window's rail: its top corners and its bottom-left corner are round, and it runs to the window's right and
bottom edges. */}
<div data-window-card={framed ? "" : undefined}
data-look={framed ? "window" : undefined} className={framed ? "relative flex min-w-0 flex-1 flex-col overflow-hidden rounded-t-[12px] rounded-bl-[12px] bg-app" : "contents"}>
{framed && strips}
<div className={framed ? "relative flex min-h-0 flex-1 overflow-x-clip" : "contents"}>
{!calendarFocus && <Sidebar
collapseToIcons={collapseSidebar}
besidePanel={sidebarBesidePanel}
open={drawerOpen}
onClose={closeDrawer}
/>}
{state.activeView === "team-map" ? (
<TeamMapPage />
) : state.activeView === "files" ? (
<FilesView />
) : state.activeView === "web-panel" ? (
<WebPanelPage />
) : state.activeView === "skill-burgers" && skillBurger ? (
<SkillBurgersPage />
) : state.activeView === "published-apps" ? (
<PublishedAppsPage />
) : state.activeView === "announcements" ? (
<AnnouncementsPage />
) : state.activeView === "team-files" && state.config?.team ? (
<TeamFilesPage />
) : state.activeView === "routines" ? (
<TriggersPage onBack={closeCalendar} onOpenRoom={openCalendarRoom} />
) : !remoteClient && localVmWorkspaceBotId ? (
<LocalVmWorkspace
primaryBotId={localVmWorkspaceBotId}
overlayOpen={nativeViewOverlayOpen}
onClose={() => setLocalVmWorkspaceBotId(null)}
onOpenComputer={openComputerFromWorkspace}
/>
) : teamWelcomeOn && team ? (
<TeamWelcome team={team} invitedBy={teamWelcomeRecord?.invitedBy ?? null} />
) : firstRun === "welcome" ? (
<CloudWelcome />
) : firstRun === "intent" ? (
<CloudIntent />
) : firstRun === "sign-in" ? (
<CloudEngineSignIn />
) : chiefStep ? (
<EmptyChatShell />
) : group && roomFeed ? (
feedThreadFull ? <ForkPanel full /> : <RoomFeedView key={group.id} group={group} />
) : group ? (
<GroupView key={group.id} group={group} />
) : bot ? (
<HandoffExchangeHost bot={shownChat ?? bot}><ChatView bot={shownChat ?? bot} /></HandoffExchangeHost>
) : noEngines ? (
<NoEngines />
) : (
<main data-app-loading={loading.text} className="relative flex h-full min-w-0 flex-1 flex-col items-center justify-center gap-3 bg-app text-ink-secondary">
<WindowDragStrip />
<div className="w-full max-w-md"><ChatNotice notice={state.notice} /></div>
{loading.busy && <Loader2 size={20} className="animate-spin" />}
<div className="text-[14px]">{t(loading.text)}</div>
{loading.command && (
<div className="text-[12px]">
{t("app.loading.startServer")} <code className="rounded bg-raised px-1.5 py-0.5">pnpm dev:server</code>
</div>
)}
</main>
)}
{/* Sibling panels need distinct keys: two keyed `bot.id` collide in React's keyed reconciliation. */}
<PlaceChatKeeper />{(state.settingsOpen || state.computerOpen) && bot && isPlaceId(bot.id) && <PlacedBotPanel key={`placed:${bot.id}`} bot={bot} />}{state.settingsOpen && bot && !isPlaceId(bot.id) && (
remoteClient
? <RemoteAgentSettingsPanel bot={bot} overlay={state.computerOpen && !twoSidePanelsFit} />
: <BotSettingsDialog key={`settings:${bot.id}`} bot={bot} overlay={((state.inspectorOpen || state.computerOpen || (notificationFeed && state.notificationsOpen)) && !twoSidePanelsFit) || botPanelFloats(sidePanels, sidebarAndBotPanelFit)} />
)}
{state.computerOpen && bot && !isPlaceId(bot.id) && (
remoteClient ? (
<RemoteDesktopPanel key={`computer:${bot.id}`} bot={bot} />
) : (
<ComputerPanel
key={`computer:${bot.id}`}
bot={bot}
onOpenVmWorkspace={openLocalVmWorkspace}
/>
)
)}
<AppPreviewPanel />
<FilePreviewPanel threadId={group?.threadId ?? bot?.threadId} />
{state.forkPanel && sidebarInline && !feedThreadFull && <ForkPanel />}
{!state.forkPanel && roomPanelOpen && group && (
<RoomPanel key={`room:${group.id}`} group={group} overlay={notificationFeed && state.notificationsOpen && !twoSidePanelsFit} />
)}
{!remoteClient && !state.forkPanel && state.inspectorOpen && bot && !isPlaceId(bot.id) && <InspectorPanel key={bot.threadId} bot={bot} />}
{!remoteClient && state.activityOpen && bot && !isPlaceId(bot.id) && <ActivityPanel key={`activity:${bot.id}`} bot={bot} />}
{inboxShown && <InboxPanel />}
{notificationTray && state.notificationsOpen && <NotificationsPanel />}
{notificationTray && !framed && <NotificationRail />}
</div>
</div>
{state.appSettingsOpen && <SettingsModal />}
{cloudAddOpened.current && <CloudAddDialog />}
<CloudHowTo />
<CloudSetup viewer={viewer} welcomeShown={welcomeOnScreen} />
<WelcomeKeeper viewer={viewer} />
{state.pluginsOpen && (team && viewer?.canSave === false ? <MemberApps /> : <PluginsPanel />)}
<AppGrantNotice />
{state.shortcutsOpen && (
<KeyboardShortcutsModal
open={state.shortcutsOpen}
onClose={() => dispatch({ type: "toggleShortcuts", open: false })}
/>
)}
{/* After the modals: same z-50 tier, so DOM order keeps the palette on top. */}
<CommandPalette onOpenChange={setPaletteOpen} />
{/* Blink resolves -webkit-app-region in DOM order, so this no-drag twin after the headers cuts the drawer button back out. */}
{!calendarFocus && <span
aria-hidden
data-drawer-button-no-drag
style={captionChrome.noDragStyle}
className="pointer-events-none absolute left-3 top-3 size-[30px] md:hidden"
/>}
</div>
{/* Last child on purpose: Blink resolves -webkit-app-region in DOM order, so no-drag buttons must follow every drag region. */}
<WindowCaptionButtons
visible={capabilities.windowChrome === "win-caption" && Boolean(window.ogb?.windowControls)}
/>
</div>
);
}
function AppLoadSignal() {
useAppLoadSignal();
return null;
}
function Application() {
useEffect(() => {
initAnalytics();
}, []);
const viewer = useWelcomeViewer();
return (
<DesktopCapabilitiesProvider>
<StoreProvider>
<AppLoadSignal />
<ThreadRefsProvider>
<Shell viewer={viewer} />
</ThreadRefsProvider>
<LazyWelcomeGate viewer={viewer} />
<LazyMausBotWelcome viewer={viewer} />
<NewBotNameHost />
<CloudTimeZoneSync viewer={viewer} />
<LazyGuidedTour />
<LiveCallHost />
<LazyFirstConversationTour quiet={spotlightsQuiet(viewer)} />
</StoreProvider>
</DesktopCapabilitiesProvider>
);
}
export default function App() {
const ended = useSessionEnded();
if (ended) return <PairPage initialCode={null} reason={t("pair.sessionEnded")} />;
return <WorkspaceBackupRecovery><Application /></WorkspaceBackupRecovery>;
}