Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Thread tabs: a bot's threads as soft tabs above its chat, behind the Thread tabs switch
milind-sonid4f989bea77b
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex bd8f00882d..d276958af5 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -88,7 +88,7 @@ import { ScreenFrame } from "./ScreenFrame";import { CompactionChip, DigestChip } from "./DigestChip";import { RenameTitle } from "./RenameTitle"; import { ChatHeadRole, chiefOfStaffBadge } from "./BotRole";import { BotActivityPicker } from "./TaskPicker"; import { ChatHeadPill } from "./ChatHeadPill"; import { HeaderShare } from "./bot-access/HeaderShare"; import { ThreadPresenceFaces } from "./TeamPresence"; import { useStoreRef } from "@/state/store-ref"; import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { sameDrawnBots } from "@/lib/drawn-bots"; import { ChatActivityControls, chatActivityMessages, useChatActivity } from "./ChatActivity";-import { ELEVATED_FLOAT, ELEVATED_HOVER } from "./elevated"; import { NewThreadHeaderButton } from "./NewThreadHeaderButton";+import { ELEVATED_FLOAT, ELEVATED_HOVER } from "./elevated"; import { NewThreadHeaderButton } from "./NewThreadHeaderButton"; import { ThreadTabStrip } from "./ThreadTabStrip";import { ModelPicker } from "./ModelPicker"; import { useFailedTurnFix } from "./FailedTurnFix";import { ChatHeaderMenu, ChatMoreMenu } from "./ChatMoreMenu"; import { TeamOwnHelperHeader, TeamPrivateFirstLine, TeamPrivateHeader, TeamSharedHeader } from "./TeamPrivateChatsLine"; import { ownChatStarted } from "@/state/team-chats"; import { isNewChatThread } from "@/state/new-chat";import { useChatFindRequests, useChatFindShortcut } from "@/lib/chat-find";@@ -920,7 +920,7 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = falreturn (<ThreadLinkContext value={threadLink}><main data-look="chat" className="relative flex h-full min-w-0 flex-1 flex-col bg-app">- <ChatBackdrop /><CallOverlay bot={bot} />+ <ChatBackdrop /><CallOverlay bot={bot} />{!inForkPanel && <ThreadTabStrip bot={bot} />}<GlassScrollFrame className="flex-1 [--glass-tint:var(--color-app)]">{/* z-[25]: above the room set-up card (z-20), below the CallOverlay (z-30). */}<GlassBar edge="top" fade={!remoteClient} data-chathead-float={simpleHead ? "" : undefined} className="z-[25]">diff --git a/src/components/NewThreadHeaderButton.tsx b/src/components/NewThreadHeaderButton.tsxindex 251957aaa7..d2684dae68 100644--- a/src/components/NewThreadHeaderButton.tsx+++ b/src/components/NewThreadHeaderButton.tsx@@ -1,9 +1,12 @@import { Plus } from "lucide-react";import { t } from "@/lib/i18n";+import { cn } from "@/lib/cn";import { useStoreDispatch } from "@/state/store-select";+import { useHeaderPlusGivesWay } from "./ThreadTabStrip";export function NewThreadHeaderButton({ botId }: { botId: string }) {const dispatch = useStoreDispatch();+ const givesWay = useHeaderPlusGivesWay(botId);return (<buttontype="button"@@ -12,7 +15,7 @@ export function NewThreadHeaderButton({ botId }: { botId: string }) {aria-label={t("task.newShort")}aria-keyshortcuts="Meta+T Control+T"title={t("task.newShort")}- className="flex size-9 shrink-0 items-center justify-center rounded-full text-ink-secondary transition-colors duration-[120ms] hover:bg-ink/[0.06] hover:text-ink active:bg-ink/[0.08] motion-reduce:transition-none"+ className={cn(givesWay && "md:hidden", "flex size-9 shrink-0 items-center justify-center rounded-full text-ink-secondary transition-colors duration-[120ms] hover:bg-ink/[0.06] hover:text-ink active:bg-ink/[0.08] motion-reduce:transition-none")}><Plus size={16} aria-hidden="true" /></button>diff --git a/src/components/SidebarThreadLabels.tsx b/src/components/SidebarThreadLabels.tsxindex 9c052b04a0..85a8a1d6de 100644--- a/src/components/SidebarThreadLabels.tsx+++ b/src/components/SidebarThreadLabels.tsx@@ -1,5 +1,4 @@-import { useEffect, useLayoutEffect, useRef, useState, type Dispatch, type KeyboardEvent as ReactKeyboardEvent } from "react";-import { createPortal } from "react-dom";+import { useLayoutEffect, useRef, useState, type Dispatch, type KeyboardEvent as ReactKeyboardEvent } from "react";import { ChevronRight, Clock3, Loader2, Plus, X } from "lucide-react";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";@@ -12,6 +11,7 @@ import { canUnfold, threadLabels, type LabelRow } from "./sidebar-thread-labels"import { isWorking } from "./SidebarThreadRow";import { showAllConversations } from "./bot-panel/Conversations";import { reducedMotion } from "./MenuMotion";+import { UndoToast, useUndoToast } from "./UndoToast";const SLOT = "pointer-events-none absolute end-[30px] top-1.5 flex size-6 items-center justify-center rounded-lg text-ink-secondary opacity-0 transition-opacity hover:bg-raised hover:text-ink group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 max-md:hidden touch:pointer-events-auto touch:opacity-70 motion-reduce:transition-none";const ROW = "group/label relative flex h-8 w-full min-w-0 items-center gap-2 rounded-lg ps-2.5 pe-2 text-start 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";@@ -62,8 +62,6 @@ function StatusMark({ row }: { row: LabelRow }) {}}-type Toast = { text: string; undo: () => void };-/** The rows under a bot in Simple mode's sidebar: what is going on while folded, the bot's active threads unfolded. */export function SidebarThreadLabels({ bot, selected, drafting = false, rowThreadId, pendingQueued, dispatch }: {bot: Bot; selected: boolean; drafting?: boolean; rowThreadId: string; pendingQueued: AppState["pendingQueued"]; dispatch: Dispatch<Action>;@@ -73,7 +71,7 @@ export function SidebarThreadLabels({ bot, selected, drafting = false, rowThreadconst { rows, more, runningMore } = threadLabels(bot, pendingQueued, { unfolded, current, rowThreadId, now: Date.now() });const [renaming, setRenaming] = useState<string | null>(null);const [draft, setDraft] = useState("");- const [toast, setToast] = useState<Toast | null>(null);+ const [toast, setToast] = useUndoToast();const [focusAt, setFocusAt] = useState<number | null>(null);const finishing = useRef(false);const tree = useRef<HTMLDivElement>(null);@@ -89,11 +87,6 @@ export function SidebarThreadLabels({ bot, selected, drafting = false, rowThreadreturn () => window.clearTimeout(timer);}, [unfolded]);useLayoutEffect(() => { shown.current = { unfolded, rows, more }; });- useEffect(() => {- if (!toast) return;- const timer = window.setTimeout(() => setToast(null), 6000);- return () => window.clearTimeout(timer);- }, [toast]);if (!rows.length && !more && !runningMore && !toast && !leaving) return null;const items = () => Array.from(tree.current?.querySelectorAll<HTMLElement>("[role=treeitem]") ?? []);@@ -204,12 +197,6 @@ export function SidebarThreadLabels({ bot, selected, drafting = false, rowThread</div>)}</div>- {toast && createPortal(- <div role="status" className="fixed bottom-4 start-[calc(var(--rail-beside,0px)_+_1rem)] z-[60] flex max-w-[340px] items-center gap-3 rounded-xl border border-hairline/50 bg-card px-3.5 py-2.5 text-[13px] text-ink shadow-xl animate-fade-in motion-reduce:animate-none">- <span className="min-w-0 line-clamp-2">{toast.text}</span>- <button type="button" onClick={() => { toast.undo(); setToast(null); }} className="shrink-0 rounded-md px-1.5 py-0.5 font-medium text-accent-text hover:bg-ink/[0.06]">{t("common.undo")}</button>- </div>,- document.body,- )}+ <UndoToast toast={toast} onDone={() => setToast(null)} /></>;}diff --git a/src/components/ThreadTabStrip.dom.test.ts b/src/components/ThreadTabStrip.dom.test.tsnew file mode 100644index 0000000000..ce28c117d0--- /dev/null+++ b/src/components/ThreadTabStrip.dom.test.ts@@ -0,0 +1,95 @@+// @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 feature = vi.hoisted(() => ({ on: true }));+const dispatch = vi.hoisted(() => vi.fn());+vi.mock("@/lib/use-feature", () => ({ useFeature: (name: string) => name === "threadTabs" && feature.on }));+vi.mock("@/state/store-select", () => ({ useStoreDispatch: () => dispatch, useStoreSelector: () => false }));++import { ThreadTabStrip } from "./ThreadTabStrip";++(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 kiwi = (tasks: Task[], threadId: string): Bot => ({ id: "kiwi", name: "Kiwi", threadId, mainThreadId: "main", tasks, messages: [] } as unknown as Bot);+const FIVE = [+ task("main", "Weekly sales", 5, { busy: true }), task("launch", "Launch plan", 1, { pinned: true }),+ task("invoice", "Invoice for Acme", 4), task("trip", "Berlin trip", 3), task("notes", "Call notes", 2),+];++let root: Root | null = null;+const render = (bot: Bot) => {+ root = createRoot(document.body.appendChild(document.createElement("div")));+ act(() => root!.render(createElement(ThreadTabStrip, { bot })));+};+const tabs = () => [...document.querySelectorAll<HTMLElement>('[role="tab"]')];+const tab = (title: string) => tabs().find((element) => element.textContent?.includes(title))!;+const closeOf = (title: string) => tab(title).querySelector<HTMLButtonElement>("button")!;+const sent = () => dispatch.mock.calls.map(([action]) => action as Action);++beforeEach(() => { feature.on = true; dispatch.mockClear(); });+afterEach(() => { act(() => root?.unmount()); root = null; document.body.innerHTML = ""; });++describe("thread tab strip", () => {+ it("is not there while Thread tabs is off, or for a bot with one thread", () => {+ feature.on = false;+ render(kiwi(FIVE, "launch"));+ expect(document.querySelector("[data-thread-tabs]")).toBeNull();+ act(() => root!.unmount());+ feature.on = true;+ render(kiwi([task("main", "Only", 1)], "main"));+ expect(document.querySelector("[data-thread-tabs]")).toBeNull();+ });++ it("lists pinned threads first, then by recent use, with the open one selected", () => {+ render(kiwi(FIVE, "launch"));+ expect(tabs().map((element) => element.textContent)).toEqual(["Launch plan", "Weekly sales", "Invoice for Acme", "Berlin trip", "Call notes"]);+ expect(tab("Launch plan").getAttribute("aria-selected")).toBe("true");+ expect(tab("Weekly sales").querySelector('[aria-label="Working"]')).not.toBeNull();+ expect(tab("Launch plan").querySelector('[aria-label="Pinned"]')).not.toBeNull();+ expect(closeOf("Weekly sales"), "no close on the main or a running thread").toBeNull();+ });++ it("archives with ✕, never deletes, and gives Undo", () => {+ render(kiwi(FIVE, "launch"));+ act(() => closeOf("Berlin trip").click());+ expect(sent()).toEqual([expect.objectContaining({ type: "updateTask", botId: "kiwi", threadId: "trip", patch: { archivedAt: expect.any(Number) } })]);+ expect(sent().some((action) => action.type === "deleteTask" || action.type === "switchTask")).toBe(false);+ const undo = [...document.querySelectorAll("button")].find((button) => button.textContent === "Undo")!;+ act(() => undo.click());+ expect(sent().at(-1)).toMatchObject({ type: "updateTask", threadId: "trip", patch: { archivedAt: null } });+ });++ it("moves to the neighbouring tab when the open one is archived", () => {+ render(kiwi(FIVE, "invoice"));+ act(() => closeOf("Invoice for Acme").click());+ expect(sent().map((action) => action.type)).toEqual(["switchTask", "updateTask"]);+ expect(sent()[0]).toMatchObject({ botId: "kiwi", threadId: "trip" });+ });++ it("archives on a middle click", () => {+ render(kiwi(FIVE, "launch"));+ act(() => { tab("Call notes").dispatchEvent(new MouseEvent("auxclick", { bubbles: true, button: 1 })); });+ expect(sent()).toEqual([expect.objectContaining({ type: "updateTask", threadId: "notes", patch: { archivedAt: expect.any(Number) } })]);+ });++ it("opens a tab on click and makes a new thread with +", () => {+ render(kiwi(FIVE, "launch"));+ act(() => tab("Berlin trip").click());+ act(() => document.querySelector<HTMLButtonElement>("[data-thread-tabs-new]")!.click());+ expect(sent()).toEqual([{ type: "switchTask", botId: "kiwi", threadId: "trip" }, { type: "newTask", botId: "kiwi" }]);+ });++ it("renames a tab in place on a double-click", () => {+ render(kiwi(FIVE, "launch"));+ act(() => { tab("Call notes").dispatchEvent(new MouseEvent("dblclick", { bubbles: true })); });+ const input = document.querySelector<HTMLInputElement>('input[aria-label="Rename thread"]')!;+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;+ act(() => { setValue.call(input, "Call with Dana"); input.dispatchEvent(new Event("input", { bubbles: true })); });+ act(() => { input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); });+ expect(sent()).toEqual([{ type: "renameTask", botId: "kiwi", threadId: "notes", title: "Call with Dana" }]);+ });+});diff --git a/src/components/ThreadTabStrip.tsx b/src/components/ThreadTabStrip.tsxnew file mode 100644index 0000000000..148acf0d38--- /dev/null+++ b/src/components/ThreadTabStrip.tsx@@ -0,0 +1,178 @@+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent } from "react";+import { Pin, Plus, X } from "lucide-react";+import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import { nextRename } from "@/lib/rename";+import { localizedTaskTitle } from "@/lib/task-title";+import { useFeature } from "@/lib/use-feature";+import type { Bot } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";+import { useCaptionChrome } from "./DesktopCapabilities";+import { reducedMotion } from "./MenuMotion";+import { botShowsTabs, neighbourOf, openTabId, showsTabs, threadTabs, type ThreadTab } from "./thread-tabs";+import { useTabMotion } from "./thread-tab-motion";+import { UndoToast, useUndoToast } from "./UndoToast";++const TAB = "thread-tab group/tab relative flex h-7 min-w-24 max-w-42 items-center rounded-t-xl ps-3 pe-1 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";+const CLOSE = "pointer-events-none ms-1 flex size-5 shrink-0 items-center justify-center rounded-full text-ink-tertiary opacity-0 transition-opacity duration-[120ms] hover:bg-ink/[0.08] hover:text-ink group-hover/tab:pointer-events-auto group-hover/tab:opacity-100 group-focus-within/tab:pointer-events-auto group-focus-within/tab:opacity-100 touch:pointer-events-auto touch:opacity-100 motion-reduce:transition-none";+const FADE = 24;++/** Whether the strip shows for this bot, so the chat header leaves New thread to the strip in windows wide enough for it. */+export function useHeaderPlusGivesWay(botId: string): boolean {+ const on = useFeature("threadTabs");+ const shown = useStoreSelector((state) => botShowsTabs(state.bots.find((bot) => bot.id === botId), state.newChat));+ return on && shown;+}++/** A bot's threads as tabs above its chat, once Thread tabs is on and the bot has two threads or more. */+export function ThreadTabStrip({ bot }: { bot: Bot }) {+ const on = useFeature("threadTabs");+ const tabs = useMemo(() => threadTabs(bot), [bot.id, bot.threadId, bot.switchingTo, bot.mainThreadId, bot.tasks, bot.busy]);+ if (!on || !showsTabs(tabs)) return null;+ return <Strip bot={bot} tabs={tabs} />;+}++function edgeFade(element: HTMLElement): string | undefined {+ const room = element.scrollWidth - element.clientWidth;+ if (room <= 1) return undefined;+ const rtl = getComputedStyle(element).direction === "rtl";+ const hiddenLeft = rtl ? room + element.scrollLeft : element.scrollLeft;+ const left = hiddenLeft > 1 ? "transparent 0, black " + FADE + "px" : "black 0";+ const right = room - hiddenLeft > 1 ? "black calc(100% - " + FADE + "px), transparent 100%" : "black 100%";+ return `linear-gradient(to right, ${left}, ${right})`;+}++function Strip({ bot, tabs }: { bot: Bot; tabs: ThreadTab[] }) {+ const dispatch = useStoreDispatch();+ const { dragProps } = useCaptionChrome();+ const scroller = useRef<HTMLDivElement>(null);+ const { shown, entering } = useTabMotion(tabs, scroller);+ const active = openTabId(bot);+ const [renaming, setRenaming] = useState<string | null>(null);+ const [draft, setDraft] = useState("");+ const finishing = useRef(false);+ const [toast, setToast] = useUndoToast();+ const [fade, setFade] = useState<string | undefined>();+ const canWrite = bot.yourAccess !== "view";++ const measure = useCallback(() => {+ const element = scroller.current;+ if (element) setFade(edgeFade(element));+ }, []);+ useLayoutEffect(measure);+ useEffect(() => {+ const element = scroller.current;+ if (!element || typeof ResizeObserver !== "function") return;+ const observer = new ResizeObserver(measure);+ observer.observe(element);+ return () => observer.disconnect();+ }, [measure]);+ useEffect(() => {+ const element = scroller.current?.querySelector<HTMLElement>(`[data-tab-id="${CSS.escape(active)}"]`);+ element?.scrollIntoView?.({ block: "nearest", inline: "nearest", behavior: reducedMotion() ? "auto" : "smooth" });+ }, [active]);++ const open = (tab: ThreadTab) => {+ if (tab.threadId !== active) dispatch({ type: "switchTask", botId: bot.id, threadId: tab.threadId });+ };+ const close = (tab: ThreadTab) => {+ if (!tab.closable) return;+ if (tab.threadId === active) {+ const next = neighbourOf(tabs, tab.threadId);+ if (next) dispatch({ type: "switchTask", botId: bot.id, threadId: next });+ }+ if (tab.draft) return;+ dispatch({ type: "updateTask", botId: bot.id, threadId: tab.threadId, patch: { archivedAt: Date.now() } });+ setToast({ text: t("sidebar.threads.hidden"), undo: () => dispatch({ type: "updateTask", botId: bot.id, threadId: tab.threadId, patch: { archivedAt: null } }) });+ };+ const focusTab = (threadId: string) =>+ requestAnimationFrame(() => scroller.current?.querySelector<HTMLElement>(`[data-tab-id="${CSS.escape(threadId)}"]`)?.focus());+ const startRename = (tab: ThreadTab) => {+ if (!tab.renamable || !canWrite) return;+ finishing.current = false;+ setDraft(tab.title);+ setRenaming(tab.threadId);+ };+ const finishRename = (tab: ThreadTab, save: boolean, refocus: boolean) => {+ if (finishing.current) return;+ finishing.current = true;+ const title = save ? nextRename(tab.title, draft) : null;+ setRenaming(null);+ if (title) dispatch({ type: "renameTask", botId: bot.id, threadId: tab.threadId, title });+ if (refocus) focusTab(tab.threadId);+ };+ const onKey = (event: ReactKeyboardEvent<HTMLDivElement>) => {+ if (renaming || event.target instanceof HTMLInputElement) return;+ const at = tabs.findIndex((tab) => tab.threadId === (event.target as HTMLElement).dataset.tabId);+ 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), tabs.length - 1) : event.key === "Home" ? 0 : event.key === "End" ? tabs.length - 1 : null;+ if (to !== null) { event.preventDefault(); focusTab(tabs[to].threadId); return; }+ if (event.key === "Enter" || event.key === " ") { event.preventDefault(); open(tabs[at]); return; }+ if (event.key === "F2") { event.preventDefault(); startRename(tabs[at]); return; }+ if (event.key === "Delete" && canWrite) {+ event.preventDefault();+ const next = neighbourOf(tabs, tabs[at].threadId);+ close(tabs[at]);+ if (next) focusTab(next);+ }+ };+ const onAuxClick = (event: ReactMouseEvent, tab: ThreadTab) => {+ if (event.button !== 1 || !canWrite) return;+ event.preventDefault();+ close(tab);+ };++ return (+ <div data-thread-tabs={bot.id} {...dragProps} className="relative z-[1] flex h-9 shrink-0 items-end bg-panel max-md:hidden">+ <div ref={scroller} role="tablist" aria-label={t("task.namedList", { name: bot.name })} onKeyDown={onKey} onScroll={measure}+ style={{ maskImage: fade, WebkitMaskImage: fade }}+ className="flex min-w-0 items-end overflow-x-auto overflow-y-hidden px-3 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">+ {shown.map((tab) => {+ const selected = tab.threadId === active && !tab.leaving;+ const title = tab.draft ? t("task.newShort") : localizedTaskTitle(tab.title);+ const closable = tab.closable && canWrite && !tab.leaving;+ return (+ <div key={tab.threadId} role="tab" data-tab-id={tab.threadId} aria-selected={selected} tabIndex={selected ? 0 : -1} title={title}+ data-entering={entering.has(tab.threadId) ? "" : undefined} data-leaving={tab.leaving ? "" : undefined} aria-hidden={tab.leaving || undefined}+ onClick={() => { if (renaming !== tab.threadId) open(tab); }} onDoubleClick={() => startRename(tab)}+ onMouseDown={(event) => { if (event.button === 1) event.preventDefault(); }} onAuxClick={(event) => onAuxClick(event, tab)}+ className={cn(TAB, selected ? "shrink-0 text-ink" : "shrink cursor-default text-ink-secondary hover:text-ink")}>+ {renaming === tab.threadId ? (+ <input autoFocus dir="auto" value={draft} maxLength={80} aria-label={t("task.renameAria")}+ onFocus={(event) => event.currentTarget.select()} onChange={(event) => setDraft(event.target.value)}+ onBlur={() => finishRename(tab, true, false)} onClick={(event) => event.stopPropagation()}+ onKeyDown={(event) => {+ if (event.key === "Enter" && !event.nativeEvent.isComposing) { event.preventDefault(); finishRename(tab, true, true); }+ if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); finishRename(tab, false, true); }+ }}+ className="-ms-1.5 h-6 w-32 min-w-0 rounded-md border border-focus bg-transparent px-1.5 text-[13px] text-ink outline-none" />+ ) : (+ <span className="flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden">+ {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>+ </span>+ )}+ {renaming === tab.threadId ? null : !closable ? <span aria-hidden="true" className="ms-1 size-5 shrink-0" /> : (+ <button type="button" tabIndex={-1} aria-label={t("sidebar.threads.hide", { title })} title={t("sidebar.threads.hideShort")}+ onClick={(event) => { event.stopPropagation(); close(tab); }} onDoubleClick={(event) => event.stopPropagation()}+ className={cn(CLOSE, selected && "pointer-events-auto opacity-100")}>+ <X size={12} aria-hidden="true" />+ </button>+ )}+ </div>+ );+ })}+ </div>+ {canWrite && (+ <button type="button" data-thread-tabs-new aria-label={t("task.newShort")} title={t("task.newShort")} onClick={() => dispatch({ type: "newTask", botId: bot.id })}+ className="mb-0.5 ms-0.5 flex size-7 shrink-0 items-center justify-center rounded-full text-ink-secondary transition-colors duration-[120ms] hover:bg-ink/[0.06] hover:text-ink active:bg-ink/[0.08] motion-reduce:transition-none">+ <Plus size={16} aria-hidden="true" />+ </button>+ )}+ <UndoToast toast={toast} onDone={() => setToast(null)} />+ </div>+ );+}diff --git a/src/components/UndoToast.tsx b/src/components/UndoToast.tsxnew file mode 100644index 0000000000..9d9486f9a5--- /dev/null+++ b/src/components/UndoToast.tsx@@ -0,0 +1,29 @@+import { useEffect, useState } from "react";+import { createPortal } from "react-dom";+import { t } from "@/lib/i18n";++export type Toast = { text: string; undo: () => void };++const SHOWN_MS = 6000;++/** A toast with Undo, kept for a few seconds; a newer one replaces it. */+export function useUndoToast(): [toast: Toast | null, show: (toast: Toast | null) => void] {+ const [toast, setToast] = useState<Toast | null>(null);+ useEffect(() => {+ if (!toast) return;+ const timer = window.setTimeout(() => setToast(null), SHOWN_MS);+ return () => window.clearTimeout(timer);+ }, [toast]);+ return [toast, setToast];+}++export function UndoToast({ toast, onDone }: { toast: Toast | null; onDone: () => void }) {+ if (!toast) return null;+ return createPortal(+ <div role="status" className="fixed bottom-4 start-[calc(var(--rail-beside,0px)_+_1rem)] z-[60] flex max-w-[340px] items-center gap-3 rounded-xl border border-hairline/50 bg-card px-3.5 py-2.5 text-[13px] text-ink shadow-xl animate-fade-in motion-reduce:animate-none">+ <span className="min-w-0 line-clamp-2">{toast.text}</span>+ <button type="button" onClick={() => { toast.undo(); onDone(); }} className="shrink-0 rounded-md px-1.5 py-0.5 font-medium text-accent-text hover:bg-ink/[0.06]">{t("common.undo")}</button>+ </div>,+ document.body,+ );+}diff --git a/src/components/thread-tab-motion.ts b/src/components/thread-tab-motion.tsnew file mode 100644index 0000000000..dd1eb3fdeb--- /dev/null+++ b/src/components/thread-tab-motion.ts@@ -0,0 +1,72 @@+import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from "react";+import { reducedMotion } from "./MenuMotion";++const TAB_MS = 200;+const EASE = "cubic-bezier(0.22, 1, 0.36, 1)";+const NONE: ReadonlySet<string> = new Set();++type MotionTab = { threadId: string; draft: boolean };+export type ShownTab<T> = T & { leaving?: true };++/** Puts tabs that just went back at the place they left, for as long as they take to fold away. */+export function withLeaving<T extends MotionTab>(tabs: readonly T[], leaving: readonly { tab: T; index: number }[]): ShownTab<T>[] {+ const shown: ShownTab<T>[] = [...tabs];+ for (const { tab, index } of [...leaving].sort((a, b) => a.index - b.index)) {+ if (!shown.some((other) => other.threadId === tab.threadId)) shown.splice(Math.min(index, shown.length), 0, { ...tab, leaving: true });+ }+ return shown;+}++/**+ * The strip's motion: a new tab widens into its place, a closed one narrows away, and tabs that change places glide+ * there. The blank New thread tab turning into its thread is one tab, so nothing moves.+ */+export function useTabMotion<T extends MotionTab>(tabs: readonly T[], scroller: RefObject<HTMLElement | null>) {+ const ids = tabs.map((tab) => tab.threadId).join("\n");+ const previous = useRef(tabs);+ const [entering, setEntering] = useState(NONE);+ const [leaving, setLeaving] = useState<{ tab: T; index: number }[]>([]);+ const timers = useRef<number[]>([]);+ const later = (run: () => void) => { timers.current.push(window.setTimeout(run, TAB_MS)); };+ useEffect(() => () => timers.current.forEach((timer) => window.clearTimeout(timer)), []);++ useLayoutEffect(() => {+ const was = previous.current;+ const before = new Set(was.map((tab) => tab.threadId)), now = new Set(tabs.map((tab) => tab.threadId));+ const added = tabs.filter((tab) => !before.has(tab.threadId));+ const gone = was.flatMap((tab, index) => (now.has(tab.threadId) ? [] : [{ tab, index }]));+ const madeFromDraft = added.length === 1 && gone.length === 1 && gone[0].tab.draft;+ if (reducedMotion() || madeFromDraft) return;+ if (added.length) {+ const fresh = new Set(added.map((tab) => tab.threadId));+ setEntering(fresh);+ later(() => setEntering((current) => (current === fresh ? NONE : current)));+ }+ if (gone.length) {+ setLeaving((current) => [...current, ...gone]);+ later(() => setLeaving((current) => current.filter((entry) => !gone.includes(entry))));+ }+ }, [ids]);+ useLayoutEffect(() => { previous.current = tabs; });++ const places = useRef<{ order: string; at: Map<string, number> }>({ order: "", at: new Map() });+ useLayoutEffect(() => {+ const root = scroller.current;+ if (!root) return;+ const at = new Map<string, number>();+ const elements = Array.from(root.querySelectorAll<HTMLElement>("[data-tab-id]:not([data-leaving])"));+ for (const element of elements) at.set(element.dataset.tabId ?? "", element.offsetLeft);+ const kept = (order: string, keep: Map<string, number>) => order.split("\n").filter((id) => keep.has(id)).join("\n");+ const moved = places.current.order && kept(places.current.order, at) !== kept(ids, places.current.at);+ if (moved && !reducedMotion()) {+ for (const element of elements) {+ const from = places.current.at.get(element.dataset.tabId ?? ""), to = at.get(element.dataset.tabId ?? "");+ if (from === undefined || to === undefined || from === to || typeof element.animate !== "function") continue;+ element.animate([{ transform: `translateX(${from - to}px)` }, { transform: "none" }], { duration: TAB_MS, easing: EASE });+ }+ }+ places.current = { order: ids, at };+ }, [ids]);++ return { shown: withLeaving(tabs, leaving), entering };+}diff --git a/src/components/thread-tabs.test.ts b/src/components/thread-tabs.test.tsnew file mode 100644index 0000000000..1b001f6315--- /dev/null+++ b/src/components/thread-tabs.test.ts@@ -0,0 +1,60 @@+import { describe, expect, it } from "vitest";+import type { Task } from "@/state/store";+import { newChatThreadId } from "@/state/new-chat";+import { botShowsTabs, neighbourOf, showsTabs, threadTabs, type TabsBot } from "./thread-tabs";++const task = (threadId: string, at: number, extra: Partial<Task> = {}): Task => ({ threadId, title: threadId, createdAt: at, lastThreadOrderAt: at, ...extra });++const bot = (tasks: Task[], extra: Partial<TabsBot> = {}): TabsBot => ({ id: "kiwi", threadId: tasks[0]?.threadId ?? "", tasks, ...extra });++describe("thread tabs", () => {+ it("lists pinned threads first, then the rest by recent use, as the sidebar does", () => {+ const tabs = threadTabs(bot([task("old", 1), task("launch", 2, { pinned: true }), task("new", 5), task("mid", 3)], { threadId: "mid" }));+ expect(tabs.map((tab) => tab.threadId)).toEqual(["launch", "new", "mid", "old"]);+ expect(tabs[0].pinned).toBe(true);+ });++ it("leaves out archived, snoozed, closed and bot-started threads, unless one is open", () => {+ const tasks = [+ task("mine", 9), task("gone", 8, { archivedAt: 1 }), task("later", 7, { snoozedUntil: 0 }), task("run", 6, { routineRunId: "r1" }),+ task("helper", 5, { openedBy: { botId: "b", name: "Rio", at: 1 } }), task("closed", 4, { closedBy: { botId: "b", name: "Rio", at: 1 } }),+ ];+ expect(threadTabs(bot(tasks, { threadId: "mine" })).map((tab) => tab.threadId)).toEqual(["mine"]);+ expect(threadTabs(bot(tasks, { threadId: "gone" })).map((tab) => tab.threadId)).toEqual(["mine", "gone"]);+ expect(threadTabs(bot(tasks, { threadId: "mine", switchingTo: "run" })).map((tab) => tab.threadId)).toEqual(["mine", "run"]);+ });++ it("shows the strip only for two threads or more, the blank New thread chat counted", () => {+ const one = bot([task("only", 1)]);+ expect(showsTabs(threadTabs(one))).toBe(false);+ expect(botShowsTabs(one, null)).toBe(false);+ expect(botShowsTabs(one, { session: 1, botId: "kiwi", held: [] })).toBe(true);+ expect(botShowsTabs(one, { session: 1, botId: "other", held: [] })).toBe(false);+ });++ it("puts the blank New thread tab where its thread will land: after the pinned ones", () => {+ const tabs = threadTabs(bot([task("pin", 1, { pinned: true }), task("a", 3), task("b", 2)], { threadId: newChatThreadId("kiwi") }));+ expect(tabs.map((tab) => tab.threadId)).toEqual(["pin", newChatThreadId("kiwi"), "a", "b"]);+ expect(tabs[1]).toMatchObject({ draft: true, closable: true, renamable: false });+ });++ it("has no close on the main thread, a running one, a shared chat or the last one left", () => {+ const tabs = threadTabs(bot([+ task("main", 5), task("busy", 4, { busy: true }), task("shared", 3, { sharedChat: true }), task("plain", 2),+ ], { mainThreadId: "main", threadId: "plain" }));+ expect(Object.fromEntries(tabs.map((tab) => [tab.threadId, tab.closable]))).toEqual({ main: false, busy: false, shared: false, plain: true });+ expect(threadTabs(bot([task("only", 1)], { mainThreadId: "elsewhere" }))[0].closable).toBe(false);+ });++ it("marks the open thread running while its bot is busy", () => {+ const tabs = threadTabs(bot([task("a", 2), task("b", 1)], { threadId: "a", busy: true }));+ expect(tabs.map((tab) => tab.working)).toEqual([true, false]);+ });++ it("moves to the tab after a closed one, else the one before", () => {+ const tabs = threadTabs(bot([task("a", 3), task("b", 2), task("c", 1)]));+ expect(neighbourOf(tabs, "a")).toBe("b");+ expect(neighbourOf(tabs, "c")).toBe("b");+ expect(neighbourOf(tabs, "nope")).toBeUndefined();+ });+});diff --git a/src/components/thread-tabs.ts b/src/components/thread-tabs.tsnew file mode 100644index 0000000000..0f7219dabe--- /dev/null+++ b/src/components/thread-tabs.ts@@ -0,0 +1,66 @@+import type { Bot, Task } from "@/state/store";+import type { NewChat } from "@/state/new-chat";+import { isNewChatThread, newChatThreadId } from "@/state/new-chat";+import { ownThread } from "./sidebar-thread-labels";+import { isArchived, isSnoozed, isWorking, orderedThreadList } from "./SidebarThreadRow";++export interface ThreadTab {+ threadId: string;+ title: string;+ pinned: boolean;+ working: boolean;+ /** The blank New thread chat, which has no thread yet. */+ draft: boolean;+ closable: boolean;+ renamable: boolean;+}++export type TabsBot = Pick<Bot, "id" | "threadId"> & Partial<Pick<Bot, "mainThreadId" | "tasks" | "busy" | "switchingTo">>;++/** The open thread: where a switch is going, or the blank New thread chat. */+export const openTabId = (bot: Pick<Bot, "threadId" | "switchingTo">): string => bot.switchingTo ?? bot.threadId;++const tabbed = (task: Task, open: string) =>+ task.threadId === open || task.pinned === true || (ownThread(task) && !isArchived(task) && !isSnoozed(task) && !task.closedBy);++/**+ * A bot's threads as tabs, in its sidebar order: pinned first, then by recent use. The blank New thread chat sits where+ * its thread will land once the first message makes it, after the pinned ones.+ */+export function threadTabs(bot: TabsBot): ThreadTab[] {+ const open = openTabId({ threadId: bot.threadId, switchingTo: bot.switchingTo });+ const tasks = orderedThreadList((bot.tasks ?? []).filter((task) => tabbed(task, open)));+ const main = bot.mainThreadId;+ const real = tasks.length;+ const tabs: ThreadTab[] = tasks.map((task) => {+ const working = isWorking(task) || (task.threadId === bot.threadId && Boolean(bot.busy));+ return {+ threadId: task.threadId, title: task.title, pinned: task.pinned === true, working, draft: false,+ closable: real > 1 && task.threadId !== main && !task.sharedChat && !working,+ renamable: !task.sharedChat,+ };+ });+ if (isNewChatThread(open)) {+ const at = tabs.findIndex((tab) => !tab.pinned);+ const draft: ThreadTab = { threadId: open, title: "", pinned: false, working: false, draft: true, closable: true, renamable: false };+ tabs.splice(at < 0 ? tabs.length : at, 0, draft);+ }+ return tabs;+}++/** The strip shows for a bot with two threads or more, its blank New thread chat counted. */+export const showsTabs = (tabs: readonly ThreadTab[]): boolean => tabs.length > 1;++/** Where closing a tab goes when it was the open one: the tab after it, else the one before. */+export function neighbourOf(tabs: readonly ThreadTab[], threadId: string): string | undefined {+ const at = tabs.findIndex((tab) => tab.threadId === threadId);+ if (at < 0) return undefined;+ return (tabs[at + 1] ?? tabs[at - 1])?.threadId;+}++/** Whether the strip shows for this bot in the chat: the header's New thread plus gives way to the strip's own. */+export function botShowsTabs(bot: TabsBot | undefined, newChat: NewChat | null | undefined): boolean {+ if (!bot) return false;+ const shown = newChat?.botId === bot.id ? { ...bot, threadId: newChatThreadId(bot.id), switchingTo: undefined } : bot;+ return showsTabs(threadTabs(shown));+}diff --git a/src/styles.css b/src/styles.cssindex 8995e57076..22c4d5ba6d 100644--- a/src/styles.css+++ b/src/styles.css@@ -3898,3 +3898,27 @@ button:disabled.bg-danger {.burger-fold > ol { overflow: hidden auto; }@media (prefers-reduced-motion: reduce) { .burger-fold { transition: none; } }:root[data-reduced-motion="true"] .burger-fold { transition: none; }+/* Thread tabs: the open tab is the chat's own ground, so it runs into the chat below, and its foot curves out into the+ strip on both sides. Separators sit between closed tabs only, and give way under the pointer. */+.thread-tab[aria-selected="true"] { background: var(--color-app); }+.thread-tab[aria-selected="true"]::before,+.thread-tab[aria-selected="true"]::after {+ content: ""; position: absolute; bottom: 0; width: var(--radius-xl); height: var(--radius-xl); pointer-events: none;+}+.thread-tab[aria-selected="true"]::before { right: 100%; background: radial-gradient(circle at 0 0, transparent calc(var(--radius-xl) - 0.5px), var(--color-app) var(--radius-xl)); }+.thread-tab[aria-selected="true"]::after { left: 100%; background: radial-gradient(circle at 100% 0, transparent calc(var(--radius-xl) - 0.5px), var(--color-app) var(--radius-xl)); }+.thread-tab:not([aria-selected="true"]) + .thread-tab:not([aria-selected="true"])::before {+ content: ""; position: absolute; inset-inline-start: 0; top: 8px; bottom: 8px; width: 1px; background: var(--color-hairline);+ transition: opacity 120ms ease-out;+}+.thread-tab:hover + .thread-tab:not([aria-selected="true"])::before,+.thread-tab:not([aria-selected="true"]):hover::before { opacity: 0; }+.thread-tab[data-entering] { animation: thread-tab-in 200ms cubic-bezier(0.22, 1, 0.36, 1) both; }+.thread-tab[data-leaving] { animation: thread-tab-out 180ms cubic-bezier(0.22, 1, 0.36, 1) both; pointer-events: none; }+@keyframes thread-tab-in { from { max-width: 0; padding-inline: 0; opacity: 0; } }+@keyframes thread-tab-out { to { max-width: 0; padding-inline: 0; opacity: 0; } }+@media (prefers-reduced-motion: reduce) {+ .thread-tab, .thread-tab::before { animation: none !important; transition: none !important; }+}+:root[data-reduced-motion="true"] .thread-tab,+:root[data-reduced-motion="true"] .thread-tab::before { animation: none !important; transition: none !important; }