Skip to content

πŸ™Œ OpenHands: AI-Driven Development

test: strengthen conversation browsing (#17363)

aivong-openhandsed1304c57fb4
diff --git a/__tests__/components/features/conversation-panel/conversation-group-folder-interactions.test.tsx b/__tests__/components/features/conversation-panel/conversation-group-folder-interactions.test.tsx
new file mode 100644
index 0000000000..72f74f1bc8
--- /dev/null
+++ b/__tests__/components/features/conversation-panel/conversation-group-folder-interactions.test.tsx
@@ -0,0 +1,455 @@
+import { act, fireEvent, render, screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import type { ComponentProps, HTMLAttributes } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
+import { ConversationGroupFolderRow } from "#/components/features/conversation-panel/conversation-group-folder-row";
+import { I18nKey } from "#/i18n/declaration";
+
+interface MockMotionSectionProps extends HTMLAttributes<HTMLElement> {
+ layout?: boolean | string;
+ transition?: {
+ type?: string;
+ stiffness?: number;
+ damping?: number;
+ };
+}
+
+vi.mock("framer-motion", async () => {
+ const { forwardRef } = await import("react");
+ const MotionSection = forwardRef<HTMLElement, MockMotionSectionProps>(
+ ({ layout, transition, ...props }, ref) => (
+ <section
+ ref={ref}
+ data-layout={String(layout)}
+ data-transition-type={transition?.type}
+ data-transition-stiffness={transition?.stiffness}
+ data-transition-damping={transition?.damping}
+ {...props}
+ />
+ ),
+ );
+ MotionSection.displayName = "MotionSection";
+
+ return { motion: { section: MotionSection } };
+});
+
+const useTranslationMock = vi.hoisted(() => vi.fn());
+
+vi.mock("react-i18next", () => ({
+ useTranslation: (namespace?: unknown) => {
+ useTranslationMock(namespace);
+ return {
+ t: (key: string, options?: { label?: string }) =>
+ options?.label ? `${key}:${options.label}` : key,
+ };
+ },
+}));
+
+const createConversation = (
+ id: string,
+ overrides: Partial<AppConversation> = {},
+): AppConversation => ({
+ id,
+ created_by_user_id: "user-1",
+ selected_repository: null,
+ selected_branch: null,
+ git_provider: null,
+ title: `Conversation ${id}`,
+ trigger: null,
+ pr_number: [],
+ llm_model: null,
+ metrics: null,
+ created_at: "2026-01-01T00:00:00.000Z",
+ updated_at: "2026-01-01T00:00:00.000Z",
+ execution_status: null,
+ conversation_url: null,
+ session_api_key: null,
+ sandbox_id: null,
+ sub_conversation_ids: [],
+ ...overrides,
+});
+
+const createConversations = (count: number): AppConversation[] =>
+ Array.from({ length: count }, (_, index) =>
+ createConversation(`conversation-${index + 1}`),
+ );
+
+type FolderRowProps = ComponentProps<typeof ConversationGroupFolderRow>;
+
+interface RenderRowOptions {
+ conversations?: AppConversation[];
+ group?: Partial<FolderRowProps["group"]>;
+ props?: Partial<Omit<FolderRowProps, "group">>;
+}
+
+const renderRow = ({
+ conversations = createConversations(3),
+ group: groupOverrides = {},
+ props: propOverrides = {},
+}: RenderRowOptions = {}) => {
+ const callbacks = {
+ onToggleExpanded: vi.fn(),
+ onDragStart: vi.fn(),
+ onDragEnd: vi.fn(),
+ onDragOver: vi.fn(),
+ onDragLeave: vi.fn(),
+ onDrop: vi.fn(),
+ onTogglePreviewExpanded: vi.fn(),
+ onLaunchFromGroup: vi.fn(),
+ renderConversationCard: (conversation: AppConversation) => (
+ <article key={conversation.id} data-testid="conversation-card">
+ {conversation.title}
+ </article>
+ ),
+ };
+ const parentEvents = {
+ onClick: vi.fn(),
+ onDragStart: vi.fn(),
+ onDragEnd: vi.fn(),
+ };
+ const group: FolderRowProps["group"] = {
+ id: "ws:/workspace/alpha",
+ label: "Workspace Alpha",
+ conversations,
+ launch: { workingDir: "/workspace/alpha" },
+ ...groupOverrides,
+ };
+ const props: FolderRowProps = {
+ group,
+ expanded: false,
+ previewExpanded: false,
+ isDragging: false,
+ dropIndicatorPosition: null,
+ animateLayout: false,
+ isCreatingConversationFlow: false,
+ activeConversationId: null,
+ ...callbacks,
+ ...propOverrides,
+ };
+ const rendered = render(
+ <div {...parentEvents}>
+ <ConversationGroupFolderRow {...props} />
+ </div>,
+ );
+
+ return {
+ ...rendered,
+ callbacks,
+ group,
+ parentEvents,
+ props,
+ user: userEvent.setup(),
+ };
+};
+
+afterEach(() => {
+ document
+ .querySelectorAll<HTMLElement>('body > section[style*="left: -9999px"]')
+ .forEach((dragImage) => dragImage.remove());
+ vi.useRealTimers();
+});
+
+describe("conversation group folder interactions", () => {
+ it("renders a sanitized, accessible collapsed folder and toggles it", async () => {
+ useTranslationMock.mockClear();
+ const { callbacks, user } = renderRow();
+ const section = screen.getByTestId("thread-folder-ws--workspace-alpha");
+ const heading = screen.getByRole("button", {
+ name: `${I18nKey.CONVERSATION_PANEL$EXPAND_FOLDER}:Workspace Alpha`,
+ });
+ const row = heading.parentElement;
+ const [folder, folderOpen] = heading.querySelectorAll("svg");
+ const add = screen.getByRole("button", {
+ name: `${I18nKey.CONVERSATION_PANEL$ADD_CONVERSATION_TO_GROUP}:Workspace Alpha`,
+ });
+
+ expect(useTranslationMock).toHaveBeenCalledWith("openhands");
+ expect(section).toHaveAttribute(
+ "aria-labelledby",
+ "thread-folder-ws--workspace-alpha",
+ );
+ expect(section).toHaveAttribute("data-layout", "false");
+ expect(section).toHaveAttribute("data-transition-type", "spring");
+ expect(section).toHaveAttribute("data-transition-stiffness", "600");
+ expect(section).toHaveAttribute("data-transition-damping", "45");
+ expect(heading).toHaveAttribute("id", "thread-folder-ws--workspace-alpha");
+ expect(heading).toHaveAttribute("aria-expanded", "false");
+ expect(heading).toHaveAttribute(
+ "aria-controls",
+ "thread-folder-content-ws--workspace-alpha",
+ );
+ expect(section).toHaveTextContent("Workspace Alpha");
+ expect(row).toHaveClass("flex", "text-[var(--oh-muted)]");
+ expect(heading).toHaveClass("cursor-grab", "focus-visible:ring-1");
+ expect(folder).toHaveClass("h-4", "block", "group-hover/folder:hidden");
+ expect(folderOpen).toHaveClass("h-4", "hidden", "group-hover/folder:block");
+ expect(add).toHaveClass(
+ "h-6",
+ "text-inherit",
+ "hover:bg-white/10",
+ "focus-visible:outline-none",
+ "disabled:cursor-not-allowed",
+ );
+ expect(screen.queryByTestId("conversation-card")).toBeNull();
+ expect(
+ screen.queryByTestId("thread-folder-drop-indicator-ws--workspace-alpha"),
+ ).toBeNull();
+
+ await user.click(heading);
+
+ expect(callbacks.onToggleExpanded).toHaveBeenCalledOnce();
+ });
+
+ it("renders every conversation without a preview action when the group is small", () => {
+ renderRow({
+ props: { expanded: true, animateLayout: true, isDragging: true },
+ });
+ const heading = screen.getByRole("button", {
+ name: `${I18nKey.CONVERSATION_PANEL$COLLAPSE_FOLDER}:Workspace Alpha`,
+ });
+ const section = screen.getByTestId("thread-folder-ws--workspace-alpha");
+ const [folder, folderOpen] = heading.querySelectorAll("svg");
+
+ expect(section).toHaveAttribute("data-layout", "position");
+ expect(heading).toHaveAttribute("aria-expanded", "true");
+ expect(folder).toHaveClass("hidden", "group-hover/folder:block");
+ expect(folderOpen).toHaveClass("block", "group-hover/folder:hidden");
+ expect(screen.getAllByTestId("conversation-card")).toHaveLength(3);
+ expect(
+ screen.queryByTestId("thread-folder-view-more-ws--workspace-alpha"),
+ ).toBeNull();
+ expect(heading.parentElement?.parentElement).toHaveClass("opacity-0");
+ });
+
+ it("shows the first five conversations and offers to reveal the rest", async () => {
+ const conversations = createConversations(6);
+ const { callbacks, user } = renderRow({
+ conversations,
+ props: { expanded: true },
+ });
+
+ const cards = screen.getAllByTestId("conversation-card");
+ expect(cards).toHaveLength(5);
+ expect(cards.map((card) => card.textContent)).toEqual(
+ conversations.slice(0, 5).map((conversation) => conversation.title),
+ );
+ expect(screen.queryByText("Conversation conversation-6")).toBeNull();
+
+ const more = screen.getByTestId(
+ "thread-folder-view-more-ws--workspace-alpha",
+ );
+ expect(more).toHaveTextContent(I18nKey.CONVERSATION_PANEL$MORE);
+ await user.click(more);
+ expect(callbacks.onTogglePreviewExpanded).toHaveBeenCalledOnce();
+ });
+
+ it("shows all truncated conversations and offers to collapse the preview", async () => {
+ const { callbacks, user } = renderRow({
+ conversations: createConversations(6),
+ props: { expanded: true, previewExpanded: true },
+ });
+
+ expect(screen.getAllByTestId("conversation-card")).toHaveLength(6);
+ const less = screen.getByTestId(
+ "thread-folder-view-more-ws--workspace-alpha",
+ );
+ expect(less).toHaveTextContent(I18nKey.CONVERSATION_PANEL$LESS);
+ await user.click(less);
+ expect(callbacks.onTogglePreviewExpanded).toHaveBeenCalledOnce();
+ });
+
+ it("keeps newly discovered conversations visible beyond the collapsed preview", () => {
+ renderRow({
+ conversations: createConversations(7),
+ props: {
+ expanded: true,
+ discoveryConversationIds: new Set(["conversation-6", "conversation-7"]),
+ },
+ });
+ expect(
+ screen
+ .getAllByTestId("conversation-card")
+ .map((card) => card.textContent),
+ ).toEqual(["Conversation conversation-6", "Conversation conversation-7"]);
+ });
+
+ it("keeps an active conversation visible beyond the collapsed preview", () => {
+ renderRow({
+ conversations: createConversations(6),
+ props: {
+ expanded: true,
+ activeConversationId: "conversation-6",
+ },
+ });
+
+ const cards = screen
+ .getAllByTestId("conversation-card")
+ .map((card) => card.textContent);
+ expect(cards).toEqual([
+ "Conversation conversation-1",
+ "Conversation conversation-2",
+ "Conversation conversation-3",
+ "Conversation conversation-4",
+ "Conversation conversation-6",
+ ]);
+ });
+
+ it.each([
+ { position: "before" as const, expectedClass: "-top-0.5" },
+ { position: "after" as const, expectedClass: "-bottom-0.5" },
+ ])("renders a $position drop indicator", ({ position, expectedClass }) => {
+ renderRow({ props: { dropIndicatorPosition: position } });
+
+ expect(
+ screen.getByTestId("thread-folder-drop-indicator-ws--workspace-alpha"),
+ ).toHaveClass("pointer-events-none", expectedClass);
+ });
+
+ it("forwards folder-level drag-over, drag-leave, and drop interactions", () => {
+ const { callbacks } = renderRow();
+ const section = screen.getByTestId("thread-folder-ws--workspace-alpha");
+ const dataTransfer = { dropEffect: "move" };
+
+ fireEvent.dragOver(section, { dataTransfer });
+ fireEvent.dragLeave(section, { dataTransfer });
+ fireEvent.drop(section, { dataTransfer });
+
+ expect(callbacks.onDragOver).toHaveBeenCalledOnce();
+ expect(callbacks.onDragLeave).toHaveBeenCalledOnce();
+ expect(callbacks.onDrop).toHaveBeenCalledOnce();
+ });
+
+ it("starts and ends a drag without bubbling to the surrounding list", () => {
+ const { callbacks, parentEvents } = renderRow();
+ const handle = screen.getByTestId("thread-folder-drag-ws--workspace-alpha");
+
+ fireEvent.dragStart(handle);
+ fireEvent.dragEnd(handle);
+
+ expect(callbacks.onDragStart).toHaveBeenCalledOnce();
+ expect(callbacks.onDragEnd).toHaveBeenCalledOnce();
+ expect(parentEvents.onDragStart).not.toHaveBeenCalled();
+ expect(parentEvents.onDragEnd).not.toHaveBeenCalled();
+ });
+
+ it("writes the group id into a native drag payload even without a custom drag image", () => {
+ const { callbacks, group } = renderRow();
+ const handle = screen.getByTestId("thread-folder-drag-ws--workspace-alpha");
+ const dataTransfer = {
+ effectAllowed: "copy",
+ setData: vi.fn(),
+ };
+
+ fireEvent.dragStart(handle, { dataTransfer });
+
+ expect(dataTransfer.effectAllowed).toBe("move");
+ expect(dataTransfer.setData).toHaveBeenCalledWith("text/plain", group.id);
+ expect(callbacks.onDragStart).toHaveBeenCalledOnce();
+ });
+
+ it("creates an anchored, styled drag image and removes it after rasterization", () => {
+ vi.useFakeTimers();
+ const { callbacks, group } = renderRow();
+ const section = screen.getByTestId("thread-folder-ws--workspace-alpha");
+ vi.spyOn(section, "getBoundingClientRect").mockReturnValue({
+ x: 10,
+ y: 20,
+ left: 10,
+ top: 20,
+ right: 330,
+ bottom: 68,
+ width: 320,
+ height: 48,
+ toJSON: () => ({}),
+ });
+ const dataTransfer = {
+ effectAllowed: "copy",
+ setData: vi.fn(),
+ setDragImage: vi.fn(),
+ };
+
+ const dragStartEvent = new Event("dragstart", {
+ bubbles: true,
+ cancelable: true,
+ });
+ Object.defineProperties(dragStartEvent, {
+ clientX: { value: 50 },
+ clientY: { value: 80 },
+ dataTransfer: { value: dataTransfer },
+ });
+ fireEvent(
+ screen.getByTestId("thread-folder-drag-ws--workspace-alpha"),
+ dragStartEvent,
+ );
+
+ expect(dataTransfer.effectAllowed).toBe("move");
+ expect(dataTransfer.setData).toHaveBeenCalledWith("text/plain", group.id);
+ expect(dataTransfer.setDragImage).toHaveBeenCalledOnce();
+ const [dragImage, offsetX, offsetY] = dataTransfer.setDragImage.mock
+ .calls[0] as [HTMLElement, number, number];
+ expect(offsetX).toBe(40);
+ expect(offsetY).toBe(60);
+ expect(document.body).toContainElement(dragImage);
+ expect(dragImage.style.position).toBe("fixed");
+ expect(dragImage.style.top).toBe("0px");
+ expect(dragImage.style.left).toBe("-9999px");
+ expect(dragImage.style.width).toBe("320px");
+ expect(dragImage.style.margin).toBe("0px");
+ expect(dragImage.style.pointerEvents).toBe("none");
+ expect(dragImage.style.borderRadius).toBe("0.5rem");
+ expect(dragImage.style.padding).toBe("0.25rem");
+ expect(dragImage.style.backgroundColor).toBe("var(--oh-surface-raised)");
+ expect(dragImage.style.boxShadow).toBe("0 8px 24px rgba(0, 0, 0, 0.35)");
+ expect(callbacks.onDragStart).toHaveBeenCalledOnce();
+
+ act(() => vi.runAllTimers());
+ expect(document.body).not.toContainElement(dragImage);
+ });
+
+ it("launches from the group without bubbling or performing a default action", () => {
+ const { callbacks, parentEvents } = renderRow();
+ const add = screen.getByTestId(
+ "add-conversation-to-group-ws--workspace-alpha",
+ );
+ const event = new MouseEvent("click", {
+ bubbles: true,
+ cancelable: true,
+ });
+
+ act(() => add.dispatchEvent(event));
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(callbacks.onLaunchFromGroup).toHaveBeenCalledOnce();
+ expect(parentEvents.onClick).not.toHaveBeenCalled();
+ });
+
+ it("prevents another group launch while conversation creation is active", async () => {
+ const { callbacks, user } = renderRow({
+ props: { isCreatingConversationFlow: true },
+ });
+ const add = screen.getByTestId(
+ "add-conversation-to-group-ws--workspace-alpha",
+ );
+
+ expect(add).toBeDisabled();
+ await user.click(add);
+ expect(callbacks.onLaunchFromGroup).not.toHaveBeenCalled();
+ });
+
+ it("renders conversation cards inside the labelled folder content region", () => {
+ renderRow({ props: { expanded: true } });
+ const heading = screen.getByTestId(
+ "thread-folder-drag-ws--workspace-alpha",
+ );
+ const content = document.getElementById(
+ heading.getAttribute("aria-controls") ?? "",
+ );
+
+ expect(content).not.toBeNull();
+ expect(
+ within(content as HTMLElement).getAllByTestId("conversation-card"),
+ ).toHaveLength(3);
+ });
+});
diff --git a/__tests__/routes/shared-conversation-viewer-behavior.test.tsx b/__tests__/routes/shared-conversation-viewer-behavior.test.tsx
new file mode 100644
index 0000000000..2d5615d60b
--- /dev/null
+++ b/__tests__/routes/shared-conversation-viewer-behavior.test.tsx
@@ -0,0 +1,457 @@
+import { createRef } from "react";
+import { render, screen } from "@testing-library/react";
+import { MemoryRouter, Route, Routes } from "react-router";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { SharedConversation as SharedConversationData } from "@openhands/typescript-client";
+
+import SharedConversation from "#/routes/shared-conversation";
+import { I18nKey } from "#/i18n/declaration";
+import {
+ SecurityRisk,
+ type ActionEvent,
+ type MessageEvent,
+ type ObservationEvent,
+ type OpenHandsEvent,
+ type SystemPromptEvent,
+} from "#/types/agent-server/core";
+
+const mocks = vi.hoisted(() => ({
+ useSharedConversation: vi.fn(),
+ useSharedConversationEvents: vi.fn(),
+ useInfiniteScroll: vi.fn(),
+ useTranslation: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: (namespace?: unknown) => {
+ mocks.useTranslation(namespace);
+ return {
+ t: (key: string) => key,
+ i18n: { language: "en", exists: () => false },
+ };
+ },
+}));
+
+vi.mock("#/hooks/query/use-shared-conversation", () => ({
+ useSharedConversation: (conversationId?: string) =>
+ mocks.useSharedConversation(conversationId),
+}));
+
+vi.mock("#/hooks/query/use-shared-conversation-events", () => ({
+ useSharedConversationEvents: (conversationId?: string) =>
+ mocks.useSharedConversationEvents(conversationId),
+}));
+
+vi.mock("#/hooks/use-infinite-scroll", () => ({
+ useInfiniteScroll: (options: unknown) => mocks.useInfiniteScroll(options),
+}));
+
+vi.mock("#/components/conversation-events/chat/messages", () => ({
+ Messages: ({
+ messages,
+ allEvents,
+ }: {
+ messages: OpenHandsEvent[];
+ allEvents: OpenHandsEvent[];
+ }) => (
+ <section
+ data-testid="shared-messages"
+ data-renderable-event-ids={messages.map((event) => event.id).join(",")}
+ data-all-event-ids={allEvents.map((event) => event.id).join(",")}
+ />
+ ),
+}));
+
+vi.mock("#/components/shared/loading-spinner", () => ({
+ LoadingSpinner: ({ size }: { size: "small" | "large" }) => (
+ <div data-testid={`loading-spinner-${size}`}>{size}</div>
+ ),
+}));
+
+const SHARED_CONVERSATION_ID = "shared-conversation-1";
+
+const createSharedConversation = (
+ overrides: Partial<SharedConversationData> = {},
+): SharedConversationData => ({
+ id: SHARED_CONVERSATION_ID,
+ created_by_user_id: "user-1",
+ selected_repository: "OpenHands/agent-canvas",
+ selected_branch: "feature/shared-viewer",
+ git_provider: "github",
+ title: "A shared debugging session",
+ pr_number: [1688],
+ llm_model: "openhands/claude-haiku-4-5-20251001",
+ metrics: null,
+ parent_conversation_id: null,
+ sub_conversation_ids: [],
+ created_at: "2026-07-13T12:00:00.000Z",
+ updated_at: "2026-07-13T12:30:00.000Z",
+ ...overrides,
+});
+
+const createMessageEvent = (
+ id: string,
+ text: string,
+ source: "agent" | "user" = "user",
+): MessageEvent => ({
+ id,
+ timestamp: "2026-07-13T12:00:00.000Z",
+ source,
+ llm_message: {
+ role: source === "user" ? "user" : "assistant",
+ content: [{ type: "text", text }],
+ },
+ activated_skills: [],
+ extended_content: [],
+});
+
+const createBashAction = (): ActionEvent => ({
+ id: "bash-action",
+ timestamp: "2026-07-13T12:01:00.000Z",
+ source: "agent",
+ thought: [{ type: "text", text: "Inspect the workspace" }],
+ thinking_blocks: [],
+ action: {
+ kind: "ExecuteBashAction",
+ command: "pwd",
+ is_input: false,
+ timeout: null,
+ reset: false,
+ },
+ tool_name: "execute_bash",
+ tool_call_id: "bash-call",
+ tool_call: {
+ id: "bash-call",
+ type: "function",
+ function: {
+ name: "execute_bash",
+ arguments: JSON.stringify({ command: "pwd" }),
+ },
+ },
+ llm_response_id: "response-1",
+ security_risk: SecurityRisk.UNKNOWN,
+});
+
+const createBashObservation = (): ObservationEvent => ({
+ id: "bash-observation",
+ timestamp: "2026-07-13T12:02:00.000Z",
+ source: "environment",
+ tool_name: "execute_bash",
+ tool_call_id: "bash-call",
+ observation: {
+ kind: "ExecuteBashObservation",
+ content: [{ type: "text", text: "/workspace/project\n" }],
+ command: "pwd",
+ exit_code: 0,
+ error: false,
+ timeout: false,
+ metadata: {
+ exit_code: 0,
+ pid: 123,
+ username: "openhands",
+ hostname: "sandbox",
+ working_dir: "/workspace/project",
+ py_interpreter_path: null,
+ prefix: "",
+ suffix: "",
+ },
+ },
+ action_id: "bash-action",
+});
+
+const createHiddenSystemPrompt = (): SystemPromptEvent => ({
+ id: "system-prompt",
+ timestamp: "2026-07-13T11:59:00.000Z",
+ source: "agent",
+ system_prompt: { type: "text", text: "Internal instructions" },
+ tools: [],
+});
+
+interface SharedEventPage {
+ items: OpenHandsEvent[];
+ next_page_id: string | null;
+}
+
+interface SharedEventsData {
+ pages: SharedEventPage[];
+}
+
+interface ConversationHookState {
+ data: SharedConversationData | null | undefined;
+ isLoading: boolean;
+ error: Error | null;
+}
+
+interface EventsHookState {
+ data: SharedEventsData | undefined;
+ isLoading: boolean;
+ error: Error | null;
+ hasNextPage: boolean | undefined;
+ fetchNextPage: () => void;
+ isFetchingNextPage: boolean;
+}
+
+const createConversationHookState = (
+ overrides: Partial<ConversationHookState> = {},
+): ConversationHookState => ({
+ data: createSharedConversation(),
+ isLoading: false,
+ error: null,
+ ...overrides,
+});
+
+const createEventsHookState = (
+ overrides: Partial<EventsHookState> = {},
+): EventsHookState => ({
+ data: { pages: [{ items: [], next_page_id: null }] },
+ isLoading: false,
+ error: null,
+ hasNextPage: false,
+ fetchNextPage: vi.fn(),
+ isFetchingNextPage: false,
+ ...overrides,
+});
+
+interface RenderViewerOptions {
+ conversationState?: Partial<ConversationHookState>;
+ eventsState?: Partial<EventsHookState>;
+}
+
+const renderViewer = ({
+ conversationState: conversationOverrides = {},
+ eventsState: eventsOverrides = {},
+}: RenderViewerOptions = {}) => {
+ const conversationState = createConversationHookState(conversationOverrides);
+ const eventsState = createEventsHookState(eventsOverrides);
+ const scrollContainerRef = createRef<HTMLDivElement>();
+
+ mocks.useSharedConversation.mockReturnValue(conversationState);
+ mocks.useSharedConversationEvents.mockReturnValue(eventsState);
+ mocks.useInfiniteScroll.mockReturnValue(scrollContainerRef);
+
+ const viewer = () => (
+ <MemoryRouter
+ initialEntries={[`/shared/conversations/${SHARED_CONVERSATION_ID}`]}
+ >
+ <Routes>
+ <Route
+ path="/shared/conversations/:conversationId"
+ element={<SharedConversation />}
+ />
+ </Routes>
+ </MemoryRouter>
+ );
+ const rendered = render(viewer());
+
+ return {
+ ...rendered,
+ conversationState,
+ eventsState,
+ scrollContainerRef,
+ rerenderViewer: () => rendered.rerender(viewer()),
+ };
+};
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("shared conversation viewer", () => {
+ it.each([
+ {
+ source: "conversation",
+ conversationState: { isLoading: true },
+ eventsState: {},
+ },
+ {
+ source: "events",
+ conversationState: {},
+ eventsState: { isLoading: true },
+ },
+ ])(
+ "shows the full-page loader while $source data is loading",
+ ({ conversationState, eventsState }) => {
+ renderViewer({ conversationState, eventsState });
+
+ expect(screen.getByTestId("loading-spinner-large")).toBeInTheDocument();
+ expect(screen.queryByRole("heading")).toBeNull();
+ },
+ );
+
+ it.each([
+ {
+ reason: "conversation request fails",
+ conversationState: { error: new Error("conversation unavailable") },
+ eventsState: {},
+ },
+ {
+ reason: "events request fails",
+ conversationState: {},
+ eventsState: { error: new Error("events unavailable") },
+ },
+ {
+ reason: "conversation is missing",
+ conversationState: { data: null },
+ eventsState: {},
+ },
+ ])(
+ "shows the not-found state when $reason",
+ ({ conversationState, eventsState }) => {
+ renderViewer({ conversationState, eventsState });
+
+ expect(
+ screen.getByText(I18nKey.CONVERSATION$NOT_FOUND),
+ ).toBeInTheDocument();
+ expect(screen.queryByTestId("shared-messages")).toBeNull();
+ },
+ );
+
+ it("renders metadata and a reconstructed, filtered multipage event stream", () => {
+ const userMessage = createMessageEvent(
+ "user-message",
+ "Please inspect the workspace",
+ );
+ const action = createBashAction();
+ const observation = createBashObservation();
+ const hiddenSystemPrompt = createHiddenSystemPrompt();
+ const fetchNextPage = vi.fn();
+ const { scrollContainerRef } = renderViewer({
+ eventsState: {
+ data: {
+ pages: [
+ {
+ items: [hiddenSystemPrompt, userMessage, action],
+ next_page_id: "page-2",
+ },
+ {
+ items: [observation],
+ next_page_id: null,
+ },
+ ],
+ },
+ hasNextPage: true,
+ fetchNextPage,
+ isFetchingNextPage: true,
+ },
+ });
+
+ expect(
+ screen.getByRole("heading", { name: "A shared debugging session" }),
+ ).toBeInTheDocument();
+ expect(mocks.useTranslation).toHaveBeenCalledWith("openhands");
+ expect(
+ screen.getByText(`${I18nKey.CONVERSATION$BRANCH}: feature/shared-viewer`),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ `${I18nKey.CONVERSATION$REPOSITORY}: OpenHands/agent-canvas`,
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ `${I18nKey.LLM$MODEL}: openhands/claude-haiku-4-5-20251001`,
+ ),
+ ).toBeInTheDocument();
+
+ const homeLink = screen.getByRole("link", {
+ name: I18nKey.BRANDING$OPENHANDS_LOGO,
+ });
+ expect(homeLink).toHaveAttribute("href", "/conversations");
+
+ const messages = screen.getByTestId("shared-messages");
+ expect(messages).toHaveAttribute(
+ "data-renderable-event-ids",
+ "user-message,bash-observation",
+ );
+ expect(messages).toHaveAttribute(
+ "data-all-event-ids",
+ "system-prompt,user-message,bash-action,bash-observation",
+ );
+ expect(screen.getByTestId("loading-spinner-small")).toBeInTheDocument();
+
+ expect(mocks.useSharedConversation).toHaveBeenCalledWith(
+ SHARED_CONVERSATION_ID,
+ );
+ expect(mocks.useSharedConversationEvents).toHaveBeenCalledWith(
+ SHARED_CONVERSATION_ID,
+ );
+ expect(mocks.useInfiniteScroll).toHaveBeenCalledWith({
+ hasNextPage: true,
+ isFetchingNextPage: true,
+ fetchNextPage,
+ });
+ expect(scrollContainerRef.current).toHaveClass("overflow-y-auto");
+ });
+
+ it("replaces the visible event stream when fetched pages change", () => {
+ const initialMessage = createMessageEvent("initial-message", "First page");
+ const replacementMessage = createMessageEvent(
+ "replacement-message",
+ "Replacement page",
+ );
+ const { rerenderViewer } = renderViewer({
+ eventsState: {
+ data: {
+ pages: [{ items: [initialMessage], next_page_id: "page-2" }],
+ },
+ },
+ });
+
+ expect(screen.getByTestId("shared-messages")).toHaveAttribute(
+ "data-renderable-event-ids",
+ "initial-message",
+ );
+
+ mocks.useSharedConversationEvents.mockReturnValue(
+ createEventsHookState({
+ data: {
+ pages: [{ items: [replacementMessage], next_page_id: null }],
+ },
+ }),
+ );
+ rerenderViewer();
+
+ expect(screen.getByTestId("shared-messages")).toHaveAttribute(
+ "data-renderable-event-ids",
+ "replacement-message",
+ );
+ expect(screen.getByTestId("shared-messages")).toHaveAttribute(
+ "data-all-event-ids",
+ "replacement-message",
+ );
+ });
+
+ it("uses fallback copy and hides optional details when history is unavailable", () => {
+ renderViewer({
+ conversationState: {
+ data: createSharedConversation({
+ title: null,
+ selected_branch: null,
+ selected_repository: null,
+ llm_model: null,
+ }),
+ },
+ eventsState: {
+ data: undefined,
+ hasNextPage: undefined,
+ },
+ });
+
+ expect(
+ screen.getByRole("heading", {
+ name: I18nKey.CONVERSATION$SHARED_CONVERSATION,
+ }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText(I18nKey.CONVERSATION$NO_HISTORY_AVAILABLE),
+ ).toBeInTheDocument();
+ expect(screen.queryByText(I18nKey.CONVERSATION$BRANCH)).toBeNull();
+ expect(screen.queryByText(I18nKey.CONVERSATION$REPOSITORY)).toBeNull();
+ expect(screen.queryByText(I18nKey.LLM$MODEL)).toBeNull();
+ expect(screen.queryByTestId("shared-messages")).toBeNull();
+ expect(screen.queryByTestId("loading-spinner-small")).toBeNull();
+ expect(mocks.useInfiniteScroll).toHaveBeenCalledWith(
+ expect.objectContaining({ hasNextPage: false }),
+ );
+ });
+});