Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Simple header: the pill names the open thread and opens the bot's threads to switch

milind-soni2ef5148f8605
diff --git a/src/components/ChatHeadPill.tsx b/src/components/ChatHeadPill.tsx
index 438df00b60..cbaf72380b 100644
--- a/src/components/ChatHeadPill.tsx
+++ b/src/components/ChatHeadPill.tsx
@@ -1,6 +1,6 @@
import { localizedTaskTitle } from "@/lib/task-title";
import { ChevronRight, Lock, UserRound, Users } from "lucide-react";
-import type { ComponentProps } from "react";
+import { useMemo, type ComponentProps } from "react";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
@@ -11,6 +11,8 @@ import { ELEVATED_FLOAT, ELEVATED_HOVER } from "./elevated";
import { sidebarBotActivityTasks } from "./SidebarBotActivity";
import { BOT_PANEL_ID } from "./bot-panel/side-panel";
import { sharedChatAudience } from "./TeamPrivateChatsLine";
+import { showsTabs, threadTabs } from "./thread-tabs";
+import { ThreadSwitcherPill } from "./ThreadSwitcherPill";
/** The factory title a new conversation starts with. */
const UNTITLED = "New thread";
@@ -29,11 +31,13 @@ function privacyLabelOf(privacy: ChatHeadPrivacy): string | null {
}
}
-/** Simple mode's whole chat header: the bot's face and name in one pill, which opens and closes the bot panel. Away from
- * the bot's main conversation it also names the one on screen. A dot says another of the bot's conversations needs a
+/** Simple mode's whole chat header: the bot's face and name in one pill, which opens and closes the bot panel. With two
+ * threads or more it also names the one on screen, which opens the bot's threads to switch; with one, away from the bot's
+ * main conversation, it names that. A dot says another of the bot's conversations needs a
* look; a team chat says who can read it with one quiet glyph. */
-export function ChatHeadPill({ bot, avatar, privacy, onToggle }: {
+export function ChatHeadPill({ bot, avatar, privacy, onToggle, switcher = false }: {
bot: Bot;
+ switcher?: boolean;
avatar: Pick<ComponentProps<typeof BotAvatar>, "state" | "motion" | "motionKey" | "animated">;
privacy: ChatHeadPrivacy;
onToggle: () => void;
@@ -47,6 +51,16 @@ export function ChatHeadPill({ bot, avatar, privacy, onToggle }: {
const conversation = !awayFromMainThread(bot, false) ? (privacy?.kind === "shared" ? t("task.sharedChat") : null)
: !title || title === UNTITLED ? t("task.untitledChat") : localizedTaskTitle(title);
const label = t("chat.openProfileAria", { name: bot.name });
+ const tabs = useMemo(() => (switcher ? threadTabs(bot) : []), [switcher, bot.id, bot.threadId, bot.switchingTo, bot.mainThreadId, bot.tasks, bot.busy]);
+ if (showsTabs(tabs)) {
+ const head = <>
+ <BotAvatar bot={bot} size={28} {...avatar} />
+ <span dir="auto" className="min-w-0 truncate text-[14px] font-medium leading-5">{bot.name}</span>
+ {privacyLabel && <span data-chathead-privacy={privacy?.kind} title={privacyLabel} className="flex shrink-0 text-ink-tertiary"><PrivacyIcon size={13} aria-hidden="true" /><span className="sr-only">{privacyLabel}</span></span>}
+ {elsewhere > 0 && <span role="img" data-chathead-elsewhere aria-label={t("task.otherActivity", { count: elsewhere })} className="size-1.5 shrink-0 rounded-full bg-accent" />}
+ </>;
+ return <ThreadSwitcherPill bot={bot} tabs={tabs} head={<span className="flex min-w-0 items-center gap-2 pe-1">{head}</span>} label={label} panelOpen={open} onToggle={onToggle} />;
+ }
return (
<button
type="button"
diff --git a/src/components/ChatView.controls.test.ts b/src/components/ChatView.controls.test.ts
index 0f54c790bc..793d5869f2 100644
--- a/src/components/ChatView.controls.test.ts
+++ b/src/components/ChatView.controls.test.ts
@@ -144,19 +144,22 @@ describe("the header's right side", () => {
});
describe("the Simple header", () => {
- it("is one pill: the avatar and name, with a dot for another busy conversation and no title, role or way back", () => {
+ it("is one pill: the avatar and name, with a dot for another busy conversation, the open thread to switch from, and no title, role or way back", () => {
const busyElsewhere: Bot = { ...bot, title: "Research", mainThreadId: "other", tasks: [...bot.tasks!, { threadId: "other", title: "Other", createdAt: 0, busy: true, activity: "working" }] };
fixture.advanced = false;
try {
const simple = renderToStaticMarkup(createElement(ChatView, { bot: busyElsewhere }));
const identity = simple.slice(simple.indexOf("data-chathead-identity"), simple.indexOf("data-chathead-controls"));
const pill = identity.match(/<button[^>]*data-chathead-pill="true"[^>]*>([\s\S]*?)<\/button>/)!;
- expect(identity.replace(pill[0], "").replace(/<span role="status"[^>]*>[^<]*<\/span>/, "")).not.toMatch(/<(button|a|span)[\s>]/);
+ const threads = identity.match(/<button[^>]*data-chathead-threads="true"[^>]*>([\s\S]*?)<\/button>/)!;
+ const shell = identity.match(/<div[^>]*data-chathead-switch="closed"[^>]*>/)!;
expect(pill[1]).toContain(">Pepper</span>");
expect(pill[1]).toContain('data-chathead-elsewhere="true"');
- expect(pill[0].match(/class="([^"]*)"/)![1]!.split(" ")).toEqual(expect.arrayContaining(["rounded-full", "bg-composer", "ring-[0.5px]", "shadow-(--shadow-float)", "py-[5.5px]", "pl-[5.5px]", "pr-[13.5px]"]));
- // Away from the bot's main conversation, the pill names the one on screen.
- expect(pill[1]).toContain("data-chathead-conversation");
+ expect(shell[0].match(/class="([^"]*)"/)![1]!.split(" ")).toEqual(expect.arrayContaining(["rounded-full", "bg-composer", "ring-[0.5px]", "shadow-(--shadow-float)", "p-[5.5px]"]));
+ // A bot with two threads names the one on screen beside it, which opens the others.
+ expect(threads[0]).toContain('aria-expanded="false"');
+ expect(threads[1]).toContain("data-chathead-conversation");
+ expect(identity.replace(pill[0], "").replace(threads[0], "").replace(/<span role="status"[^>]*>[^<]*<\/span>/, "")).not.toMatch(/<(button|a|span)[\s>]/);
for (const gone of ["data-chathead-role", "data-background-activity", "data-chathead-back", 'data-testid="chat-more"']) {
expect(simple, gone).not.toContain(gone);
}
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index 8c4a1a972b..187ad11157 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -936,7 +936,7 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = fal
<div data-chathead-identity className={cn("flex min-w-0 items-center gap-2", phone ? "flex-1" : "@max-[30rem]/chathead:basis-full @min-[30rem]/chathead:col-start-2 @min-[30rem]/chathead:justify-self-center", simpleHead && phone && "justify-center")} style={headerNoDragStyle}>{headTabs && <HeaderThreadTabs bot={bot} />}
{simpleHead ? (
<ChatHeadPill
- bot={bot}
+ bot={bot} switcher={!inForkPanel}
avatar={{ state: stateForBot({ ...bot, messages }), motion: headerMotion, motionKey: mascotMotion?.nonce ?? 0, animated: headerAnimated }}
privacy={privateChat ? { kind: "private" } : ownHelper ? { kind: "ownHelper" } : sharedChat && team ? { kind: "shared", team: team.name, onlyPeopleAdded: bot.onlyPeopleAdded, sharedWith: currentTask?.sharedWith?.name } : null}
onToggle={() => dispatch({ type: "toggleSettings", open: !state.settingsOpen })}
diff --git a/src/components/HeaderThreadTabs.tsx b/src/components/HeaderThreadTabs.tsx
index 7e3eb4bef2..a0b06489eb 100644
--- a/src/components/HeaderThreadTabs.tsx
+++ b/src/components/HeaderThreadTabs.tsx
@@ -33,7 +33,8 @@ export function HeaderThreadTabs({ bot }: { bot: Bot }) {
return <Strip bot={bot} tabs={tabs} />;
}
-function edgeFade(element: HTMLElement): string | undefined {
+/** The mask that fades a sideways-scrolling row's edges where more of it is hidden, none when it all fits. */
+export function edgeFade(element: HTMLElement): string | undefined {
const room = element.scrollWidth - element.clientWidth;
if (room <= 1) return undefined;
const rtl = getComputedStyle(element).direction === "rtl";
diff --git a/src/components/ThreadSwitcherPill.dom.test.ts b/src/components/ThreadSwitcherPill.dom.test.ts
new file mode 100644
index 0000000000..39d819492b
--- /dev/null
+++ b/src/components/ThreadSwitcherPill.dom.test.ts
@@ -0,0 +1,84 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { Action, Bot, Task } from "@/state/store";
+
+const dispatch = vi.hoisted(() => vi.fn());
+vi.mock("@/state/store-select", () => ({ useStoreDispatch: () => dispatch, useStoreSelector: (select: (state: unknown) => unknown) => select({ settingsOpen: false, pendingQueued: {}, bots: [], newChat: null }) }));
+vi.mock("./Avatar", () => ({ BotAvatar: () => null }));
+
+import { ChatHeadPill } from "./ChatHeadPill";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const task = (threadId: string, title: string, at: number, extra: Partial<Task> = {}): Task => ({ threadId, title, createdAt: at, lastThreadOrderAt: at, ...extra });
+const pepper = (tasks: Task[], threadId: string): Bot => ({ id: "pepper", name: "Pepper", threadId, mainThreadId: "sales", tasks, messages: [] } as unknown as Bot);
+const THREADS = [task("sales", "Weekly sales", 5, { busy: true }), task("launch", "Launch plan", 1, { pinned: true }), task("trip", "Berlin trip", 3)];
+
+let root: Root | null = null;
+const onToggle = vi.fn();
+const render = (bot: Bot) => {
+ root = createRoot(document.body.appendChild(document.createElement("div")));
+ act(() => root!.render(createElement(ChatHeadPill, { bot, avatar: {} as never, privacy: null, onToggle, switcher: true })));
+};
+const q = <T extends Element = HTMLElement>(selector: string) => document.querySelector<T & HTMLElement>(selector);
+const chips = () => [...document.querySelectorAll<HTMLElement>("[role=option]")];
+const sent = () => dispatch.mock.calls.map(([action]) => action as Action);
+
+beforeEach(() => { dispatch.mockClear(); onToggle.mockClear(); });
+afterEach(() => { act(() => root?.unmount()); root = null; document.body.innerHTML = ""; });
+
+describe("the pill's thread switcher", () => {
+ it("names the open thread beside the bot, and the bot's name still opens its panel", () => {
+ render(pepper(THREADS, "launch"));
+ expect(q("[data-chathead-conversation]")?.textContent).toBe("Launch plan");
+ act(() => q("[data-chathead-pill]")!.click());
+ expect(onToggle).toHaveBeenCalledOnce();
+ expect(q("[role=listbox]")).toBeNull();
+ });
+
+ it("opens on a click, never on hover, into the threads: pinned first, the open one selected", () => {
+ render(pepper(THREADS, "launch"));
+ act(() => { q("[data-chathead-threads]")!.dispatchEvent(new MouseEvent("mouseover", { bubbles: true })); });
+ expect(q("[role=listbox]")).toBeNull();
+ act(() => q("[data-chathead-threads]")!.click());
+ expect(chips().map((chip) => chip.textContent)).toEqual(["Launch plan", "Weekly sales", "Berlin trip"]);
+ expect(chips()[0].getAttribute("aria-selected")).toBe("true");
+ expect(chips()[1].querySelector('[aria-label="Working"]')).not.toBeNull();
+ expect(chips()[0].querySelector('[aria-label="Pinned"]')).not.toBeNull();
+ });
+
+ it("switches to a picked thread and folds back", () => {
+ render(pepper(THREADS, "launch"));
+ act(() => q("[data-chathead-threads]")!.click());
+ act(() => chips()[2].click());
+ expect(sent()).toEqual([{ type: "switchTask", botId: "pepper", threadId: "trip" }]);
+ expect(q("[role=listbox]")).toBeNull();
+ });
+
+ it("moves between threads with the arrow keys, and folds back on Escape", () => {
+ render(pepper(THREADS, "launch"));
+ act(() => q("[data-chathead-threads]")!.click());
+ act(() => chips()[0].focus());
+ act(() => { chips()[0].dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })); });
+ expect(document.activeElement).toBe(chips()[1]);
+ act(() => { chips()[1].dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });
+ expect(q("[role=listbox]")).toBeNull();
+ expect(sent()).toEqual([]);
+ });
+
+ it("starts a new thread from its plus", () => {
+ render(pepper(THREADS, "launch"));
+ act(() => q("[data-chathead-threads]")!.click());
+ act(() => q("[data-thread-chip-new]")!.click());
+ expect(sent()).toEqual([{ type: "newTask", botId: "pepper" }]);
+ });
+
+ it("stays the plain pill for a bot with one thread", () => {
+ render(pepper([task("sales", "Weekly sales", 5)], "sales"));
+ expect(q("[data-chathead-threads]")).toBeNull();
+ expect(q("[data-chathead-switch]")).toBeNull();
+ expect(q("[data-chathead-pill]")).not.toBeNull();
+ });
+});
diff --git a/src/components/ThreadSwitcherPill.tsx b/src/components/ThreadSwitcherPill.tsx
new file mode 100644
index 0000000000..964fa69a17
--- /dev/null
+++ b/src/components/ThreadSwitcherPill.tsx
@@ -0,0 +1,153 @@
+import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from "react";
+import { ChevronDown, Pin, Plus } from "lucide-react";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+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 } from "./elevated";
+import { edgeFade } from "./HeaderThreadTabs";
+import { reducedMotion } from "./MenuMotion";
+import { openTabId, type ThreadTab } from "./thread-tabs";
+
+const RESIZE_MS = 240;
+const EASE = "cubic-bezier(0.22, 1, 0.36, 1)";
+const PART = "flex h-full min-w-0 items-center rounded-full outline-none transition-colors duration-[120ms] hover:bg-ink/[0.06] active:bg-ink/[0.08] focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus motion-reduce:transition-none";
+const CHIP = "flex h-7 max-w-42 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] leading-[18px] outline-none transition-colors duration-[120ms] focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus motion-reduce:transition-none";
+
+export const tabTitle = (tab: ThreadTab): string => (tab.draft ? t("task.newShort") : !tab.title || tab.title === "New thread" ? t("task.untitledChat") : localizedTaskTitle(tab.title));
+
+/** The pill's width glides from what it was to what its new content needs, then lets go. */
+function useGlidingWidth(key: unknown) {
+ const box = useRef<HTMLDivElement>(null);
+ const last = useRef<number | null>(null);
+ useLayoutEffect(() => {
+ const element = box.current;
+ if (!element) return;
+ element.style.transition = "";
+ element.style.width = "";
+ const to = element.getBoundingClientRect().width;
+ const from = last.current;
+ last.current = to;
+ if (from === null || Math.abs(from - to) < 1 || reducedMotion()) return;
+ element.style.width = `${from}px`;
+ void element.offsetWidth;
+ element.style.transition = `width ${RESIZE_MS}ms ${EASE}`;
+ element.style.width = `${to}px`;
+ const done = window.setTimeout(() => { element.style.transition = ""; element.style.width = ""; }, RESIZE_MS);
+ return () => { window.clearTimeout(done); element.style.transition = ""; element.style.width = ""; };
+ }, [key]);
+ return box;
+}
+
+/**
+ * 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 widens the pill in place into the bot's threads, to pick one or start one. A pick, Escape
+ * or a click elsewhere folds it back.
+ */
+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 box = useGlidingWidth(open);
+ const list = useRef<HTMLDivElement>(null);
+ const toggle = useRef<HTMLButtonElement>(null);
+ const [fade, setFade] = useState<string | undefined>();
+ const active = openTabId(bot);
+ const current = tabs.find((tab) => tab.threadId === active);
+ const canWrite = bot.yourAccess !== "view";
+
+ const close = (refocus: boolean) => {
+ setOpen(false);
+ if (refocus) requestAnimationFrame(() => toggle.current?.focus());
+ };
+ useEffect(() => {
+ if (!open) return;
+ const away = (event: PointerEvent) => { if (!box.current?.contains(event.target as Node)) setOpen(false); };
+ document.addEventListener("pointerdown", away);
+ return () => document.removeEventListener("pointerdown", away);
+ }, [open]);
+ useLayoutEffect(() => {
+ if (!open || !list.current) return;
+ const row = list.current;
+ row.scrollLeft = 0;
+ const chip = row.querySelector<HTMLElement>('[aria-selected="true"]') ?? row.querySelector<HTMLElement>("[role=option]");
+ chip?.focus({ preventScroll: true });
+ const settle = window.setTimeout(() => {
+ chip?.scrollIntoView?.({ block: "nearest", inline: "nearest" });
+ setFade(edgeFade(row));
+ }, reducedMotion() ? 0 : RESIZE_MS);
+ return () => window.clearTimeout(settle);
+ }, [open]);
+
+ const pick = (tab: ThreadTab) => {
+ if (tab.threadId !== active) dispatch({ type: "switchTask", botId: bot.id, threadId: tab.threadId });
+ close(true);
+ };
+ const onKey = (event: ReactKeyboardEvent<HTMLDivElement>) => {
+ if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); close(true); return; }
+ const chips = Array.from(list.current?.querySelectorAll<HTMLElement>("[role=option]") ?? []);
+ const at = chips.indexOf(document.activeElement as HTMLElement);
+ if (at < 0) return;
+ const rtl = getComputedStyle(event.currentTarget).direction === "rtl";
+ const step = event.key === "ArrowRight" ? (rtl ? -1 : 1) : event.key === "ArrowLeft" ? (rtl ? 1 : -1) : 0;
+ const to = step ? Math.min(Math.max(at + step, 0), chips.length - 1) : event.key === "Home" ? 0 : event.key === "End" ? chips.length - 1 : null;
+ if (to === null) return;
+ event.preventDefault();
+ chips[to]?.focus();
+ };
+
+ return (
+ <div ref={box} data-chathead-switch={open ? "open" : "closed"} onKeyDown={open ? onKey : undefined}
+ className={cn("flex h-[39px] min-w-0 max-w-full items-center overflow-hidden rounded-full p-[5.5px] text-ink", ELEVATED_FLOAT, open && "max-w-[min(720px,100cqw_-_34rem)]")}>
+ {open ? (
+ <div key="open" className="flex min-w-0 animate-fade-in items-center gap-1 motion-reduce:animate-none">
+ <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-0")}>
+ {head}
+ </button>
+ <div ref={list} role="listbox" aria-label={t("task.namedList", { name: bot.name })} aria-orientation="horizontal"
+ onScroll={(event) => setFade(edgeFade(event.currentTarget))} style={{ maskImage: fade, WebkitMaskImage: fade }}
+ className="flex min-w-0 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
+ {tabs.map((tab) => {
+ const selected = tab.threadId === active;
+ const title = tabTitle(tab);
+ return (
+ <button key={tab.threadId} type="button" role="option" aria-selected={selected} tabIndex={selected ? 0 : -1} title={title}
+ data-thread-chip={tab.threadId} onClick={() => pick(tab)}
+ className={cn(CHIP, selected ? "bg-ink/[0.1] text-ink" : "text-ink-secondary hover:bg-ink/[0.06] hover:text-ink")}>
+ {tab.working ? <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" />
+ : tab.pinned ? <Pin size={12} role="img" aria-label={t("task.pinned")} className="shrink-0 text-ink-tertiary" /> : null}
+ <span dir="auto" className="min-w-0 truncate">{title}</span>
+ </button>
+ );
+ })}
+ </div>
+ {canWrite && (
+ <button type="button" data-thread-chip-new aria-label={t("task.newShort")} title={t("task.newShort")}
+ onClick={() => { dispatch({ type: "newTask", botId: bot.id }); close(false); }}
+ className={cn(PART, "size-7 shrink-0 justify-center text-ink-secondary hover:text-ink")}>
+ <Plus size={16} aria-hidden="true" />
+ </button>
+ )}
+ </div>
+ ) : (
+ <div key="closed" className="flex min-w-0 items-center">
+ <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-0")}>
+ {head}
+ </button>
+ <button ref={toggle} type="button" data-chathead-threads aria-haspopup="listbox" aria-expanded={false}
+ aria-label={t("task.namedList", { name: bot.name })} onClick={() => setOpen(true)}
+ className={cn(PART, "gap-1.5 pe-2.5 ps-1.5 text-[14px] font-medium leading-5 text-ink-secondary hover:text-ink")}>
+ <span aria-hidden="true" className="text-ink-tertiary">·</span>
+ <span data-chathead-conversation dir="auto" className="min-w-0 max-w-[180px] truncate">{current ? tabTitle(current) : ""}</span>
+ <ChevronDown size={12} aria-hidden="true" className="shrink-0 text-ink-tertiary" />
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}