Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from "react";
import { Check, ChevronDown, Pin, SquarePen } from "lucide-react";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
import { useSharedClock } from "@/lib/shared-clock";
import { localizedTaskTitle } from "@/lib/task-title";
import type { Bot } from "@/state/store";
import { useStoreDispatch } from "@/state/store-select";
import { BOT_PANEL_ID } from "./bot-panel/side-panel";
import { ELEVATED_FLOAT, ELEVATED_OPEN, ELEVATED_TINT } from "./elevated";
import { ShortcutHint } from "./ShortcutHint";
import { threadRecency, threadUpdatedLabel } from "./SidebarThreadRow";
import { SidebarPopoverMenu, type SidebarMenuItem } from "./SidebarPopoverMenu";
import { openTabId, type ThreadTab } from "./thread-tabs";
const PART = "flex h-full min-w-0 items-center rounded-full outline-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus";
const NAVIGATION_KEYS = new Set(["Tab", "Enter", " ", "Escape", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"]);
export const tabTitle = (tab: ThreadTab): string => (tab.draft ? t("task.newShort") : !tab.title || tab.title === "New thread" ? t("task.untitledChat") : localizedTaskTitle(tab.title));
/**
* Whether the pill was last used with a pointer, which hides its focus ring until a key moves or presses something.
* Chrome (158) matches :focus-visible on a scripted focus that follows an element showing its ring, and on any key,
* Shift or a letter included, pressed while an element has focus: without this, the pill focused again after a pick
* would show the ring to someone who only clicked.
*/
function usePointerUse() {
const [pointer, setPointer] = useState(false);
useEffect(() => {
if (!pointer) return;
const key = (event: KeyboardEvent) => { if (NAVIGATION_KEYS.has(event.key)) setPointer(false); };
document.addEventListener("keydown", key, true);
return () => document.removeEventListener("keydown", key, true);
}, [pointer]);
return { pointer, onPointerDown: () => setPointer(true) };
}
function ThreadMark({ tab }: { tab: ThreadTab }) {
if (tab.working) return <span role="img" aria-label={t("chat.activity.working")} className="size-1.5 shrink-0 animate-pulse rounded-full bg-success motion-reduce:animate-none" />;
if (tab.pinned) return <span className="flex"><Pin size={12} role="img" aria-label={t("task.pinned")} className="text-ink-tertiary" /></span>;
return null;
}
/** The open thread's row in the pill's open menu. */
function openThreadRow(pill: HTMLElement | null) {
const id = pill?.querySelector('[aria-haspopup="menu"]')?.getAttribute("aria-controls");
const menu = id ? document.getElementById(id) : null;
const row = menu?.querySelector<HTMLElement>('[aria-checked="true"]');
return menu && row ? { menu, row } : null;
}
/** Kept in view on opening; a keyboard opening lands on it rather than the menu's first row. */
function landOnOpenThread(pill: HTMLElement | null) {
const open = openThreadRow(pill);
if (!open) return;
open.row.scrollIntoView?.({ block: "nearest" });
if (open.menu.contains(document.activeElement)) open.row.focus({ preventScroll: true });
}
/**
* Simple mode's pill for a bot with two threads or more: its face and name open the bot panel as ever, and the open
* thread's name beside them opens the bot's threads in a menu under the pill, to pick one or start one.
*/
export function ThreadSwitcherPill({ bot, tabs, head, label, panelOpen, onToggle }: {
bot: Bot; tabs: ThreadTab[]; head: ReactNode; label: string; panelOpen: boolean; onToggle: () => void;
}) {
const dispatch = useStoreDispatch();
const [open, setOpen] = useState(false);
const pill = useRef<HTMLDivElement>(null);
const now = useSharedClock(30_000, open);
const active = openTabId(bot);
const current = tabs.find((tab) => tab.threadId === active);
const canWrite = bot.yourAccess !== "view";
const { pointer, onPointerDown } = usePointerUse();
const items: SidebarMenuItem[] = tabs.map((tab) => {
const selected = tab.threadId === active;
const task = tab.draft ? undefined : bot.tasks?.find((each) => each.threadId === tab.threadId);
const at = task ? threadRecency(task) : 0;
return {
key: `thread:${tab.threadId}`,
label: tabTitle(tab),
title: tabTitle(tab),
checked: selected,
icon: selected ? <Check size={16} aria-hidden="true" /> : <ThreadMark tab={tab} />,
value: at ? threadUpdatedLabel(at, now) : undefined,
trailing: selected && (tab.working || tab.pinned) ? <ThreadMark tab={tab} /> : undefined,
onSelect: () => { if (!selected) dispatch({ type: "switchTask", botId: bot.id, threadId: tab.threadId }); },
};
});
if (canWrite) {
items.push({ key: "new-thread", separatorBefore: true, label: t("task.newShort"), icon: <SquarePen size={16} />,
trailing: <ShortcutHint id="new-thread" />, onSelect: () => dispatch({ type: "newTask", botId: bot.id }) });
}
const onOpenChange = (next: boolean) => {
setOpen(next);
if (next) requestAnimationFrame(() => landOnOpenThread(pill.current));
};
// A menu opened with the mouse leaves focus on the pill: an arrow then steps into it, at the open thread.
const intoMenu = (event: ReactKeyboardEvent) => {
if (!open || (event.key !== "ArrowDown" && event.key !== "ArrowUp") || (event.target as HTMLElement).getAttribute("aria-haspopup") !== "menu") return;
const row = openThreadRow(pill.current)?.row;
if (!row) return;
event.preventDefault();
row.focus();
};
return (
<div ref={pill} data-chathead-switch={open ? "open" : "closed"} data-pointer-used={pointer ? "" : undefined} onPointerDown={onPointerDown} onKeyDown={intoMenu}
className={cn("group/pill flex h-[39px] min-w-0 max-w-full items-center rounded-full p-[5.5px] text-ink", ELEVATED_FLOAT, open ? ELEVATED_OPEN : ELEVATED_TINT)}>
<button type="button" data-chathead-pill data-tour="bot-pill" onClick={onToggle} title={t("chat.openBotPanel")} aria-label={label}
aria-expanded={panelOpen} aria-controls={panelOpen ? BOT_PANEL_ID : undefined} className={cn(PART, "shrink")}>
{head}
</button>
<SidebarPopoverMenu items={items} ariaLabel={t("task.namedList", { name: bot.name })} onOpenChange={onOpenChange}
triggerClassName={cn(PART, "group/threads pe-2 ps-1 text-[14px] font-medium leading-5 transition-colors duration-[120ms] motion-reduce:transition-none",
open ? "text-ink" : "text-ink-secondary hover:text-ink")}
renderTrigger={({ open: shown }) => (
<span data-chathead-threads className="flex min-w-0 items-center gap-1">
<span data-chathead-conversation dir="auto" className="min-w-0 max-w-[180px] truncate max-md:max-w-[120px]">{current ? tabTitle(current) : ""}</span>
<ChevronDown size={12} aria-hidden="true"
className={cn("shrink-0 text-ink-tertiary transition-[opacity,rotate] duration-[120ms] ease-out motion-reduce:transition-none",
shown ? "rotate-180 opacity-100" : "opacity-0 group-hover/pill:opacity-100 group-focus-visible/threads:opacity-100 touch:opacity-100")} />
</span>
)} />
</div>
);
}