Compare commits

..

4 Commits

Author SHA1 Message Date
b12a443abe test(web): add Mission Control frontend tests for phase 2 gate
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-07 15:22:04 -06:00
31af6c26ec Merge pull request 'feat(web): MS23-P2-008 Panel grid responsive layout' (#731) from feat/ms23-p2-grid into main
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-07 20:48:36 +00:00
e4f942dde7 feat(web): MS23-P2-008 panel grid responsive layout
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-07 14:47:39 -06:00
4ea31c5749 Merge pull request 'feat: MS23-P2-007 AuditLogDrawer + audit log endpoint' (#730) from feat/ms23-p2-audit into main
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2026-03-07 20:40:21 +00:00
8 changed files with 1072 additions and 40 deletions

View File

@@ -0,0 +1,155 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import * as MosaicUi from "@mosaic/ui";
import type { ButtonHTMLAttributes, ReactNode } from "react";
interface MockButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
children: ReactNode;
}
const mockApiPost = vi.fn<(endpoint: string, body?: unknown) => Promise<{ message?: string }>>();
const mockShowToast = vi.fn<(message: string, variant?: string) => void>();
const useToastSpy = vi.spyOn(MosaicUi, "useToast");
vi.mock("@/lib/api/client", () => ({
apiPost: (endpoint: string, body?: unknown): Promise<{ message?: string }> =>
mockApiPost(endpoint, body),
}));
vi.mock("@/components/ui/button", () => ({
Button: ({ children, ...props }: MockButtonProps): React.JSX.Element => (
<button {...props}>{children}</button>
),
}));
import { BargeInInput } from "./BargeInInput";
describe("BargeInInput", (): void => {
beforeEach((): void => {
vi.clearAllMocks();
vi.stubGlobal("fetch", vi.fn());
mockApiPost.mockResolvedValue({ message: "ok" });
useToastSpy.mockReturnValue({
showToast: mockShowToast,
removeToast: vi.fn(),
} as ReturnType<typeof MosaicUi.useToast>);
});
afterEach((): void => {
vi.unstubAllGlobals();
});
it("renders input controls and keeps send disabled for empty content", (): void => {
render(<BargeInInput sessionId="session-1" />);
expect(screen.getByLabelText("Inject message")).toBeInTheDocument();
expect(screen.getByRole("checkbox", { name: "Pause before send" })).not.toBeChecked();
expect(screen.getByRole("button", { name: "Send" })).toBeDisabled();
});
it("sends a trimmed message and clears the textarea", async (): Promise<void> => {
const onSent = vi.fn<() => void>();
const user = userEvent.setup();
render(<BargeInInput sessionId="session-1" onSent={onSent} />);
const textarea = screen.getByLabelText("Inject message");
await user.type(textarea, " execute plan ");
await user.click(screen.getByRole("button", { name: "Send" }));
await waitFor((): void => {
expect(mockApiPost).toHaveBeenCalledWith("/api/mission-control/sessions/session-1/inject", {
content: "execute plan",
});
});
expect(onSent).toHaveBeenCalledTimes(1);
expect(textarea).toHaveValue("");
});
it("pauses and resumes the session around injection when checkbox is enabled", async (): Promise<void> => {
const user = userEvent.setup();
render(<BargeInInput sessionId="session-2" />);
await user.click(screen.getByRole("checkbox", { name: "Pause before send" }));
await user.type(screen.getByLabelText("Inject message"), "hello world");
await user.click(screen.getByRole("button", { name: "Send" }));
await waitFor((): void => {
expect(mockApiPost).toHaveBeenCalledTimes(3);
});
const calls = mockApiPost.mock.calls as [string, unknown?][];
expect(calls[0]).toEqual(["/api/mission-control/sessions/session-2/pause", undefined]);
expect(calls[1]).toEqual([
"/api/mission-control/sessions/session-2/inject",
{ content: "hello world" },
]);
expect(calls[2]).toEqual(["/api/mission-control/sessions/session-2/resume", undefined]);
});
it("submits with Enter and does not submit on Shift+Enter", async (): Promise<void> => {
const user = userEvent.setup();
render(<BargeInInput sessionId="session-3" />);
const textarea = screen.getByLabelText("Inject message");
await user.type(textarea, "first");
fireEvent.keyDown(textarea, { key: "Enter", code: "Enter", shiftKey: true });
expect(mockApiPost).not.toHaveBeenCalled();
fireEvent.keyDown(textarea, { key: "Enter", code: "Enter", shiftKey: false });
await waitFor((): void => {
expect(mockApiPost).toHaveBeenCalledWith("/api/mission-control/sessions/session-3/inject", {
content: "first",
});
});
});
it("shows an inline error and toast when injection fails", async (): Promise<void> => {
const user = userEvent.setup();
mockApiPost.mockRejectedValueOnce(new Error("Injection failed"));
render(<BargeInInput sessionId="session-4" />);
await user.type(screen.getByLabelText("Inject message"), "help");
await user.click(screen.getByRole("button", { name: "Send" }));
await waitFor((): void => {
expect(screen.getByRole("alert")).toHaveTextContent("Injection failed");
});
expect(mockShowToast).toHaveBeenCalledWith("Injection failed", "error");
});
it("reports resume failures after a successful send", async (): Promise<void> => {
const user = userEvent.setup();
mockApiPost
.mockResolvedValueOnce({ message: "paused" })
.mockResolvedValueOnce({ message: "sent" })
.mockRejectedValueOnce(new Error("resume failed"));
render(<BargeInInput sessionId="session-5" />);
await user.click(screen.getByRole("checkbox", { name: "Pause before send" }));
await user.type(screen.getByLabelText("Inject message"), "deploy now");
await user.click(screen.getByRole("button", { name: "Send" }));
await waitFor((): void => {
expect(screen.getByRole("alert")).toHaveTextContent(
"Message sent, but failed to resume session: resume failed"
);
});
expect(mockShowToast).toHaveBeenCalledWith(
"Message sent, but failed to resume session: resume failed",
"error"
);
});
});

View File

@@ -0,0 +1,203 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ButtonHTMLAttributes, HTMLAttributes, ReactNode } from "react";
interface MockButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
children: ReactNode;
}
interface MockContainerProps extends HTMLAttributes<HTMLElement> {
children: ReactNode;
}
interface MockSession {
id: string;
providerId: string;
providerType: string;
status: "active" | "paused" | "killed";
createdAt: string;
updatedAt: string;
metadata?: Record<string, unknown>;
}
const mockApiGet = vi.fn<(endpoint: string) => Promise<MockSession[]>>();
const mockApiPost = vi.fn<(endpoint: string, body?: unknown) => Promise<{ message: string }>>();
const mockKillAllDialog = vi.fn<() => React.JSX.Element>();
vi.mock("@/lib/api/client", () => ({
apiGet: (endpoint: string): Promise<MockSession[]> => mockApiGet(endpoint),
apiPost: (endpoint: string, body?: unknown): Promise<{ message: string }> =>
mockApiPost(endpoint, body),
}));
vi.mock("@/components/mission-control/KillAllDialog", () => ({
KillAllDialog: (): React.JSX.Element => mockKillAllDialog(),
}));
vi.mock("@/components/ui/button", () => ({
Button: ({ children, ...props }: MockButtonProps): React.JSX.Element => (
<button {...props}>{children}</button>
),
}));
vi.mock("@/components/ui/badge", () => ({
Badge: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<span {...props}>{children}</span>
),
}));
vi.mock("@/components/ui/card", () => ({
Card: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<section {...props}>{children}</section>
),
CardHeader: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<header {...props}>{children}</header>
),
CardContent: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<div {...props}>{children}</div>
),
CardTitle: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<h2 {...props}>{children}</h2>
),
}));
import { GlobalAgentRoster } from "./GlobalAgentRoster";
function renderWithQueryClient(ui: React.JSX.Element): ReturnType<typeof render> {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
});
return render(<QueryClientProvider client={queryClient}>{ui}</QueryClientProvider>);
}
function makeSession(overrides: Partial<MockSession>): MockSession {
return {
id: "session-12345678",
providerId: "internal",
providerType: "internal",
status: "active",
createdAt: "2026-03-07T10:00:00.000Z",
updatedAt: "2026-03-07T10:01:00.000Z",
...overrides,
};
}
function getRowForSessionLabel(label: string): HTMLElement {
const sessionLabel = screen.getByText(label);
const row = sessionLabel.closest('[role="button"]');
if (!(row instanceof HTMLElement)) {
throw new Error(`Expected a row element for session label ${label}`);
}
return row;
}
describe("GlobalAgentRoster", (): void => {
beforeEach((): void => {
vi.clearAllMocks();
vi.stubGlobal("fetch", vi.fn());
mockApiGet.mockResolvedValue([]);
mockApiPost.mockResolvedValue({ message: "ok" });
mockKillAllDialog.mockImplementation(
(): React.JSX.Element => <div data-testid="kill-all-dialog">kill-all-dialog</div>
);
});
afterEach((): void => {
vi.unstubAllGlobals();
});
it("renders the empty state when no active sessions are returned", async (): Promise<void> => {
renderWithQueryClient(<GlobalAgentRoster />);
await waitFor((): void => {
expect(screen.getByText("No active agents")).toBeInTheDocument();
});
expect(screen.queryByTestId("kill-all-dialog")).not.toBeInTheDocument();
});
it("groups sessions by provider and shows kill-all control when sessions exist", async (): Promise<void> => {
mockApiGet.mockResolvedValue([
makeSession({ id: "alpha123456", providerId: "internal", providerType: "internal" }),
makeSession({ id: "bravo123456", providerId: "codex", providerType: "openai" }),
]);
renderWithQueryClient(<GlobalAgentRoster />);
await waitFor((): void => {
expect(screen.getByText("internal")).toBeInTheDocument();
expect(screen.getByText("codex (openai)")).toBeInTheDocument();
});
expect(screen.getByText("alpha123")).toBeInTheDocument();
expect(screen.getByText("bravo123")).toBeInTheDocument();
expect(screen.getByTestId("kill-all-dialog")).toBeInTheDocument();
});
it("calls onSelectSession on row click and keyboard activation", async (): Promise<void> => {
const onSelectSession = vi.fn<(sessionId: string) => void>();
mockApiGet.mockResolvedValue([makeSession({ id: "target123456" })]);
renderWithQueryClient(<GlobalAgentRoster onSelectSession={onSelectSession} />);
await waitFor((): void => {
expect(screen.getByText("target12")).toBeInTheDocument();
});
const row = getRowForSessionLabel("target12");
fireEvent.click(row);
fireEvent.keyDown(row, { key: "Enter" });
expect(onSelectSession).toHaveBeenCalledTimes(2);
expect(onSelectSession).toHaveBeenNthCalledWith(1, "target123456");
expect(onSelectSession).toHaveBeenNthCalledWith(2, "target123456");
});
it("kills a session from the roster", async (): Promise<void> => {
mockApiGet.mockResolvedValue([makeSession({ id: "killme123456" })]);
renderWithQueryClient(<GlobalAgentRoster />);
await waitFor((): void => {
expect(screen.getByRole("button", { name: "Kill session killme12" })).toBeInTheDocument();
});
fireEvent.click(screen.getByRole("button", { name: "Kill session killme12" }));
await waitFor((): void => {
expect(mockApiPost).toHaveBeenCalledWith("/api/mission-control/sessions/killme123456/kill", {
force: false,
});
});
});
it("collapses and reopens provider groups", async (): Promise<void> => {
mockApiGet.mockResolvedValue([makeSession({ id: "grouped12345" })]);
renderWithQueryClient(<GlobalAgentRoster />);
await waitFor((): void => {
expect(screen.getByText("grouped1")).toBeInTheDocument();
});
fireEvent.click(screen.getByRole("button", { name: /internal/i }));
expect(screen.queryByText("grouped1")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: /internal/i }));
expect(screen.getByText("grouped1")).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,70 @@
import { render, screen } from "@testing-library/react";
import type { ButtonHTMLAttributes, ReactNode } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
interface MockButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
children: ReactNode;
}
const mockGlobalAgentRoster = vi.fn();
const mockMissionControlPanel = vi.fn();
vi.mock("@/components/mission-control/AuditLogDrawer", () => ({
AuditLogDrawer: ({ trigger }: { trigger: ReactNode }): React.JSX.Element => (
<div data-testid="audit-log-drawer">{trigger}</div>
),
}));
vi.mock("@/components/mission-control/GlobalAgentRoster", () => ({
GlobalAgentRoster: (props: unknown): React.JSX.Element => {
mockGlobalAgentRoster(props);
return <div data-testid="global-agent-roster" />;
},
}));
vi.mock("@/components/mission-control/MissionControlPanel", () => ({
MissionControlPanel: (props: unknown): React.JSX.Element => {
mockMissionControlPanel(props);
return <div data-testid="mission-control-panel" />;
},
MAX_PANEL_COUNT: 6,
MIN_PANEL_COUNT: 1,
}));
vi.mock("@/components/ui/button", () => ({
Button: ({ children, ...props }: MockButtonProps): React.JSX.Element => (
<button {...props}>{children}</button>
),
}));
import { MissionControlLayout } from "./MissionControlLayout";
describe("MissionControlLayout", (): void => {
beforeEach((): void => {
vi.clearAllMocks();
vi.stubGlobal("fetch", vi.fn());
});
afterEach((): void => {
vi.unstubAllGlobals();
});
it("renders without crashing", (): void => {
render(<MissionControlLayout />);
expect(screen.getByRole("region", { name: "Mission Control" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Audit Log" })).toBeInTheDocument();
});
it("renders sidebar and panel grid container", (): void => {
render(<MissionControlLayout />);
const region = screen.getByRole("region", { name: "Mission Control" });
expect(region.querySelector(".grid")).toBeInTheDocument();
expect(region.querySelector("aside")).toBeInTheDocument();
expect(region.querySelector("main")).toBeInTheDocument();
expect(screen.getByTestId("global-agent-roster")).toBeInTheDocument();
expect(screen.getByTestId("mission-control-panel")).toBeInTheDocument();
});
});

View File

@@ -1,21 +1,86 @@
"use client";
import { useState } from "react";
import { useCallback, useState } from "react";
import { AuditLogDrawer } from "@/components/mission-control/AuditLogDrawer";
import { GlobalAgentRoster } from "@/components/mission-control/GlobalAgentRoster";
import { MissionControlPanel } from "@/components/mission-control/MissionControlPanel";
import {
MAX_PANEL_COUNT,
MIN_PANEL_COUNT,
MissionControlPanel,
type PanelConfig,
} from "@/components/mission-control/MissionControlPanel";
import { Button } from "@/components/ui/button";
import { useSessions } from "@/hooks/useMissionControl";
const DEFAULT_PANEL_SLOTS = ["panel-1", "panel-2", "panel-3", "panel-4"] as const;
const INITIAL_PANELS: PanelConfig[] = [{}];
export function MissionControlLayout(): React.JSX.Element {
const { sessions } = useSessions();
const [panels, setPanels] = useState<PanelConfig[]>(INITIAL_PANELS);
const [selectedSessionId, setSelectedSessionId] = useState<string>();
// First panel: selected session (from roster click) or first available session
const firstPanelSessionId = selectedSessionId ?? sessions[0]?.id;
const panelSessionIds = [firstPanelSessionId, undefined, undefined, undefined] as const;
const handleSelectSession = useCallback((sessionId: string): void => {
setSelectedSessionId(sessionId);
setPanels((currentPanels) => {
if (currentPanels.some((panel) => panel.sessionId === sessionId)) {
return currentPanels;
}
const firstEmptyPanelIndex = currentPanels.findIndex(
(panel) => panel.sessionId === undefined
);
if (firstEmptyPanelIndex >= 0) {
return currentPanels.map((panel, index) =>
index === firstEmptyPanelIndex ? { ...panel, sessionId } : panel
);
}
if (currentPanels.length >= MAX_PANEL_COUNT) {
return currentPanels;
}
return [...currentPanels, { sessionId }];
});
}, []);
const handleAddPanel = useCallback((): void => {
setPanels((currentPanels) => {
if (currentPanels.length >= MAX_PANEL_COUNT) {
return currentPanels;
}
return [...currentPanels, {}];
});
}, []);
const handleRemovePanel = useCallback((panelIndex: number): void => {
setPanels((currentPanels) => {
if (panelIndex < 0 || panelIndex >= currentPanels.length) {
return currentPanels;
}
if (currentPanels.length <= MIN_PANEL_COUNT) {
return currentPanels;
}
const nextPanels = currentPanels.filter((_, index) => index !== panelIndex);
return nextPanels.length === 0 ? INITIAL_PANELS : nextPanels;
});
}, []);
const handleExpandPanel = useCallback((panelIndex: number): void => {
setPanels((currentPanels) => {
if (panelIndex < 0 || panelIndex >= currentPanels.length) {
return currentPanels;
}
const shouldExpand = !currentPanels[panelIndex]?.expanded;
return currentPanels.map((panel, index) => ({
...panel,
expanded: shouldExpand && index === panelIndex,
}));
});
}, []);
return (
<section className="flex h-full min-h-0 flex-col overflow-hidden" aria-label="Mission Control">
@@ -32,12 +97,17 @@ export function MissionControlLayout(): React.JSX.Element {
<div className="grid min-h-0 flex-1 gap-4 xl:grid-cols-[280px_minmax(0,1fr)]">
<aside className="h-full min-h-0">
<GlobalAgentRoster
onSelectSession={setSelectedSessionId}
onSelectSession={handleSelectSession}
{...(selectedSessionId !== undefined ? { selectedSessionId } : {})}
/>
</aside>
<main className="h-full min-h-0 overflow-hidden">
<MissionControlPanel panels={DEFAULT_PANEL_SLOTS} panelSessionIds={panelSessionIds} />
<MissionControlPanel
panels={panels}
onAddPanel={handleAddPanel}
onRemovePanel={handleRemovePanel}
onExpandPanel={handleExpandPanel}
/>
</main>
</div>
</section>

View File

@@ -1,27 +1,107 @@
"use client";
import { useEffect } from "react";
import { OrchestratorPanel } from "@/components/mission-control/OrchestratorPanel";
import { Button } from "@/components/ui/button";
export interface PanelConfig {
sessionId?: string;
expanded?: boolean;
}
interface MissionControlPanelProps {
panels: readonly string[];
panelSessionIds?: readonly (string | undefined)[];
panels: PanelConfig[];
onAddPanel: () => void;
onRemovePanel: (index: number) => void;
onExpandPanel: (index: number) => void;
}
export const MIN_PANEL_COUNT = 1;
export const MAX_PANEL_COUNT = 6;
export function MissionControlPanel({
panels,
panelSessionIds,
onAddPanel,
onRemovePanel,
onExpandPanel,
}: MissionControlPanelProps): React.JSX.Element {
const expandedPanelIndex = panels.findIndex((panel) => panel.expanded);
const expandedPanel = expandedPanelIndex >= 0 ? panels[expandedPanelIndex] : undefined;
const canAddPanel = panels.length < MAX_PANEL_COUNT;
const canRemovePanel = panels.length > MIN_PANEL_COUNT;
useEffect(() => {
if (expandedPanelIndex < 0) {
return;
}
const handleKeyDown = (event: KeyboardEvent): void => {
if (event.key === "Escape") {
onExpandPanel(expandedPanelIndex);
}
};
window.addEventListener("keydown", handleKeyDown);
return (): void => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [expandedPanelIndex, onExpandPanel]);
return (
<div className="grid h-full min-h-0 auto-rows-fr grid-cols-1 gap-4 overflow-y-auto pr-1 md:grid-cols-2">
{panels.map((panelId, index) => {
const sessionId = panelSessionIds?.[index];
if (sessionId === undefined) {
return <OrchestratorPanel key={panelId} />;
}
return <OrchestratorPanel key={panelId} sessionId={sessionId} />;
})}
<div className="flex h-full min-h-0 flex-col gap-3">
<div className="flex items-center justify-between">
<h2 className="text-sm font-medium text-muted-foreground">Panels</h2>
<Button
type="button"
variant="outline"
size="icon"
onClick={onAddPanel}
disabled={!canAddPanel}
aria-label="Add panel"
title={canAddPanel ? "Add panel" : "Maximum of 6 panels"}
>
<span aria-hidden="true" className="text-lg leading-none">
+
</span>
</Button>
</div>
<div className="min-h-0 flex-1">
{expandedPanelIndex >= 0 && expandedPanel ? (
<div className="h-full min-h-0">
<OrchestratorPanel
{...(expandedPanel.sessionId !== undefined
? { sessionId: expandedPanel.sessionId }
: {})}
onClose={() => {
onRemovePanel(expandedPanelIndex);
}}
closeDisabled={!canRemovePanel}
onExpand={() => {
onExpandPanel(expandedPanelIndex);
}}
expanded
/>
</div>
) : (
<div className="grid h-full min-h-0 auto-rows-fr grid-cols-1 gap-4 overflow-y-auto pr-1 md:grid-cols-2 xl:grid-cols-3">
{panels.map((panel, index) => (
<OrchestratorPanel
key={`panel-${String(index)}`}
{...(panel.sessionId !== undefined ? { sessionId: panel.sessionId } : {})}
onClose={() => {
onRemovePanel(index);
}}
closeDisabled={!canRemovePanel}
onExpand={() => {
onExpandPanel(index);
}}
expanded={panel.expanded ?? false}
/>
))}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,218 @@
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import type { ButtonHTMLAttributes, HTMLAttributes, ReactNode } from "react";
interface MockButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
children: ReactNode;
}
interface MockContainerProps extends HTMLAttributes<HTMLElement> {
children: ReactNode;
}
type MockConnectionStatus = "connected" | "connecting" | "error";
type MockRole = "user" | "assistant" | "tool" | "system";
interface MockMessage {
id: string;
role: MockRole;
content: string;
timestamp: string;
}
interface MockSession {
id: string;
status: string;
}
interface MockSessionStreamResult {
messages: MockMessage[];
status: MockConnectionStatus;
error: string | null;
}
interface MockSessionsResult {
sessions: MockSession[];
loading: boolean;
error: Error | null;
}
interface MockPanelControlsProps {
sessionId: string;
status: string;
onStatusChange?: (nextStatus: string) => void;
}
interface MockBargeInInputProps {
sessionId: string;
}
const mockUseSessionStream = vi.fn<(sessionId: string) => MockSessionStreamResult>();
const mockUseSessions = vi.fn<() => MockSessionsResult>();
const mockPanelControls = vi.fn<(props: MockPanelControlsProps) => React.JSX.Element>();
const mockBargeInInput = vi.fn<(props: MockBargeInInputProps) => React.JSX.Element>();
vi.mock("date-fns", () => ({
formatDistanceToNow: (): string => "moments ago",
}));
vi.mock("@/hooks/useMissionControl", () => ({
useSessionStream: (sessionId: string): MockSessionStreamResult => mockUseSessionStream(sessionId),
useSessions: (): MockSessionsResult => mockUseSessions(),
}));
vi.mock("@/components/mission-control/PanelControls", () => ({
PanelControls: (props: MockPanelControlsProps): React.JSX.Element => mockPanelControls(props),
}));
vi.mock("@/components/mission-control/BargeInInput", () => ({
BargeInInput: (props: MockBargeInInputProps): React.JSX.Element => mockBargeInInput(props),
}));
vi.mock("@/components/ui/button", () => ({
Button: ({ children, ...props }: MockButtonProps): React.JSX.Element => (
<button {...props}>{children}</button>
),
}));
vi.mock("@/components/ui/badge", () => ({
Badge: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<span {...props}>{children}</span>
),
}));
vi.mock("@/components/ui/card", () => ({
Card: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<section {...props}>{children}</section>
),
CardHeader: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<header {...props}>{children}</header>
),
CardContent: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<div {...props}>{children}</div>
),
CardTitle: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<h2 {...props}>{children}</h2>
),
}));
vi.mock("@/components/ui/scroll-area", () => ({
ScrollArea: ({ children, ...props }: MockContainerProps): React.JSX.Element => (
<div {...props}>{children}</div>
),
}));
import { OrchestratorPanel } from "./OrchestratorPanel";
beforeAll((): void => {
Object.defineProperty(window.HTMLElement.prototype, "scrollIntoView", {
configurable: true,
value: vi.fn(),
});
});
describe("OrchestratorPanel", (): void => {
beforeEach((): void => {
vi.clearAllMocks();
vi.stubGlobal("fetch", vi.fn());
mockUseSessionStream.mockReturnValue({
messages: [],
status: "connecting",
error: null,
});
mockUseSessions.mockReturnValue({
sessions: [],
loading: false,
error: null,
});
mockPanelControls.mockImplementation(
({ status }: MockPanelControlsProps): React.JSX.Element => (
<div data-testid="panel-controls">status:{status}</div>
)
);
mockBargeInInput.mockImplementation(
({ sessionId }: MockBargeInInputProps): React.JSX.Element => (
<textarea aria-label="barge-input" data-session-id={sessionId} />
)
);
});
afterEach((): void => {
vi.unstubAllGlobals();
});
it("renders a selectable empty state when no session is provided", (): void => {
render(<OrchestratorPanel />);
expect(screen.getByText("Select an agent to view its stream")).toBeInTheDocument();
expect(screen.queryByText("Session: session-1")).not.toBeInTheDocument();
});
it("renders connection indicator and panel controls for an active session", (): void => {
mockUseSessionStream.mockReturnValue({
messages: [],
status: "connected",
error: null,
});
mockUseSessions.mockReturnValue({
sessions: [{ id: "session-1", status: "paused" }],
loading: false,
error: null,
});
render(<OrchestratorPanel sessionId="session-1" />);
expect(screen.getByText("Connected")).toBeInTheDocument();
expect(screen.getByText("Session: session-1")).toBeInTheDocument();
expect(screen.getByText("Waiting for messages...")).toBeInTheDocument();
expect(screen.getByTestId("panel-controls")).toHaveTextContent("status:paused");
});
it("renders stream messages with role and content", (): void => {
mockUseSessionStream.mockReturnValue({
status: "connected",
error: null,
messages: [
{
id: "msg-1",
role: "assistant",
content: "Mission accepted.",
timestamp: "2026-03-07T18:42:00.000Z",
},
],
});
render(<OrchestratorPanel sessionId="session-2" />);
expect(screen.getByText("assistant")).toBeInTheDocument();
expect(screen.getByText("Mission accepted.")).toBeInTheDocument();
expect(screen.getByText("moments ago")).toBeInTheDocument();
expect(screen.getByLabelText("barge-input")).toHaveAttribute("data-session-id", "session-2");
});
it("renders stream error text when the session has no messages", (): void => {
mockUseSessionStream.mockReturnValue({
messages: [],
status: "error",
error: "Mission Control stream disconnected.",
});
render(<OrchestratorPanel sessionId="session-3" />);
expect(screen.getByText("Error")).toBeInTheDocument();
expect(screen.getByText("Mission Control stream disconnected.")).toBeInTheDocument();
});
it("respects close button disabled state in panel actions", (): void => {
const onClose = vi.fn<() => void>();
render(<OrchestratorPanel onClose={onClose} closeDisabled />);
expect(screen.getByRole("button", { name: "Remove panel" })).toBeDisabled();
});
});

View File

@@ -5,6 +5,7 @@ import { formatDistanceToNow } from "date-fns";
import { BargeInInput } from "@/components/mission-control/BargeInInput";
import { Badge } from "@/components/ui/badge";
import type { BadgeVariant } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { PanelControls } from "@/components/mission-control/PanelControls";
import { ScrollArea } from "@/components/ui/scroll-area";
@@ -36,6 +37,64 @@ const CONNECTION_TEXT: Record<MissionControlConnectionStatus, string> = {
export interface OrchestratorPanelProps {
sessionId?: string;
onClose?: () => void;
closeDisabled?: boolean;
onExpand?: () => void;
expanded?: boolean;
}
interface PanelHeaderActionsProps {
onClose?: () => void;
closeDisabled?: boolean;
onExpand?: () => void;
expanded?: boolean;
}
function PanelHeaderActions({
onClose,
closeDisabled = false,
onExpand,
expanded = false,
}: PanelHeaderActionsProps): React.JSX.Element | null {
if (!onClose && !onExpand) {
return null;
}
return (
<div className="flex items-center gap-1">
{onExpand ? (
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={onExpand}
aria-label={expanded ? "Collapse panel" : "Expand panel"}
title={expanded ? "Collapse panel" : "Expand panel"}
>
<span aria-hidden="true" className="text-base leading-none">
{expanded ? "↙" : "↗"}
</span>
</Button>
) : null}
{onClose ? (
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={onClose}
disabled={closeDisabled}
aria-label="Remove panel"
title="Remove panel"
>
<span aria-hidden="true" className="text-base leading-none">
×
</span>
</Button>
) : null}
</div>
);
}
function formatRelativeTimestamp(timestamp: string): string {
@@ -47,7 +106,13 @@ function formatRelativeTimestamp(timestamp: string): string {
return formatDistanceToNow(parsedDate, { addSuffix: true });
}
export function OrchestratorPanel({ sessionId }: OrchestratorPanelProps): React.JSX.Element {
export function OrchestratorPanel({
sessionId,
onClose,
closeDisabled,
onExpand,
expanded,
}: OrchestratorPanelProps): React.JSX.Element {
const { messages, status, error } = useSessionStream(sessionId ?? "");
const { sessions } = useSessions();
const bottomAnchorRef = useRef<HTMLDivElement | null>(null);
@@ -55,6 +120,12 @@ export function OrchestratorPanel({ sessionId }: OrchestratorPanelProps): React.
const selectedSessionStatus = sessions.find((session) => session.id === sessionId)?.status;
const controlsStatus = optimisticStatus ?? selectedSessionStatus ?? "unknown";
const panelHeaderActionProps = {
...(onClose !== undefined ? { onClose } : {}),
...(closeDisabled !== undefined ? { closeDisabled } : {}),
...(onExpand !== undefined ? { onExpand } : {}),
...(expanded !== undefined ? { expanded } : {}),
};
useEffect(() => {
bottomAnchorRef.current?.scrollIntoView({ block: "end" });
@@ -68,7 +139,10 @@ export function OrchestratorPanel({ sessionId }: OrchestratorPanelProps): React.
return (
<Card className="flex h-full min-h-[220px] flex-col">
<CardHeader>
<CardTitle className="text-base">Orchestrator Panel</CardTitle>
<div className="flex items-start justify-between gap-2">
<CardTitle className="text-base">Orchestrator Panel</CardTitle>
<PanelHeaderActions {...panelHeaderActionProps} />
</div>
</CardHeader>
<CardContent className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
Select an agent to view its stream
@@ -80,24 +154,25 @@ export function OrchestratorPanel({ sessionId }: OrchestratorPanelProps): React.
return (
<Card className="flex h-full min-h-[220px] flex-col">
<CardHeader className="space-y-2">
<div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
<div className="flex items-start justify-between gap-2">
<CardTitle className="text-base">Orchestrator Panel</CardTitle>
<div className="flex flex-col items-start gap-2 sm:items-end">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span
className={`h-2.5 w-2.5 rounded-full ${CONNECTION_DOT_CLASS[status]} ${
status === "connecting" ? "animate-pulse" : ""
}`}
aria-hidden="true"
/>
<span>{CONNECTION_TEXT[status]}</span>
</div>
<PanelControls
sessionId={sessionId}
status={controlsStatus}
onStatusChange={setOptimisticStatus}
<PanelHeaderActions {...panelHeaderActionProps} />
</div>
<div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span
className={`h-2.5 w-2.5 rounded-full ${CONNECTION_DOT_CLASS[status]} ${
status === "connecting" ? "animate-pulse" : ""
}`}
aria-hidden="true"
/>
<span>{CONNECTION_TEXT[status]}</span>
</div>
<PanelControls
sessionId={sessionId}
status={controlsStatus}
onStatusChange={setOptimisticStatus}
/>
</div>
<p className="truncate text-xs text-muted-foreground">Session: {sessionId}</p>
</CardHeader>

View File

@@ -0,0 +1,161 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ButtonHTMLAttributes, HTMLAttributes, ReactNode } from "react";
interface MockButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
children: ReactNode;
}
interface MockBadgeProps extends HTMLAttributes<HTMLElement> {
children: ReactNode;
}
const mockApiPost = vi.fn<(endpoint: string, body?: unknown) => Promise<{ message: string }>>();
vi.mock("@/lib/api/client", () => ({
apiPost: (endpoint: string, body?: unknown): Promise<{ message: string }> =>
mockApiPost(endpoint, body),
}));
vi.mock("@/components/ui/button", () => ({
Button: ({ children, ...props }: MockButtonProps): React.JSX.Element => (
<button {...props}>{children}</button>
),
}));
vi.mock("@/components/ui/badge", () => ({
Badge: ({ children, ...props }: MockBadgeProps): React.JSX.Element => (
<span {...props}>{children}</span>
),
}));
import { PanelControls } from "./PanelControls";
function renderWithQueryClient(ui: React.JSX.Element): ReturnType<typeof render> {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
});
return render(<QueryClientProvider client={queryClient}>{ui}</QueryClientProvider>);
}
describe("PanelControls", (): void => {
beforeEach((): void => {
vi.clearAllMocks();
vi.stubGlobal("fetch", vi.fn());
mockApiPost.mockResolvedValue({ message: "ok" });
});
afterEach((): void => {
vi.unstubAllGlobals();
});
it("renders action buttons with correct disabled state for active sessions", (): void => {
renderWithQueryClient(<PanelControls sessionId="session-1" status="active" />);
expect(screen.getByRole("button", { name: "Pause session" })).toBeEnabled();
expect(screen.getByRole("button", { name: "Resume session" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Gracefully kill session" })).toBeEnabled();
expect(screen.getByRole("button", { name: "Force kill session" })).toBeEnabled();
});
it("disables all action buttons when session is already killed", (): void => {
renderWithQueryClient(<PanelControls sessionId="session-2" status="killed" />);
expect(screen.getByRole("button", { name: "Pause session" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Resume session" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Gracefully kill session" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Force kill session" })).toBeDisabled();
});
it("pauses a running session and reports the next status", async (): Promise<void> => {
const onStatusChange = vi.fn<(status: string) => void>();
const user = userEvent.setup();
renderWithQueryClient(
<PanelControls
sessionId="session with space"
status="active"
onStatusChange={onStatusChange}
/>
);
await user.click(screen.getByRole("button", { name: "Pause session" }));
await waitFor((): void => {
expect(mockApiPost).toHaveBeenCalledWith(
"/api/mission-control/sessions/session%20with%20space/pause",
undefined
);
});
expect(onStatusChange).toHaveBeenCalledWith("paused");
});
it("asks for graceful kill confirmation before submitting", async (): Promise<void> => {
const onStatusChange = vi.fn<(status: string) => void>();
const user = userEvent.setup();
renderWithQueryClient(
<PanelControls sessionId="session-4" status="active" onStatusChange={onStatusChange} />
);
await user.click(screen.getByRole("button", { name: "Gracefully kill session" }));
expect(
screen.getByText("Gracefully stop this agent after it finishes the current step?")
).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Confirm" }));
await waitFor((): void => {
expect(mockApiPost).toHaveBeenCalledWith("/api/mission-control/sessions/session-4/kill", {
force: false,
});
});
expect(onStatusChange).toHaveBeenCalledWith("killed");
});
it("sends force kill after confirmation", async (): Promise<void> => {
const onStatusChange = vi.fn<(status: string) => void>();
const user = userEvent.setup();
renderWithQueryClient(
<PanelControls sessionId="session-5" status="paused" onStatusChange={onStatusChange} />
);
await user.click(screen.getByRole("button", { name: "Force kill session" }));
expect(screen.getByText("This will hard-kill the agent immediately.")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Confirm" }));
await waitFor((): void => {
expect(mockApiPost).toHaveBeenCalledWith("/api/mission-control/sessions/session-5/kill", {
force: true,
});
});
expect(onStatusChange).toHaveBeenCalledWith("killed");
});
it("shows an error badge when an action fails", async (): Promise<void> => {
const user = userEvent.setup();
mockApiPost.mockRejectedValueOnce(new Error("unable to pause"));
renderWithQueryClient(<PanelControls sessionId="session-6" status="active" />);
await user.click(screen.getByRole("button", { name: "Pause session" }));
await waitFor((): void => {
expect(screen.getByText("unable to pause")).toBeInTheDocument();
});
});
});