Enterprise agent platform for building, deploying, and operating AI teammates.
import React from "react"
import { cleanup, fireEvent, render, screen } from "@testing-library/react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { WidgetChromeControls } from "./widget-chrome-controls"
vi.mock("@/contexts/i18n-context", () => ({
useI18n: () => ({ t: (key: string) => key }),
}))
describe("WidgetChromeControls", () => {
const postMessageSpy = vi.fn()
const onNewConversation = vi.fn()
beforeEach(() => {
postMessageSpy.mockReset()
onNewConversation.mockReset()
vi.stubGlobal("parent", { postMessage: postMessageSpy })
})
afterEach(() => {
cleanup()
vi.unstubAllGlobals()
})
it("renders the minimize button and a collapsed menu trigger even with no new-conversation action", () => {
// Expand/collapse is always offered regardless of newConversation, so
// the "..." trigger has something to open onto even without it.
render(<WidgetChromeControls />)
const minimizeButton = screen.getByRole("button", { name: "widgetChat.minimize" })
expect(minimizeButton).toBeInTheDocument()
expect(minimizeButton.querySelector('[data-icon="minimize"]')).not.toBeNull()
const menuTrigger = screen.getByRole("button", { name: "widgetChat.moreOptions" })
expect(menuTrigger).toHaveAttribute("aria-expanded", "false")
expect(screen.queryByRole("menu")).toBeNull()
})
it("omits the new-conversation menu item when no action is given, but still offers expand", () => {
render(<WidgetChromeControls />)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
const items = screen.getAllByRole("menuitem")
expect(items).toHaveLength(1)
expect(items[0]).toHaveTextContent("widgetChat.expandWindow")
})
it("posts widget_close to the parent window when the minimize button is clicked", () => {
render(<WidgetChromeControls />)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.minimize" }))
expect(postMessageSpy).toHaveBeenCalledWith(
{ xagent: true, v: 1, type: "widget_close" },
"*",
)
})
it("announces chrome_ready exactly once on mount and chrome_not_ready exactly once on unmount", () => {
// widget.js's mobile FAB-hiding guard keys off exactly this pair: without
// a reliable not-ready signal when this component disappears (e.g. a
// Session degrading mid-conversation), the parent's only fallback close
// control would stay hidden with no way to bring it back. Exact counts,
// not just toHaveBeenCalledWith, so a dependency-array bug that re-runs
// this effect mid-life (flashing the fallback FAB during an otherwise
// uneventful re-render) would actually fail this test.
const { unmount, rerender } = render(<WidgetChromeControls />)
expect(postMessageSpy).toHaveBeenCalledTimes(1)
expect(postMessageSpy).toHaveBeenNthCalledWith(
1,
{ xagent: true, v: 1, type: "widget_chrome_ready" },
"*",
)
// An unrelated prop change re-renders the component without unmounting
// it -- the effect's empty deps array must not treat this as a fresh
// mount.
rerender(<WidgetChromeControls newConversation={{ label: "Start over", onClick: onNewConversation }} />)
expect(postMessageSpy).toHaveBeenCalledTimes(1)
unmount()
expect(postMessageSpy).toHaveBeenCalledTimes(2)
expect(postMessageSpy).toHaveBeenNthCalledWith(
2,
{ xagent: true, v: 1, type: "widget_chrome_not_ready" },
"*",
)
})
it("does not post a message when the page is visited directly (window.parent === window)", () => {
// window.parent === window here means the guard's else-branch calls the
// real window.postMessage, not the postMessageSpy stub above -- spy on
// the real one directly so a missing guard would actually be caught.
vi.stubGlobal("parent", window)
const realPostMessageSpy = vi.spyOn(window, "postMessage")
render(<WidgetChromeControls />)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.minimize" }))
expect(realPostMessageSpy).not.toHaveBeenCalled()
realPostMessageSpy.mockRestore()
})
it("opens the menu on trigger click, shows the given label, and calls onClick then closes the menu", () => {
render(<WidgetChromeControls newConversation={{ label: "Start over", onClick: onNewConversation }} />)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
const item = screen.getByRole("menuitem", { name: "Start over" })
expect(item).toBeInTheDocument()
fireEvent.click(item)
expect(onNewConversation).toHaveBeenCalledTimes(1)
expect(screen.queryByRole("menu")).toBeNull()
})
it("disables the new-conversation menu item when told to", () => {
render(
<WidgetChromeControls
newConversation={{ label: "Resetting...", onClick: onNewConversation, disabled: true }}
/>,
)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
expect(screen.getByRole("menuitem", { name: "Resetting..." })).toBeDisabled()
})
it("keeps a pending action visible on the trigger after the menu closes on click", () => {
// The menu closes immediately on menuitem click (standard menu UX), so a
// slow round-trip needs feedback that survives that -- the trigger itself
// switches to a spinner rather than depending on the visitor reopening
// the (by-then pending) menu to see anything changed.
const { rerender } = render(
<WidgetChromeControls
newConversation={{ label: "Start over", onClick: onNewConversation }}
/>,
)
const trigger = screen.getByRole("button", { name: "widgetChat.moreOptions" })
fireEvent.click(trigger)
fireEvent.click(screen.getByRole("menuitem", { name: "Start over" }))
expect(screen.queryByRole("menu")).toBeNull()
expect(onNewConversation).toHaveBeenCalledTimes(1)
rerender(
<WidgetChromeControls
newConversation={{
label: "Resetting...",
onClick: onNewConversation,
disabled: true,
pending: true,
}}
/>,
)
expect(screen.queryByRole("menu")).toBeNull()
// The spinner is status feedback, not a lockout -- sizing has no
// dependency on the conversation reset, so the trigger itself must stay
// reachable (the reset item's own `disabled` is what actually blocks
// re-triggering it while pending).
expect(trigger).not.toBeDisabled()
expect(trigger.querySelector("svg.animate-spin")).not.toBeNull()
})
it("keeps expand/collapse reachable while a conversation reset is pending", () => {
render(
<WidgetChromeControls
newConversation={{
label: "Resetting...",
onClick: onNewConversation,
disabled: true,
pending: true,
}}
/>,
)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
expect(screen.getByRole("menuitem", { name: "Resetting..." })).toBeDisabled()
fireEvent.click(screen.getByRole("menuitem", { name: "widgetChat.expandWindow" }))
expect(postMessageSpy).toHaveBeenCalledWith(
{ xagent: true, v: 1, type: "widget_expand" },
"*",
)
})
it("toggles expand/collapse: posts the right message each way and flips the item's icon and label", () => {
render(<WidgetChromeControls />)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
const expandIcon = screen.getByRole("menuitem", { name: "widgetChat.expandWindow" })
.querySelector("svg[data-icon='expand']")
expect(expandIcon).not.toBeNull()
// data-icon is authored by this component's own branch, so it survives a
// source edit that swaps which Lucide icon actually renders there. The
// polyline's `points` geometry comes from lucide-react's own icon
// definition and differs per icon, so it can't drift out of sync the
// same way -- a real assertion of icon identity, not just the label.
expect(expandIcon?.querySelector("polyline[points='15 3 21 3 21 9']")).not.toBeNull()
fireEvent.click(screen.getByRole("menuitem", { name: "widgetChat.expandWindow" }))
expect(postMessageSpy).toHaveBeenCalledWith(
{ xagent: true, v: 1, type: "widget_expand" },
"*",
)
// The menu closes on click, same as every other menu item.
expect(screen.queryByRole("menu")).toBeNull()
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
const collapseIcon = screen.getByRole("menuitem", { name: "widgetChat.collapseWindow" })
.querySelector("svg[data-icon='collapse']")
expect(collapseIcon).not.toBeNull()
expect(collapseIcon?.querySelector("polyline[points='4 14 10 14 10 20']")).not.toBeNull()
fireEvent.click(screen.getByRole("menuitem", { name: "widgetChat.collapseWindow" }))
expect(postMessageSpy).toHaveBeenCalledWith(
{ xagent: true, v: 1, type: "widget_collapse" },
"*",
)
})
it("corrects the optimistic expand guess when the host rejects it (its own mobile guard)", () => {
// widget.js's expandPanel() no-ops under the mobile breakpoint and
// replies with widget_expand_rejected instead -- without listening for
// that, this component's own optimistic setIsExpanded(true) is never
// corrected, and the menu keeps reading "Collapse window" with nothing
// actually expanded.
render(<WidgetChromeControls />)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
fireEvent.click(screen.getByRole("menuitem", { name: "widgetChat.expandWindow" }))
fireEvent(window, new MessageEvent("message", {
data: { xagent: true, v: 1, type: "widget_expand_rejected" },
source: window.parent as unknown as MessageEventSource,
}))
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
expect(screen.getByRole("menuitem", { name: "widgetChat.expandWindow" })).toBeInTheDocument()
})
it("ignores a rejection message not sourced from window.parent", () => {
render(<WidgetChromeControls />)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
fireEvent.click(screen.getByRole("menuitem", { name: "widgetChat.expandWindow" }))
fireEvent(window, new MessageEvent("message", {
data: { xagent: true, v: 1, type: "widget_expand_rejected" },
source: window as unknown as MessageEventSource,
}))
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
expect(screen.getByRole("menuitem", { name: "widgetChat.collapseWindow" })).toBeInTheDocument()
})
it("ignores a same-window rejection message on a direct (non-embedded) visit", () => {
// window.parent === window here, so event.source === window also equals
// window.parent -- the "not sourced from window.parent" check above
// alone would NOT catch this; only an explicit window.parent === window
// check does, mirroring postToParentWidget's own direct-visit guard.
vi.stubGlobal("parent", window)
render(<WidgetChromeControls />)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
fireEvent.click(screen.getByRole("menuitem", { name: "widgetChat.expandWindow" }))
fireEvent(window, new MessageEvent("message", {
data: { xagent: true, v: 1, type: "widget_expand_rejected" },
source: window as unknown as MessageEventSource,
}))
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
expect(screen.getByRole("menuitem", { name: "widgetChat.collapseWindow" })).toBeInTheDocument()
})
describe("follows the size widget.js reports", () => {
function hostState(data: Record<string, unknown>, source: unknown = window.parent) {
fireEvent(window, new MessageEvent("message", {
data: { xagent: true, v: 1, type: "widget_expand_state", ...data },
source: source as MessageEventSource,
}))
}
function openMenuItem() {
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
return screen.getByRole("menuitem")
}
it.each([true, false])("posts nothing back to widget.js on expanded: %s", (expanded) => {
render(<WidgetChromeControls />)
postMessageSpy.mockClear()
hostState({ expanded })
expect(postMessageSpy).not.toHaveBeenCalled()
})
it.each([
{ expanded: true, label: "widgetChat.collapseWindow", icon: "collapse" },
{ expanded: false, label: "widgetChat.expandWindow", icon: "expand" },
])("shows $label after expanded: $expanded", ({ expanded, label, icon }) => {
render(<WidgetChromeControls />)
// Start from the opposite state, so following the message is a change.
if (!expanded) fireEvent.click(openMenuItem())
hostState({ expanded })
const item = openMenuItem()
expect(item).toHaveTextContent(label)
expect(item.querySelector(`svg[data-icon='${icon}']`)).not.toBeNull()
})
it.each([
{ name: "a string expanded", data: { expanded: "true" }, source: undefined, direct: false },
{ name: "a missing expanded", data: {}, source: undefined, direct: false },
{ name: "a message not from window.parent", data: { expanded: true }, source: window, direct: false },
{ name: "a direct visit", data: { expanded: true }, source: window, direct: true },
])("ignores $name", ({ data, source, direct }) => {
if (direct) vi.stubGlobal("parent", window)
render(<WidgetChromeControls />)
hostState(data, source ?? window.parent)
expect(openMenuItem()).toHaveTextContent("widgetChat.expandWindow")
})
it("hands the reported size to a controlling parent", () => {
const onExpandedChange = vi.fn()
render(<WidgetChromeControls expanded={false} onExpandedChange={onExpandedChange} />)
hostState({ expanded: true })
expect(onExpandedChange.mock.calls).toEqual([[true]])
})
it("collapses with one click after the host page expanded the panel", () => {
render(<WidgetChromeControls />)
hostState({ expanded: true })
postMessageSpy.mockClear()
fireEvent.click(openMenuItem())
expect(postMessageSpy.mock.calls).toEqual([[{ xagent: true, v: 1, type: "widget_collapse" }, "*"]])
})
})
it("keeps the new-conversation item and the expand toggle as two independent menu items", () => {
render(<WidgetChromeControls newConversation={{ label: "Start over", onClick: onNewConversation }} />)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
const items = screen.getAllByRole("menuitem")
expect(items).toHaveLength(2)
fireEvent.click(screen.getByRole("menuitem", { name: "widgetChat.expandWindow" }))
expect(onNewConversation).not.toHaveBeenCalled()
expect(postMessageSpy).toHaveBeenCalledWith(
{ xagent: true, v: 1, type: "widget_expand" },
"*",
)
})
describe("the history item", () => {
const onHistory = vi.fn()
beforeEach(() => onHistory.mockReset())
it("offers no history item unless one is given", () => {
render(<WidgetChromeControls newConversation={{ label: "Start over", onClick: onNewConversation }} />)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
expect(screen.getAllByRole("menuitem").map((item) => item.textContent)).toEqual([
"Start over",
"widgetChat.expandWindow",
])
})
it("shows the given label between the new-conversation item and the expand toggle", () => {
render(
<WidgetChromeControls
newConversation={{ label: "Start over", onClick: onNewConversation }}
history={{ label: "Earlier chats", onClick: onHistory }}
/>,
)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
expect(screen.getAllByRole("menuitem").map((item) => item.textContent)).toEqual([
"Start over",
"Earlier chats",
"widgetChat.expandWindow",
])
})
it("offers it without a new-conversation item", () => {
render(<WidgetChromeControls history={{ label: "Earlier chats", onClick: onHistory }} />)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
expect(screen.getAllByRole("menuitem").map((item) => item.textContent)).toEqual([
"Earlier chats",
"widgetChat.expandWindow",
])
})
it("calls the handler once and closes the menu when it is chosen", () => {
render(<WidgetChromeControls history={{ label: "Earlier chats", onClick: onHistory }} />)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
fireEvent.click(screen.getByRole("menuitem", { name: "Earlier chats" }))
expect(onHistory).toHaveBeenCalledTimes(1)
expect(screen.queryByRole("menu")).toBeNull()
expect(postMessageSpy).not.toHaveBeenCalledWith(
expect.objectContaining({ type: "widget_expand" }),
"*",
)
})
})
it("closes the menu on Escape", () => {
render(<WidgetChromeControls newConversation={{ label: "Start over", onClick: onNewConversation }} />)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
expect(screen.getByRole("menu")).toBeInTheDocument()
fireEvent.keyDown(document, { key: "Escape" })
expect(screen.queryByRole("menu")).toBeNull()
})
it("closes the menu when the iframe window loses focus", () => {
// e.g. the host page's own FAB, entirely outside this document, hiding
// the panel -- neither the pointerdown nor the Escape listener fires.
render(<WidgetChromeControls newConversation={{ label: "Start over", onClick: onNewConversation }} />)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
expect(screen.getByRole("menu")).toBeInTheDocument()
fireEvent(window, new Event("blur"))
expect(screen.queryByRole("menu")).toBeNull()
})
it("ignores a blur caused by focus moving within this same document, not the panel being hidden", () => {
// e.g. focus moving into the chat composer -- document.hasFocus() stays
// true because the iframe itself was never actually hidden; only a blur
// where it goes false (focus left the iframe's document entirely) means
// the host page hid the panel out from under an open menu.
const hasFocusSpy = vi.spyOn(document, "hasFocus").mockReturnValue(true)
render(<WidgetChromeControls newConversation={{ label: "Start over", onClick: onNewConversation }} />)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
expect(screen.getByRole("menu")).toBeInTheDocument()
fireEvent(window, new Event("blur"))
expect(screen.getByRole("menu")).toBeInTheDocument()
hasFocusSpy.mockRestore()
})
it("ignores a pointerdown whose target was removed from the DOM during dispatch", () => {
// A sibling handler on the target itself can synchronously detach it
// before the event finishes bubbling to this component's document
// listener; Node.contains() on a now-disconnected node would otherwise
// read the same as a genuine outside click and close the menu.
render(<WidgetChromeControls newConversation={{ label: "Start over", onClick: onNewConversation }} />)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
expect(screen.getByRole("menu")).toBeInTheDocument()
const ephemeral = document.createElement("button")
document.body.appendChild(ephemeral)
ephemeral.addEventListener("pointerdown", () => ephemeral.remove())
fireEvent.pointerDown(ephemeral)
expect(screen.getByRole("menu")).toBeInTheDocument()
})
it("closes the menu on an outside pointer press", () => {
render(
<div>
<div data-testid="outside">outside</div>
<WidgetChromeControls newConversation={{ label: "Start over", onClick: onNewConversation }} />
</div>,
)
fireEvent.click(screen.getByRole("button", { name: "widgetChat.moreOptions" }))
expect(screen.getByRole("menu")).toBeInTheDocument()
fireEvent.pointerDown(screen.getByTestId("outside"))
expect(screen.queryByRole("menu")).toBeNull()
})
})