Files
PaperClipAI/ui/src/components/Layout.test.tsx
T
673742bfc6 fix(ui): keep artifact previews in agent chat (#22252)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agent Chat lets people discuss work and review the plans and
documents it produces.
> - A document link in Chat promises to open the sidebar. It currently
moves the reader to Tasks.
> - Readers need to see the document and the conversation together, even
when the window is narrow.
> - This pull request opens the document in Chat, frees space for
reading, and gives readers a link to the source task.
> - Readers can review the saved revision in context and open the task
when they need its details.

## Linked Issues or Issue Description

Refs #11226 for the document sidebar that this change builds on.

**What happened?**

Opening a saved plan from Agent Chat changed the route to Tasks. The
document could show the same title twice. At narrow desktop widths, the
chat list left too little space for the conversation beside the
document. A task opened by UUID could still show a Chat header.

**Expected behavior**

The sidebar shows the saved revision beside the current conversation. It
shows a matching title once. The chat list collapses when space is
tight. The source link opens the standard task header with status, name,
and ID.

**Steps to reproduce**

1. Open an Agent Chat with a saved plan and select its sidebar link.
2. Use a narrow desktop window and inspect the conversation and plan.
3. Open the task that owns the plan and inspect the breadcrumb.

**Paperclip version or commit**

Reproduced on source commit `8285a81280`.

**Deployment mode**

Local trusted development instance with synthetic data.

## What Changed

- Open sidebar document links on the current Chat route. Keep the
requested revision and document owner, including links inside another
task’s preview. Provide an **Open source task** link.
- Show one title when the document title matches the opening Markdown
heading.
- Collapse the desktop chat list when an artifact tab would leave less
than 420 px for the conversation. Keep **Browse chats** in the header
with access to saved chat history. Restore the list when there is room.
- Use the task breadcrumb on task URLs, with the short UUID for a
conversation-backed task without a number.

## Verification

- Ran 618 focused Vitest tests across 18 UI files on the published
revision `2ff6c9e931`. All passed.
- Ran `pnpm --filter @paperclipai/ui typecheck`. It passed.
- Checked the synthetic demo in Chromium. Opened the plan in Chat,
checked the title, resized the window, and followed **Open source task**
to check its breadcrumb. Also verified a link inside a preview owned by
another task.
- Reproduced the chat navigation failure from the CI trace. The same
Playwright test passed locally after limiting collapse to artifact tabs.
- GitHub CI passed on `2ff6c9e931`, including build, typecheck, and all
browser shards. The remaining jobs passed on a retry after runner
shutdowns and a server handover test failure. The handover suite also
passed locally (19 tests). [GitHub
CI](https://github.com/paperclipai/paperclip/actions/runs/44423540581/attempts/2)
- `pnpm verify` selected broader CI coverage because `doc/PRODUCT.md`
changed. The full local suite was not run.

## Risks

The chat list changes visibility when an artifact tab is active and the
available width crosses the threshold. The list stays mounted to keep
its search text. Document tabs use the existing read API and check the
owning company. This change adds no database migration or API contract
change.

## Model Used

OpenAI Codex (GPT-6), with repository tools, shell execution, and
Chromium.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either linked existing issues or described the issue in-PR
following the relevant issue template
- [x] I have used public GitHub references for linked work
- [x] My branch name describes the change and contains no internal
Paperclip ticket ID
- [x] I have run focused tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Scott Tong <1504818+scotttong@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-18 16:19:13 -08:00

1378 lines
45 KiB
TypeScript

// @vitest-environment jsdom
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Layout } from "./Layout";
import { Layout as ProductionLayout } from "./Layout.production";
import { existsSync, readFileSync } from "node:fs";
import { act as reactAct } from "react";
import type { ReactNode } from "react";
const classicWorkspace = vi.hoisted(() => ({ enabled: true }));
vi.mock("./Sidebar.production", async () => await import("./Sidebar"));
vi.mock("./CompanySettingsSidebar.production", async () => await import("./CompanySettingsSidebar"));
vi.mock("./AppsSidebar.production", async () => await import("./AppsSidebar"));
vi.mock("./AppConnectionSidebar.production", async () => await import("./AppConnectionSidebar"));
vi.mock("./BreadcrumbBar.production", async () => await import("./BreadcrumbBar"));
vi.mock("./SidebarAccountMenu.production", async () => await import("./SidebarAccountMenu"));
vi.mock("@/hooks/useCoordinatorWorkspaceEnabled", () => ({
useCoordinatorWorkspaceEnabled: () => ({ enabled: !classicWorkspace.enabled, loaded: true, userId: "viewer" }),
}));
const browserTimeZoneSync = vi.hoisted(() => vi.fn());
vi.mock("@/hooks/useBrowserTimeZoneSync", () => ({ useBrowserTimeZoneSync: browserTimeZoneSync }));
const mockDesignSandbox = vi.hoisted(() => ({ enabled: false }));
vi.mock("@/context/DesignSandboxContext", () => ({ useDesignSandbox: () => mockDesignSandbox.enabled }));
vi.mock("./DesignSandboxSidebar", () => ({ DesignSandboxSidebar: () => <div>Proposed sidebar</div> }));
const mockHealthApi = vi.hoisted(() => ({
get: vi.fn(),
}));
const mockInstanceSettingsApi = vi.hoisted(() => ({
getGeneral: vi.fn(),
getExperimental: vi.fn(),
}));
const mockNavigate = vi.hoisted(() => vi.fn());
const mockSetSelectedCompanyId = vi.hoisted(() => vi.fn());
const mockSetSidebarOpen = vi.hoisted(() => vi.fn());
const mockCompanyState = vi.hoisted(() => ({
companies: [{ id: "company-1", issuePrefix: "PAP", name: "Paperclip" }],
selectedCompany: { id: "company-1", issuePrefix: "PAP", name: "Paperclip" },
selectedCompanyId: "company-1",
}));
const mockPluginSlots = vi.hoisted(() => ({
slots: [] as Array<Record<string, unknown>>,
}));
const mockUsePluginSlots = vi.hoisted(() => vi.fn());
const mockPluginSlotContexts = vi.hoisted(
() => [] as Array<Record<string, unknown>>,
);
const mockSidebarState = vi.hoisted(() => ({
sidebarOpen: true,
isMobile: false,
}));
const mockPanelState = vi.hoisted(() => ({ visible: false, showsArtifact: false, content: null as ReactNode, setVisible: vi.fn() }));
let currentPathname = "/PAP/dashboard";
vi.mock("@/lib/router", () => ({
Outlet: () => <div>Outlet content</div>,
useLocation: () => ({
pathname: currentPathname,
search: "",
hash: "",
state: null,
}),
useNavigate: () => mockNavigate,
useNavigationType: () => "PUSH",
useParams: () => {
const [firstSegment, secondSegment, entityId] = currentPathname
.split("/")
.filter(Boolean);
return {
companyPrefix: firstSegment ?? "PAP",
pluginRoutePath: secondSegment,
agentId: secondSegment === "agents" ? entityId : undefined,
routineId: secondSegment === "routines" ? entityId : undefined,
};
},
}));
vi.mock("./Sidebar", () => ({
Sidebar: ({ contentHeaderControls }: { contentHeaderControls?: boolean }) => (
<div data-content-header-controls={String(contentHeaderControls ?? false)}>
Main company nav
</div>
),
}));
vi.mock("./CompanySettingsSidebar", () => ({
CompanySettingsSidebar: () => <div>Company settings sidebar</div>,
}));
vi.mock("./AppsSidebar", () => ({
AppsSidebar: () => <div>Apps sidebar</div>,
AppsMobileNav: () => <nav aria-label="Mobile connectors">Browse Review</nav>,
}));
vi.mock("./AgentContextualSidebar", () => ({
AgentContextualSidebar: ({ agentRef }: { agentRef: string }) => (
<div>Agent sidebar {agentRef}</div>
),
}));
vi.mock("./SkillsContextualSidebar", () => ({
SkillsContextualSidebar: () => <div>Skills sidebar</div>,
}));
vi.mock("./AppConnectionSidebar", () => ({
AppDetailSidebar: (
props:
| { kind: "connection"; connectionId: string }
| { kind: "application"; applicationId: string },
) => (
<div>
{props.kind === "connection"
? `App detail sidebar connection ${props.connectionId}`
: `App detail sidebar application ${props.applicationId}`}
</div>
),
}));
vi.mock("./BreadcrumbBar", () => ({
BreadcrumbBar: ({ toolbarAction }: { toolbarAction?: ReactNode }) => <div>Breadcrumbs{toolbarAction}</div>,
}));
vi.mock("./AgentConversationsSidebar", () => ({
AgentConversationsSidebar: ({ compact }: { compact?: boolean }) => compact ? <button>Browse chats</button> : <aside aria-label="Chat contacts" />,
}));
vi.mock("./PropertiesPanel", () => ({
PropertiesPanel: () => null,
}));
// Overlay account/company lifecycle has its own integration test. These tests
// exercise route navigation with intentionally minimal context providers.
vi.mock("./PluginAppShellOverlays", () => ({
PluginAppShellOverlays: () => null,
}));
vi.mock("./CommandPalette", () => ({
CommandPalette: () => null,
}));
vi.mock("./NewIssueDialog", () => ({
NewIssueDialog: () => null,
}));
vi.mock("./NewProjectDialog", () => ({
NewProjectDialog: () => null,
}));
vi.mock("./NewGoalDialog", () => ({
NewGoalDialog: () => null,
}));
vi.mock("./NewAgentDialog", () => ({
NewAgentDialog: () => null,
}));
vi.mock("./KeyboardShortcutsCheatsheet", () => ({
KeyboardShortcutsCheatsheet: () => null,
}));
vi.mock("./ToastViewport", () => ({
ToastViewport: () => null,
}));
vi.mock("./AnnouncementWell", () => ({
AnnouncementWell: () => <div data-announcement-well />,
}));
vi.mock("./GitHubStarPrompt", () => ({
GitHubStarPrompt: () => null,
}));
vi.mock("./MobileBottomNav", () => ({
MobileBottomNav: () => null,
}));
vi.mock("./WorktreeBanner", () => ({
WorktreeBanner: () => null,
}));
vi.mock("./DevRestartBanner", () => ({
DevRestartBanner: () => null,
}));
vi.mock("./SidebarAccountMenu", () => ({
SidebarAccountMenu: () => <div>Account menu</div>,
}));
vi.mock("../plugins/slots", async () => {
const actual =
await vi.importActual<typeof import("../plugins/slots")>(
"../plugins/slots",
);
return {
resolveRouteSidebarSlot: actual.resolveRouteSidebarSlot,
usePluginSlots: (params: Record<string, unknown>) => {
mockUsePluginSlots(params);
return {
slots: mockPluginSlots.slots,
isLoading: false,
errorMessage: null,
};
},
PluginSlotMount: ({
slot,
context,
className,
}: {
slot: { displayName: string };
context: Record<string, unknown>;
className?: string;
}) => {
mockPluginSlotContexts.push(context);
return (
<div data-plugin-slot-class={className}>
Plugin route sidebar: {slot.displayName}
</div>
);
},
};
});
vi.mock("../context/DialogContext", () => ({
useDialogState: () => ({ newIssueOpen: false, newProjectOpen: false, newGoalOpen: false, newAgentOpen: false }),
useDialog: () => ({
openNewIssue: vi.fn(),
openOnboarding: vi.fn(),
}),
useDialogActions: () => ({
openNewIssue: vi.fn(),
openOnboarding: vi.fn(),
}),
}));
vi.mock("../context/PanelContext", () => ({
usePanel: () => ({
panelVisible: mockPanelState.visible,
panelShowsArtifact: mockPanelState.showsArtifact,
panelContent: mockPanelState.content,
togglePanelVisible: vi.fn(),
setPanelVisible: mockPanelState.setVisible,
}),
}));
vi.mock("../context/CompanyContext", () => ({
useCompany: () => ({
companies: mockCompanyState.companies,
loading: false,
selectedCompany: mockCompanyState.selectedCompany,
selectedCompanyId: mockCompanyState.selectedCompanyId,
selectionSource: "manual",
setSelectedCompanyId: mockSetSelectedCompanyId,
}),
}));
vi.mock("../context/SidebarContext", () => ({
useSidebar: () => ({
sidebarOpen: mockSidebarState.sidebarOpen,
setSidebarOpen: mockSetSidebarOpen,
toggleSidebar: vi.fn(),
isMobile: mockSidebarState.isMobile,
}),
}));
vi.mock("../hooks/useKeyboardShortcuts", () => ({
useKeyboardShortcuts: () => undefined,
}));
vi.mock("../hooks/useCompanyPageMemory", () => ({
useCompanyPageMemory: () => undefined,
}));
vi.mock("../api/health", () => ({
healthApi: mockHealthApi,
}));
vi.mock("../api/instanceSettings", () => ({
instanceSettingsApi: mockInstanceSettingsApi,
}));
vi.mock("../lib/company-selection", () => ({
shouldSyncCompanySelectionFromRoute: () => false,
// No bounce in the shared harness: these tests exercise layout chrome, not
// archived-company routing (covered by company-selection unit tests and the
// archived-company-url e2e).
resolveArchivedCompanyBounce: () => null,
}));
vi.mock("../lib/main-content-focus", () => ({
scheduleMainContentFocus: () => () => undefined,
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
async function act(callback: () => void | Promise<void>) {
let result: void | Promise<void> = undefined;
flushSync(() => {
result = callback();
});
await result;
}
async function flushReact() {
await act(async () => {
await Promise.resolve();
await new Promise((resolve) => window.setTimeout(resolve, 0));
});
}
function renderLayoutView(root: ReturnType<typeof createRoot>, queryClient: QueryClient) {
root.render(
<QueryClientProvider client={queryClient}>
<Layout />
</QueryClientProvider>,
);
}
describe("Layout", () => {
let container: HTMLDivElement;
it.each([
{ ShellLayout: Layout, width: 1024 },
{ ShellLayout: Layout, width: 1366 },
{ ShellLayout: ProductionLayout, width: 1024 },
{ ShellLayout: ProductionLayout, width: 1366 },
])("sizes a desktop-width conversation above the keyboard (%#)", async ({ ShellLayout, width }) => {
const viewport = Object.assign(new EventTarget(), { height: 1024, scale: 1, offsetTop: 0 });
vi.stubGlobal("visualViewport", viewport);
vi.stubGlobal("innerWidth", width);
Object.defineProperty(document.documentElement, "clientHeight", { configurable: true, value: 1024 });
const root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
try {
await reactAct(async () => root.render(<QueryClientProvider client={queryClient}><ShellLayout /></QueryClientProvider>));
const shell = container.querySelector(".paperclip-app-shell") as HTMLElement;
const conversation = document.createElement("div");
conversation.dataset.taskChatShell = "";
shell.querySelector("#main-content")!.append(conversation);
viewport.height = 600;
viewport.dispatchEvent(new Event("resize"));
expect(shell.dataset.mobile).toBeUndefined();
expect(shell.dataset.keyboardOpen).toBe("true");
expect(shell.style.getPropertyValue("--mobile-chat-viewport-height")).toBe("600px");
const style = document.createElement("style");
const css = readFileSync(existsSync("ui/src/index.css") ? "ui/src/index.css" : "src/index.css", "utf8");
style.textContent = css.slice(css.indexOf("html:has(.paperclip-app-shell"), css.indexOf("@media (prefers-reduced-motion: reduce)", css.indexOf("html:has(.paperclip-app-shell")));
document.head.append(style);
try {
expect(getComputedStyle(shell).position).toBe("fixed");
const sizingRule = Array.from(style.sheet!.cssRules).find((rule) =>
"selectorText" in rule && shell.matches((rule as CSSStyleRule).selectorText) && (rule as CSSStyleRule).style.height,
) as CSSStyleRule;
expect(sizingRule.style.height).toBe("var(--mobile-chat-viewport-height)");
expect(getComputedStyle(shell.querySelector(".app-main-row")!).minHeight).toBe("0px");
expect(getComputedStyle(shell.querySelector("#main-content")!).overflow).toBe("hidden");
viewport.scale = 2;
viewport.height = 300;
viewport.dispatchEvent(new Event("resize"));
expect(shell.style.getPropertyValue("--mobile-chat-viewport-height")).toBe("600px");
viewport.scale = 1;
viewport.height = 1024;
viewport.dispatchEvent(new Event("resize"));
expect(shell.dataset.keyboardOpen).toBeUndefined();
expect(getComputedStyle(shell).position).not.toBe("fixed");
viewport.height = 600;
viewport.dispatchEvent(new Event("resize"));
conversation.remove();
expect(getComputedStyle(shell).position).not.toBe("fixed");
} finally { style.remove(); }
} finally {
await reactAct(async () => root.unmount());
queryClient.clear();
Reflect.deleteProperty(document.documentElement, "clientHeight");
vi.unstubAllGlobals();
}
});
beforeEach(() => {
classicWorkspace.enabled = true;
mockDesignSandbox.enabled = false;
container = document.createElement("div");
document.body.appendChild(container);
currentPathname = "/PAP/dashboard";
mockCompanyState.companies = [
{ id: "company-1", issuePrefix: "PAP", name: "Paperclip" },
];
mockCompanyState.selectedCompany = {
id: "company-1",
issuePrefix: "PAP",
name: "Paperclip",
};
mockCompanyState.selectedCompanyId = "company-1";
mockHealthApi.get.mockResolvedValue({
status: "ok",
deploymentMode: "authenticated",
deploymentExposure: "private",
version: "1.2.3",
});
mockInstanceSettingsApi.getGeneral.mockResolvedValue({
censorUsernameInLogs: false,
});
mockInstanceSettingsApi.getExperimental.mockResolvedValue({
enableApps: true,
});
mockPluginSlots.slots = [];
mockPluginSlotContexts.length = 0;
mockSidebarState.sidebarOpen = true;
mockSidebarState.isMobile = false;
mockPanelState.visible = false;
mockPanelState.showsArtifact = false;
mockPanelState.content = null;
});
afterEach(() => {
container.remove();
document.body.innerHTML = "";
vi.clearAllMocks();
});
it("uses the standard workspace presentation when Classic is off", async () => {
classicWorkspace.enabled = false;
const root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
try {
await act(async () => renderLayoutView(root, queryClient));
await flushReact();
expect(container.querySelector(".coordinator-workspace")).not.toBeNull();
classicWorkspace.enabled = true;
await act(async () => renderLayoutView(root, queryClient));
expect(container.querySelector(".coordinator-workspace")).toBeNull();
} finally { await act(async () => root.unmount()); queryClient.clear(); }
});
it("collapses the mounted chat list only when an artifact crowds the conversation", async () => {
classicWorkspace.enabled = false;
currentPathname = "/PAP/chats/planner";
const root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const style = document.createElement("style");
style.textContent = ":root { --sz-280px: 280px; --sz-420px: 420px; }";
document.head.append(style);
let readingWidth = 416;
let measure: ResizeObserverCallback | undefined;
const width = vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockImplementation(() => readingWidth);
vi.stubGlobal("ResizeObserver", class {
constructor(callback: ResizeObserverCallback) { measure = callback; }
observe() {}
disconnect() {}
});
const render = () => reactAct(async () => renderLayoutView(root, queryClient));
try {
await render();
const list = container.querySelector('[aria-label="Chat contacts"]')?.closest("[data-secondary-sidebar]");
expect(list?.classList.contains("hidden")).toBe(false);
expect(container.textContent).not.toContain("Browse chats");
mockPanelState.visible = true;
mockPanelState.content = <div>Tasks</div>;
await render();
expect(list?.classList.contains("hidden")).toBe(false);
mockPanelState.showsArtifact = true;
await render();
expect(list?.classList.contains("hidden")).toBe(true);
expect(container.textContent).toContain("Browse chats");
mockPanelState.showsArtifact = false;
await render();
expect(list?.classList.contains("hidden")).toBe(false);
mockPanelState.showsArtifact = true;
await render();
expect(list?.classList.contains("hidden")).toBe(true);
readingWidth = 700;
await reactAct(async () => measure?.([], {} as ResizeObserver));
expect(list?.classList.contains("hidden")).toBe(false);
readingWidth = 699;
await reactAct(async () => measure?.([], {} as ResizeObserver));
expect(list?.classList.contains("hidden")).toBe(true);
mockPanelState.visible = false;
await render();
expect(list?.classList.contains("hidden")).toBe(false);
expect(container.textContent).not.toContain("Browse chats");
} finally {
await reactAct(async () => root.unmount());
queryClient.clear();
width.mockRestore();
vi.unstubAllGlobals();
style.remove();
}
});
it("does not render the deployment explainer in the shared layout", async () => {
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(mockHealthApi.get).toHaveBeenCalled();
expect(container.textContent).toContain("Breadcrumbs");
expect(container.textContent).toContain("Outlet content");
expect(container.querySelectorAll("[data-announcement-well]")).toHaveLength(1);
expect(container.textContent).not.toContain("Company rail");
expect(container.textContent).not.toContain("Authenticated private");
expect(container.textContent).not.toContain(
"Sign-in is required and this instance is intended for private-network access.",
);
await act(async () => {
root.unmount();
});
});
it("scopes the Streamlined task-detail surface while preserving balanced horizontal gutters", async () => {
currentPathname = "/PAP/issues/PAP-1";
mockInstanceSettingsApi.getExperimental.mockResolvedValue({
enableApps: true,
enableStreamlinedUi: true,
});
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(
container.querySelector(".streamlined-task-detail-surface"),
).not.toBeNull();
expect(
container.querySelector("#main-content")?.classList.contains("pt-0"),
).toBe(true);
expect(
container.querySelector("#main-content")?.classList.contains("md:pt-0"),
).toBe(true);
expect(
container.querySelector("#main-content")?.classList.contains("p-4"),
).toBe(true);
expect(
container.querySelector("#main-content")?.classList.contains("md:p-6"),
).toBe(true);
expect(
container.querySelector("#main-content")?.classList.contains("pr-0"),
).toBe(false);
expect(
container.querySelector("#main-content")?.classList.contains("md:pr-0"),
).toBe(false);
await act(async () => {
root.unmount();
});
});
it("retains settings navigation and route content beside the proposed sandbox sidebar", async () => {
currentPathname = "/PAP/company/settings/access";
mockDesignSandbox.enabled = true;
const root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => { root.render(<QueryClientProvider client={queryClient}><Layout /></QueryClientProvider>); });
await flushReact();
expect(container.textContent).toContain("Proposed sidebar");
expect(container.textContent).toContain("Company settings sidebar");
expect(container.textContent).toContain("Outlet content");
expect(container.textContent).not.toContain("Main company nav");
await act(async () => { root.unmount(); });
});
it("replaces the app sidebar with settings navigation on Streamlined settings routes", async () => {
currentPathname = "/PAP/company/settings/access";
mockPluginSlots.slots = [
{
type: "page",
id: "company-page",
displayName: "Company Page",
exportName: "CompanyPage",
routePath: "company",
pluginId: "plugin-1",
pluginKey: "fake-plugin",
pluginDisplayName: "Fake Plugin",
pluginVersion: "1.0.0",
},
{
type: "routeSidebar",
id: "company-sidebar",
displayName: "Company Route Sidebar",
exportName: "CompanySidebar",
routePath: "company",
pluginId: "plugin-1",
pluginKey: "fake-plugin",
pluginDisplayName: "Fake Plugin",
pluginVersion: "1.0.0",
},
];
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Company settings sidebar");
expect(container.textContent).not.toContain("Main company nav");
const secondaryRail = container.querySelector("[data-secondary-sidebar]");
expect(secondaryRail).not.toBeNull();
expect(secondaryRail?.classList.contains("w-60")).toBe(false);
expect(container.textContent).not.toContain("Company rail");
expect(container.textContent).not.toContain("Instance sidebar");
expect(container.textContent).not.toContain("Plugin route sidebar");
await act(async () => {
root.unmount();
});
});
it("keeps the global sidebar beside legacy settings navigation when Streamlined UI is off", async () => {
currentPathname = "/PAP/company/settings/access";
mockInstanceSettingsApi.getExperimental.mockResolvedValue({
enableApps: true,
enableStreamlinedUi: false,
});
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Main company nav");
expect(container.textContent).toContain("Company settings sidebar");
expect(container.querySelector<HTMLElement>(".sidebar-shell-panel")?.style.width).toBe("240px");
await act(async () => {
root.unmount();
});
});
it.each(["/PAP/apps", "/PAP/apps/review"])("shows top connector segments without a side rail on mobile: %s", async (path) => {
currentPathname = path;
mockSidebarState.isMobile = true;
mockSidebarState.sidebarOpen = false;
const root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => renderLayoutView(root, queryClient));
await flushReact();
expect(container.querySelector('#main-content [aria-label="Mobile connectors"]')).not.toBeNull();
expect(container.querySelector('.app-content-row [data-secondary-sidebar]')).toBeNull();
await act(async () => root.unmount());
});
it("renders a mobile company settings selector on company settings routes", async () => {
currentPathname = "/PAP/company/settings/secrets";
mockSidebarState.isMobile = true;
mockSidebarState.sidebarOpen = false;
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
const selector = container.querySelector("select");
expect(selector).not.toBeNull();
expect(selector?.value).toBe("secrets");
const selectorText = selector?.textContent?.toLowerCase() ?? "";
expect(selectorText).toContain("general");
expect(selectorText).toContain("export");
expect(selectorText).toContain("import");
expect(selectorText).toContain("members");
// Invites live on a tab of the Members page now, so the selector no
// longer carries a standalone entry for them.
expect(selectorText).not.toContain("invites");
expect(selectorText).toContain("secrets");
expect(selectorText).toContain("profile");
expect(selectorText).toContain("environments");
expect(selectorText).toContain("plugins");
expect(selectorText).not.toContain("instance general");
await act(async () => {
root.unmount();
});
});
it("replaces the company nav on instance settings routes", async () => {
currentPathname = "/PAP/company/settings/instance/general";
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Company settings sidebar");
expect(container.textContent).not.toContain("Main company nav");
expect(container.textContent).not.toContain("Company rail");
expect(container.textContent).not.toContain("Plugin route sidebar");
await act(async () => {
root.unmount();
});
});
it.each(["/PAP/company/export", "/PAP/company/import"])(
"replaces the company nav with the shared settings sidebar on %s",
async (pathname) => {
currentPathname = pathname;
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Company settings sidebar");
expect(container.textContent).not.toContain("Main company nav");
await act(async () => {
root.unmount();
});
},
);
it("keeps the company nav beside Apps navigation on legacy tools routes", async () => {
currentPathname = "/PAP/tools/runtime";
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Apps sidebar");
expect(container.textContent).toContain("Main company nav");
expect(container.textContent).not.toContain("Company settings sidebar");
await act(async () => {
root.unmount();
});
});
it("mounts the Apps secondary sidebar regardless of the retired experimental flag", async () => {
currentPathname = "/PAP/apps";
mockInstanceSettingsApi.getExperimental.mockResolvedValue({
enableApps: false,
});
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Apps sidebar");
expect(container.textContent).toContain("Main company nav");
const secondaryRail = container.querySelector("[data-secondary-sidebar]");
expect(secondaryRail?.classList.contains("w-60")).toBe(true);
expect(secondaryRail?.classList.contains("shrink-0")).toBe(true);
await act(async () => {
root.unmount();
});
});
it("keeps the Apps sidebar on the M8 advanced-setup tabs", async () => {
currentPathname = "/PAP/apps/advanced/paste-config";
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Apps sidebar");
expect(container.textContent).toContain("Main company nav");
await act(async () => {
root.unmount();
});
});
it("keeps the Apps sidebar on legacy developer tabs behind the Advanced door", async () => {
currentPathname = "/PAP/apps/advanced/runtime";
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Apps sidebar");
expect(container.textContent).toContain("Main company nav");
await act(async () => {
root.unmount();
});
});
// Reserved Apps subroutes are not connection ids. They must keep the
// top-level Apps sidebar, never mount a detail sidebar for a phantom app.
it.each(["browse", "connections", "vercel-connect", "review", "chat"])(
"keeps the Apps sidebar on the %s surface",
async (route) => {
currentPathname = `/PAP/apps/${route}`;
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Apps sidebar");
expect(container.textContent).toContain("Main company nav");
expect(container.textContent).not.toContain("App detail sidebar");
await act(async () => {
root.unmount();
});
},
);
it("keeps the Apps sidebar on the gateways list and detail routes", async () => {
for (const pathname of [
"/PAP/apps/gateways",
"/PAP/apps/gateways/gw-1/overview",
]) {
currentPathname = pathname;
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Apps sidebar");
expect(container.textContent).toContain("Main company nav");
expect(container.textContent).not.toContain("App detail sidebar");
await act(async () => {
root.unmount();
});
}
});
it("uses the app connection sidebar on app detail routes", async () => {
currentPathname = "/PAP/apps/conn-1/permissions";
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain(
"App detail sidebar connection conn-1",
);
expect(container.textContent).toContain("Main company nav");
expect(container.textContent).not.toContain("Apps sidebar");
await act(async () => {
root.unmount();
});
});
it("uses the app detail sidebar on not-connected app routes", async () => {
currentPathname = "/PAP/apps/app/app-1/permissions";
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain(
"App detail sidebar application app-1",
);
expect(container.textContent).toContain("Main company nav");
expect(container.textContent).not.toContain("Apps sidebar");
await act(async () => {
root.unmount();
});
});
it("keeps global navigation beside Agent details", async () => {
async function renderAt(pathname: string) {
currentPathname = pathname;
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
return root;
}
for (const [pathname, sidebarText] of [
["/PAP/agents/briefing-analyst/skills", "Agent sidebar briefing-analyst"],
[
"/PAP/agents/briefing-analyst/runs/run-1",
"Agent sidebar briefing-analyst",
],
] as const) {
const root = await renderAt(pathname);
expect(container.textContent).toContain(sidebarText);
expect(container.textContent).toContain("Main company nav");
const secondaryRail = container.querySelector("[data-secondary-sidebar]");
expect(secondaryRail?.classList.contains("w-60")).toBe(true);
expect(secondaryRail?.classList.contains("bg-background")).toBe(true);
const breadcrumb = Array.from(container.querySelectorAll("div")).find(
(element) => element.textContent === "Breadcrumbs",
);
expect(breadcrumb).toBeDefined();
expect(
breadcrumb && secondaryRail
? breadcrumb.compareDocumentPosition(secondaryRail) &
Node.DOCUMENT_POSITION_FOLLOWING
: 0,
).not.toBe(0);
await act(async () => {
root.unmount();
});
container.innerHTML = "";
}
});
it("keeps global navigation with agent configuration navigation in the legacy shell", async () => {
mockInstanceSettingsApi.getExperimental.mockResolvedValue({
enableApps: true,
enableStreamlinedUi: false,
});
for (const pathname of [
"/PAP/agents/briefing-analyst/skills",
"/PAP/routines/routine-1/overview",
]) {
currentPathname = pathname;
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Main company nav");
if (pathname.includes("/agents/")) expect(container.textContent).toContain("Agent sidebar");
else expect(container.textContent).not.toContain("Agent sidebar");
if (pathname.includes("/routines/")) expect(container.querySelector("[data-secondary-sidebar]")).toBeNull();
await act(async () => {
root.unmount();
});
container.innerHTML = "";
}
});
it("uses the global rail without secondary Skills navigation in the streamlined shell", async () => {
for (const path of ["/PAP/skills", "/PAP/skills?tab=discover", "/PAP/skills/studio", "/PAP/skills/sources"]) {
currentPathname = path;
const root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => { root.render(<QueryClientProvider client={queryClient}><Layout /></QueryClientProvider>); });
await flushReact();
await flushReact();
expect(container.textContent).toContain("Main company nav");
expect(container.textContent).not.toContain("Skills sidebar");
await act(async () => root.unmount());
container.innerHTML = "";
}
});
it("keeps the global sidebar beside Skills navigation in the legacy shell", async () => {
currentPathname = "/PAP/skills/studio";
mockInstanceSettingsApi.getExperimental.mockResolvedValue({
enableApps: true,
enableStreamlinedUi: false,
});
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Main company nav");
expect(container.textContent).toContain("Skills sidebar");
expect(container.querySelector<HTMLElement>(".sidebar-shell-panel")?.style.width).toBe("240px");
await act(async () => {
root.unmount();
});
});
it("keeps Agent and Routine collection routes in global navigation", async () => {
for (const pathname of [
"/PAP/agents/all",
"/PAP/agents/new",
"/PAP/routines",
]) {
currentPathname = pathname;
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Main company nav");
expect(container.textContent).not.toContain("Agent sidebar");
if (pathname.includes("/routines/")) expect(container.querySelector("[data-secondary-sidebar]")).toBeNull();
await act(async () => {
root.unmount();
});
container.innerHTML = "";
}
});
it("renders a route-scoped plugin sidebar for a matching plugin page route", async () => {
currentPathname = "/PAP/wiki";
mockPluginSlots.slots = [
{
type: "page",
id: "wiki-page",
displayName: "Wiki Page",
exportName: "WikiPage",
routePath: "wiki",
pluginId: "plugin-1",
pluginKey: "wiki-plugin",
pluginDisplayName: "Wiki Plugin",
pluginVersion: "1.0.0",
},
{
type: "routeSidebar",
id: "wiki-route-sidebar",
displayName: "Wiki Sidebar",
exportName: "WikiSidebar",
routePath: "wiki",
pluginId: "plugin-1",
pluginKey: "wiki-plugin",
pluginDisplayName: "Wiki Plugin",
pluginVersion: "1.0.0",
},
];
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain(
"Plugin route sidebar: Wiki Sidebar",
);
expect(
container.querySelector("[data-plugin-slot-class='min-h-0 flex-1']"),
).not.toBeNull();
expect(container.textContent).not.toContain("Main company nav");
expect(container.textContent).not.toContain("Company settings sidebar");
expect(container.textContent).not.toContain("Instance sidebar");
await act(async () => {
root.unmount();
});
});
it("keeps the route-scoped plugin sidebar on nested plugin page routes", async () => {
currentPathname = "/PAP/wiki/page/templates";
mockPluginSlots.slots = [
{
type: "page",
id: "wiki-page",
displayName: "Wiki Page",
exportName: "WikiPage",
routePath: "wiki",
pluginId: "plugin-1",
pluginKey: "wiki-plugin",
pluginDisplayName: "Wiki Plugin",
pluginVersion: "1.0.0",
},
{
type: "routeSidebar",
id: "wiki-route-sidebar",
displayName: "Wiki Sidebar",
exportName: "WikiSidebar",
routePath: "wiki",
pluginId: "plugin-1",
pluginKey: "wiki-plugin",
pluginDisplayName: "Wiki Plugin",
pluginVersion: "1.0.0",
},
];
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(mockUsePluginSlots).toHaveBeenCalledWith(
expect.objectContaining({
companyId: "company-1",
enabled: true,
}),
);
expect(container.textContent).toContain(
"Plugin route sidebar: Wiki Sidebar",
);
expect(container.textContent).not.toContain("Main company nav");
await act(async () => {
root.unmount();
});
});
it("uses the route company context for plugin route sidebars on the first render", async () => {
currentPathname = "/ALT/wiki";
mockCompanyState.companies = [
{ id: "company-1", issuePrefix: "PAP", name: "Paperclip" },
{ id: "company-2", issuePrefix: "ALT", name: "Alternate" },
];
mockCompanyState.selectedCompany = {
id: "company-1",
issuePrefix: "PAP",
name: "Paperclip",
};
mockCompanyState.selectedCompanyId = "company-1";
mockPluginSlots.slots = [
{
type: "page",
id: "wiki-page",
displayName: "Wiki Page",
exportName: "WikiPage",
routePath: "wiki",
pluginId: "plugin-1",
pluginKey: "wiki-plugin",
pluginDisplayName: "Wiki Plugin",
pluginVersion: "1.0.0",
},
{
type: "routeSidebar",
id: "wiki-route-sidebar",
displayName: "Wiki Sidebar",
exportName: "WikiSidebar",
routePath: "wiki",
pluginId: "plugin-1",
pluginKey: "wiki-plugin",
pluginDisplayName: "Wiki Plugin",
pluginVersion: "1.0.0",
},
];
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(mockUsePluginSlots).toHaveBeenCalledWith(
expect.objectContaining({
companyId: "company-2",
enabled: true,
}),
);
expect(mockPluginSlotContexts).toContainEqual({
companyId: "company-2",
companyPrefix: "ALT",
});
expect(mockPluginSlotContexts).not.toContainEqual({
companyId: "company-1",
companyPrefix: "PAP",
});
await act(async () => {
root.unmount();
});
});
it("keeps the normal company sidebar when a plugin page route is ambiguous", async () => {
currentPathname = "/PAP/wiki";
mockPluginSlots.slots = [
{
type: "page",
id: "wiki-page-a",
displayName: "Wiki Page A",
exportName: "WikiPageA",
routePath: "wiki",
pluginId: "plugin-1",
pluginKey: "wiki-plugin-a",
pluginDisplayName: "Wiki Plugin A",
pluginVersion: "1.0.0",
},
{
type: "page",
id: "wiki-page-b",
displayName: "Wiki Page B",
exportName: "WikiPageB",
routePath: "wiki",
pluginId: "plugin-2",
pluginKey: "wiki-plugin-b",
pluginDisplayName: "Wiki Plugin B",
pluginVersion: "1.0.0",
},
{
type: "routeSidebar",
id: "wiki-route-sidebar",
displayName: "Wiki Sidebar",
exportName: "WikiSidebar",
routePath: "wiki",
pluginId: "plugin-1",
pluginKey: "wiki-plugin-a",
pluginDisplayName: "Wiki Plugin A",
pluginVersion: "1.0.0",
},
];
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Main company nav");
expect(container.textContent).not.toContain("Plugin route sidebar");
await act(async () => {
root.unmount();
});
});
async function renderLayoutRoot(): Promise<{
root: ReturnType<typeof createRoot>;
rootEl: HTMLElement;
}> {
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
renderLayoutView(root, queryClient);
});
await flushReact();
const rootEl = container.firstElementChild as HTMLElement;
return { root, rootEl };
}
it("clips horizontal overflow on the mobile layout root so the viewport can't scroll sideways", async () => {
mockSidebarState.isMobile = true;
mockSidebarState.sidebarOpen = false;
const { root, rootEl } = await renderLayoutRoot();
expect(rootEl.tagName).toBe("DIV");
expect(rootEl.className).toContain("bg-background");
// The mobile root must clip horizontal overflow to prevent a stray wide
// descendant from making the whole viewport scroll sideways. clip (not
// hidden) keeps overflow-y visible so body scroll keeps working.
expect(rootEl.classList.contains("overflow-x-clip")).toBe(true);
expect(rootEl.classList.contains("overflow-hidden")).toBe(false);
await act(async () => {
root.unmount();
});
});
it("clips overflow on the desktop layout root", async () => {
mockSidebarState.isMobile = false;
const { root, rootEl } = await renderLayoutRoot();
expect(rootEl.className).toContain("bg-background");
expect(rootEl.classList.contains("overflow-clip")).toBe(true);
await act(async () => {
root.unmount();
});
});
});