Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(chat): open a teammate hand-off as a live, read-only exchange in the chat column (#6870)
Aditya Umale18f24c73c744
diff --git a/scripts/testing/direct-coordination-ui.e2e.test.ts b/scripts/testing/direct-coordination-ui.e2e.test.tsindex 8fa524968b..41a9b9b6c3 100644--- a/scripts/testing/direct-coordination-ui.e2e.test.ts+++ b/scripts/testing/direct-coordination-ui.e2e.test.ts@@ -12,7 +12,7 @@ import { UI_TOOLS_DIR } from "./control-omb-ui.ts";const ROOT = fileURLToPath(new URL("../..", import.meta.url));const enabled = process.env.OMB_UI_E2E === "1" || Boolean(resolveAgentBrowserBinary({ dataDir: UI_TOOLS_DIR, env: process.env }));-(enabled ? it : it.skip)("coordinates from the real composer and opens the exact child task from its existing inline receipt", async () => {+(enabled ? it : it.skip)("coordinates from the real composer and opens the exact child task as an exchange from its existing inline receipt", async () => {const temporary = mkdtempSync(join(tmpdir(), "omb-direct-ui-plan-"));const planPath = join(temporary, "plan.json");writeFileSync(planPath, "{}");@@ -65,7 +65,7 @@ const enabled = process.env.OMB_UI_E2E === "1" || Boolean(resolveAgentBrowserBinwriteFileSync(gateFile, "complete fixture work");await ui("wait-settle", "--timeout", "60");await expect.poll(snapshot, { timeout: 15_000 }).toContain("Engineer checked the fixture CSV export");- expect(await snapshot()).toContain("Sent to Engineer");+ expect(await snapshot()).toContain('button "Open exchange with Engineer"');const state = await api("/api/bots");const parent = state.bots.find((bot: any) => bot.id === info.botId);const receipt = parent.messages.find((message: any) => message.tool?.name === "Sent to Engineer");@@ -73,13 +73,16 @@ const enabled = process.env.OMB_UI_E2E === "1" || Boolean(resolveAgentBrowserBinexpect(receipt.threadRef.threadId).not.toBe(lead.threadId);const screenshot = info.logPath + ".direct-coordination.png";await ui("screenshot", "--out", screenshot);- await click("Sent to Engineer");+ await click("Open exchange with Engineer");await expect.poll(snapshot, { timeout: 15_000 }).toContain("CSV export checked in my separate task");- // The request in the teammate's thread names the bot that sent it.- expect(await snapshot()).toMatch(/Pepper[\s\S]{0,80}sent a request/);- const selected = (await api("/api/bots")).bots.find((bot: any) => bot.id === lead.id);- expect(selected.threadId).toBe(receipt.threadRef.threadId);- const evidence = { source: parent.messages, receipt, selectedThread: selected.threadId, final: await snapshot(), screenshot };+ expect(await snapshot()).toContain('group "Bot exchange between Pepper and Engineer"');+ expect(await snapshot()).not.toContain('textbox "Message');+ const shown = (await ui("eval", "--js", "document.querySelector('[data-handoff-exchange]')?.getAttribute('data-handoff-exchange')")).result;+ expect(shown).toBe(receipt.threadRef.threadId);+ expect((await api("/api/bots")).bots.find((bot: any) => bot.id === info.botId).threadId).toBe(parent.threadId);+ await click("Back to Pepper");+ await expect.poll(snapshot, { timeout: 15_000 }).toContain('textbox "Message Pepper"');+ const evidence = { source: parent.messages, receipt, exchangeThread: shown, final: await snapshot(), screenshot };writeFileSync(info.logPath + ".direct-coordination.json", JSON.stringify(evidence, null, 2));console.log("Direct coordination UI evidence:", info.logPath + ".direct-coordination.json");} finally {diff --git a/src/App.tsx b/src/App.tsxindex e84653a833..ee27254959 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -20,6 +20,7 @@ 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 { GroupView } from "@/components/GroupView";import { ForkPanel } from "@/components/ForkPanel";import { SIDEBAR_AND_NARROW_PANEL_FIT, SIDEBAR_AND_PANEL_FIT, SIDEBAR_INLINE, TWO_SIDE_PANELS_FIT, useMediaQuery } from "@/lib/use-media-query";@@ -434,7 +435,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {) : group ? (<GroupView key={group.id} group={group} />) : bot ? (- <ChatView bot={chatBot ?? bot} />+ <HandoffExchangeHost bot={chatBot ?? bot}><ChatView bot={chatBot ?? bot} /></HandoffExchangeHost>) : noEngines ? (<NoEngines />) : (diff --git a/src/components/HandoffExchange.dom.test.ts b/src/components/HandoffExchange.dom.test.tsnew file mode 100644index 0000000000..ce90b615ce--- /dev/null+++ b/src/components/HandoffExchange.dom.test.ts@@ -0,0 +1,196 @@+// @vitest-environment happy-dom+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ServerFrame } from "../../shared/wire";+import { setLocale } from "@/lib/i18n";+import type { LiveFrameListener } from "@/lib/live-events";+import type { Bot, Message } from "@/state/store";++const fixture = vi.hoisted(() => ({+ dispatch: vi.fn(),+ listeners: new Set<LiveFrameListener>(),+ load: vi.fn(),+}));+const bot = (id: string, name: string, color: string, threadId: string, tasks: Bot["tasks"] = []): Bot => ({+ id, threadId, name, title: "", description: "", notifications: true, color, unread: false, messages: [],+ modelSelection: { instanceId: "fake", model: "test" }, tasks,+} as Bot);+const maestro = bot("maestro", "Maestro", "blue", "maestro-main");+const helper = bot("tool", "Ferramenteiro", "green", "tool-main", [+ { threadId: "tool-main", title: "Main", createdAt: 1 },+ { threadId: "help-1", title: "Check the build", createdAt: 2 },+]);+vi.mock("@/state/store", async (importOriginal) => {+ const original = await importOriginal<typeof import("@/state/store")>();+ return { ...original, useStore: () => ({ state: { ...original.initialState, bots: [maestro, helper] }, dispatch: fixture.dispatch }) };+});+vi.mock("@/state/store-select", async (importOriginal) => ({+ ...await importOriginal<typeof import("@/state/store-select")>(),+ useStoreSelector: (select: (state: unknown) => unknown) => select({ bots: [maestro, helper] }),+}));+vi.mock("@/state/message-history", async (importOriginal) => ({+ ...await importOriginal<typeof import("@/state/message-history")>(), loadFullThread: fixture.load,+}));+vi.mock("@/lib/live-events", async (importOriginal) => ({+ ...await importOriginal<typeof import("@/lib/live-events")>(),+ listenLiveFrames: (listener: LiveFrameListener) => { fixture.listeners.add(listener); return () => fixture.listeners.delete(listener); },+}));+vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => true }));+vi.mock("./Avatar", () => ({+ BotAvatar: ({ bot: shown }: { bot: Bot }) => createElement("span", { "data-avatar": shown.id }),+ InitialsAvatar: ({ initials }: { initials: string }) => createElement("span", { "data-avatar": initials }),+}));+import { HandoffExchangeHost } from "./HandoffExchange";+import { ThreadChip } from "./ThreadChip";++const sent = (extra: Partial<Message> = {}): Message => ({+ id: "sent", role: "bot", kind: "activity", at: 1_000,+ tool: { name: "Sent to Ferramenteiro", ok: true },+ from: { botId: "maestro", name: "Maestro", color: "blue" },+ threadRef: { botId: "tool", threadId: "help-1", title: "Check the build" },+ ...extra,+});+const ask: Message = { id: "m1", role: "user", kind: "text", text: "Please check the build", at: 1_000, parentId: null, peerAsk: { botId: "maestro", name: "Maestro" } };+const answer: Message = { id: "m2", role: "bot", kind: "text", text: "Build is green", at: 2_000, parentId: "m1" };++let host: HTMLDivElement;+let root: Root;++beforeEach(() => {+ setLocale("en");+ fixture.dispatch.mockClear();+ fixture.listeners.clear();+ fixture.load.mockReset();+ if (typeof globalThis.ResizeObserver === "undefined") {+ vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} unobserve() {} });+ }+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});++afterEach(() => {+ flushSync(() => root.unmount());+ document.body.replaceChildren();+});++/** The asker's chat in the main column: a stand-in chat with the hand-off line and a message box. */+const render = (message: Message, shown: Bot = maestro) => flushSync(() => root.render(createElement(HandoffExchangeHost, {+ bot: shown, children: createElement("main", { "data-chat": "" }, createElement(ThreadChip, { message, threadId: shown.threadId }), createElement("textarea")),+})));+const chip = () => host.querySelector<HTMLButtonElement>("[data-thread-chip]")!;+const exchange = () => host.querySelector<HTMLElement>("[data-handoff-exchange]");+const chatShown = () => host.querySelector("[data-chat]") !== null;+const named = (name: string) => exchange()!.querySelector<HTMLButtonElement>(`button[aria-label="${name}"]`)!;+const rows = () => Array.from(exchange()!.querySelectorAll("[data-side]")).map((row) => `${row.getAttribute("data-side")}: ${row.textContent}`);+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));+const send = (frame: ServerFrame) => flushSync(() => { for (const listener of fixture.listeners) listener.onFrame(frame); });++async function openLoaded(messages: Message[] = [ask, answer]) {+ fixture.load.mockResolvedValue({ messages, activeLeafId: messages.at(-1)?.id ?? null });+ render(sent());+ flushSync(() => chip().click());+ await settle();+ flushSync(() => {});+}++describe("a teammate's hand-off line", () => {+ it("is a chip with the helper's face and name that opens the exchange in place of the chat, with no pop-up", () => {+ fixture.load.mockReturnValue(new Promise(() => {}));+ render(sent());+ expect(chip().textContent).toBe("Ferramenteiro");+ expect(chip().getAttribute("aria-label")).toBe("Open exchange with Ferramenteiro");+ expect(chip().querySelector("[data-avatar=tool]")).not.toBeNull();+ flushSync(() => chip().click());+ expect(fixture.dispatch).not.toHaveBeenCalled();+ expect(fixture.load).toHaveBeenCalledWith("help-1");+ expect(chatShown()).toBe(false);+ expect(exchange()!.parentElement).toBe(host);+ expect(document.querySelector("[role=dialog]")).toBeNull();+ const pill = exchange()!.querySelector("[role=group]")!;+ expect(pill.getAttribute("aria-label")).toBe("Bot exchange between Maestro and Ferramenteiro");+ expect(pill.textContent).toBe("MaestroFerramenteiro");+ expect(exchange()!.textContent).toContain("Loading the conversation…");+ });++ it("shows the two bots' lines as plain bubbles, adds lines as they come in, and has no message box", async () => {+ await openLoaded();+ expect(rows()).toEqual(["asker: MaestroPlease check the build", "helper: FerramenteiroBuild is green"]);+ expect(exchange()!.querySelector("textarea")).toBeNull();+ expect(exchange()!.textContent).not.toMatch(/Read-only|Talk to|Open full thread|messages/);++ send({ kind: "message", threadId: "other", message: { id: "x", role: "bot", kind: "text", text: "Elsewhere", at: 3_000 } } as ServerFrame);+ send({ kind: "message", threadId: "help-1", message: { id: "m3", role: "bot", kind: "text", text: "Lint passes too", at: 3_000, parentId: "m2" } } as ServerFrame);+ expect(rows()).toEqual(["asker: MaestroPlease check the build", "helper: FerramenteiroBuild is green", "helper: Lint passes too"]);+ expect(exchange()!.textContent).not.toContain("Elsewhere");+ });++ it("keeps the newest line in sight as lines come in, unless the person scrolled up", async () => {+ await openLoaded();+ const list = exchange()!.querySelector<HTMLElement>(".glass-scroller")!;+ Object.defineProperty(list, "scrollHeight", { configurable: true, value: 900 });+ Object.defineProperty(list, "clientHeight", { configurable: true, value: 300 });+ send({ kind: "message", threadId: "help-1", message: { id: "m3", role: "bot", kind: "text", text: "More", at: 3_000, parentId: "m2" } } as ServerFrame);+ expect(list.scrollTop).toBe(900);+ list.scrollTop = 100;+ list.dispatchEvent(new Event("scroll"));+ Object.defineProperty(list, "scrollHeight", { configurable: true, value: 1_200 });+ send({ kind: "message", threadId: "help-1", message: { id: "m4", role: "bot", kind: "text", text: "Even more", at: 4_000, parentId: "m3" } } as ServerFrame);+ expect(list.scrollTop).toBe(100);+ });++ it("Back to the asker and the Back chevron both return to the chat", async () => {+ await openLoaded();+ flushSync(() => named("Back to Maestro").click());+ expect(exchange()).toBeNull();+ expect(chatShown()).toBe(true);+ flushSync(() => chip().click());+ flushSync(() => named("Back").click());+ expect(exchange()).toBeNull();+ expect(chatShown()).toBe(true);+ expect(fixture.dispatch).not.toHaveBeenCalled();+ });++ it("closes when the column moves to another chat, and stays closed on coming back", async () => {+ await openLoaded();+ render(sent(), { ...maestro, threadId: "maestro-other" });+ expect(exchange()).toBeNull();+ render(sent());+ expect(exchange()).toBeNull();+ expect(chatShown()).toBe(true);+ });++ it("says so when the conversation can't load, and can try again", async () => {+ fixture.load.mockRejectedValueOnce(new Error("offline")).mockResolvedValue({ messages: [ask], activeLeafId: "m1" });+ render(sent());+ flushSync(() => chip().click());+ await settle();+ flushSync(() => {});+ expect(exchange()!.textContent).toContain("Couldn't load the conversation.");+ flushSync(() => Array.from(exchange()!.querySelectorAll("button")).find((item) => item.textContent === "Try again")!.click());+ await settle();+ flushSync(() => {});+ expect(rows()).toEqual(["asker: MaestroPlease check the build"]);+ });++ it("keeps opening the thread for a line the person sent directly, the helper's main chat, or a thread it no longer has", () => {+ for (const message of [sent({ sentDirectly: { name: "Ferramenteiro" } }), sent({ threadRef: { botId: "tool", threadId: "tool-main", title: "Main" } }),+ sent({ threadRef: { botId: "tool", threadId: "gone", title: "Old" } })]) {+ fixture.dispatch.mockClear();+ render(message);+ expect(chip().hasAttribute("data-exchange-chip")).toBe(false);+ flushSync(() => chip().click());+ expect(exchange()).toBeNull();+ expect(fixture.dispatch).toHaveBeenCalled();+ }+ });++ it("opens the thread as before where no chat column hosts the exchange", () => {+ flushSync(() => root.render(createElement(ThreadChip, { message: sent(), threadId: "maestro-main" })));+ expect(chip().hasAttribute("data-exchange-chip")).toBe(false);+ flushSync(() => chip().click());+ expect(fixture.dispatch).toHaveBeenCalled();+ });+});diff --git a/src/components/HandoffExchange.tsx b/src/components/HandoffExchange.tsxnew file mode 100644index 0000000000..01eca85727--- /dev/null+++ b/src/components/HandoffExchange.tsx@@ -0,0 +1,200 @@+// A teammate's hand-off, read in place of the asker's chat: the two bots' exchange, live, with no message box.+import { createContext, Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, type ReactNode } from "react";+import { ArrowLeftRight, ChevronLeft } from "lucide-react";+import { BotAvatar, InitialsAvatar } from "./Avatar";+import { ChatMarkdown } from "./ChatMarkdown";+import { DaySeparator } from "./DaySeparator";+import { ClusterLabel } from "./RoomClusterLabel";+import { GlassBar, GlassScrollFrame } from "./GlassScrollFrame";+import { ELEVATED_FLOAT, ELEVATED_HOVER, ELEVATED_TINT } from "./elevated";+import { joinedCorners, SIMPLE_BOT_BUBBLE, SIMPLE_BUBBLE_MAX, SIMPLE_STACKED, SIMPLE_USER_BUBBLE } from "./chat-bubble";+import { useCaptionChrome } from "@/components/DesktopCapabilities";+import { cn } from "@/lib/cn";+import { conversationRows, handoffTranscript, LOADING_TRANSCRIPT, type ConversationRow, type ConversationSpeaker } from "@/lib/handoff-conversation";+import { intlLocale, t } from "@/lib/i18n";+import { listenLiveFrames } from "@/lib/live-events";+import { localDay } from "@/lib/transcript-derivations";+import { loadFullThread } from "@/state/message-history";+import type { Bot, Message } from "@/state/store";+import { useStoreSelector } from "@/state/store-select";++type Named = ConversationSpeaker & { botId: string };++export interface HandoffExchange {+ asker: Named;+ helper: Named;+ /** The helper's work thread the hand-off went to. */+ threadId: string;+}++/** Opens a hand-off's exchange in place of the chat it is in. Null where no chat column hosts one (a room, the side+ * panel): a hand-off line there opens the helper's thread instead. */+export const OpenExchangeContext = createContext<((exchange: HandoffExchange) => void) | null>(null);++/** The main chat column: the chat, or a hand-off's exchange in its place. Back mounts the chat again, which opens+ * where the person was reading. */+export function HandoffExchangeHost({ bot, children }: { bot: Bot; children: ReactNode }) {+ const chat = `${bot.id}:${bot.threadId}`;+ const [open, setOpen] = useState<{ chat: string; exchange: HandoffExchange } | null>(null);+ if (open && open.chat !== chat) setOpen(null);+ const openExchange = useCallback((exchange: HandoffExchange) => setOpen({ chat, exchange }), [chat]);+ const exchange = open?.chat === chat ? open.exchange : null;+ if (exchange) return <HandoffExchangeView key={exchange.threadId} exchange={exchange} onBack={() => setOpen(null)} />;+ return <OpenExchangeContext value={openExchange}>{children}</OpenExchangeContext>;+}++export function HandoffExchangeView({ exchange: { asker, helper, threadId }, onBack }: { exchange: HandoffExchange; onBack: () => void }) {+ const [transcript, dispatch] = useReducer(handoffTranscript, LOADING_TRANSCRIPT);+ const [load, setLoad] = useState(0);+ const reload = () => {+ dispatch({ type: "reload" });+ setLoad((count) => count + 1);+ };+ const bots = useStoreSelector((state) => state.bots);+ const { dragProps, noDragStyle } = useCaptionChrome();+ const remoteClient = window.ogb?.remoteClient?.active === true;++ useEffect(() => {+ let current = true;+ loadFullThread(threadId).then(+ ({ messages, activeLeafId }) => current && dispatch({ type: "loaded", messages, activeLeafId }),+ () => current && dispatch({ type: "failed" }),+ );+ return () => { current = false; };+ }, [threadId, load]);++ useEffect(() => listenLiveFrames({+ onFrame: (frame) => {+ if (!("threadId" in frame) || frame.threadId !== threadId) return;+ if (frame.kind === "message" || frame.kind === "message.patch") {+ dispatch({ type: "message", message: frame.message as Message, patch: frame.kind === "message.patch" });+ } else if (frame.kind === "thread") dispatch({ type: "active", activeLeafId: frame.activeLeafId });+ },+ onMissedFrames: reload,+ }), [threadId]);++ const you = t("chat.you");+ const rows = useMemo(() => conversationRows(transcript, asker, helper, you),+ [transcript, asker.botId, asker.name, asker.color, helper.botId, helper.name, helper.color, you]);+ // The newest line stays in sight as lines come in, unless the person scrolled up to read.+ const listRef = useRef<HTMLDivElement>(null);+ const atEnd = useRef(true);+ useLayoutEffect(() => {+ const list = listRef.current;+ if (list && atEnd.current) list.scrollTop = list.scrollHeight;+ }, [rows]);++ const today = localDay(Date.now());+ const label = t("chat.handoffExchange.label", { asker: asker.name, helper: helper.name });+ const backTo = t("chat.handoffExchange.backTo", { name: asker.name });+ const botOf = (speaker: ConversationSpeaker) => speaker.botId ? bots.find((candidate) => candidate.id === speaker.botId) : undefined;++ return (+ <main data-look="chat" data-handoff-exchange={threadId} className="relative flex h-full min-w-0 flex-1 flex-col bg-app">+ <GlassScrollFrame className="flex-1 [--glass-tint:var(--color-app)]">+ <GlassBar edge="top" fade={!remoteClient} className="z-[25]">+ <div {...dragProps} data-look="chat-header" className="px-5 pb-2.5 pt-2.5 max-md:pl-14 max-md:pr-3">+ <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,auto)_minmax(0,1fr)] items-center gap-2">+ <button+ type="button"+ data-exchange-back+ onClick={onBack}+ aria-label={t("chat.handoffExchange.back")}+ title={t("chat.handoffExchange.back")}+ style={noDragStyle}+ className={cn("flex size-9 items-center justify-center justify-self-start rounded-full text-ink-secondary hover:text-ink", ELEVATED_FLOAT, ELEVATED_HOVER)}+ >+ <ChevronLeft size={16} aria-hidden="true" />+ </button>+ <div+ role="group"+ aria-label={label}+ data-chathead-pill+ style={noDragStyle}+ className={cn("flex min-w-0 max-w-full items-center gap-1.5 rounded-full p-[3px] pr-[13.5px] text-ink", ELEVATED_FLOAT)}+ >+ <button+ type="button"+ onClick={onBack}+ aria-label={backTo}+ title={backTo}+ className={cn("flex min-w-0 items-center gap-2 rounded-full py-[4.5px] pl-[4.5px] pr-2", ELEVATED_TINT)}+ >+ <Face speaker={asker} bot={botOf(asker)} />+ <span dir="auto" className="min-w-0 truncate text-[14px] font-medium leading-5">{asker.name}</span>+ </button>+ <ArrowLeftRight size={14} aria-hidden="true" className="shrink-0 text-ink-tertiary" />+ <span className="flex min-w-0 items-center gap-2 py-[4.5px] pl-1">+ <Face speaker={helper} bot={botOf(helper)} />+ <span dir="auto" className="min-w-0 truncate text-[14px] font-medium leading-5">{helper.name}</span>+ </span>+ </div>+ </div>+ </div>+ </GlassBar>++ <div+ ref={listRef}+ className="glass-scroller h-full overflow-x-hidden overflow-y-auto overscroll-y-contain px-4"+ onScroll={(event) => {+ const list = event.currentTarget;+ atEnd.current = list.scrollHeight - list.scrollTop - list.clientHeight < 48;+ }}+ >+ <div role="log" aria-live="polite" aria-label={label} data-simple-rows=""+ className="glass-scroller-content chat-column relative flex w-full flex-col gap-4 pb-8">+ {rows.map((row, index) => {+ const previous = rows[index - 1], next = rows[index + 1];+ const day = !previous || localDay(row.at) !== localDay(previous.at);+ const above = Boolean(previous) && !day && sameSpeaker(previous!, row);+ const below = Boolean(next) && localDay(next!.at) === localDay(row.at) && sameSpeaker(next!, row);+ const person = row.side === "person";+ return (+ <Fragment key={row.id}>+ {day && <DaySeparator at={row.at} today={today} simple />}+ <div data-mid={row.id} data-side={row.side} className={cn("flex w-full flex-col", person ? "items-end" : "items-start", above && SIMPLE_STACKED)}>+ {!above && !person && (+ <div className="mb-1"><ClusterLabel bot={botOf(row.speaker)} name={row.speaker.name} color={row.speaker.color ?? ""} /></div>+ )}+ <div+ data-chat-bubble="simple"+ title={new Date(row.at).toLocaleString(intlLocale())}+ className={cn("chat-text w-fit", SIMPLE_BUBBLE_MAX,+ person ? cn(SIMPLE_USER_BUBBLE, "whitespace-pre-wrap [overflow-wrap:anywhere] text-ink") : SIMPLE_BOT_BUBBLE,+ joinedCorners(person ? "end" : "start", { above, below }))}+ >+ {person ? row.text : <ChatMarkdown text={row.text} />}+ </div>+ </div>+ </Fragment>+ );+ })}+ {!rows.length && (+ <p className="py-6 text-center text-[13px] text-ink-secondary">+ {transcript.loading ? t("chat.handoffExchange.loading")+ : transcript.failed ? t("chat.handoffExchange.failed") : t("chat.handoffExchange.empty")}+ </p>+ )}+ {transcript.failed && (+ <div className="text-center">+ <button type="button" onClick={reload}+ className="rounded-full bg-control px-3 py-1.5 text-[13px] font-medium text-ink hover:bg-raised-hover">+ {t("common.tryAgain")}+ </button>+ </div>+ )}+ </div>+ </div>+ </GlassScrollFrame>+ </main>+ );+}++function sameSpeaker(a: ConversationRow, b: ConversationRow): boolean {+ return a.side === b.side && a.speaker.botId === b.speaker.botId && a.speaker.name === b.speaker.name;+}++function Face({ speaker, bot }: { speaker: ConversationSpeaker; bot: Bot | undefined }) {+ if (bot) return <BotAvatar bot={bot} state="happy" size={24} animated={false} />;+ return <InitialsAvatar initials={speaker.name.slice(0, 1).toUpperCase()} size={24} />;+}diff --git a/src/components/ThreadChip.tsx b/src/components/ThreadChip.tsxindex fb6dde43d3..0c524caac3 100644--- a/src/components/ThreadChip.tsx+++ b/src/components/ThreadChip.tsx@@ -1,3 +1,4 @@+import { use } from "react";import { ChevronRight, MessagesSquare } from "lucide-react";import { openThread, useStore, type Message } from "@/state/store";import { useShowThreads } from "@/lib/thread-preferences";@@ -5,12 +6,14 @@ import { t } from "@/lib/i18n";import { activityText } from "@/lib/activity-text";import { cn } from "@/lib/cn";import { BotAvatar } from "./Avatar";+import { OpenExchangeContext } from "./HandoffExchange";import { HandoffReply } from "./HandoffReply";import { HandoffStatusChip } from "./HandoffStatusChip";export function ThreadChip({ message, threadId }: { message: Message; threadId?: string }) {const { state, dispatch } = useStore();const showThreads = useShowThreads();+ const openExchange = use(OpenExchangeContext);const ref = message.threadRef;const tool = message.tool;if (!ref || !tool) return null;@@ -18,20 +21,42 @@ export function ThreadChip({ message, threadId }: { message: Message; threadId?:const direct = message.sentDirectly;const label = !direct ? activityText(tool, tool.name): direct.room ? t("chat.sentDirectlyNotInRoom", { name: direct.name, room: direct.room }) : t("chat.sentDirectly", { name: direct.name });+ // A teammate's work for the bot that sent it is read in place of this chat; any other thread still opens in its own chat.+ const asker = message.from;+ // The helper's main chat is its talk with the person, not with the asker: that still opens there.+ const workThread = bot && ref.threadId !== bot.threadId && (bot.tasks ?? []).some((task) => task.threadId === ref.threadId);+ const exchange = openExchange && !direct && asker && bot && asker.botId !== bot.id && workThread+ ? { asker, helper: { botId: bot.id, name: bot.name, color: bot.color }, threadId: ref.threadId } : null;+ const exchangeLabel = bot ? t("chat.handoffExchange.open", { name: bot.name }) : "";return (<HandoffReply message={message} threadId={threadId}><span className="flex min-w-0 max-w-full flex-wrap items-center gap-x-2 gap-y-1">- <button- type="button"- data-thread-chip={ref.threadId}- onClick={() => openThread(dispatch, ref, state, showThreads)}- title={t("chat.openThread", { title: ref.title })}- className={cn("ui-pill", tool.ok === false && "text-danger")}- >- {bot ? <BotAvatar bot={bot} state="happy" size={16} animated={false} /> : <MessagesSquare size={13} aria-hidden="true" />}- <span className="max-w-[480px] truncate">{label}</span>- <ChevronRight size={13} />- </button>+ {exchange ? (+ <button+ type="button"+ data-thread-chip={ref.threadId}+ data-exchange-chip+ onClick={() => openExchange?.(exchange)}+ aria-label={exchangeLabel}+ title={exchangeLabel}+ className={cn("ui-pill", tool.ok === false && "text-danger")}+ >+ {bot && <BotAvatar bot={bot} state="happy" size={16} animated={false} />}+ <span dir="auto" className="max-w-[240px] truncate">{exchange.helper.name}</span>+ </button>+ ) : (+ <button+ type="button"+ data-thread-chip={ref.threadId}+ onClick={() => openThread(dispatch, ref, state, showThreads)}+ title={t("chat.openThread", { title: ref.title })}+ className={cn("ui-pill", tool.ok === false && "text-danger")}+ >+ {bot ? <BotAvatar bot={bot} state="happy" size={16} animated={false} /> : <MessagesSquare size={13} aria-hidden="true" />}+ <span className="max-w-[480px] truncate">{label}</span>+ <ChevronRight size={13} />+ </button>+ )}{message.handoff && <HandoffStatusChip line={message.handoff} />}</span></HandoffReply>diff --git a/src/lib/handoff-conversation.test.ts b/src/lib/handoff-conversation.test.tsnew file mode 100644index 0000000000..00970a608c--- /dev/null+++ b/src/lib/handoff-conversation.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from "vitest";+import type { Message } from "@/state/store";+import { conversationRows, handoffTranscript, LOADING_TRANSCRIPT, type HandoffTranscript } from "./handoff-conversation";++const asker = { botId: "maestro", name: "Maestro", color: "blue" };+const helper = { botId: "tool", name: "Ferramenteiro", color: "green" };+const line = (id: string, role: Message["role"], text: string, extra: Partial<Message> = {}): Message =>+ ({ id, role, kind: "text", text, at: Number(id.replace(/\D/g, "")) || 1, ...extra });+const loaded = (messages: Message[], activeLeafId: string | null = null): HandoffTranscript =>+ handoffTranscript(LOADING_TRANSCRIPT, { type: "loaded", messages, activeLeafId });++describe("conversationRows", () => {+ it("names the asking bot, the helper and a person, and leaves out tool steps and empty lines", () => {+ const rows = conversationRows(loaded([+ line("m1", "user", "Please check the build", { peerAsk: { botId: "maestro", name: "Maestro" } }),+ { id: "m2", role: "bot", kind: "activity", at: 2, tool: { name: "Ran tests" } },+ line("m3", "bot", "Build is green"),+ line("m4", "bot", " "),+ line("m5", "user", "Thanks, also run lint"),+ ]), asker, helper, "You");+ expect(rows.map((row) => [row.id, row.side, row.speaker.name, row.text])).toEqual([+ ["m1", "asker", "Maestro", "Please check the build"],+ ["m3", "helper", "Ferramenteiro", "Build is green"],+ ["m5", "person", "You", "Thanks, also run lint"],+ ]);+ });++ it("shows only the branch the thread is on", () => {+ const rows = conversationRows(loaded([+ line("m1", "user", "Ask", { peerAsk: { botId: "maestro", name: "Maestro" }, parentId: null }),+ line("m2", "bot", "Old answer", { parentId: "m1" }),+ line("m3", "bot", "New answer", { parentId: "m1" }),+ ], "m3"), asker, helper, "You");+ expect(rows.map((row) => row.text)).toEqual(["Ask", "New answer"]);+ });++ it("names a third bot that joined the helper's thread", () => {+ const rows = conversationRows(loaded([line("m1", "user", "Me too", { peerAsk: { botId: "other", name: "Other" } })]), asker, helper, "You");+ expect(rows[0]).toMatchObject({ side: "asker", speaker: { botId: "other", name: "Other" } });+ });+});++describe("handoffTranscript", () => {+ it("keeps lines that arrived live while the thread was loading", () => {+ const live = handoffTranscript(LOADING_TRANSCRIPT, { type: "message", message: line("m2", "bot", "Live, edited") });+ const state = handoffTranscript(live, { type: "loaded", messages: [line("m1", "user", "Ask"), line("m2", "bot", "Live")], activeLeafId: "m2" });+ expect(state.loading).toBe(false);+ expect(state.messages.map((message) => message.text)).toEqual(["Ask", "Live, edited"]);+ });++ it("moves the branch on to a line that arrived while loading and continues it", () => {+ const live = handoffTranscript(LOADING_TRANSCRIPT, { type: "message", message: line("m3", "bot", "Next", { parentId: "m2" }) });+ const state = handoffTranscript(live, { type: "loaded", messages: [line("m1", "user", "Ask", { parentId: null }), line("m2", "bot", "First", { parentId: "m1" })], activeLeafId: "m2" });+ expect(state.activeLeafId).toBe("m3");+ expect(conversationRows(state, asker, helper, "You").map((row) => row.text)).toEqual(["Ask", "First", "Next"]);+ });++ it("moves the branch on to a live line that the loaded copy also holds", () => {+ let state = handoffTranscript(LOADING_TRANSCRIPT, { type: "active", activeLeafId: "m1" });+ state = handoffTranscript(state, { type: "message", message: line("m2", "bot", "Reply", { parentId: "m1" }) });+ state = handoffTranscript(state, { type: "loaded", messages: [line("m1", "user", "Ask", { parentId: null }), line("m2", "bot", "Reply", { parentId: "m1" })], activeLeafId: "m2" });+ expect(state.activeLeafId).toBe("m2");+ expect(conversationRows(state, asker, helper, "You").map((row) => row.text)).toEqual(["Ask", "Reply"]);+ });++ it("follows the branch with each new line and patches lines it holds", () => {+ let state = loaded([line("m1", "user", "Ask", { parentId: null })], "m1");+ state = handoffTranscript(state, { type: "message", message: line("m2", "bot", "Working", { parentId: "m1" }) });+ expect(state.activeLeafId).toBe("m2");+ state = handoffTranscript(state, { type: "message", message: line("m2", "bot", "Done", { parentId: "m1" }), patch: true });+ expect(state.messages.map((message) => message.text)).toEqual(["Ask", "Done"]);+ expect(handoffTranscript(state, { type: "message", message: line("m9", "bot", "Unknown"), patch: true })).toBe(state);+ });++ it("loads again from the start after missed live updates, so the loaded copy replaces stale lines", () => {+ const stale = handoffTranscript(loaded([line("m1", "user", "Ask"), line("m2", "bot", "Working")], "m2"), { type: "reload" });+ expect(stale).toMatchObject({ messages: [], loading: true, failed: false, activeLeafId: null });+ const state = handoffTranscript(stale, { type: "loaded", messages: [line("m1", "user", "Ask"), line("m2", "bot", "Done")], activeLeafId: "m2" });+ expect(state.messages.map((message) => message.text)).toEqual(["Ask", "Done"]);+ });++ it("keeps a change to a line that arrives before the thread has loaded", () => {+ const live = handoffTranscript(LOADING_TRANSCRIPT, { type: "message", message: line("m2", "bot", "Checked, all green"), patch: true });+ const state = handoffTranscript(live, { type: "loaded", messages: [line("m1", "user", "Ask"), line("m2", "bot", "Chec")], activeLeafId: "m2" });+ expect(state.messages.map((message) => message.text)).toEqual(["Ask", "Checked, all green"]);+ });+});diff --git a/src/lib/handoff-conversation.ts b/src/lib/handoff-conversation.tsnew file mode 100644index 0000000000..119a977094--- /dev/null+++ b/src/lib/handoff-conversation.ts@@ -0,0 +1,90 @@+// What a hand-off's exchange view shows: the helper bot's thread as one conversation between two bots.+import { visibleMessages } from "@/state/snapshot-navigation";+import type { Message } from "@/state/store";+import { botLineText } from "./transcript-derivations";++export interface HandoffTranscript {+ messages: Message[];+ activeLeafId: string | null;+ loading: boolean;+ failed: boolean;+}++export type HandoffTranscriptAction =+ | { type: "loaded"; messages: Message[]; activeLeafId: string | null }+ | { type: "failed" }+ | { type: "reload" }+ | { type: "message"; message: Message; patch?: boolean }+ | { type: "active"; activeLeafId: string };++export const LOADING_TRANSCRIPT: HandoffTranscript = { messages: [], activeLeafId: null, loading: true, failed: false };++/** Lines that arrive live while the thread loads are kept: the loaded copy of a line never replaces a newer live one. */+export function handoffTranscript(state: HandoffTranscript, action: HandoffTranscriptAction): HandoffTranscript {+ switch (action.type) {+ case "loaded": {+ const live = new Map(state.messages.map((message) => [message.id, message]));+ const loaded = new Set(action.messages.map((message) => message.id));+ const newer = state.messages.filter((message) => !loaded.has(message.id));+ const messages = [...action.messages.map((message) => live.get(message.id) ?? message), ...newer];+ // A line that came in while loading and continues the branch moves it on, also when the loaded copy holds it.+ const activeLeafId = state.messages.reduce((leaf, message) => (message.parentId ?? null) === leaf ? message.id : leaf,+ state.activeLeafId ?? action.activeLeafId);+ return { messages, activeLeafId, loading: false, failed: false };+ }+ case "failed": return { ...state, loading: false, failed: true };+ // Only lines that arrive after this reload are newer than what it loads.+ case "reload": return { messages: [], activeLeafId: null, loading: true, failed: false };+ case "active": return { ...state, activeLeafId: action.activeLeafId };+ case "message": {+ const existing = state.messages.some((message) => message.id === action.message.id);+ // While loading, a change to a line not held yet is kept: the loaded copy may be older than it.+ if (!existing && action.patch && !state.loading) return state;+ const messages = existing+ ? state.messages.map((message) => message.id === action.message.id ? action.message : message)+ : [...state.messages, action.message];+ const continues = !existing && !state.loading && (action.message.parentId ?? null) === state.activeLeafId;+ return { ...state, messages, activeLeafId: continues ? action.message.id : state.activeLeafId };+ }+ }+}++export interface ConversationSpeaker {+ botId?: string;+ name: string;+ color?: string;+}++export interface ConversationRow {+ id: string;+ at: number;+ text: string;+ /** "asker": a bot that asked; "helper": the bot doing the work; "person": someone typing in the helper's thread. */+ side: "asker" | "helper" | "person";+ speaker: ConversationSpeaker;+}++type Named = ConversationSpeaker & { botId: string };++/** The written lines on the thread's shown branch, each with who said it. Tool steps and cards are left out. */+export function conversationRows(transcript: Pick<HandoffTranscript, "messages" | "activeLeafId">, asker: Named, helper: Named,+ personName: string): ConversationRow[] {+ const rows: ConversationRow[] = [];+ for (const message of visibleMessages(transcript)) {+ if (message.kind !== "text") continue;+ const text = message.role === "bot" ? botLineText(message) : message.text ?? "";+ if (!text.trim()) continue;+ rows.push({ id: message.id, at: message.at, text, ...speakerOf(message, asker, helper, personName) });+ }+ return rows;+}++function speakerOf(message: Message, asker: Named, helper: Named, personName: string): Pick<ConversationRow, "side" | "speaker"> {+ const bot = message.role === "user" ? message.peerAsk ?? message.from : message.from;+ if (bot?.botId === asker.botId) return { side: "asker", speaker: asker };+ if (bot && bot.botId !== helper.botId) {+ return { side: "asker", speaker: { botId: bot.botId, name: bot.name, color: "color" in bot ? bot.color : undefined } };+ }+ if (message.role === "bot") return { side: "helper", speaker: helper };+ return { side: "person", speaker: { name: personName } };+}diff --git a/src/locales/de.json b/src/locales/de.jsonindex a283d95739..0f46260a0c 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -4093,5 +4093,12 @@"inbox.settled.title": "Erledigt","inbox.settled.read": "Gelesen","server.notify.handoff": "{who} wartet auf dich",- "serverError.signIn.expired": "Diese Anfrage ist bereits abgelaufen"+ "serverError.signIn.expired": "Diese Anfrage ist bereits abgelaufen",+ "chat.handoffExchange.open": "Austausch mit {name} öffnen",+ "chat.handoffExchange.label": "Austausch zwischen den Bots {asker} und {helper}",+ "chat.handoffExchange.backTo": "Zurück zu {name}",+ "chat.handoffExchange.back": "Zurück",+ "chat.handoffExchange.loading": "Unterhaltung wird geladen…",+ "chat.handoffExchange.failed": "Die Unterhaltung konnte nicht geladen werden.",+ "chat.handoffExchange.empty": "Noch keine Nachrichten."}diff --git a/src/locales/en.json b/src/locales/en.jsonindex ffaa44f058..445bdf6a90 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -11477,5 +11477,12 @@"viewer.stop": "Stop","sidebar.preview.waitingFor": "Waiting for you: {what}","handoff.importSignIn": "Use my sign-in from my own browser",- "handoff.inPanel": "Showing in the Browser panel"+ "handoff.inPanel": "Showing in the Browser panel",+ "chat.handoffExchange.open": "Open exchange with {name}",+ "chat.handoffExchange.label": "Bot exchange between {asker} and {helper}",+ "chat.handoffExchange.backTo": "Back to {name}",+ "chat.handoffExchange.back": "Back",+ "chat.handoffExchange.loading": "Loading the conversation…",+ "chat.handoffExchange.failed": "Couldn't load the conversation.",+ "chat.handoffExchange.empty": "No messages yet."}diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 58a571d123..b5d377f15b 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -11477,5 +11477,12 @@"viewer.stop": "Parar","sidebar.preview.waitingFor": "Esperando você: {what}","handoff.importSignIn": "Usar meu login do meu próprio navegador",- "handoff.inPanel": "Aparece no painel do navegador"+ "handoff.inPanel": "Aparece no painel do navegador",+ "chat.handoffExchange.open": "Abrir conversa com {name}",+ "chat.handoffExchange.label": "Conversa entre os bots {asker} e {helper}",+ "chat.handoffExchange.backTo": "Voltar para {name}",+ "chat.handoffExchange.back": "Voltar",+ "chat.handoffExchange.loading": "Carregando a conversa…",+ "chat.handoffExchange.failed": "Não foi possível carregar a conversa.",+ "chat.handoffExchange.empty": "Nenhuma mensagem ainda."}diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex a9370bf3aa..d51d7473e6 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -4096,7 +4096,14 @@"server.reach.place.thisCloud": "9d7319debd5cbf68bbf4d9455f9c4f78d9168a490f936d60f455ca673fa0e3da","server.reach.place.cloudDesktop": "f5720ce8c1477b72dd219523d39dfe814771b693627de08bca13ef631370d579","server.notify.handoff": "9e45c29c7a067fc2b830ef5647b7dcd0962f2dbb438a62792c3a09f1d7d48ddb",- "serverError.signIn.expired": "a3b5091baeded57a62e8410a1e0e9df538f73161f3613c3a879a3bf386c2d169"+ "serverError.signIn.expired": "a3b5091baeded57a62e8410a1e0e9df538f73161f3613c3a879a3bf386c2d169",+ "chat.handoffExchange.open": "f7c1034c502cfbd020cc6c7a00d6aeafcf2957853b24bf08f689679f75aaf14e",+ "chat.handoffExchange.label": "62b00eda3fb12bc5fc268c60883841abd8a7774ea096109771d2a130364b6a50",+ "chat.handoffExchange.backTo": "11b2bf44df264af7dbb26dfd164187bd2ce06ba8cf6a756567c49b6ca1604041",+ "chat.handoffExchange.back": "76900f1bfd16c8d4dd3d25e6f46638d7165aee23883ccea6bfe071c514421769",+ "chat.handoffExchange.loading": "08cd9919453184389e78d9924a9dc3d4b68f2529b79bdd195dd51fb6139f927c",+ "chat.handoffExchange.failed": "9205f816010803c4e86ee0b2e43f1b99582f2dc452ac93d7c187e8d1e6686b2f",+ "chat.handoffExchange.empty": "f0d5968f615ed7ab11fdf8f17586cfaeb2845eee5757459e804b4e9d663a3588"},"es": {"whop.description": "1a07cf04ef17029448d3781415cbac16d54e66b821907a40d94e0e6349710e70",@@ -37473,7 +37480,14 @@"viewer.stop": "cae7d57bc067a514b8e34c9589631a95c7dc051638ddd2a190773269279a99df","sidebar.preview.waitingFor": "bb64342e2466a9319496bbb378b4711b661425abeb68b009163078d4c49524b6","handoff.importSignIn": "6472eeb450eea0fc019b9f5d7e02adbb926cfdff1d9c4e43de7a2aaf9b081fd5",- "handoff.inPanel": "8ffda3f9407104c180c4fe7b48fa2b6903ca43c9eeea2b1b6ec83befed353a86"+ "handoff.inPanel": "8ffda3f9407104c180c4fe7b48fa2b6903ca43c9eeea2b1b6ec83befed353a86",+ "chat.handoffExchange.open": "f7c1034c502cfbd020cc6c7a00d6aeafcf2957853b24bf08f689679f75aaf14e",+ "chat.handoffExchange.label": "62b00eda3fb12bc5fc268c60883841abd8a7774ea096109771d2a130364b6a50",+ "chat.handoffExchange.backTo": "11b2bf44df264af7dbb26dfd164187bd2ce06ba8cf6a756567c49b6ca1604041",+ "chat.handoffExchange.back": "76900f1bfd16c8d4dd3d25e6f46638d7165aee23883ccea6bfe071c514421769",+ "chat.handoffExchange.loading": "08cd9919453184389e78d9924a9dc3d4b68f2529b79bdd195dd51fb6139f927c",+ "chat.handoffExchange.failed": "9205f816010803c4e86ee0b2e43f1b99582f2dc452ac93d7c187e8d1e6686b2f",+ "chat.handoffExchange.empty": "f0d5968f615ed7ab11fdf8f17586cfaeb2845eee5757459e804b4e9d663a3588"},"zh": {"pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b",